blob: 22b90c8332c25fec014c5aeebe247ff095f82737 [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 {
380 EMSG(_(e_invarg));
381 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
499 || (cmd = get_tv_string_chk(
500 &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);
532
533 /* Mark the buffer as not modifiable. It can only be made modifiable after
534 * the job finished. */
535 curbuf->b_p_ma = FALSE;
536
537 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200538#ifdef WIN3264
539 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
540#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200541 setup_job_options(opt, term->tl_rows, term->tl_cols);
542
Bram Moolenaar13568252018-03-16 20:46:58 +0100543 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100544 return curbuf;
545
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100546#if defined(FEAT_SESSION)
547 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100548 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100549 {
550 term->tl_command = vim_strsave((char_u *)"NONE");
551 }
552 else if (argvar->v_type == VAR_STRING)
553 {
554 char_u *cmd = argvar->vval.v_string;
555
556 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
557 term->tl_command = vim_strsave(cmd);
558 }
559 else if (argvar->v_type == VAR_LIST
560 && argvar->vval.v_list != NULL
561 && argvar->vval.v_list->lv_len > 0)
562 {
563 garray_T ga;
564 listitem_T *item;
565
566 ga_init2(&ga, 1, 100);
567 for (item = argvar->vval.v_list->lv_first;
568 item != NULL; item = item->li_next)
569 {
570 char_u *s = get_tv_string_chk(&item->li_tv);
571 char_u *p;
572
573 if (s == NULL)
574 break;
575 p = vim_strsave_fnameescape(s, FALSE);
576 if (p == NULL)
577 break;
578 ga_concat(&ga, p);
579 vim_free(p);
580 ga_append(&ga, ' ');
581 }
582 if (item == NULL)
583 {
584 ga_append(&ga, NUL);
585 term->tl_command = ga.ga_data;
586 }
587 else
588 ga_clear(&ga);
589 }
590#endif
591
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100592 if (opt->jo_term_kill != NULL)
593 {
594 char_u *p = skiptowhite(opt->jo_term_kill);
595
596 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
597 }
598
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200599 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100600 if (argv == NULL
601 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200602 && argvar->vval.v_string != NULL
603 && STRCMP(argvar->vval.v_string, "NONE") == 0)
604 res = create_pty_only(term, opt);
605 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200606 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200607
608 newbuf = curbuf;
609 if (res == OK)
610 {
611 /* Get and remember the size we ended up with. Update the pty. */
612 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
613 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100614#ifdef FEAT_GUI
615 if (term->tl_system)
616 {
617 /* display first line below typed command */
618 term->tl_toprow = msg_row + 1;
619 term->tl_dirty_row_end = 0;
620 }
621#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200622
623 /* Make sure we don't get stuck on sending keys to the job, it leads to
624 * a deadlock if the job is waiting for Vim to read. */
625 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
626
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200627 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200628 {
629 --curbuf->b_nwindows;
630 curbuf = old_curbuf;
631 curwin->w_buffer = curbuf;
632 ++curbuf->b_nwindows;
633 }
634 }
635 else
636 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100637 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200638 return NULL;
639 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100640
Bram Moolenaar13568252018-03-16 20:46:58 +0100641 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200642 return newbuf;
643}
644
645/*
646 * ":terminal": open a terminal window and execute a job in it.
647 */
648 void
649ex_terminal(exarg_T *eap)
650{
651 typval_T argvar[2];
652 jobopt_T opt;
653 char_u *cmd;
654 char_u *tofree = NULL;
655
656 init_job_options(&opt);
657
658 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100659 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200660 {
661 char_u *p, *ep;
662
663 cmd += 2;
664 p = skiptowhite(cmd);
665 ep = vim_strchr(cmd, '=');
666 if (ep != NULL && ep < p)
667 p = ep;
668
669 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
670 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100671 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
672 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200673 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
674 opt.jo_term_finish = 'o';
675 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
676 opt.jo_curwin = 1;
677 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
678 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100679 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
680 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100681 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
682 && ep != NULL)
683 {
684 opt.jo_set2 |= JO2_TERM_KILL;
685 opt.jo_term_kill = ep + 1;
686 p = skiptowhite(cmd);
687 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200688 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
689 && ep != NULL && isdigit(ep[1]))
690 {
691 opt.jo_set2 |= JO2_TERM_ROWS;
692 opt.jo_term_rows = atoi((char *)ep + 1);
693 p = skiptowhite(cmd);
694 }
695 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
696 && ep != NULL && isdigit(ep[1]))
697 {
698 opt.jo_set2 |= JO2_TERM_COLS;
699 opt.jo_term_cols = atoi((char *)ep + 1);
700 p = skiptowhite(cmd);
701 }
702 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
703 && ep != NULL)
704 {
705 char_u *buf = NULL;
706 char_u *keys;
707
708 p = skiptowhite(cmd);
709 *p = NUL;
710 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
711 opt.jo_set2 |= JO2_EOF_CHARS;
712 opt.jo_eof_chars = vim_strsave(keys);
713 vim_free(buf);
714 *p = ' ';
715 }
716 else
717 {
718 if (*p)
719 *p = NUL;
720 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100721 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200722 }
723 cmd = skipwhite(p);
724 }
725 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100726 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200727 /* Make a copy of 'shell', an autocommand may change the option. */
728 tofree = cmd = vim_strsave(p_sh);
729
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100730 /* default to close when the shell exits */
731 if (opt.jo_term_finish == NUL)
732 opt.jo_term_finish = 'c';
733 }
734
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200735 if (eap->addr_count > 0)
736 {
737 /* Write lines from current buffer to the job. */
738 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
739 opt.jo_io[PART_IN] = JIO_BUFFER;
740 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
741 opt.jo_in_top = eap->line1;
742 opt.jo_in_bot = eap->line2;
743 }
744
745 argvar[0].v_type = VAR_STRING;
746 argvar[0].vval.v_string = cmd;
747 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100748 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200749 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100750
751theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200752 vim_free(opt.jo_eof_chars);
753}
754
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100755#if defined(FEAT_SESSION) || defined(PROTO)
756/*
757 * Write a :terminal command to the session file to restore the terminal in
758 * window "wp".
759 * Return FAIL if writing fails.
760 */
761 int
762term_write_session(FILE *fd, win_T *wp)
763{
764 term_T *term = wp->w_buffer->b_term;
765
766 /* Create the terminal and run the command. This is not without
767 * risk, but let's assume the user only creates a session when this
768 * will be OK. */
769 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
770 term->tl_cols, term->tl_rows) < 0)
771 return FAIL;
772 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
773 return FAIL;
774
775 return put_eol(fd);
776}
777
778/*
779 * Return TRUE if "buf" has a terminal that should be restored.
780 */
781 int
782term_should_restore(buf_T *buf)
783{
784 term_T *term = buf->b_term;
785
786 return term != NULL && (term->tl_command == NULL
787 || STRCMP(term->tl_command, "NONE") != 0);
788}
789#endif
790
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200791/*
792 * Free the scrollback buffer for "term".
793 */
794 static void
795free_scrollback(term_T *term)
796{
797 int i;
798
799 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
800 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
801 ga_clear(&term->tl_scrollback);
802}
803
804/*
805 * Free a terminal and everything it refers to.
806 * Kills the job if there is one.
807 * Called when wiping out a buffer.
808 */
809 void
810free_terminal(buf_T *buf)
811{
812 term_T *term = buf->b_term;
813 term_T *tp;
814
815 if (term == NULL)
816 return;
817 if (first_term == term)
818 first_term = term->tl_next;
819 else
820 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
821 if (tp->tl_next == term)
822 {
823 tp->tl_next = term->tl_next;
824 break;
825 }
826
827 if (term->tl_job != NULL)
828 {
829 if (term->tl_job->jv_status != JOB_ENDED
830 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100831 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200832 job_stop(term->tl_job, NULL, "kill");
833 job_unref(term->tl_job);
834 }
835
836 free_scrollback(term);
837
838 term_free_vterm(term);
839 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100840#ifdef FEAT_SESSION
841 vim_free(term->tl_command);
842#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100843 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200844 vim_free(term->tl_status_text);
845 vim_free(term->tl_opencmd);
846 vim_free(term->tl_eof_chars);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200847#ifdef WIN3264
848 if (term->tl_out_fd != NULL)
849 fclose(term->tl_out_fd);
850#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200851 vim_free(term->tl_cursor_color);
852 vim_free(term);
853 buf->b_term = NULL;
854 if (in_terminal_loop == term)
855 in_terminal_loop = NULL;
856}
857
858/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100859 * Get the part that is connected to the tty. Normally this is PART_IN, but
860 * when writing buffer lines to the job it can be another. This makes it
861 * possible to do "1,5term vim -".
862 */
863 static ch_part_T
864get_tty_part(term_T *term)
865{
866#ifdef UNIX
867 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
868 int i;
869
870 for (i = 0; i < 3; ++i)
871 {
872 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
873
874 if (isatty(fd))
875 return parts[i];
876 }
877#endif
878 return PART_IN;
879}
880
881/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200882 * Write job output "msg[len]" to the vterm.
883 */
884 static void
885term_write_job_output(term_T *term, char_u *msg, size_t len)
886{
887 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100888 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200889
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100890 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200891
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100892 /* flush vterm buffer when vterm responded to control sequence */
893 if (prevlen != vterm_output_get_buffer_current(vterm))
894 {
895 char buf[KEY_BUF_LEN];
896 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
897
898 if (curlen > 0)
899 channel_send(term->tl_job->jv_channel, get_tty_part(term),
900 (char_u *)buf, (int)curlen, NULL);
901 }
902
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200903 /* this invokes the damage callbacks */
904 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
905}
906
907 static void
908update_cursor(term_T *term, int redraw)
909{
910 if (term->tl_normal_mode)
911 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100912#ifdef FEAT_GUI
913 if (term->tl_system)
914 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
915 term->tl_cursor_pos.col);
916 else
917#endif
918 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200919 if (redraw)
920 {
921 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
922 cursor_on();
923 out_flush();
924#ifdef FEAT_GUI
925 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100926 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200927 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100928 gui_mch_flush();
929 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200930#endif
931 }
932}
933
934/*
935 * Invoked when "msg" output from a job was received. Write it to the terminal
936 * of "buffer".
937 */
938 void
939write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
940{
941 size_t len = STRLEN(msg);
942 term_T *term = buffer->b_term;
943
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200944#ifdef WIN3264
945 /* Win32: Cannot redirect output of the job, intercept it here and write to
946 * the file. */
947 if (term->tl_out_fd != NULL)
948 {
949 ch_log(channel, "Writing %d bytes to output file", (int)len);
950 fwrite(msg, len, 1, term->tl_out_fd);
951 return;
952 }
953#endif
954
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200955 if (term->tl_vterm == NULL)
956 {
957 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
958 return;
959 }
960 ch_log(channel, "writing %d bytes to terminal", (int)len);
961 term_write_job_output(term, msg, len);
962
Bram Moolenaar13568252018-03-16 20:46:58 +0100963#ifdef FEAT_GUI
964 if (term->tl_system)
965 {
966 /* show system output, scrolling up the screen as needed */
967 update_system_term(term);
968 update_cursor(term, TRUE);
969 }
970 else
971#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200972 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
973 * contents, thus no screen update is needed. */
974 if (!term->tl_normal_mode)
975 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +0200976 // Don't use update_screen() when editing the command line, it gets
977 // cleared.
978 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200979 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +0200980 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200981 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +0200982 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +0200983 /* update_screen() can be slow, check the terminal wasn't closed
984 * already */
985 if (buffer == curbuf && curbuf->b_term != NULL)
986 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200987 }
988 else
989 redraw_after_callback(TRUE);
990 }
991}
992
993/*
994 * Send a mouse position and click to the vterm
995 */
996 static int
997term_send_mouse(VTerm *vterm, int button, int pressed)
998{
999 VTermModifier mod = VTERM_MOD_NONE;
1000
1001 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001002 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001003 if (button != 0)
1004 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001005 return TRUE;
1006}
1007
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001008static int enter_mouse_col = -1;
1009static int enter_mouse_row = -1;
1010
1011/*
1012 * Handle a mouse click, drag or release.
1013 * Return TRUE when a mouse event is sent to the terminal.
1014 */
1015 static int
1016term_mouse_click(VTerm *vterm, int key)
1017{
1018#if defined(FEAT_CLIPBOARD)
1019 /* For modeless selection mouse drag and release events are ignored, unless
1020 * they are preceded with a mouse down event */
1021 static int ignore_drag_release = TRUE;
1022 VTermMouseState mouse_state;
1023
1024 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1025 if (mouse_state.flags == 0)
1026 {
1027 /* Terminal is not using the mouse, use modeless selection. */
1028 switch (key)
1029 {
1030 case K_LEFTDRAG:
1031 case K_LEFTRELEASE:
1032 case K_RIGHTDRAG:
1033 case K_RIGHTRELEASE:
1034 /* Ignore drag and release events when the button-down wasn't
1035 * seen before. */
1036 if (ignore_drag_release)
1037 {
1038 int save_mouse_col, save_mouse_row;
1039
1040 if (enter_mouse_col < 0)
1041 break;
1042
1043 /* mouse click in the window gave us focus, handle that
1044 * click now */
1045 save_mouse_col = mouse_col;
1046 save_mouse_row = mouse_row;
1047 mouse_col = enter_mouse_col;
1048 mouse_row = enter_mouse_row;
1049 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1050 mouse_col = save_mouse_col;
1051 mouse_row = save_mouse_row;
1052 }
1053 /* FALLTHROUGH */
1054 case K_LEFTMOUSE:
1055 case K_RIGHTMOUSE:
1056 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1057 ignore_drag_release = TRUE;
1058 else
1059 ignore_drag_release = FALSE;
1060 /* Should we call mouse_has() here? */
1061 if (clip_star.available)
1062 {
1063 int button, is_click, is_drag;
1064
1065 button = get_mouse_button(KEY2TERMCAP1(key),
1066 &is_click, &is_drag);
1067 if (mouse_model_popup() && button == MOUSE_LEFT
1068 && (mod_mask & MOD_MASK_SHIFT))
1069 {
1070 /* Translate shift-left to right button. */
1071 button = MOUSE_RIGHT;
1072 mod_mask &= ~MOD_MASK_SHIFT;
1073 }
1074 clip_modeless(button, is_click, is_drag);
1075 }
1076 break;
1077
1078 case K_MIDDLEMOUSE:
1079 if (clip_star.available)
1080 insert_reg('*', TRUE);
1081 break;
1082 }
1083 enter_mouse_col = -1;
1084 return FALSE;
1085 }
1086#endif
1087 enter_mouse_col = -1;
1088
1089 switch (key)
1090 {
1091 case K_LEFTMOUSE:
1092 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1093 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1094 case K_LEFTRELEASE:
1095 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1096 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1097 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1098 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1099 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1100 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1101 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1102 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1103 }
1104 return TRUE;
1105}
1106
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001107/*
1108 * Convert typed key "c" into bytes to send to the job.
1109 * Return the number of bytes in "buf".
1110 */
1111 static int
1112term_convert_key(term_T *term, int c, char *buf)
1113{
1114 VTerm *vterm = term->tl_vterm;
1115 VTermKey key = VTERM_KEY_NONE;
1116 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001117 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001118
1119 switch (c)
1120 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001121 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1122
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001123 /* don't use VTERM_KEY_BACKSPACE, it always
1124 * becomes 0x7f DEL */
1125 case K_BS: c = term_backspace_char; break;
1126
1127 case ESC: key = VTERM_KEY_ESCAPE; break;
1128 case K_DEL: key = VTERM_KEY_DEL; break;
1129 case K_DOWN: key = VTERM_KEY_DOWN; break;
1130 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1131 key = VTERM_KEY_DOWN; break;
1132 case K_END: key = VTERM_KEY_END; break;
1133 case K_S_END: mod = VTERM_MOD_SHIFT;
1134 key = VTERM_KEY_END; break;
1135 case K_C_END: mod = VTERM_MOD_CTRL;
1136 key = VTERM_KEY_END; break;
1137 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1138 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1139 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1140 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1141 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1142 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1143 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1144 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1145 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1146 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1147 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1148 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1149 case K_HOME: key = VTERM_KEY_HOME; break;
1150 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1151 key = VTERM_KEY_HOME; break;
1152 case K_C_HOME: mod = VTERM_MOD_CTRL;
1153 key = VTERM_KEY_HOME; break;
1154 case K_INS: key = VTERM_KEY_INS; break;
1155 case K_K0: key = VTERM_KEY_KP_0; break;
1156 case K_K1: key = VTERM_KEY_KP_1; break;
1157 case K_K2: key = VTERM_KEY_KP_2; break;
1158 case K_K3: key = VTERM_KEY_KP_3; break;
1159 case K_K4: key = VTERM_KEY_KP_4; break;
1160 case K_K5: key = VTERM_KEY_KP_5; break;
1161 case K_K6: key = VTERM_KEY_KP_6; break;
1162 case K_K7: key = VTERM_KEY_KP_7; break;
1163 case K_K8: key = VTERM_KEY_KP_8; break;
1164 case K_K9: key = VTERM_KEY_KP_9; break;
1165 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1166 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1167 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1168 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1169 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1170 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1171 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1172 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1173 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1174 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1175 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1176 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1177 case K_LEFT: key = VTERM_KEY_LEFT; break;
1178 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1179 key = VTERM_KEY_LEFT; break;
1180 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1181 key = VTERM_KEY_LEFT; break;
1182 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1183 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1184 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1185 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1186 key = VTERM_KEY_RIGHT; break;
1187 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1188 key = VTERM_KEY_RIGHT; break;
1189 case K_UP: key = VTERM_KEY_UP; break;
1190 case K_S_UP: mod = VTERM_MOD_SHIFT;
1191 key = VTERM_KEY_UP; break;
1192 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001193 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1194 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001195
Bram Moolenaara42ad572017-11-16 13:08:04 +01001196 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1197 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001198 case K_MOUSELEFT: /* TODO */ return 0;
1199 case K_MOUSERIGHT: /* TODO */ return 0;
1200
1201 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001202 case K_LEFTMOUSE_NM:
1203 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001204 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001205 case K_LEFTRELEASE_NM:
1206 case K_MOUSEMOVE:
1207 case K_MIDDLEMOUSE:
1208 case K_MIDDLEDRAG:
1209 case K_MIDDLERELEASE:
1210 case K_RIGHTMOUSE:
1211 case K_RIGHTDRAG:
1212 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1213 return 0;
1214 other = TRUE;
1215 break;
1216
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001217 case K_X1MOUSE: /* TODO */ return 0;
1218 case K_X1DRAG: /* TODO */ return 0;
1219 case K_X1RELEASE: /* TODO */ return 0;
1220 case K_X2MOUSE: /* TODO */ return 0;
1221 case K_X2DRAG: /* TODO */ return 0;
1222 case K_X2RELEASE: /* TODO */ return 0;
1223
1224 case K_IGNORE: return 0;
1225 case K_NOP: return 0;
1226 case K_UNDO: return 0;
1227 case K_HELP: return 0;
1228 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1229 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1230 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1231 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1232 case K_SELECT: return 0;
1233#ifdef FEAT_GUI
1234 case K_VER_SCROLLBAR: return 0;
1235 case K_HOR_SCROLLBAR: return 0;
1236#endif
1237#ifdef FEAT_GUI_TABLINE
1238 case K_TABLINE: return 0;
1239 case K_TABMENU: return 0;
1240#endif
1241#ifdef FEAT_NETBEANS_INTG
1242 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1243#endif
1244#ifdef FEAT_DND
1245 case K_DROP: return 0;
1246#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001247 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001248 case K_PS: vterm_keyboard_start_paste(vterm);
1249 other = TRUE;
1250 break;
1251 case K_PE: vterm_keyboard_end_paste(vterm);
1252 other = TRUE;
1253 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001254 }
1255
1256 /*
1257 * Convert special keys to vterm keys:
1258 * - Write keys to vterm: vterm_keyboard_key()
1259 * - Write output to channel.
1260 * TODO: use mod_mask
1261 */
1262 if (key != VTERM_KEY_NONE)
1263 /* Special key, let vterm convert it. */
1264 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001265 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001266 /* Normal character, let vterm convert it. */
1267 vterm_keyboard_unichar(vterm, c, mod);
1268
1269 /* Read back the converted escape sequence. */
1270 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1271}
1272
1273/*
1274 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001275 * If "check_job_status" is TRUE update the job status.
1276 */
1277 static int
1278term_job_running_check(term_T *term, int check_job_status)
1279{
1280 /* Also consider the job finished when the channel is closed, to avoid a
1281 * race condition when updating the title. */
1282 if (term != NULL
1283 && term->tl_job != NULL
1284 && channel_is_open(term->tl_job->jv_channel))
1285 {
1286 if (check_job_status)
1287 job_status(term->tl_job);
1288 return (term->tl_job->jv_status == JOB_STARTED
1289 || term->tl_job->jv_channel->ch_keep_open);
1290 }
1291 return FALSE;
1292}
1293
1294/*
1295 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001296 */
1297 int
1298term_job_running(term_T *term)
1299{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001300 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001301}
1302
1303/*
1304 * Return TRUE if "term" has an active channel and used ":term NONE".
1305 */
1306 int
1307term_none_open(term_T *term)
1308{
1309 /* Also consider the job finished when the channel is closed, to avoid a
1310 * race condition when updating the title. */
1311 return term != NULL
1312 && term->tl_job != NULL
1313 && channel_is_open(term->tl_job->jv_channel)
1314 && term->tl_job->jv_channel->ch_keep_open;
1315}
1316
1317/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001318 * Used when exiting: kill the job in "buf" if so desired.
1319 * Return OK when the job finished.
1320 * Return FAIL when the job is still running.
1321 */
1322 int
1323term_try_stop_job(buf_T *buf)
1324{
1325 int count;
1326 char *how = (char *)buf->b_term->tl_kill;
1327
1328#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1329 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1330 {
1331 char_u buff[DIALOG_MSG_SIZE];
1332 int ret;
1333
1334 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1335 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1336 if (ret == VIM_YES)
1337 how = "kill";
1338 else if (ret == VIM_CANCEL)
1339 return FAIL;
1340 }
1341#endif
1342 if (how == NULL || *how == NUL)
1343 return FAIL;
1344
1345 job_stop(buf->b_term->tl_job, NULL, how);
1346
1347 /* wait for up to a second for the job to die */
1348 for (count = 0; count < 100; ++count)
1349 {
1350 /* buffer, terminal and job may be cleaned up while waiting */
1351 if (!buf_valid(buf)
1352 || buf->b_term == NULL
1353 || buf->b_term->tl_job == NULL)
1354 return OK;
1355
1356 /* call job_status() to update jv_status */
1357 job_status(buf->b_term->tl_job);
1358 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1359 return OK;
1360 ui_delay(10L, FALSE);
1361 mch_check_messages();
1362 parse_queued_messages();
1363 }
1364 return FAIL;
1365}
1366
1367/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001368 * Add the last line of the scrollback buffer to the buffer in the window.
1369 */
1370 static void
1371add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1372{
1373 buf_T *buf = term->tl_buffer;
1374 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1375 linenr_T lnum = buf->b_ml.ml_line_count;
1376
1377#ifdef WIN3264
1378 if (!enc_utf8 && enc_codepage > 0)
1379 {
1380 WCHAR *ret = NULL;
1381 int length = 0;
1382
1383 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1384 &ret, &length);
1385 if (ret != NULL)
1386 {
1387 WideCharToMultiByte_alloc(enc_codepage, 0,
1388 ret, length, (char **)&text, &len, 0, 0);
1389 vim_free(ret);
1390 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1391 vim_free(text);
1392 }
1393 }
1394 else
1395#endif
1396 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1397 if (empty)
1398 {
1399 /* Delete the empty line that was in the empty buffer. */
1400 curbuf = buf;
1401 ml_delete(1, FALSE);
1402 curbuf = curwin->w_buffer;
1403 }
1404}
1405
1406 static void
1407cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1408{
1409 attr->width = cell->width;
1410 attr->attrs = cell->attrs;
1411 attr->fg = cell->fg;
1412 attr->bg = cell->bg;
1413}
1414
1415 static int
1416equal_celattr(cellattr_T *a, cellattr_T *b)
1417{
1418 /* Comparing the colors should be sufficient. */
1419 return a->fg.red == b->fg.red
1420 && a->fg.green == b->fg.green
1421 && a->fg.blue == b->fg.blue
1422 && a->bg.red == b->bg.red
1423 && a->bg.green == b->bg.green
1424 && a->bg.blue == b->bg.blue;
1425}
1426
Bram Moolenaard96ff162018-02-18 22:13:29 +01001427/*
1428 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1429 * line at this position. Otherwise at the end.
1430 */
1431 static int
1432add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1433{
1434 if (ga_grow(&term->tl_scrollback, 1) == OK)
1435 {
1436 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1437 + term->tl_scrollback.ga_len;
1438
1439 if (lnum > 0)
1440 {
1441 int i;
1442
1443 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1444 {
1445 *line = *(line - 1);
1446 --line;
1447 }
1448 }
1449 line->sb_cols = 0;
1450 line->sb_cells = NULL;
1451 line->sb_fill_attr = *fill_attr;
1452 ++term->tl_scrollback.ga_len;
1453 return OK;
1454 }
1455 return FALSE;
1456}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001457
1458/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001459 * Remove the terminal contents from the scrollback and the buffer.
1460 * Used before adding a new scrollback line or updating the buffer for lines
1461 * displayed in the terminal.
1462 */
1463 static void
1464cleanup_scrollback(term_T *term)
1465{
1466 sb_line_T *line;
1467 garray_T *gap;
1468
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001469 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001470 gap = &term->tl_scrollback;
1471 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1472 && gap->ga_len > 0)
1473 {
1474 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1475 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1476 vim_free(line->sb_cells);
1477 --gap->ga_len;
1478 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001479 curbuf = curwin->w_buffer;
1480 if (curbuf == term->tl_buffer)
1481 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001482}
1483
1484/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001485 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001486 */
1487 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001488update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001489{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001490 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001491 int len;
1492 int lines_skipped = 0;
1493 VTermPos pos;
1494 VTermScreenCell cell;
1495 cellattr_T fill_attr, new_fill_attr;
1496 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001497
1498 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1499 "Adding terminal window snapshot to buffer");
1500
1501 /* First remove the lines that were appended before, they might be
1502 * outdated. */
1503 cleanup_scrollback(term);
1504
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001505 screen = vterm_obtain_screen(term->tl_vterm);
1506 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001507 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1508 {
1509 len = 0;
1510 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1511 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1512 && cell.chars[0] != NUL)
1513 {
1514 len = pos.col + 1;
1515 new_fill_attr = term->tl_default_color;
1516 }
1517 else
1518 /* Assume the last attr is the filler attr. */
1519 cell2cellattr(&cell, &new_fill_attr);
1520
1521 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1522 ++lines_skipped;
1523 else
1524 {
1525 while (lines_skipped > 0)
1526 {
1527 /* Line was skipped, add an empty line. */
1528 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001529 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001530 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001531 }
1532
1533 if (len == 0)
1534 p = NULL;
1535 else
1536 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1537 if ((p != NULL || len == 0)
1538 && ga_grow(&term->tl_scrollback, 1) == OK)
1539 {
1540 garray_T ga;
1541 int width;
1542 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1543 + term->tl_scrollback.ga_len;
1544
1545 ga_init2(&ga, 1, 100);
1546 for (pos.col = 0; pos.col < len; pos.col += width)
1547 {
1548 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1549 {
1550 width = 1;
1551 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1552 if (ga_grow(&ga, 1) == OK)
1553 ga.ga_len += utf_char2bytes(' ',
1554 (char_u *)ga.ga_data + ga.ga_len);
1555 }
1556 else
1557 {
1558 width = cell.width;
1559
1560 cell2cellattr(&cell, &p[pos.col]);
1561
1562 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1563 {
1564 int i;
1565 int c;
1566
1567 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1568 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1569 (char_u *)ga.ga_data + ga.ga_len);
1570 }
1571 }
1572 }
1573 line->sb_cols = len;
1574 line->sb_cells = p;
1575 line->sb_fill_attr = new_fill_attr;
1576 fill_attr = new_fill_attr;
1577 ++term->tl_scrollback.ga_len;
1578
1579 if (ga_grow(&ga, 1) == FAIL)
1580 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1581 else
1582 {
1583 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1584 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1585 }
1586 ga_clear(&ga);
1587 }
1588 else
1589 vim_free(p);
1590 }
1591 }
1592
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001593 term->tl_dirty_snapshot = FALSE;
1594#ifdef FEAT_TIMERS
1595 term->tl_timer_set = FALSE;
1596#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001597}
1598
1599/*
1600 * If needed, add the current lines of the terminal to scrollback and to the
1601 * buffer. Called after the job has ended and when switching to
1602 * Terminal-Normal mode.
1603 * When "redraw" is TRUE redraw the windows that show the terminal.
1604 */
1605 static void
1606may_move_terminal_to_buffer(term_T *term, int redraw)
1607{
1608 win_T *wp;
1609
1610 if (term->tl_vterm == NULL)
1611 return;
1612
1613 /* Update the snapshot only if something changes or the buffer does not
1614 * have all the lines. */
1615 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1616 <= term->tl_scrollback_scrolled)
1617 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001618
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001619 /* Obtain the current background color. */
1620 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1621 &term->tl_default_color.fg, &term->tl_default_color.bg);
1622
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001623 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001624 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001625 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001626 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001628 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1629 wp->w_cursor.col = 0;
1630 wp->w_valid = 0;
1631 if (wp->w_cursor.lnum >= wp->w_height)
1632 {
1633 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001634
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001635 if (wp->w_topline < min_topline)
1636 wp->w_topline = min_topline;
1637 }
1638 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001639 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001640 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001641}
1642
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001643#if defined(FEAT_TIMERS) || defined(PROTO)
1644/*
1645 * Check if any terminal timer expired. If so, copy text from the terminal to
1646 * the buffer.
1647 * Return the time until the next timer will expire.
1648 */
1649 int
1650term_check_timers(int next_due_arg, proftime_T *now)
1651{
1652 term_T *term;
1653 int next_due = next_due_arg;
1654
1655 for (term = first_term; term != NULL; term = term->tl_next)
1656 {
1657 if (term->tl_timer_set && !term->tl_normal_mode)
1658 {
1659 long this_due = proftime_time_left(&term->tl_timer_due, now);
1660
1661 if (this_due <= 1)
1662 {
1663 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001664 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001665 }
1666 else if (next_due == -1 || next_due > this_due)
1667 next_due = this_due;
1668 }
1669 }
1670
1671 return next_due;
1672}
1673#endif
1674
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001675 static void
1676set_terminal_mode(term_T *term, int normal_mode)
1677{
1678 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001679 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001680 if (term->tl_buffer == curbuf)
1681 maketitle();
1682}
1683
1684/*
1685 * Called after the job if finished and Terminal mode is not active:
1686 * Move the vterm contents into the scrollback buffer and free the vterm.
1687 */
1688 static void
1689cleanup_vterm(term_T *term)
1690{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001691 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001692 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001693 term_free_vterm(term);
1694 set_terminal_mode(term, FALSE);
1695}
1696
1697/*
1698 * Switch from Terminal-Job mode to Terminal-Normal mode.
1699 * Suspends updating the terminal window.
1700 */
1701 static void
1702term_enter_normal_mode(void)
1703{
1704 term_T *term = curbuf->b_term;
1705
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001706 set_terminal_mode(term, TRUE);
1707
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001708 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001709 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001710
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001711 /* Move the window cursor to the position of the cursor in the
1712 * terminal. */
1713 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1714 + term->tl_cursor_pos.row + 1;
1715 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001716 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1717 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001718
1719 /* Display the same lines as in the terminal. */
1720 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1721}
1722
1723/*
1724 * Returns TRUE if the current window contains a terminal and we are in
1725 * Terminal-Normal mode.
1726 */
1727 int
1728term_in_normal_mode(void)
1729{
1730 term_T *term = curbuf->b_term;
1731
1732 return term != NULL && term->tl_normal_mode;
1733}
1734
1735/*
1736 * Switch from Terminal-Normal mode to Terminal-Job mode.
1737 * Restores updating the terminal window.
1738 */
1739 void
1740term_enter_job_mode()
1741{
1742 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001743
1744 set_terminal_mode(term, FALSE);
1745
1746 if (term->tl_channel_closed)
1747 cleanup_vterm(term);
1748 redraw_buf_and_status_later(curbuf, NOT_VALID);
1749}
1750
1751/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001752 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001753 * Note: while waiting a terminal may be closed and freed if the channel is
1754 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001755 */
1756 static int
1757term_vgetc()
1758{
1759 int c;
1760 int save_State = State;
1761
1762 State = TERMINAL;
1763 got_int = FALSE;
1764#ifdef WIN3264
1765 ctrl_break_was_pressed = FALSE;
1766#endif
1767 c = vgetc();
1768 got_int = FALSE;
1769 State = save_State;
1770 return c;
1771}
1772
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001773static int mouse_was_outside = FALSE;
1774
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001775/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001776 * Send keys to terminal.
1777 * Return FAIL when the key needs to be handled in Normal mode.
1778 * Return OK when the key was dropped or sent to the terminal.
1779 */
1780 int
1781send_keys_to_term(term_T *term, int c, int typed)
1782{
1783 char msg[KEY_BUF_LEN];
1784 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001785 int dragging_outside = FALSE;
1786
1787 /* Catch keys that need to be handled as in Normal mode. */
1788 switch (c)
1789 {
1790 case NUL:
1791 case K_ZERO:
1792 if (typed)
1793 stuffcharReadbuff(c);
1794 return FAIL;
1795
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001796 case K_TABLINE:
1797 stuffcharReadbuff(c);
1798 return FAIL;
1799
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001800 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001801 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001802 return FAIL;
1803
1804 case K_LEFTDRAG:
1805 case K_MIDDLEDRAG:
1806 case K_RIGHTDRAG:
1807 case K_X1DRAG:
1808 case K_X2DRAG:
1809 dragging_outside = mouse_was_outside;
1810 /* FALLTHROUGH */
1811 case K_LEFTMOUSE:
1812 case K_LEFTMOUSE_NM:
1813 case K_LEFTRELEASE:
1814 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001815 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001816 case K_MIDDLEMOUSE:
1817 case K_MIDDLERELEASE:
1818 case K_RIGHTMOUSE:
1819 case K_RIGHTRELEASE:
1820 case K_X1MOUSE:
1821 case K_X1RELEASE:
1822 case K_X2MOUSE:
1823 case K_X2RELEASE:
1824
1825 case K_MOUSEUP:
1826 case K_MOUSEDOWN:
1827 case K_MOUSELEFT:
1828 case K_MOUSERIGHT:
1829 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001830 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001831 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001832 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001833 || dragging_outside)
1834 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001835 /* click or scroll outside the current window or on status line
1836 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001837 if (typed)
1838 {
1839 stuffcharReadbuff(c);
1840 mouse_was_outside = TRUE;
1841 }
1842 return FAIL;
1843 }
1844 }
1845 if (typed)
1846 mouse_was_outside = FALSE;
1847
1848 /* Convert the typed key to a sequence of bytes for the job. */
1849 len = term_convert_key(term, c, msg);
1850 if (len > 0)
1851 /* TODO: if FAIL is returned, stop? */
1852 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1853 (char_u *)msg, (int)len, NULL);
1854
1855 return OK;
1856}
1857
1858 static void
1859position_cursor(win_T *wp, VTermPos *pos)
1860{
1861 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1862 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1863 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1864}
1865
1866/*
1867 * Handle CTRL-W "": send register contents to the job.
1868 */
1869 static void
1870term_paste_register(int prev_c UNUSED)
1871{
1872 int c;
1873 list_T *l;
1874 listitem_T *item;
1875 long reglen = 0;
1876 int type;
1877
1878#ifdef FEAT_CMDL_INFO
1879 if (add_to_showcmd(prev_c))
1880 if (add_to_showcmd('"'))
1881 out_flush();
1882#endif
1883 c = term_vgetc();
1884#ifdef FEAT_CMDL_INFO
1885 clear_showcmd();
1886#endif
1887 if (!term_use_loop())
1888 /* job finished while waiting for a character */
1889 return;
1890
1891 /* CTRL-W "= prompt for expression to evaluate. */
1892 if (c == '=' && get_expr_register() != '=')
1893 return;
1894 if (!term_use_loop())
1895 /* job finished while waiting for a character */
1896 return;
1897
1898 l = (list_T *)get_reg_contents(c, GREG_LIST);
1899 if (l != NULL)
1900 {
1901 type = get_reg_type(c, &reglen);
1902 for (item = l->lv_first; item != NULL; item = item->li_next)
1903 {
1904 char_u *s = get_tv_string(&item->li_tv);
1905#ifdef WIN3264
1906 char_u *tmp = s;
1907
1908 if (!enc_utf8 && enc_codepage > 0)
1909 {
1910 WCHAR *ret = NULL;
1911 int length = 0;
1912
1913 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1914 (int)STRLEN(s), &ret, &length);
1915 if (ret != NULL)
1916 {
1917 WideCharToMultiByte_alloc(CP_UTF8, 0,
1918 ret, length, (char **)&s, &length, 0, 0);
1919 vim_free(ret);
1920 }
1921 }
1922#endif
1923 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1924 s, (int)STRLEN(s), NULL);
1925#ifdef WIN3264
1926 if (tmp != s)
1927 vim_free(s);
1928#endif
1929
1930 if (item->li_next != NULL || type == MLINE)
1931 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1932 (char_u *)"\r", 1, NULL);
1933 }
1934 list_free(l);
1935 }
1936}
1937
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001938/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001939 * Return TRUE when waiting for a character in the terminal, the cursor of the
1940 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001941 */
1942 int
1943terminal_is_active()
1944{
1945 return in_terminal_loop != NULL;
1946}
1947
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001948#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001949 cursorentry_T *
1950term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1951{
1952 term_T *term = in_terminal_loop;
1953 static cursorentry_T entry;
1954
1955 vim_memset(&entry, 0, sizeof(entry));
1956 entry.shape = entry.mshape =
1957 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1958 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1959 SHAPE_BLOCK;
1960 entry.percentage = 20;
1961 if (term->tl_cursor_blink)
1962 {
1963 entry.blinkwait = 700;
1964 entry.blinkon = 400;
1965 entry.blinkoff = 250;
1966 }
1967 *fg = gui.back_pixel;
1968 if (term->tl_cursor_color == NULL)
1969 *bg = gui.norm_pixel;
1970 else
1971 *bg = color_name2handle(term->tl_cursor_color);
1972 entry.name = "n";
1973 entry.used_for = SHAPE_CURSOR;
1974
1975 return &entry;
1976}
1977#endif
1978
Bram Moolenaard317b382018-02-08 22:33:31 +01001979 static void
1980may_output_cursor_props(void)
1981{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02001982 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01001983 || last_set_cursor_shape != desired_cursor_shape
1984 || last_set_cursor_blink != desired_cursor_blink)
1985 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02001986 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01001987 last_set_cursor_shape = desired_cursor_shape;
1988 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02001989 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01001990 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1991 /* this will restore the initial cursor style, if possible */
1992 ui_cursor_shape_forced(TRUE);
1993 else
1994 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1995 }
1996}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001997
Bram Moolenaard317b382018-02-08 22:33:31 +01001998/*
1999 * Set the cursor color and shape, if not last set to these.
2000 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002001 static void
2002may_set_cursor_props(term_T *term)
2003{
2004#ifdef FEAT_GUI
2005 /* For the GUI the cursor properties are obtained with
2006 * term_get_cursor_shape(). */
2007 if (gui.in_use)
2008 return;
2009#endif
2010 if (in_terminal_loop == term)
2011 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002012 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002013 desired_cursor_shape = term->tl_cursor_shape;
2014 desired_cursor_blink = term->tl_cursor_blink;
2015 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016 }
2017}
2018
Bram Moolenaard317b382018-02-08 22:33:31 +01002019/*
2020 * Reset the desired cursor properties and restore them when needed.
2021 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002023prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002024{
2025#ifdef FEAT_GUI
2026 if (gui.in_use)
2027 return;
2028#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002029 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002030 desired_cursor_shape = -1;
2031 desired_cursor_blink = -1;
2032 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002033}
2034
2035/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002036 * Returns TRUE if the current window contains a terminal and we are sending
2037 * keys to the job.
2038 * If "check_job_status" is TRUE update the job status.
2039 */
2040 static int
2041term_use_loop_check(int check_job_status)
2042{
2043 term_T *term = curbuf->b_term;
2044
2045 return term != NULL
2046 && !term->tl_normal_mode
2047 && term->tl_vterm != NULL
2048 && term_job_running_check(term, check_job_status);
2049}
2050
2051/*
2052 * Returns TRUE if the current window contains a terminal and we are sending
2053 * keys to the job.
2054 */
2055 int
2056term_use_loop(void)
2057{
2058 return term_use_loop_check(FALSE);
2059}
2060
2061/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002062 * Called when entering a window with the mouse. If this is a terminal window
2063 * we may want to change state.
2064 */
2065 void
2066term_win_entered()
2067{
2068 term_T *term = curbuf->b_term;
2069
2070 if (term != NULL)
2071 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002072 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002073 {
2074 reset_VIsual_and_resel();
2075 if (State & INSERT)
2076 stop_insert_mode = TRUE;
2077 }
2078 mouse_was_outside = FALSE;
2079 enter_mouse_col = mouse_col;
2080 enter_mouse_row = mouse_row;
2081 }
2082}
2083
2084/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002085 * Wait for input and send it to the job.
2086 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2087 * when there is no more typahead.
2088 * Return when the start of a CTRL-W command is typed or anything else that
2089 * should be handled as a Normal mode command.
2090 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2091 * the terminal was closed.
2092 */
2093 int
2094terminal_loop(int blocking)
2095{
2096 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002097 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002098 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002099#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002100 int tty_fd = curbuf->b_term->tl_job->jv_channel
2101 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002102#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002103 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002104
2105 /* Remember the terminal we are sending keys to. However, the terminal
2106 * might be closed while waiting for a character, e.g. typing "exit" in a
2107 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2108 * stored reference. */
2109 in_terminal_loop = curbuf->b_term;
2110
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002111 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002112 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002113 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002114 if (termwinkey == Ctrl_W)
2115 termwinkey = 0;
2116 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002117 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2118 may_set_cursor_props(curbuf->b_term);
2119
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002120 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002121 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002122#ifdef FEAT_GUI
2123 if (!curbuf->b_term->tl_system)
2124#endif
2125 /* TODO: skip screen update when handling a sequence of keys. */
2126 /* Repeat redrawing in case a message is received while redrawing.
2127 */
2128 while (must_redraw != 0)
2129 if (update_screen(0) == FAIL)
2130 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002131 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002132 /* job finished while redrawing */
2133 break;
2134
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002135 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002136 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002137
2138 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002139 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002140 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002141 /* Job finished while waiting for a character. Push back the
2142 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002143 if (c != K_IGNORE)
2144 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002145 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002146 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002147 if (c == K_IGNORE)
2148 continue;
2149
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002150#ifdef UNIX
2151 /*
2152 * The shell or another program may change the tty settings. Getting
2153 * them for every typed character is a bit of overhead, but it's needed
2154 * for the first character typed, e.g. when Vim starts in a shell.
2155 */
2156 if (isatty(tty_fd))
2157 {
2158 ttyinfo_T info;
2159
2160 /* Get the current backspace character of the pty. */
2161 if (get_tty_info(tty_fd, &info) == OK)
2162 term_backspace_char = info.backspace;
2163 }
2164#endif
2165
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166#ifdef WIN3264
2167 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2168 * Use CTRL-BREAK to kill the job. */
2169 if (ctrl_break_was_pressed)
2170 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2171#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002172 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002173 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002174 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002175#ifdef FEAT_GUI
2176 && !curbuf->b_term->tl_system
2177#endif
2178 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002179 {
2180 int prev_c = c;
2181
2182#ifdef FEAT_CMDL_INFO
2183 if (add_to_showcmd(c))
2184 out_flush();
2185#endif
2186 c = term_vgetc();
2187#ifdef FEAT_CMDL_INFO
2188 clear_showcmd();
2189#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002190 if (!term_use_loop_check(TRUE)
2191 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002192 /* job finished while waiting for a character */
2193 break;
2194
2195 if (prev_c == Ctrl_BSL)
2196 {
2197 if (c == Ctrl_N)
2198 {
2199 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2200 term_enter_normal_mode();
2201 ret = FAIL;
2202 goto theend;
2203 }
2204 /* Send both keys to the terminal. */
2205 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2206 }
2207 else if (c == Ctrl_C)
2208 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002209 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002210 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2211 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002212 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002213 {
2214 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002215 /* "'termwinkey' .": send 'termwinkey' to the job */
2216 c = termwinkey == 0 ? Ctrl_W : termwinkey;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002217 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002218 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002219 {
2220 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2221 c = Ctrl_BSL;
2222 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002223 else if (c == 'N')
2224 {
2225 /* CTRL-W N : go to Terminal-Normal mode. */
2226 term_enter_normal_mode();
2227 ret = FAIL;
2228 goto theend;
2229 }
2230 else if (c == '"')
2231 {
2232 term_paste_register(prev_c);
2233 continue;
2234 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002235 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 {
2237 stuffcharReadbuff(Ctrl_W);
2238 stuffcharReadbuff(c);
2239 ret = OK;
2240 goto theend;
2241 }
2242 }
2243# ifdef WIN3264
2244 if (!enc_utf8 && has_mbyte && c >= 0x80)
2245 {
2246 WCHAR wc;
2247 char_u mb[3];
2248
2249 mb[0] = (unsigned)c >> 8;
2250 mb[1] = c;
2251 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2252 c = wc;
2253 }
2254# endif
2255 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2256 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002257 if (c == K_MOUSEMOVE)
2258 /* We are sure to come back here, don't reset the cursor color
2259 * and shape to avoid flickering. */
2260 restore_cursor = FALSE;
2261
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262 ret = OK;
2263 goto theend;
2264 }
2265 }
2266 ret = FAIL;
2267
2268theend:
2269 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002270 if (restore_cursor)
2271 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002272
2273 /* Move a snapshot of the screen contents to the buffer, so that completion
2274 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002275 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2276 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002277
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002278 return ret;
2279}
2280
2281/*
2282 * Called when a job has finished.
2283 * This updates the title and status, but does not close the vterm, because
2284 * there might still be pending output in the channel.
2285 */
2286 void
2287term_job_ended(job_T *job)
2288{
2289 term_T *term;
2290 int did_one = FALSE;
2291
2292 for (term = first_term; term != NULL; term = term->tl_next)
2293 if (term->tl_job == job)
2294 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002295 VIM_CLEAR(term->tl_title);
2296 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002297 redraw_buf_and_status_later(term->tl_buffer, VALID);
2298 did_one = TRUE;
2299 }
2300 if (did_one)
2301 redraw_statuslines();
2302 if (curbuf->b_term != NULL)
2303 {
2304 if (curbuf->b_term->tl_job == job)
2305 maketitle();
2306 update_cursor(curbuf->b_term, TRUE);
2307 }
2308}
2309
2310 static void
2311may_toggle_cursor(term_T *term)
2312{
2313 if (in_terminal_loop == term)
2314 {
2315 if (term->tl_cursor_visible)
2316 cursor_on();
2317 else
2318 cursor_off();
2319 }
2320}
2321
2322/*
2323 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002324 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002325 */
2326 static int
2327color2index(VTermColor *color, int fg, int *boldp)
2328{
2329 int red = color->red;
2330 int blue = color->blue;
2331 int green = color->green;
2332
Bram Moolenaar46359e12017-11-29 22:33:38 +01002333 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002334 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002335 /* First 16 colors and default: use the ANSI index, because these
2336 * colors can be redefined. */
2337 if (t_colors >= 16)
2338 return color->ansi_index;
2339 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002340 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002341 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002342 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002343 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2344 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2345 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002346 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002347 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2348 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2349 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2350 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2351 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2352 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2353 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2354 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2355 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2356 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2357 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358 }
2359 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002360
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002361 if (t_colors >= 256)
2362 {
2363 if (red == blue && red == green)
2364 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002365 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002366 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002367 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2368 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2369 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002370 int i;
2371
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002372 if (red < 5)
2373 return 17; /* 00/00/00 */
2374 if (red > 245) /* ff/ff/ff */
2375 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002376 for (i = 0; i < 23; ++i)
2377 if (red < cutoff[i])
2378 return i + 233;
2379 return 256;
2380 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002381 {
2382 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2383 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002384
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002385 /* 216-color cube */
2386 for (ri = 0; ri < 5; ++ri)
2387 if (red < cutoff[ri])
2388 break;
2389 for (gi = 0; gi < 5; ++gi)
2390 if (green < cutoff[gi])
2391 break;
2392 for (bi = 0; bi < 5; ++bi)
2393 if (blue < cutoff[bi])
2394 break;
2395 return 17 + ri * 36 + gi * 6 + bi;
2396 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002397 }
2398 return 0;
2399}
2400
2401/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002402 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002403 */
2404 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002405vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002406{
2407 int attr = 0;
2408
2409 if (cellattrs.bold)
2410 attr |= HL_BOLD;
2411 if (cellattrs.underline)
2412 attr |= HL_UNDERLINE;
2413 if (cellattrs.italic)
2414 attr |= HL_ITALIC;
2415 if (cellattrs.strike)
2416 attr |= HL_STRIKETHROUGH;
2417 if (cellattrs.reverse)
2418 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002419 return attr;
2420}
2421
2422/*
2423 * Store Vterm attributes in "cell" from highlight flags.
2424 */
2425 static void
2426hl2vtermAttr(int attr, cellattr_T *cell)
2427{
2428 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2429 if (attr & HL_BOLD)
2430 cell->attrs.bold = 1;
2431 if (attr & HL_UNDERLINE)
2432 cell->attrs.underline = 1;
2433 if (attr & HL_ITALIC)
2434 cell->attrs.italic = 1;
2435 if (attr & HL_STRIKETHROUGH)
2436 cell->attrs.strike = 1;
2437 if (attr & HL_INVERSE)
2438 cell->attrs.reverse = 1;
2439}
2440
2441/*
2442 * Convert the attributes of a vterm cell into an attribute index.
2443 */
2444 static int
2445cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2446{
2447 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002448
2449#ifdef FEAT_GUI
2450 if (gui.in_use)
2451 {
2452 guicolor_T fg, bg;
2453
2454 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2455 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2456 return get_gui_attr_idx(attr, fg, bg);
2457 }
2458 else
2459#endif
2460#ifdef FEAT_TERMGUICOLORS
2461 if (p_tgc)
2462 {
2463 guicolor_T fg, bg;
2464
2465 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2466 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2467
2468 return get_tgc_attr_idx(attr, fg, bg);
2469 }
2470 else
2471#endif
2472 {
2473 int bold = MAYBE;
2474 int fg = color2index(&cellfg, TRUE, &bold);
2475 int bg = color2index(&cellbg, FALSE, &bold);
2476
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002477 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002478 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002479 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002480 if (fg == 0 && term_default_cterm_fg >= 0)
2481 fg = term_default_cterm_fg + 1;
2482 if (bg == 0 && term_default_cterm_bg >= 0)
2483 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002484 }
2485
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002486 /* with 8 colors set the bold attribute to get a bright foreground */
2487 if (bold == TRUE)
2488 attr |= HL_BOLD;
2489 return get_cterm_attr_idx(attr, fg, bg);
2490 }
2491 return 0;
2492}
2493
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002494 static void
2495set_dirty_snapshot(term_T *term)
2496{
2497 term->tl_dirty_snapshot = TRUE;
2498#ifdef FEAT_TIMERS
2499 if (!term->tl_normal_mode)
2500 {
2501 /* Update the snapshot after 100 msec of not getting updates. */
2502 profile_setlimit(100L, &term->tl_timer_due);
2503 term->tl_timer_set = TRUE;
2504 }
2505#endif
2506}
2507
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002508 static int
2509handle_damage(VTermRect rect, void *user)
2510{
2511 term_T *term = (term_T *)user;
2512
2513 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2514 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002515 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002516 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002517 return 1;
2518}
2519
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002520 static void
2521term_scroll_up(term_T *term, int start_row, int count)
2522{
2523 win_T *wp;
2524 VTermColor fg, bg;
2525 VTermScreenCellAttrs attr;
2526 int clear_attr;
2527
2528 /* Set the color to clear lines with. */
2529 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2530 &fg, &bg);
2531 vim_memset(&attr, 0, sizeof(attr));
2532 clear_attr = cell2attr(attr, fg, bg);
2533
2534 FOR_ALL_WINDOWS(wp)
2535 {
2536 if (wp->w_buffer == term->tl_buffer)
2537 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2538 }
2539}
2540
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002541 static int
2542handle_moverect(VTermRect dest, VTermRect src, void *user)
2543{
2544 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002545 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002546
2547 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002548 * redrawing the text. But avoid doing this multiple times, postpone until
2549 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002550 if (dest.start_col == src.start_col
2551 && dest.end_col == src.end_col
2552 && dest.start_row < src.start_row)
2553 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002554 if (dest.start_row == 0)
2555 term->tl_postponed_scroll += count;
2556 else
2557 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002558 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002559
2560 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2561 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002562 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002563
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002564 /* Note sure if the scrolling will work correctly, let's do a complete
2565 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002566 redraw_buf_later(term->tl_buffer, NOT_VALID);
2567 return 1;
2568}
2569
2570 static int
2571handle_movecursor(
2572 VTermPos pos,
2573 VTermPos oldpos UNUSED,
2574 int visible,
2575 void *user)
2576{
2577 term_T *term = (term_T *)user;
2578 win_T *wp;
2579
2580 term->tl_cursor_pos = pos;
2581 term->tl_cursor_visible = visible;
2582
2583 FOR_ALL_WINDOWS(wp)
2584 {
2585 if (wp->w_buffer == term->tl_buffer)
2586 position_cursor(wp, &pos);
2587 }
2588 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2589 {
2590 may_toggle_cursor(term);
2591 update_cursor(term, term->tl_cursor_visible);
2592 }
2593
2594 return 1;
2595}
2596
2597 static int
2598handle_settermprop(
2599 VTermProp prop,
2600 VTermValue *value,
2601 void *user)
2602{
2603 term_T *term = (term_T *)user;
2604
2605 switch (prop)
2606 {
2607 case VTERM_PROP_TITLE:
2608 vim_free(term->tl_title);
2609 /* a blank title isn't useful, make it empty, so that "running" is
2610 * displayed */
2611 if (*skipwhite((char_u *)value->string) == NUL)
2612 term->tl_title = NULL;
2613#ifdef WIN3264
2614 else if (!enc_utf8 && enc_codepage > 0)
2615 {
2616 WCHAR *ret = NULL;
2617 int length = 0;
2618
2619 MultiByteToWideChar_alloc(CP_UTF8, 0,
2620 (char*)value->string, (int)STRLEN(value->string),
2621 &ret, &length);
2622 if (ret != NULL)
2623 {
2624 WideCharToMultiByte_alloc(enc_codepage, 0,
2625 ret, length, (char**)&term->tl_title,
2626 &length, 0, 0);
2627 vim_free(ret);
2628 }
2629 }
2630#endif
2631 else
2632 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002633 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002634 if (term == curbuf->b_term)
2635 maketitle();
2636 break;
2637
2638 case VTERM_PROP_CURSORVISIBLE:
2639 term->tl_cursor_visible = value->boolean;
2640 may_toggle_cursor(term);
2641 out_flush();
2642 break;
2643
2644 case VTERM_PROP_CURSORBLINK:
2645 term->tl_cursor_blink = value->boolean;
2646 may_set_cursor_props(term);
2647 break;
2648
2649 case VTERM_PROP_CURSORSHAPE:
2650 term->tl_cursor_shape = value->number;
2651 may_set_cursor_props(term);
2652 break;
2653
2654 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002655 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002656 may_set_cursor_props(term);
2657 break;
2658
2659 case VTERM_PROP_ALTSCREEN:
2660 /* TODO: do anything else? */
2661 term->tl_using_altscreen = value->boolean;
2662 break;
2663
2664 default:
2665 break;
2666 }
2667 /* Always return 1, otherwise vterm doesn't store the value internally. */
2668 return 1;
2669}
2670
2671/*
2672 * The job running in the terminal resized the terminal.
2673 */
2674 static int
2675handle_resize(int rows, int cols, void *user)
2676{
2677 term_T *term = (term_T *)user;
2678 win_T *wp;
2679
2680 term->tl_rows = rows;
2681 term->tl_cols = cols;
2682 if (term->tl_vterm_size_changed)
2683 /* Size was set by vterm_set_size(), don't set the window size. */
2684 term->tl_vterm_size_changed = FALSE;
2685 else
2686 {
2687 FOR_ALL_WINDOWS(wp)
2688 {
2689 if (wp->w_buffer == term->tl_buffer)
2690 {
2691 win_setheight_win(rows, wp);
2692 win_setwidth_win(cols, wp);
2693 }
2694 }
2695 redraw_buf_later(term->tl_buffer, NOT_VALID);
2696 }
2697 return 1;
2698}
2699
2700/*
2701 * Handle a line that is pushed off the top of the screen.
2702 */
2703 static int
2704handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2705{
2706 term_T *term = (term_T *)user;
2707
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002708 /* First remove the lines that were appended before, the pushed line goes
2709 * above it. */
2710 cleanup_scrollback(term);
2711
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002712 /* If the number of lines that are stored goes over 'termscrollback' then
2713 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002714 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002715 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002716 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002717 int i;
2718
2719 curbuf = term->tl_buffer;
2720 for (i = 0; i < todo; ++i)
2721 {
2722 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2723 ml_delete(1, FALSE);
2724 }
2725 curbuf = curwin->w_buffer;
2726
2727 term->tl_scrollback.ga_len -= todo;
2728 mch_memmove(term->tl_scrollback.ga_data,
2729 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2730 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
Bram Moolenaar4d6cd292018-05-15 23:53:26 +02002731 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002732 }
2733
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002734 if (ga_grow(&term->tl_scrollback, 1) == OK)
2735 {
2736 cellattr_T *p = NULL;
2737 int len = 0;
2738 int i;
2739 int c;
2740 int col;
2741 sb_line_T *line;
2742 garray_T ga;
2743 cellattr_T fill_attr = term->tl_default_color;
2744
2745 /* do not store empty cells at the end */
2746 for (i = 0; i < cols; ++i)
2747 if (cells[i].chars[0] != 0)
2748 len = i + 1;
2749 else
2750 cell2cellattr(&cells[i], &fill_attr);
2751
2752 ga_init2(&ga, 1, 100);
2753 if (len > 0)
2754 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2755 if (p != NULL)
2756 {
2757 for (col = 0; col < len; col += cells[col].width)
2758 {
2759 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2760 {
2761 ga.ga_len = 0;
2762 break;
2763 }
2764 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2765 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2766 (char_u *)ga.ga_data + ga.ga_len);
2767 cell2cellattr(&cells[col], &p[col]);
2768 }
2769 }
2770 if (ga_grow(&ga, 1) == FAIL)
2771 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2772 else
2773 {
2774 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2775 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2776 }
2777 ga_clear(&ga);
2778
2779 line = (sb_line_T *)term->tl_scrollback.ga_data
2780 + term->tl_scrollback.ga_len;
2781 line->sb_cols = len;
2782 line->sb_cells = p;
2783 line->sb_fill_attr = fill_attr;
2784 ++term->tl_scrollback.ga_len;
2785 ++term->tl_scrollback_scrolled;
2786 }
2787 return 0; /* ignored */
2788}
2789
2790static VTermScreenCallbacks screen_callbacks = {
2791 handle_damage, /* damage */
2792 handle_moverect, /* moverect */
2793 handle_movecursor, /* movecursor */
2794 handle_settermprop, /* settermprop */
2795 NULL, /* bell */
2796 handle_resize, /* resize */
2797 handle_pushline, /* sb_pushline */
2798 NULL /* sb_popline */
2799};
2800
2801/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002802 * Do the work after the channel of a terminal was closed.
2803 * Must be called only when updating_screen is FALSE.
2804 * Returns TRUE when a buffer was closed (list of terminals may have changed).
2805 */
2806 static int
2807term_after_channel_closed(term_T *term)
2808{
2809 /* Unless in Terminal-Normal mode: clear the vterm. */
2810 if (!term->tl_normal_mode)
2811 {
2812 int fnum = term->tl_buffer->b_fnum;
2813
2814 cleanup_vterm(term);
2815
2816 if (term->tl_finish == TL_FINISH_CLOSE)
2817 {
2818 aco_save_T aco;
2819
2820 /* ++close or term_finish == "close" */
2821 ch_log(NULL, "terminal job finished, closing window");
2822 aucmd_prepbuf(&aco, term->tl_buffer);
2823 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
2824 aucmd_restbuf(&aco);
2825 return TRUE;
2826 }
2827 if (term->tl_finish == TL_FINISH_OPEN
2828 && term->tl_buffer->b_nwindows == 0)
2829 {
2830 char buf[50];
2831
2832 /* TODO: use term_opencmd */
2833 ch_log(NULL, "terminal job finished, opening window");
2834 vim_snprintf(buf, sizeof(buf),
2835 term->tl_opencmd == NULL
2836 ? "botright sbuf %d"
2837 : (char *)term->tl_opencmd, fnum);
2838 do_cmdline_cmd((char_u *)buf);
2839 }
2840 else
2841 ch_log(NULL, "terminal job finished");
2842 }
2843
2844 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2845 return FALSE;
2846}
2847
2848/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002849 * Called when a channel has been closed.
2850 * If this was a channel for a terminal window then finish it up.
2851 */
2852 void
2853term_channel_closed(channel_T *ch)
2854{
2855 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002856 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002857 int did_one = FALSE;
2858
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002859 for (term = first_term; term != NULL; term = next_term)
2860 {
2861 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002862 if (term->tl_job == ch->ch_job)
2863 {
2864 term->tl_channel_closed = TRUE;
2865 did_one = TRUE;
2866
Bram Moolenaard23a8232018-02-10 18:45:26 +01002867 VIM_CLEAR(term->tl_title);
2868 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002869#ifdef WIN3264
2870 if (term->tl_out_fd != NULL)
2871 {
2872 fclose(term->tl_out_fd);
2873 term->tl_out_fd = NULL;
2874 }
2875#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002876
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002877 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002878 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002879 /* Cannot open or close windows now. Can happen when
2880 * 'lazyredraw' is set. */
2881 term->tl_channel_recently_closed = TRUE;
2882 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002883 }
2884
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002885 if (term_after_channel_closed(term))
2886 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002887 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002888 }
2889
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002890 if (did_one)
2891 {
2892 redraw_statuslines();
2893
2894 /* Need to break out of vgetc(). */
2895 ins_char_typebuf(K_IGNORE);
2896 typebuf_was_filled = TRUE;
2897
2898 term = curbuf->b_term;
2899 if (term != NULL)
2900 {
2901 if (term->tl_job == ch->ch_job)
2902 maketitle();
2903 update_cursor(term, term->tl_cursor_visible);
2904 }
2905 }
2906}
2907
2908/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002909 * To be called after resetting updating_screen: handle any terminal where the
2910 * channel was closed.
2911 */
2912 void
2913term_check_channel_closed_recently()
2914{
2915 term_T *term;
2916 term_T *next_term;
2917
2918 for (term = first_term; term != NULL; term = next_term)
2919 {
2920 next_term = term->tl_next;
2921 if (term->tl_channel_recently_closed)
2922 {
2923 term->tl_channel_recently_closed = FALSE;
2924 if (term_after_channel_closed(term))
2925 // start over, the list may have changed
2926 next_term = first_term;
2927 }
2928 }
2929}
2930
2931/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002932 * Fill one screen line from a line of the terminal.
2933 * Advances "pos" to past the last column.
2934 */
2935 static void
2936term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2937{
2938 int off = screen_get_current_line_off();
2939
2940 for (pos->col = 0; pos->col < max_col; )
2941 {
2942 VTermScreenCell cell;
2943 int c;
2944
2945 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2946 vim_memset(&cell, 0, sizeof(cell));
2947
2948 c = cell.chars[0];
2949 if (c == NUL)
2950 {
2951 ScreenLines[off] = ' ';
2952 if (enc_utf8)
2953 ScreenLinesUC[off] = NUL;
2954 }
2955 else
2956 {
2957 if (enc_utf8)
2958 {
2959 int i;
2960
2961 /* composing chars */
2962 for (i = 0; i < Screen_mco
2963 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2964 {
2965 ScreenLinesC[i][off] = cell.chars[i + 1];
2966 if (cell.chars[i + 1] == 0)
2967 break;
2968 }
2969 if (c >= 0x80 || (Screen_mco > 0
2970 && ScreenLinesC[0][off] != 0))
2971 {
2972 ScreenLines[off] = ' ';
2973 ScreenLinesUC[off] = c;
2974 }
2975 else
2976 {
2977 ScreenLines[off] = c;
2978 ScreenLinesUC[off] = NUL;
2979 }
2980 }
2981#ifdef WIN3264
2982 else if (has_mbyte && c >= 0x80)
2983 {
2984 char_u mb[MB_MAXBYTES+1];
2985 WCHAR wc = c;
2986
2987 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2988 (char*)mb, 2, 0, 0) > 1)
2989 {
2990 ScreenLines[off] = mb[0];
2991 ScreenLines[off + 1] = mb[1];
2992 cell.width = mb_ptr2cells(mb);
2993 }
2994 else
2995 ScreenLines[off] = c;
2996 }
2997#endif
2998 else
2999 ScreenLines[off] = c;
3000 }
3001 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3002
3003 ++pos->col;
3004 ++off;
3005 if (cell.width == 2)
3006 {
3007 if (enc_utf8)
3008 ScreenLinesUC[off] = NUL;
3009
3010 /* don't set the second byte to NUL for a DBCS encoding, it
3011 * has been set above */
3012 if (enc_utf8 || !has_mbyte)
3013 ScreenLines[off] = NUL;
3014
3015 ++pos->col;
3016 ++off;
3017 }
3018 }
3019}
3020
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003021#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003022 static void
3023update_system_term(term_T *term)
3024{
3025 VTermPos pos;
3026 VTermScreen *screen;
3027
3028 if (term->tl_vterm == NULL)
3029 return;
3030 screen = vterm_obtain_screen(term->tl_vterm);
3031
3032 /* Scroll up to make more room for terminal lines if needed. */
3033 while (term->tl_toprow > 0
3034 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3035 {
3036 int save_p_more = p_more;
3037
3038 p_more = FALSE;
3039 msg_row = Rows - 1;
3040 msg_puts((char_u *)"\n");
3041 p_more = save_p_more;
3042 --term->tl_toprow;
3043 }
3044
3045 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3046 && pos.row < Rows; ++pos.row)
3047 {
3048 if (pos.row < term->tl_rows)
3049 {
3050 int max_col = MIN(Columns, term->tl_cols);
3051
3052 term_line2screenline(screen, &pos, max_col);
3053 }
3054 else
3055 pos.col = 0;
3056
3057 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
3058 }
3059
3060 term->tl_dirty_row_start = MAX_ROW;
3061 term->tl_dirty_row_end = 0;
3062 update_cursor(term, TRUE);
3063}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003064#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003065
3066/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003067 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3068 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003069 * Terminal-Normal mode.
3070 */
3071 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003072term_do_update_window(win_T *wp)
3073{
3074 term_T *term = wp->w_buffer->b_term;
3075
3076 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3077}
3078
3079/*
3080 * Called to update a window that contains an active terminal.
3081 */
3082 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003083term_update_window(win_T *wp)
3084{
3085 term_T *term = wp->w_buffer->b_term;
3086 VTerm *vterm;
3087 VTermScreen *screen;
3088 VTermState *state;
3089 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003090 int rows, cols;
3091 int newrows, newcols;
3092 int minsize;
3093 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003094
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 vterm = term->tl_vterm;
3096 screen = vterm_obtain_screen(vterm);
3097 state = vterm_obtain_state(vterm);
3098
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003099 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3100 * SOME_VALID only redraw what was marked dirty. */
3101 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003102 {
3103 term->tl_dirty_row_start = 0;
3104 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003105
3106 if (term->tl_postponed_scroll > 0
3107 && term->tl_postponed_scroll < term->tl_rows / 3)
3108 /* Scrolling is usually faster than redrawing, when there are only
3109 * a few lines to scroll. */
3110 term_scroll_up(term, 0, term->tl_postponed_scroll);
3111 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003112 }
3113
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003114 /*
3115 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003116 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003117 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003118 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003119
Bram Moolenaar498c2562018-04-15 23:45:15 +02003120 newrows = 99999;
3121 newcols = 99999;
3122 FOR_ALL_WINDOWS(twp)
3123 {
3124 /* When more than one window shows the same terminal, use the
3125 * smallest size. */
3126 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003127 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003128 newrows = MIN(newrows, twp->w_height);
3129 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003131 }
3132 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3133 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3134
3135 if (term->tl_rows != newrows || term->tl_cols != newcols)
3136 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003137 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003138 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003139 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003140 newrows);
3141 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003142
3143 // Updating the terminal size will cause the snapshot to be cleared.
3144 // When not in terminal_loop() we need to restore it.
3145 if (term != in_terminal_loop)
3146 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003147 }
3148
3149 /* The cursor may have been moved when resizing. */
3150 vterm_state_get_cursorpos(state, &pos);
3151 position_cursor(wp, &pos);
3152
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003153 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3154 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003155 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156 if (pos.row < term->tl_rows)
3157 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003158 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003159
Bram Moolenaar13568252018-03-16 20:46:58 +01003160 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003161 }
3162 else
3163 pos.col = 0;
3164
Bram Moolenaarf118d482018-03-13 13:14:00 +01003165 screen_line(wp->w_winrow + pos.row
3166#ifdef FEAT_MENU
3167 + winbar_height(wp)
3168#endif
3169 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003170 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003171 term->tl_dirty_row_start = MAX_ROW;
3172 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003173}
3174
3175/*
3176 * Return TRUE if "wp" is a terminal window where the job has finished.
3177 */
3178 int
3179term_is_finished(buf_T *buf)
3180{
3181 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3182}
3183
3184/*
3185 * Return TRUE if "wp" is a terminal window where the job has finished or we
3186 * are in Terminal-Normal mode, thus we show the buffer contents.
3187 */
3188 int
3189term_show_buffer(buf_T *buf)
3190{
3191 term_T *term = buf->b_term;
3192
3193 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3194}
3195
3196/*
3197 * The current buffer is going to be changed. If there is terminal
3198 * highlighting remove it now.
3199 */
3200 void
3201term_change_in_curbuf(void)
3202{
3203 term_T *term = curbuf->b_term;
3204
3205 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3206 {
3207 free_scrollback(term);
3208 redraw_buf_later(term->tl_buffer, NOT_VALID);
3209
3210 /* The buffer is now like a normal buffer, it cannot be easily
3211 * abandoned when changed. */
3212 set_string_option_direct((char_u *)"buftype", -1,
3213 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3214 }
3215}
3216
3217/*
3218 * Get the screen attribute for a position in the buffer.
3219 * Use a negative "col" to get the filler background color.
3220 */
3221 int
3222term_get_attr(buf_T *buf, linenr_T lnum, int col)
3223{
3224 term_T *term = buf->b_term;
3225 sb_line_T *line;
3226 cellattr_T *cellattr;
3227
3228 if (lnum > term->tl_scrollback.ga_len)
3229 cellattr = &term->tl_default_color;
3230 else
3231 {
3232 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3233 if (col < 0 || col >= line->sb_cols)
3234 cellattr = &line->sb_fill_attr;
3235 else
3236 cellattr = line->sb_cells + col;
3237 }
3238 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3239}
3240
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003241/*
3242 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003243 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003244 */
3245 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003246cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003247{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003248 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003249}
3250
3251/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003252 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003253 */
3254 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003255init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003256{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003257 VTermColor *fg, *bg;
3258 int fgval, bgval;
3259 int id;
3260
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003261 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3262 term->tl_default_color.width = 1;
3263 fg = &term->tl_default_color.fg;
3264 bg = &term->tl_default_color.bg;
3265
3266 /* Vterm uses a default black background. Set it to white when
3267 * 'background' is "light". */
3268 if (*p_bg == 'l')
3269 {
3270 fgval = 0;
3271 bgval = 255;
3272 }
3273 else
3274 {
3275 fgval = 255;
3276 bgval = 0;
3277 }
3278 fg->red = fg->green = fg->blue = fgval;
3279 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003280 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003281
3282 /* The "Terminal" highlight group overrules the defaults. */
3283 id = syn_name2id((char_u *)"Terminal");
3284
Bram Moolenaar46359e12017-11-29 22:33:38 +01003285 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003286#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3287 if (0
3288# ifdef FEAT_GUI
3289 || gui.in_use
3290# endif
3291# ifdef FEAT_TERMGUICOLORS
3292 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003293# ifdef FEAT_VTP
3294 /* Finally get INVALCOLOR on this execution path */
3295 || (!p_tgc && t_colors >= 256)
3296# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003297# endif
3298 )
3299 {
3300 guicolor_T fg_rgb = INVALCOLOR;
3301 guicolor_T bg_rgb = INVALCOLOR;
3302
3303 if (id != 0)
3304 syn_id2colors(id, &fg_rgb, &bg_rgb);
3305
3306# ifdef FEAT_GUI
3307 if (gui.in_use)
3308 {
3309 if (fg_rgb == INVALCOLOR)
3310 fg_rgb = gui.norm_pixel;
3311 if (bg_rgb == INVALCOLOR)
3312 bg_rgb = gui.back_pixel;
3313 }
3314# ifdef FEAT_TERMGUICOLORS
3315 else
3316# endif
3317# endif
3318# ifdef FEAT_TERMGUICOLORS
3319 {
3320 if (fg_rgb == INVALCOLOR)
3321 fg_rgb = cterm_normal_fg_gui_color;
3322 if (bg_rgb == INVALCOLOR)
3323 bg_rgb = cterm_normal_bg_gui_color;
3324 }
3325# endif
3326 if (fg_rgb != INVALCOLOR)
3327 {
3328 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3329
3330 fg->red = (unsigned)(rgb >> 16);
3331 fg->green = (unsigned)(rgb >> 8) & 255;
3332 fg->blue = (unsigned)rgb & 255;
3333 }
3334 if (bg_rgb != INVALCOLOR)
3335 {
3336 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3337
3338 bg->red = (unsigned)(rgb >> 16);
3339 bg->green = (unsigned)(rgb >> 8) & 255;
3340 bg->blue = (unsigned)rgb & 255;
3341 }
3342 }
3343 else
3344#endif
3345 if (id != 0 && t_colors >= 16)
3346 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003347 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003348 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003349 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003350 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003351 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003352 else
3353 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003354#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003355 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003356#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357
3358 /* In an MS-Windows console we know the normal colors. */
3359 if (cterm_normal_fg_color > 0)
3360 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003361 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003362# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003363 tmp = fg->red;
3364 fg->red = fg->blue;
3365 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003366# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003367 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003368# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003369 else
3370 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003371# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003372
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003373 if (cterm_normal_bg_color > 0)
3374 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003375 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003376# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003377 tmp = bg->red;
3378 bg->red = bg->blue;
3379 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003380# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003381 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003382# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003383 else
3384 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003385# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003386 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003387}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003388
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003389#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3390/*
3391 * Set the 16 ANSI colors from array of RGB values
3392 */
3393 static void
3394set_vterm_palette(VTerm *vterm, long_u *rgb)
3395{
3396 int index = 0;
3397 VTermState *state = vterm_obtain_state(vterm);
3398 for (; index < 16; index++)
3399 {
3400 VTermColor color;
3401 color.red = (unsigned)(rgb[index] >> 16);
3402 color.green = (unsigned)(rgb[index] >> 8) & 255;
3403 color.blue = (unsigned)rgb[index] & 255;
3404 vterm_state_set_palette_color(state, index, &color);
3405 }
3406}
3407
3408/*
3409 * Set the ANSI color palette from a list of colors
3410 */
3411 static int
3412set_ansi_colors_list(VTerm *vterm, list_T *list)
3413{
3414 int n = 0;
3415 long_u rgb[16];
3416 listitem_T *li = list->lv_first;
3417
3418 for (; li != NULL && n < 16; li = li->li_next, n++)
3419 {
3420 char_u *color_name;
3421 guicolor_T guicolor;
3422
3423 color_name = get_tv_string_chk(&li->li_tv);
3424 if (color_name == NULL)
3425 return FAIL;
3426
3427 guicolor = GUI_GET_COLOR(color_name);
3428 if (guicolor == INVALCOLOR)
3429 return FAIL;
3430
3431 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3432 }
3433
3434 if (n != 16 || li != NULL)
3435 return FAIL;
3436
3437 set_vterm_palette(vterm, rgb);
3438
3439 return OK;
3440}
3441
3442/*
3443 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3444 */
3445 static void
3446init_vterm_ansi_colors(VTerm *vterm)
3447{
3448 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3449
3450 if (var != NULL
3451 && (var->di_tv.v_type != VAR_LIST
3452 || var->di_tv.vval.v_list == NULL
3453 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3454 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3455}
3456#endif
3457
Bram Moolenaar52acb112018-03-18 19:20:22 +01003458/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003459 * Handles a "drop" command from the job in the terminal.
3460 * "item" is the file name, "item->li_next" may have options.
3461 */
3462 static void
3463handle_drop_command(listitem_T *item)
3464{
3465 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003466 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003467 int bufnr;
3468 win_T *wp;
3469 tabpage_T *tp;
3470 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003471 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003472
3473 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3474 FOR_ALL_TAB_WINDOWS(tp, wp)
3475 {
3476 if (wp->w_buffer->b_fnum == bufnr)
3477 {
3478 /* buffer is in a window already, go there */
3479 goto_tabpage_win(tp, wp);
3480 return;
3481 }
3482 }
3483
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003484 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003485
3486 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3487 && opt_item->li_tv.vval.v_dict != NULL)
3488 {
3489 dict_T *dict = opt_item->li_tv.vval.v_dict;
3490 char_u *p;
3491
3492 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3493 if (p == NULL)
3494 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3495 if (p != NULL)
3496 {
3497 if (check_ff_value(p) == FAIL)
3498 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3499 else
3500 ea.force_ff = *p;
3501 }
3502 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3503 if (p == NULL)
3504 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3505 if (p != NULL)
3506 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003507 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003508 if (ea.cmd != NULL)
3509 {
3510 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3511 ea.force_enc = 11;
3512 tofree = ea.cmd;
3513 }
3514 }
3515
3516 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3517 if (p != NULL)
3518 get_bad_opt(p, &ea);
3519
3520 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3521 ea.force_bin = FORCE_BIN;
3522 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3523 ea.force_bin = FORCE_BIN;
3524 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3525 ea.force_bin = FORCE_NOBIN;
3526 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3527 ea.force_bin = FORCE_NOBIN;
3528 }
3529
3530 /* open in new window, like ":split fname" */
3531 if (ea.cmd == NULL)
3532 ea.cmd = (char_u *)"split";
3533 ea.arg = fname;
3534 ea.cmdidx = CMD_split;
3535 ex_splitview(&ea);
3536
3537 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003538}
3539
3540/*
3541 * Handles a function call from the job running in a terminal.
3542 * "item" is the function name, "item->li_next" has the arguments.
3543 */
3544 static void
3545handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3546{
3547 char_u *func;
3548 typval_T argvars[2];
3549 typval_T rettv;
3550 int doesrange;
3551
3552 if (item->li_next == NULL)
3553 {
3554 ch_log(channel, "Missing function arguments for call");
3555 return;
3556 }
3557 func = get_tv_string(&item->li_tv);
3558
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003559 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003560 {
3561 ch_log(channel, "Invalid function name: %s", func);
3562 return;
3563 }
3564
3565 argvars[0].v_type = VAR_NUMBER;
3566 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3567 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003568 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003569 2, argvars, /* argv_func */ NULL,
3570 /* firstline */ 1, /* lastline */ 1,
3571 &doesrange, /* evaluate */ TRUE,
3572 /* partial */ NULL, /* selfdict */ NULL) == OK)
3573 {
3574 clear_tv(&rettv);
3575 ch_log(channel, "Function %s called", func);
3576 }
3577 else
3578 ch_log(channel, "Calling function %s failed", func);
3579}
3580
3581/*
3582 * Called by libvterm when it cannot recognize an OSC sequence.
3583 * We recognize a terminal API command.
3584 */
3585 static int
3586parse_osc(const char *command, size_t cmdlen, void *user)
3587{
3588 term_T *term = (term_T *)user;
3589 js_read_T reader;
3590 typval_T tv;
3591 channel_T *channel = term->tl_job == NULL ? NULL
3592 : term->tl_job->jv_channel;
3593
3594 /* We recognize only OSC 5 1 ; {command} */
3595 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3596 return 0; /* not handled */
3597
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003598 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003599 if (reader.js_buf == NULL)
3600 return 1;
3601 reader.js_fill = NULL;
3602 reader.js_used = 0;
3603 if (json_decode(&reader, &tv, 0) == OK
3604 && tv.v_type == VAR_LIST
3605 && tv.vval.v_list != NULL)
3606 {
3607 listitem_T *item = tv.vval.v_list->lv_first;
3608
3609 if (item == NULL)
3610 ch_log(channel, "Missing command");
3611 else
3612 {
3613 char_u *cmd = get_tv_string(&item->li_tv);
3614
Bram Moolenaara997b452018-04-17 23:24:06 +02003615 /* Make sure an invoked command doesn't delete the buffer (and the
3616 * terminal) under our fingers. */
3617 ++term->tl_buffer->b_locked;
3618
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003619 item = item->li_next;
3620 if (item == NULL)
3621 ch_log(channel, "Missing argument for %s", cmd);
3622 else if (STRCMP(cmd, "drop") == 0)
3623 handle_drop_command(item);
3624 else if (STRCMP(cmd, "call") == 0)
3625 handle_call_command(term, channel, item);
3626 else
3627 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003628 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003629 }
3630 }
3631 else
3632 ch_log(channel, "Invalid JSON received");
3633
3634 vim_free(reader.js_buf);
3635 clear_tv(&tv);
3636 return 1;
3637}
3638
3639static VTermParserCallbacks parser_fallbacks = {
3640 NULL, /* text */
3641 NULL, /* control */
3642 NULL, /* escape */
3643 NULL, /* csi */
3644 parse_osc, /* osc */
3645 NULL, /* dcs */
3646 NULL /* resize */
3647};
3648
3649/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003650 * Use Vim's allocation functions for vterm so profiling works.
3651 */
3652 static void *
3653vterm_malloc(size_t size, void *data UNUSED)
3654{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003655 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003656}
3657
3658 static void
3659vterm_memfree(void *ptr, void *data UNUSED)
3660{
3661 vim_free(ptr);
3662}
3663
3664static VTermAllocatorFunctions vterm_allocator = {
3665 &vterm_malloc,
3666 &vterm_memfree
3667};
3668
3669/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003670 * Create a new vterm and initialize it.
3671 */
3672 static void
3673create_vterm(term_T *term, int rows, int cols)
3674{
3675 VTerm *vterm;
3676 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003677 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003678 VTermValue value;
3679
Bram Moolenaar756ef112018-04-10 12:04:27 +02003680 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003681 term->tl_vterm = vterm;
3682 screen = vterm_obtain_screen(vterm);
3683 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3684 /* TODO: depends on 'encoding'. */
3685 vterm_set_utf8(vterm, 1);
3686
3687 init_default_colors(term);
3688
3689 vterm_state_set_default_colors(
3690 vterm_obtain_state(vterm),
3691 &term->tl_default_color.fg,
3692 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003693
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003694 if (t_colors >= 16)
3695 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3696
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003697 /* Required to initialize most things. */
3698 vterm_screen_reset(screen, 1 /* hard */);
3699
3700 /* Allow using alternate screen. */
3701 vterm_screen_enable_altscreen(screen, 1);
3702
3703 /* For unix do not use a blinking cursor. In an xterm this causes the
3704 * cursor to blink if it's blinking in the xterm.
3705 * For Windows we respect the system wide setting. */
3706#ifdef WIN3264
3707 if (GetCaretBlinkTime() == INFINITE)
3708 value.boolean = 0;
3709 else
3710 value.boolean = 1;
3711#else
3712 value.boolean = 0;
3713#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003714 state = vterm_obtain_state(vterm);
3715 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3716 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003717}
3718
3719/*
3720 * Return the text to show for the buffer name and status.
3721 */
3722 char_u *
3723term_get_status_text(term_T *term)
3724{
3725 if (term->tl_status_text == NULL)
3726 {
3727 char_u *txt;
3728 size_t len;
3729
3730 if (term->tl_normal_mode)
3731 {
3732 if (term_job_running(term))
3733 txt = (char_u *)_("Terminal");
3734 else
3735 txt = (char_u *)_("Terminal-finished");
3736 }
3737 else if (term->tl_title != NULL)
3738 txt = term->tl_title;
3739 else if (term_none_open(term))
3740 txt = (char_u *)_("active");
3741 else if (term_job_running(term))
3742 txt = (char_u *)_("running");
3743 else
3744 txt = (char_u *)_("finished");
3745 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3746 term->tl_status_text = alloc((int)len);
3747 if (term->tl_status_text != NULL)
3748 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3749 term->tl_buffer->b_fname, txt);
3750 }
3751 return term->tl_status_text;
3752}
3753
3754/*
3755 * Mark references in jobs of terminals.
3756 */
3757 int
3758set_ref_in_term(int copyID)
3759{
3760 int abort = FALSE;
3761 term_T *term;
3762 typval_T tv;
3763
3764 for (term = first_term; term != NULL; term = term->tl_next)
3765 if (term->tl_job != NULL)
3766 {
3767 tv.v_type = VAR_JOB;
3768 tv.vval.v_job = term->tl_job;
3769 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3770 }
3771 return abort;
3772}
3773
3774/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003775 * Cache "Terminal" highlight group colors.
3776 */
3777 void
3778set_terminal_default_colors(int cterm_fg, int cterm_bg)
3779{
3780 term_default_cterm_fg = cterm_fg - 1;
3781 term_default_cterm_bg = cterm_bg - 1;
3782}
3783
3784/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003785 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003786 * Returns NULL when the buffer is not for a terminal window and logs a message
3787 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003788 */
3789 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003790term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003791{
3792 buf_T *buf;
3793
3794 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3795 ++emsg_off;
3796 buf = get_buf_tv(&argvars[0], FALSE);
3797 --emsg_off;
3798 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003799 {
3800 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003801 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003802 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003803 return buf;
3804}
3805
Bram Moolenaard96ff162018-02-18 22:13:29 +01003806 static int
3807same_color(VTermColor *a, VTermColor *b)
3808{
3809 return a->red == b->red
3810 && a->green == b->green
3811 && a->blue == b->blue
3812 && a->ansi_index == b->ansi_index;
3813}
3814
3815 static void
3816dump_term_color(FILE *fd, VTermColor *color)
3817{
3818 fprintf(fd, "%02x%02x%02x%d",
3819 (int)color->red, (int)color->green, (int)color->blue,
3820 (int)color->ansi_index);
3821}
3822
3823/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003824 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003825 *
3826 * Each screen cell in full is:
3827 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3828 * {characters} is a space for an empty cell
3829 * For a double-width character "+" is changed to "*" and the next cell is
3830 * skipped.
3831 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3832 * when "&" use the same as the previous cell.
3833 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3834 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3835 * {color-idx} is a number from 0 to 255
3836 *
3837 * Screen cell with same width, attributes and color as the previous one:
3838 * |{characters}
3839 *
3840 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3841 *
3842 * Repeating the previous screen cell:
3843 * @{count}
3844 */
3845 void
3846f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3847{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003848 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003849 term_T *term;
3850 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003851 int max_height = 0;
3852 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003853 stat_T st;
3854 FILE *fd;
3855 VTermPos pos;
3856 VTermScreen *screen;
3857 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003858 VTermState *state;
3859 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003860
3861 if (check_restricted() || check_secure())
3862 return;
3863 if (buf == NULL)
3864 return;
3865 term = buf->b_term;
3866
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003867 if (argvars[2].v_type != VAR_UNKNOWN)
3868 {
3869 dict_T *d;
3870
3871 if (argvars[2].v_type != VAR_DICT)
3872 {
3873 EMSG(_(e_dictreq));
3874 return;
3875 }
3876 d = argvars[2].vval.v_dict;
3877 if (d != NULL)
3878 {
3879 max_height = get_dict_number(d, (char_u *)"rows");
3880 max_width = get_dict_number(d, (char_u *)"columns");
3881 }
3882 }
3883
Bram Moolenaard96ff162018-02-18 22:13:29 +01003884 fname = get_tv_string_chk(&argvars[1]);
3885 if (fname == NULL)
3886 return;
3887 if (mch_stat((char *)fname, &st) >= 0)
3888 {
3889 EMSG2(_("E953: File exists: %s"), fname);
3890 return;
3891 }
3892
Bram Moolenaard96ff162018-02-18 22:13:29 +01003893 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3894 {
3895 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3896 return;
3897 }
3898
3899 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3900
3901 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003902 state = vterm_obtain_state(term->tl_vterm);
3903 vterm_state_get_cursorpos(state, &cursor_pos);
3904
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003905 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3906 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003907 {
3908 int repeat = 0;
3909
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003910 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3911 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003912 {
3913 VTermScreenCell cell;
3914 int same_attr;
3915 int same_chars = TRUE;
3916 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003917 int is_cursor_pos = (pos.col == cursor_pos.col
3918 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003919
3920 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3921 vim_memset(&cell, 0, sizeof(cell));
3922
3923 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3924 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003925 int c = cell.chars[i];
3926 int pc = prev_cell.chars[i];
3927
3928 /* For the first character NUL is the same as space. */
3929 if (i == 0)
3930 {
3931 c = (c == NUL) ? ' ' : c;
3932 pc = (pc == NUL) ? ' ' : pc;
3933 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003934 if (cell.chars[i] != prev_cell.chars[i])
3935 same_chars = FALSE;
3936 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3937 break;
3938 }
3939 same_attr = vtermAttr2hl(cell.attrs)
3940 == vtermAttr2hl(prev_cell.attrs)
3941 && same_color(&cell.fg, &prev_cell.fg)
3942 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003943 if (same_chars && cell.width == prev_cell.width && same_attr
3944 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003945 {
3946 ++repeat;
3947 }
3948 else
3949 {
3950 if (repeat > 0)
3951 {
3952 fprintf(fd, "@%d", repeat);
3953 repeat = 0;
3954 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003955 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003956
3957 if (cell.chars[0] == NUL)
3958 fputs(" ", fd);
3959 else
3960 {
3961 char_u charbuf[10];
3962 int len;
3963
3964 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3965 && cell.chars[i] != NUL; ++i)
3966 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003967 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003968 fwrite(charbuf, len, 1, fd);
3969 }
3970 }
3971
3972 /* When only the characters differ we don't write anything, the
3973 * following "|", "@" or NL will indicate using the same
3974 * attributes. */
3975 if (cell.width != prev_cell.width || !same_attr)
3976 {
3977 if (cell.width == 2)
3978 {
3979 fputs("*", fd);
3980 ++pos.col;
3981 }
3982 else
3983 fputs("+", fd);
3984
3985 if (same_attr)
3986 {
3987 fputs("&", fd);
3988 }
3989 else
3990 {
3991 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3992 if (same_color(&cell.fg, &prev_cell.fg))
3993 fputs("&", fd);
3994 else
3995 {
3996 fputs("#", fd);
3997 dump_term_color(fd, &cell.fg);
3998 }
3999 if (same_color(&cell.bg, &prev_cell.bg))
4000 fputs("&", fd);
4001 else
4002 {
4003 fputs("#", fd);
4004 dump_term_color(fd, &cell.bg);
4005 }
4006 }
4007 }
4008
4009 prev_cell = cell;
4010 }
4011 }
4012 if (repeat > 0)
4013 fprintf(fd, "@%d", repeat);
4014 fputs("\n", fd);
4015 }
4016
4017 fclose(fd);
4018}
4019
4020/*
4021 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4022 */
4023 static void
4024dump_is_corrupt(garray_T *gap)
4025{
4026 ga_concat(gap, (char_u *)"CORRUPT");
4027}
4028
4029 static void
4030append_cell(garray_T *gap, cellattr_T *cell)
4031{
4032 if (ga_grow(gap, 1) == OK)
4033 {
4034 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4035 ++gap->ga_len;
4036 }
4037}
4038
4039/*
4040 * Read the dump file from "fd" and append lines to the current buffer.
4041 * Return the cell width of the longest line.
4042 */
4043 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004044read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004045{
4046 int c;
4047 garray_T ga_text;
4048 garray_T ga_cell;
4049 char_u *prev_char = NULL;
4050 int attr = 0;
4051 cellattr_T cell;
4052 term_T *term = curbuf->b_term;
4053 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004054 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004055
4056 ga_init2(&ga_text, 1, 90);
4057 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4058 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004059 cursor_pos->row = -1;
4060 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004061
4062 c = fgetc(fd);
4063 for (;;)
4064 {
4065 if (c == EOF)
4066 break;
4067 if (c == '\n')
4068 {
4069 /* End of a line: append it to the buffer. */
4070 if (ga_text.ga_data == NULL)
4071 dump_is_corrupt(&ga_text);
4072 if (ga_grow(&term->tl_scrollback, 1) == OK)
4073 {
4074 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4075 + term->tl_scrollback.ga_len;
4076
4077 if (max_cells < ga_cell.ga_len)
4078 max_cells = ga_cell.ga_len;
4079 line->sb_cols = ga_cell.ga_len;
4080 line->sb_cells = ga_cell.ga_data;
4081 line->sb_fill_attr = term->tl_default_color;
4082 ++term->tl_scrollback.ga_len;
4083 ga_init(&ga_cell);
4084
4085 ga_append(&ga_text, NUL);
4086 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4087 ga_text.ga_len, FALSE);
4088 }
4089 else
4090 ga_clear(&ga_cell);
4091 ga_text.ga_len = 0;
4092
4093 c = fgetc(fd);
4094 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004095 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004096 {
4097 int prev_len = ga_text.ga_len;
4098
Bram Moolenaar9271d052018-02-25 21:39:46 +01004099 if (c == '>')
4100 {
4101 if (cursor_pos->row != -1)
4102 dump_is_corrupt(&ga_text); /* duplicate cursor */
4103 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4104 cursor_pos->col = ga_cell.ga_len;
4105 }
4106
Bram Moolenaard96ff162018-02-18 22:13:29 +01004107 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4108 c = fgetc(fd);
4109 if (c != EOF)
4110 ga_append(&ga_text, c);
4111 for (;;)
4112 {
4113 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004114 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004115 || c == EOF || c == '\n')
4116 break;
4117 ga_append(&ga_text, c);
4118 }
4119
4120 /* save the character for repeating it */
4121 vim_free(prev_char);
4122 if (ga_text.ga_data != NULL)
4123 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4124 ga_text.ga_len - prev_len);
4125
Bram Moolenaar9271d052018-02-25 21:39:46 +01004126 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004127 {
4128 /* use all attributes from previous cell */
4129 }
4130 else if (c == '+' || c == '*')
4131 {
4132 int is_bg;
4133
4134 cell.width = c == '+' ? 1 : 2;
4135
4136 c = fgetc(fd);
4137 if (c == '&')
4138 {
4139 /* use same attr as previous cell */
4140 c = fgetc(fd);
4141 }
4142 else if (isdigit(c))
4143 {
4144 /* get the decimal attribute */
4145 attr = 0;
4146 while (isdigit(c))
4147 {
4148 attr = attr * 10 + (c - '0');
4149 c = fgetc(fd);
4150 }
4151 hl2vtermAttr(attr, &cell);
4152 }
4153 else
4154 dump_is_corrupt(&ga_text);
4155
4156 /* is_bg == 0: fg, is_bg == 1: bg */
4157 for (is_bg = 0; is_bg <= 1; ++is_bg)
4158 {
4159 if (c == '&')
4160 {
4161 /* use same color as previous cell */
4162 c = fgetc(fd);
4163 }
4164 else if (c == '#')
4165 {
4166 int red, green, blue, index = 0;
4167
4168 c = fgetc(fd);
4169 red = hex2nr(c);
4170 c = fgetc(fd);
4171 red = (red << 4) + hex2nr(c);
4172 c = fgetc(fd);
4173 green = hex2nr(c);
4174 c = fgetc(fd);
4175 green = (green << 4) + hex2nr(c);
4176 c = fgetc(fd);
4177 blue = hex2nr(c);
4178 c = fgetc(fd);
4179 blue = (blue << 4) + hex2nr(c);
4180 c = fgetc(fd);
4181 if (!isdigit(c))
4182 dump_is_corrupt(&ga_text);
4183 while (isdigit(c))
4184 {
4185 index = index * 10 + (c - '0');
4186 c = fgetc(fd);
4187 }
4188
4189 if (is_bg)
4190 {
4191 cell.bg.red = red;
4192 cell.bg.green = green;
4193 cell.bg.blue = blue;
4194 cell.bg.ansi_index = index;
4195 }
4196 else
4197 {
4198 cell.fg.red = red;
4199 cell.fg.green = green;
4200 cell.fg.blue = blue;
4201 cell.fg.ansi_index = index;
4202 }
4203 }
4204 else
4205 dump_is_corrupt(&ga_text);
4206 }
4207 }
4208 else
4209 dump_is_corrupt(&ga_text);
4210
4211 append_cell(&ga_cell, &cell);
4212 }
4213 else if (c == '@')
4214 {
4215 if (prev_char == NULL)
4216 dump_is_corrupt(&ga_text);
4217 else
4218 {
4219 int count = 0;
4220
4221 /* repeat previous character, get the count */
4222 for (;;)
4223 {
4224 c = fgetc(fd);
4225 if (!isdigit(c))
4226 break;
4227 count = count * 10 + (c - '0');
4228 }
4229
4230 while (count-- > 0)
4231 {
4232 ga_concat(&ga_text, prev_char);
4233 append_cell(&ga_cell, &cell);
4234 }
4235 }
4236 }
4237 else
4238 {
4239 dump_is_corrupt(&ga_text);
4240 c = fgetc(fd);
4241 }
4242 }
4243
4244 if (ga_text.ga_len > 0)
4245 {
4246 /* trailing characters after last NL */
4247 dump_is_corrupt(&ga_text);
4248 ga_append(&ga_text, NUL);
4249 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4250 ga_text.ga_len, FALSE);
4251 }
4252
4253 ga_clear(&ga_text);
4254 vim_free(prev_char);
4255
4256 return max_cells;
4257}
4258
4259/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004260 * Return an allocated string with at least "text_width" "=" characters and
4261 * "fname" inserted in the middle.
4262 */
4263 static char_u *
4264get_separator(int text_width, char_u *fname)
4265{
4266 int width = MAX(text_width, curwin->w_width);
4267 char_u *textline;
4268 int fname_size;
4269 char_u *p = fname;
4270 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004271 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004272
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004273 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004274 if (textline == NULL)
4275 return NULL;
4276
4277 fname_size = vim_strsize(fname);
4278 if (fname_size < width - 8)
4279 {
4280 /* enough room, don't use the full window width */
4281 width = MAX(text_width, fname_size + 8);
4282 }
4283 else if (fname_size > width - 8)
4284 {
4285 /* full name doesn't fit, use only the tail */
4286 p = gettail(fname);
4287 fname_size = vim_strsize(p);
4288 }
4289 /* skip characters until the name fits */
4290 while (fname_size > width - 8)
4291 {
4292 p += (*mb_ptr2len)(p);
4293 fname_size = vim_strsize(p);
4294 }
4295
4296 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4297 textline[i] = '=';
4298 textline[i++] = ' ';
4299
4300 STRCPY(textline + i, p);
4301 off = STRLEN(textline);
4302 textline[off] = ' ';
4303 for (i = 1; i < (width - fname_size) / 2; ++i)
4304 textline[off + i] = '=';
4305 textline[off + i] = NUL;
4306
4307 return textline;
4308}
4309
4310/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004311 * Common for "term_dumpdiff()" and "term_dumpload()".
4312 */
4313 static void
4314term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4315{
4316 jobopt_T opt;
4317 buf_T *buf;
4318 char_u buf1[NUMBUFLEN];
4319 char_u buf2[NUMBUFLEN];
4320 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004321 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004322 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004323 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004324 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004325 char_u *textline = NULL;
4326
4327 /* First open the files. If this fails bail out. */
4328 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4329 if (do_diff)
4330 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4331 if (fname1 == NULL || (do_diff && fname2 == NULL))
4332 {
4333 EMSG(_(e_invarg));
4334 return;
4335 }
4336 fd1 = mch_fopen((char *)fname1, READBIN);
4337 if (fd1 == NULL)
4338 {
4339 EMSG2(_(e_notread), fname1);
4340 return;
4341 }
4342 if (do_diff)
4343 {
4344 fd2 = mch_fopen((char *)fname2, READBIN);
4345 if (fd2 == NULL)
4346 {
4347 fclose(fd1);
4348 EMSG2(_(e_notread), fname2);
4349 return;
4350 }
4351 }
4352
4353 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004354 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4355 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4356 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4357 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4358 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004359
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004360 if (opt.jo_term_name == NULL)
4361 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004362 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004363
Bram Moolenaarb571c632018-03-21 22:27:59 +01004364 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004365 if (fname_tofree != NULL)
4366 {
4367 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4368 opt.jo_term_name = fname_tofree;
4369 }
4370 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004371
Bram Moolenaar13568252018-03-16 20:46:58 +01004372 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004373 if (buf != NULL && buf->b_term != NULL)
4374 {
4375 int i;
4376 linenr_T bot_lnum;
4377 linenr_T lnum;
4378 term_T *term = buf->b_term;
4379 int width;
4380 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004381 VTermPos cursor_pos1;
4382 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004383
Bram Moolenaar52acb112018-03-18 19:20:22 +01004384 init_default_colors(term);
4385
Bram Moolenaard96ff162018-02-18 22:13:29 +01004386 rettv->vval.v_number = buf->b_fnum;
4387
4388 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004389 width = read_dump_file(fd1, &cursor_pos1);
4390
4391 /* position the cursor */
4392 if (cursor_pos1.row >= 0)
4393 {
4394 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4395 coladvance(cursor_pos1.col);
4396 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004397
4398 /* Delete the empty line that was in the empty buffer. */
4399 ml_delete(1, FALSE);
4400
4401 /* For term_dumpload() we are done here. */
4402 if (!do_diff)
4403 goto theend;
4404
4405 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4406
Bram Moolenaar4a696342018-04-05 18:45:26 +02004407 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004408 if (textline == NULL)
4409 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004410 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4411 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4412 vim_free(textline);
4413
4414 textline = get_separator(width, fname2);
4415 if (textline == NULL)
4416 goto theend;
4417 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4418 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004419 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004420
4421 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004422 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004423 if (width2 > width)
4424 {
4425 vim_free(textline);
4426 textline = alloc(width2 + 1);
4427 if (textline == NULL)
4428 goto theend;
4429 width = width2;
4430 textline[width] = NUL;
4431 }
4432 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4433
4434 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4435 {
4436 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4437 {
4438 /* bottom part has fewer rows, fill with "-" */
4439 for (i = 0; i < width; ++i)
4440 textline[i] = '-';
4441 }
4442 else
4443 {
4444 char_u *line1;
4445 char_u *line2;
4446 char_u *p1;
4447 char_u *p2;
4448 int col;
4449 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4450 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4451 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4452 ->sb_cells;
4453
4454 /* Make a copy, getting the second line will invalidate it. */
4455 line1 = vim_strsave(ml_get(lnum));
4456 if (line1 == NULL)
4457 break;
4458 p1 = line1;
4459
4460 line2 = ml_get(lnum + bot_lnum);
4461 p2 = line2;
4462 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4463 {
4464 int len1 = utfc_ptr2len(p1);
4465 int len2 = utfc_ptr2len(p2);
4466
4467 textline[col] = ' ';
4468 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004469 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004470 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004471 else if (lnum == cursor_pos1.row + 1
4472 && col == cursor_pos1.col
4473 && (cursor_pos1.row != cursor_pos2.row
4474 || cursor_pos1.col != cursor_pos2.col))
4475 /* cursor in first but not in second */
4476 textline[col] = '>';
4477 else if (lnum == cursor_pos2.row + 1
4478 && col == cursor_pos2.col
4479 && (cursor_pos1.row != cursor_pos2.row
4480 || cursor_pos1.col != cursor_pos2.col))
4481 /* cursor in second but not in first */
4482 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004483 else if (cellattr1 != NULL && cellattr2 != NULL)
4484 {
4485 if ((cellattr1 + col)->width
4486 != (cellattr2 + col)->width)
4487 textline[col] = 'w';
4488 else if (!same_color(&(cellattr1 + col)->fg,
4489 &(cellattr2 + col)->fg))
4490 textline[col] = 'f';
4491 else if (!same_color(&(cellattr1 + col)->bg,
4492 &(cellattr2 + col)->bg))
4493 textline[col] = 'b';
4494 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4495 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4496 textline[col] = 'a';
4497 }
4498 p1 += len1;
4499 p2 += len2;
4500 /* TODO: handle different width */
4501 }
4502 vim_free(line1);
4503
4504 while (col < width)
4505 {
4506 if (*p1 == NUL && *p2 == NUL)
4507 textline[col] = '?';
4508 else if (*p1 == NUL)
4509 {
4510 textline[col] = '+';
4511 p2 += utfc_ptr2len(p2);
4512 }
4513 else
4514 {
4515 textline[col] = '-';
4516 p1 += utfc_ptr2len(p1);
4517 }
4518 ++col;
4519 }
4520 }
4521 if (add_empty_scrollback(term, &term->tl_default_color,
4522 term->tl_top_diff_rows) == OK)
4523 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4524 ++bot_lnum;
4525 }
4526
4527 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4528 {
4529 /* bottom part has more rows, fill with "+" */
4530 for (i = 0; i < width; ++i)
4531 textline[i] = '+';
4532 if (add_empty_scrollback(term, &term->tl_default_color,
4533 term->tl_top_diff_rows) == OK)
4534 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4535 ++lnum;
4536 ++bot_lnum;
4537 }
4538
4539 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004540
4541 /* looks better without wrapping */
4542 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004543 }
4544
4545theend:
4546 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004547 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004548 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004549 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004550 fclose(fd2);
4551}
4552
4553/*
4554 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4555 * bottom files.
4556 * Return FAIL when this is not possible.
4557 */
4558 int
4559term_swap_diff()
4560{
4561 term_T *term = curbuf->b_term;
4562 linenr_T line_count;
4563 linenr_T top_rows;
4564 linenr_T bot_rows;
4565 linenr_T bot_start;
4566 linenr_T lnum;
4567 char_u *p;
4568 sb_line_T *sb_line;
4569
4570 if (term == NULL
4571 || !term_is_finished(curbuf)
4572 || term->tl_top_diff_rows == 0
4573 || term->tl_scrollback.ga_len == 0)
4574 return FAIL;
4575
4576 line_count = curbuf->b_ml.ml_line_count;
4577 top_rows = term->tl_top_diff_rows;
4578 bot_rows = term->tl_bot_diff_rows;
4579 bot_start = line_count - bot_rows;
4580 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4581
4582 /* move lines from top to above the bottom part */
4583 for (lnum = 1; lnum <= top_rows; ++lnum)
4584 {
4585 p = vim_strsave(ml_get(1));
4586 if (p == NULL)
4587 return OK;
4588 ml_append(bot_start, p, 0, FALSE);
4589 ml_delete(1, FALSE);
4590 vim_free(p);
4591 }
4592
4593 /* move lines from bottom to the top */
4594 for (lnum = 1; lnum <= bot_rows; ++lnum)
4595 {
4596 p = vim_strsave(ml_get(bot_start + lnum));
4597 if (p == NULL)
4598 return OK;
4599 ml_delete(bot_start + lnum, FALSE);
4600 ml_append(lnum - 1, p, 0, FALSE);
4601 vim_free(p);
4602 }
4603
4604 if (top_rows == bot_rows)
4605 {
4606 /* rows counts are equal, can swap cell properties */
4607 for (lnum = 0; lnum < top_rows; ++lnum)
4608 {
4609 sb_line_T temp;
4610
4611 temp = *(sb_line + lnum);
4612 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4613 *(sb_line + bot_start + lnum) = temp;
4614 }
4615 }
4616 else
4617 {
4618 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4619 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4620
4621 /* need to copy cell properties into temp memory */
4622 if (temp != NULL)
4623 {
4624 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4625 mch_memmove(term->tl_scrollback.ga_data,
4626 temp + bot_start,
4627 sizeof(sb_line_T) * bot_rows);
4628 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4629 temp + top_rows,
4630 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4631 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4632 + line_count - top_rows,
4633 temp,
4634 sizeof(sb_line_T) * top_rows);
4635 vim_free(temp);
4636 }
4637 }
4638
4639 term->tl_top_diff_rows = bot_rows;
4640 term->tl_bot_diff_rows = top_rows;
4641
4642 update_screen(NOT_VALID);
4643 return OK;
4644}
4645
4646/*
4647 * "term_dumpdiff(filename, filename, options)" function
4648 */
4649 void
4650f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4651{
4652 term_load_dump(argvars, rettv, TRUE);
4653}
4654
4655/*
4656 * "term_dumpload(filename, options)" function
4657 */
4658 void
4659f_term_dumpload(typval_T *argvars, typval_T *rettv)
4660{
4661 term_load_dump(argvars, rettv, FALSE);
4662}
4663
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004664/*
4665 * "term_getaltscreen(buf)" function
4666 */
4667 void
4668f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4669{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004670 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004671
4672 if (buf == NULL)
4673 return;
4674 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4675}
4676
4677/*
4678 * "term_getattr(attr, name)" function
4679 */
4680 void
4681f_term_getattr(typval_T *argvars, typval_T *rettv)
4682{
4683 int attr;
4684 size_t i;
4685 char_u *name;
4686
4687 static struct {
4688 char *name;
4689 int attr;
4690 } attrs[] = {
4691 {"bold", HL_BOLD},
4692 {"italic", HL_ITALIC},
4693 {"underline", HL_UNDERLINE},
4694 {"strike", HL_STRIKETHROUGH},
4695 {"reverse", HL_INVERSE},
4696 };
4697
4698 attr = get_tv_number(&argvars[0]);
4699 name = get_tv_string_chk(&argvars[1]);
4700 if (name == NULL)
4701 return;
4702
4703 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4704 if (STRCMP(name, attrs[i].name) == 0)
4705 {
4706 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4707 break;
4708 }
4709}
4710
4711/*
4712 * "term_getcursor(buf)" function
4713 */
4714 void
4715f_term_getcursor(typval_T *argvars, typval_T *rettv)
4716{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004717 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004718 term_T *term;
4719 list_T *l;
4720 dict_T *d;
4721
4722 if (rettv_list_alloc(rettv) == FAIL)
4723 return;
4724 if (buf == NULL)
4725 return;
4726 term = buf->b_term;
4727
4728 l = rettv->vval.v_list;
4729 list_append_number(l, term->tl_cursor_pos.row + 1);
4730 list_append_number(l, term->tl_cursor_pos.col + 1);
4731
4732 d = dict_alloc();
4733 if (d != NULL)
4734 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02004735 dict_add_number(d, "visible", term->tl_cursor_visible);
4736 dict_add_number(d, "blink", blink_state_is_inverted()
4737 ? !term->tl_cursor_blink : term->tl_cursor_blink);
4738 dict_add_number(d, "shape", term->tl_cursor_shape);
4739 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004740 list_append_dict(l, d);
4741 }
4742}
4743
4744/*
4745 * "term_getjob(buf)" function
4746 */
4747 void
4748f_term_getjob(typval_T *argvars, typval_T *rettv)
4749{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004750 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004751
4752 rettv->v_type = VAR_JOB;
4753 rettv->vval.v_job = NULL;
4754 if (buf == NULL)
4755 return;
4756
4757 rettv->vval.v_job = buf->b_term->tl_job;
4758 if (rettv->vval.v_job != NULL)
4759 ++rettv->vval.v_job->jv_refcount;
4760}
4761
4762 static int
4763get_row_number(typval_T *tv, term_T *term)
4764{
4765 if (tv->v_type == VAR_STRING
4766 && tv->vval.v_string != NULL
4767 && STRCMP(tv->vval.v_string, ".") == 0)
4768 return term->tl_cursor_pos.row;
4769 return (int)get_tv_number(tv) - 1;
4770}
4771
4772/*
4773 * "term_getline(buf, row)" function
4774 */
4775 void
4776f_term_getline(typval_T *argvars, typval_T *rettv)
4777{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004778 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004779 term_T *term;
4780 int row;
4781
4782 rettv->v_type = VAR_STRING;
4783 if (buf == NULL)
4784 return;
4785 term = buf->b_term;
4786 row = get_row_number(&argvars[1], term);
4787
4788 if (term->tl_vterm == NULL)
4789 {
4790 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4791
4792 /* vterm is finished, get the text from the buffer */
4793 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4794 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4795 }
4796 else
4797 {
4798 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4799 VTermRect rect;
4800 int len;
4801 char_u *p;
4802
4803 if (row < 0 || row >= term->tl_rows)
4804 return;
4805 len = term->tl_cols * MB_MAXBYTES + 1;
4806 p = alloc(len);
4807 if (p == NULL)
4808 return;
4809 rettv->vval.v_string = p;
4810
4811 rect.start_col = 0;
4812 rect.end_col = term->tl_cols;
4813 rect.start_row = row;
4814 rect.end_row = row + 1;
4815 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4816 }
4817}
4818
4819/*
4820 * "term_getscrolled(buf)" function
4821 */
4822 void
4823f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4824{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004825 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004826
4827 if (buf == NULL)
4828 return;
4829 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4830}
4831
4832/*
4833 * "term_getsize(buf)" function
4834 */
4835 void
4836f_term_getsize(typval_T *argvars, typval_T *rettv)
4837{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004838 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004839 list_T *l;
4840
4841 if (rettv_list_alloc(rettv) == FAIL)
4842 return;
4843 if (buf == NULL)
4844 return;
4845
4846 l = rettv->vval.v_list;
4847 list_append_number(l, buf->b_term->tl_rows);
4848 list_append_number(l, buf->b_term->tl_cols);
4849}
4850
4851/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004852 * "term_setsize(buf, rows, cols)" function
4853 */
4854 void
4855f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4856{
4857 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4858 term_T *term;
4859 varnumber_T rows, cols;
4860
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004861 if (buf == NULL)
4862 {
4863 EMSG(_("E955: Not a terminal buffer"));
4864 return;
4865 }
4866 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004867 return;
4868 term = buf->b_term;
4869 rows = get_tv_number(&argvars[1]);
4870 rows = rows <= 0 ? term->tl_rows : rows;
4871 cols = get_tv_number(&argvars[2]);
4872 cols = cols <= 0 ? term->tl_cols : cols;
4873 vterm_set_size(term->tl_vterm, rows, cols);
4874 /* handle_resize() will resize the windows */
4875
4876 /* Get and remember the size we ended up with. Update the pty. */
4877 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4878 term_report_winsize(term, term->tl_rows, term->tl_cols);
4879}
4880
4881/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004882 * "term_getstatus(buf)" function
4883 */
4884 void
4885f_term_getstatus(typval_T *argvars, typval_T *rettv)
4886{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004887 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004888 term_T *term;
4889 char_u val[100];
4890
4891 rettv->v_type = VAR_STRING;
4892 if (buf == NULL)
4893 return;
4894 term = buf->b_term;
4895
4896 if (term_job_running(term))
4897 STRCPY(val, "running");
4898 else
4899 STRCPY(val, "finished");
4900 if (term->tl_normal_mode)
4901 STRCAT(val, ",normal");
4902 rettv->vval.v_string = vim_strsave(val);
4903}
4904
4905/*
4906 * "term_gettitle(buf)" function
4907 */
4908 void
4909f_term_gettitle(typval_T *argvars, typval_T *rettv)
4910{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004911 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004912
4913 rettv->v_type = VAR_STRING;
4914 if (buf == NULL)
4915 return;
4916
4917 if (buf->b_term->tl_title != NULL)
4918 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4919}
4920
4921/*
4922 * "term_gettty(buf)" function
4923 */
4924 void
4925f_term_gettty(typval_T *argvars, typval_T *rettv)
4926{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004927 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02004928 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004929 int num = 0;
4930
4931 rettv->v_type = VAR_STRING;
4932 if (buf == NULL)
4933 return;
4934 if (argvars[1].v_type != VAR_UNKNOWN)
4935 num = get_tv_number(&argvars[1]);
4936
4937 switch (num)
4938 {
4939 case 0:
4940 if (buf->b_term->tl_job != NULL)
4941 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004942 break;
4943 case 1:
4944 if (buf->b_term->tl_job != NULL)
4945 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004946 break;
4947 default:
4948 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4949 return;
4950 }
4951 if (p != NULL)
4952 rettv->vval.v_string = vim_strsave(p);
4953}
4954
4955/*
4956 * "term_list()" function
4957 */
4958 void
4959f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4960{
4961 term_T *tp;
4962 list_T *l;
4963
4964 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4965 return;
4966
4967 l = rettv->vval.v_list;
4968 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4969 if (tp != NULL && tp->tl_buffer != NULL)
4970 if (list_append_number(l,
4971 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4972 return;
4973}
4974
4975/*
4976 * "term_scrape(buf, row)" function
4977 */
4978 void
4979f_term_scrape(typval_T *argvars, typval_T *rettv)
4980{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004981 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004982 VTermScreen *screen = NULL;
4983 VTermPos pos;
4984 list_T *l;
4985 term_T *term;
4986 char_u *p;
4987 sb_line_T *line;
4988
4989 if (rettv_list_alloc(rettv) == FAIL)
4990 return;
4991 if (buf == NULL)
4992 return;
4993 term = buf->b_term;
4994
4995 l = rettv->vval.v_list;
4996 pos.row = get_row_number(&argvars[1], term);
4997
4998 if (term->tl_vterm != NULL)
4999 {
5000 screen = vterm_obtain_screen(term->tl_vterm);
5001 p = NULL;
5002 line = NULL;
5003 }
5004 else
5005 {
5006 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5007
5008 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5009 return;
5010 p = ml_get_buf(buf, lnum + 1, FALSE);
5011 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5012 }
5013
5014 for (pos.col = 0; pos.col < term->tl_cols; )
5015 {
5016 dict_T *dcell;
5017 int width;
5018 VTermScreenCellAttrs attrs;
5019 VTermColor fg, bg;
5020 char_u rgb[8];
5021 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5022 int off = 0;
5023 int i;
5024
5025 if (screen == NULL)
5026 {
5027 cellattr_T *cellattr;
5028 int len;
5029
5030 /* vterm has finished, get the cell from scrollback */
5031 if (pos.col >= line->sb_cols)
5032 break;
5033 cellattr = line->sb_cells + pos.col;
5034 width = cellattr->width;
5035 attrs = cellattr->attrs;
5036 fg = cellattr->fg;
5037 bg = cellattr->bg;
5038 len = MB_PTR2LEN(p);
5039 mch_memmove(mbs, p, len);
5040 mbs[len] = NUL;
5041 p += len;
5042 }
5043 else
5044 {
5045 VTermScreenCell cell;
5046 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5047 break;
5048 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5049 {
5050 if (cell.chars[i] == 0)
5051 break;
5052 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5053 }
5054 mbs[off] = NUL;
5055 width = cell.width;
5056 attrs = cell.attrs;
5057 fg = cell.fg;
5058 bg = cell.bg;
5059 }
5060 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005061 if (dcell == NULL)
5062 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005063 list_append_dict(l, dcell);
5064
Bram Moolenaare0be1672018-07-08 16:50:37 +02005065 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005066
5067 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5068 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005069 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005070 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5071 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005072 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005073
Bram Moolenaare0be1672018-07-08 16:50:37 +02005074 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5075 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005076
5077 ++pos.col;
5078 if (width == 2)
5079 ++pos.col;
5080 }
5081}
5082
5083/*
5084 * "term_sendkeys(buf, keys)" function
5085 */
5086 void
5087f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5088{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005089 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005090 char_u *msg;
5091 term_T *term;
5092
5093 rettv->v_type = VAR_UNKNOWN;
5094 if (buf == NULL)
5095 return;
5096
5097 msg = get_tv_string_chk(&argvars[1]);
5098 if (msg == NULL)
5099 return;
5100 term = buf->b_term;
5101 if (term->tl_vterm == NULL)
5102 return;
5103
5104 while (*msg != NUL)
5105 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005106 int c;
5107
5108 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5109 {
5110 c = TO_SPECIAL(msg[1], msg[2]);
5111 msg += 3;
5112 }
5113 else
5114 {
5115 c = PTR2CHAR(msg);
5116 msg += MB_CPTR2LEN(msg);
5117 }
5118 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005119 }
5120}
5121
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005122#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5123/*
5124 * "term_getansicolors(buf)" function
5125 */
5126 void
5127f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5128{
5129 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5130 term_T *term;
5131 VTermState *state;
5132 VTermColor color;
5133 char_u hexbuf[10];
5134 int index;
5135 list_T *list;
5136
5137 if (rettv_list_alloc(rettv) == FAIL)
5138 return;
5139
5140 if (buf == NULL)
5141 return;
5142 term = buf->b_term;
5143 if (term->tl_vterm == NULL)
5144 return;
5145
5146 list = rettv->vval.v_list;
5147 state = vterm_obtain_state(term->tl_vterm);
5148 for (index = 0; index < 16; index++)
5149 {
5150 vterm_state_get_palette_color(state, index, &color);
5151 sprintf((char *)hexbuf, "#%02x%02x%02x",
5152 color.red, color.green, color.blue);
5153 if (list_append_string(list, hexbuf, 7) == FAIL)
5154 return;
5155 }
5156}
5157
5158/*
5159 * "term_setansicolors(buf, list)" function
5160 */
5161 void
5162f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5163{
5164 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5165 term_T *term;
5166
5167 if (buf == NULL)
5168 return;
5169 term = buf->b_term;
5170 if (term->tl_vterm == NULL)
5171 return;
5172
5173 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5174 {
5175 EMSG(_(e_listreq));
5176 return;
5177 }
5178
5179 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
5180 EMSG(_(e_invarg));
5181}
5182#endif
5183
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005184/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005185 * "term_setrestore(buf, command)" function
5186 */
5187 void
5188f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5189{
5190#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005191 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005192 term_T *term;
5193 char_u *cmd;
5194
5195 if (buf == NULL)
5196 return;
5197 term = buf->b_term;
5198 vim_free(term->tl_command);
5199 cmd = get_tv_string_chk(&argvars[1]);
5200 if (cmd != NULL)
5201 term->tl_command = vim_strsave(cmd);
5202 else
5203 term->tl_command = NULL;
5204#endif
5205}
5206
5207/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005208 * "term_setkill(buf, how)" function
5209 */
5210 void
5211f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5212{
5213 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5214 term_T *term;
5215 char_u *how;
5216
5217 if (buf == NULL)
5218 return;
5219 term = buf->b_term;
5220 vim_free(term->tl_kill);
5221 how = get_tv_string_chk(&argvars[1]);
5222 if (how != NULL)
5223 term->tl_kill = vim_strsave(how);
5224 else
5225 term->tl_kill = NULL;
5226}
5227
5228/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005229 * "term_start(command, options)" function
5230 */
5231 void
5232f_term_start(typval_T *argvars, typval_T *rettv)
5233{
5234 jobopt_T opt;
5235 buf_T *buf;
5236
5237 init_job_options(&opt);
5238 if (argvars[1].v_type != VAR_UNKNOWN
5239 && get_job_options(&argvars[1], &opt,
5240 JO_TIMEOUT_ALL + JO_STOPONEXIT
5241 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5242 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5243 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5244 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005245 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005246 + JO2_NORESTORE + JO2_TERM_KILL
5247 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005248 return;
5249
Bram Moolenaar13568252018-03-16 20:46:58 +01005250 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005251
5252 if (buf != NULL && buf->b_term != NULL)
5253 rettv->vval.v_number = buf->b_fnum;
5254}
5255
5256/*
5257 * "term_wait" function
5258 */
5259 void
5260f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5261{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005262 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005263
5264 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005265 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005266 if (buf->b_term->tl_job == NULL)
5267 {
5268 ch_log(NULL, "term_wait(): no job to wait for");
5269 return;
5270 }
5271 if (buf->b_term->tl_job->jv_channel == NULL)
5272 /* channel is closed, nothing to do */
5273 return;
5274
5275 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005276 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005277 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5278 {
5279 /* The job is dead, keep reading channel I/O until the channel is
5280 * closed. buf->b_term may become NULL if the terminal was closed while
5281 * waiting. */
5282 ch_log(NULL, "term_wait(): waiting for channel to close");
5283 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5284 {
5285 mch_check_messages();
5286 parse_queued_messages();
Bram Moolenaard45aa552018-05-21 22:50:29 +02005287 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005288 if (!buf_valid(buf))
5289 /* If the terminal is closed when the channel is closed the
5290 * buffer disappears. */
5291 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005292 }
5293 mch_check_messages();
5294 parse_queued_messages();
5295 }
5296 else
5297 {
5298 long wait = 10L;
5299
5300 mch_check_messages();
5301 parse_queued_messages();
5302
5303 /* Wait for some time for any channel I/O. */
5304 if (argvars[1].v_type != VAR_UNKNOWN)
5305 wait = get_tv_number(&argvars[1]);
5306 ui_delay(wait, TRUE);
5307 mch_check_messages();
5308
5309 /* Flushing messages on channels is hopefully sufficient.
5310 * TODO: is there a better way? */
5311 parse_queued_messages();
5312 }
5313}
5314
5315/*
5316 * Called when a channel has sent all the lines to a terminal.
5317 * Send a CTRL-D to mark the end of the text.
5318 */
5319 void
5320term_send_eof(channel_T *ch)
5321{
5322 term_T *term;
5323
5324 for (term = first_term; term != NULL; term = term->tl_next)
5325 if (term->tl_job == ch->ch_job)
5326 {
5327 if (term->tl_eof_chars != NULL)
5328 {
5329 channel_send(ch, PART_IN, term->tl_eof_chars,
5330 (int)STRLEN(term->tl_eof_chars), NULL);
5331 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5332 }
5333# ifdef WIN3264
5334 else
5335 /* Default: CTRL-D */
5336 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5337# endif
5338 }
5339}
5340
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005341 job_T *
5342term_getjob(term_T *term)
5343{
5344 return term != NULL ? term->tl_job : NULL;
5345}
5346
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005347# if defined(WIN3264) || defined(PROTO)
5348
5349/**************************************
5350 * 2. MS-Windows implementation.
5351 */
5352
5353# ifndef PROTO
5354
5355#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5356#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005357#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005358
5359void* (*winpty_config_new)(UINT64, void*);
5360void* (*winpty_open)(void*, void*);
5361void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5362BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5363void (*winpty_config_set_mouse_mode)(void*, int);
5364void (*winpty_config_set_initial_size)(void*, int, int);
5365LPCWSTR (*winpty_conin_name)(void*);
5366LPCWSTR (*winpty_conout_name)(void*);
5367LPCWSTR (*winpty_conerr_name)(void*);
5368void (*winpty_free)(void*);
5369void (*winpty_config_free)(void*);
5370void (*winpty_spawn_config_free)(void*);
5371void (*winpty_error_free)(void*);
5372LPCWSTR (*winpty_error_msg)(void*);
5373BOOL (*winpty_set_size)(void*, int, int, void*);
5374HANDLE (*winpty_agent_process)(void*);
5375
5376#define WINPTY_DLL "winpty.dll"
5377
5378static HINSTANCE hWinPtyDLL = NULL;
5379# endif
5380
5381 static int
5382dyn_winpty_init(int verbose)
5383{
5384 int i;
5385 static struct
5386 {
5387 char *name;
5388 FARPROC *ptr;
5389 } winpty_entry[] =
5390 {
5391 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5392 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5393 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5394 {"winpty_config_set_mouse_mode",
5395 (FARPROC*)&winpty_config_set_mouse_mode},
5396 {"winpty_config_set_initial_size",
5397 (FARPROC*)&winpty_config_set_initial_size},
5398 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5399 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5400 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5401 {"winpty_free", (FARPROC*)&winpty_free},
5402 {"winpty_open", (FARPROC*)&winpty_open},
5403 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5404 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5405 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5406 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5407 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5408 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5409 {NULL, NULL}
5410 };
5411
5412 /* No need to initialize twice. */
5413 if (hWinPtyDLL)
5414 return OK;
5415 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5416 * winpty.dll. */
5417 if (*p_winptydll != NUL)
5418 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5419 if (!hWinPtyDLL)
5420 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5421 if (!hWinPtyDLL)
5422 {
5423 if (verbose)
5424 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5425 : (char_u *)WINPTY_DLL);
5426 return FAIL;
5427 }
5428 for (i = 0; winpty_entry[i].name != NULL
5429 && winpty_entry[i].ptr != NULL; ++i)
5430 {
5431 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5432 winpty_entry[i].name)) == NULL)
5433 {
5434 if (verbose)
5435 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5436 return FAIL;
5437 }
5438 }
5439
5440 return OK;
5441}
5442
5443/*
5444 * Create a new terminal of "rows" by "cols" cells.
5445 * Store a reference in "term".
5446 * Return OK or FAIL.
5447 */
5448 static int
5449term_and_job_init(
5450 term_T *term,
5451 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005452 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005453 jobopt_T *opt,
5454 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005455{
5456 WCHAR *cmd_wchar = NULL;
5457 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005458 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005459 channel_T *channel = NULL;
5460 job_T *job = NULL;
5461 DWORD error;
5462 HANDLE jo = NULL;
5463 HANDLE child_process_handle;
5464 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005465 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005466 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005467 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005468 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005469
5470 if (dyn_winpty_init(TRUE) == FAIL)
5471 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005472 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5473 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005474
5475 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005476 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005477 cmd = argvar->vval.v_string;
5478 }
5479 else if (argvar->v_type == VAR_LIST)
5480 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005481 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005482 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005483 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005484 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005485 if (cmd == NULL || *cmd == NUL)
5486 {
5487 EMSG(_(e_invarg));
5488 goto failed;
5489 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005490
5491 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005492 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005493 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005494 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005495 if (opt->jo_cwd != NULL)
5496 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005497
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005498 win32_build_env(opt->jo_env, &ga_env, TRUE);
5499 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005500
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005501 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5502 if (term->tl_winpty_config == NULL)
5503 goto failed;
5504
5505 winpty_config_set_mouse_mode(term->tl_winpty_config,
5506 WINPTY_MOUSE_MODE_FORCE);
5507 winpty_config_set_initial_size(term->tl_winpty_config,
5508 term->tl_cols, term->tl_rows);
5509 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5510 if (term->tl_winpty == NULL)
5511 goto failed;
5512
5513 spawn_config = winpty_spawn_config_new(
5514 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5515 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5516 NULL,
5517 cmd_wchar,
5518 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005519 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005520 &winpty_err);
5521 if (spawn_config == NULL)
5522 goto failed;
5523
5524 channel = add_channel();
5525 if (channel == NULL)
5526 goto failed;
5527
5528 job = job_alloc();
5529 if (job == NULL)
5530 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005531 if (argvar->v_type == VAR_STRING)
5532 {
5533 int argc;
5534
5535 build_argv_from_string(cmd, &job->jv_argv, &argc);
5536 }
5537 else
5538 {
5539 int argc;
5540
5541 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5542 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005543
5544 if (opt->jo_set & JO_IN_BUF)
5545 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5546
5547 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5548 &child_thread_handle, &error, &winpty_err))
5549 goto failed;
5550
5551 channel_set_pipes(channel,
5552 (sock_T)CreateFileW(
5553 winpty_conin_name(term->tl_winpty),
5554 GENERIC_WRITE, 0, NULL,
5555 OPEN_EXISTING, 0, NULL),
5556 (sock_T)CreateFileW(
5557 winpty_conout_name(term->tl_winpty),
5558 GENERIC_READ, 0, NULL,
5559 OPEN_EXISTING, 0, NULL),
5560 (sock_T)CreateFileW(
5561 winpty_conerr_name(term->tl_winpty),
5562 GENERIC_READ, 0, NULL,
5563 OPEN_EXISTING, 0, NULL));
5564
5565 /* Write lines with CR instead of NL. */
5566 channel->ch_write_text_mode = TRUE;
5567
5568 jo = CreateJobObject(NULL, NULL);
5569 if (jo == NULL)
5570 goto failed;
5571
5572 if (!AssignProcessToJobObject(jo, child_process_handle))
5573 {
5574 /* Failed, switch the way to terminate process with TerminateProcess. */
5575 CloseHandle(jo);
5576 jo = NULL;
5577 }
5578
5579 winpty_spawn_config_free(spawn_config);
5580 vim_free(cmd_wchar);
5581 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005582 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005583
5584 create_vterm(term, term->tl_rows, term->tl_cols);
5585
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005586#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5587 if (opt->jo_set2 & JO2_ANSI_COLORS)
5588 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5589 else
5590 init_vterm_ansi_colors(term->tl_vterm);
5591#endif
5592
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005593 channel_set_job(channel, job, opt);
5594 job_set_options(job, opt);
5595
5596 job->jv_channel = channel;
5597 job->jv_proc_info.hProcess = child_process_handle;
5598 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5599 job->jv_job_object = jo;
5600 job->jv_status = JOB_STARTED;
5601 job->jv_tty_in = utf16_to_enc(
5602 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5603 job->jv_tty_out = utf16_to_enc(
5604 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5605 ++job->jv_refcount;
5606 term->tl_job = job;
5607
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005608 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5609 * open the file here and handle it in. opt->jo_io was changed in
5610 * setup_job_options(), use the original flags here. */
5611 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5612 {
5613 char_u *fname = opt->jo_io_name[PART_OUT];
5614
5615 ch_log(channel, "Opening output file %s", fname);
5616 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5617 if (term->tl_out_fd == NULL)
5618 EMSG2(_(e_notopen), fname);
5619 }
5620
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005621 return OK;
5622
5623failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005624 ga_clear(&ga_cmd);
5625 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005626 vim_free(cmd_wchar);
5627 vim_free(cwd_wchar);
5628 if (spawn_config != NULL)
5629 winpty_spawn_config_free(spawn_config);
5630 if (channel != NULL)
5631 channel_clear(channel);
5632 if (job != NULL)
5633 {
5634 job->jv_channel = NULL;
5635 job_cleanup(job);
5636 }
5637 term->tl_job = NULL;
5638 if (jo != NULL)
5639 CloseHandle(jo);
5640 if (term->tl_winpty != NULL)
5641 winpty_free(term->tl_winpty);
5642 term->tl_winpty = NULL;
5643 if (term->tl_winpty_config != NULL)
5644 winpty_config_free(term->tl_winpty_config);
5645 term->tl_winpty_config = NULL;
5646 if (winpty_err != NULL)
5647 {
5648 char_u *msg = utf16_to_enc(
5649 (short_u *)winpty_error_msg(winpty_err), NULL);
5650
5651 EMSG(msg);
5652 winpty_error_free(winpty_err);
5653 }
5654 return FAIL;
5655}
5656
5657 static int
5658create_pty_only(term_T *term, jobopt_T *options)
5659{
5660 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5661 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5662 char in_name[80], out_name[80];
5663 channel_T *channel = NULL;
5664
5665 create_vterm(term, term->tl_rows, term->tl_cols);
5666
5667 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5668 GetCurrentProcessId(),
5669 curbuf->b_fnum);
5670 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5671 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5672 PIPE_UNLIMITED_INSTANCES,
5673 0, 0, NMPWAIT_NOWAIT, NULL);
5674 if (hPipeIn == INVALID_HANDLE_VALUE)
5675 goto failed;
5676
5677 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5678 GetCurrentProcessId(),
5679 curbuf->b_fnum);
5680 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5681 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5682 PIPE_UNLIMITED_INSTANCES,
5683 0, 0, 0, NULL);
5684 if (hPipeOut == INVALID_HANDLE_VALUE)
5685 goto failed;
5686
5687 ConnectNamedPipe(hPipeIn, NULL);
5688 ConnectNamedPipe(hPipeOut, NULL);
5689
5690 term->tl_job = job_alloc();
5691 if (term->tl_job == NULL)
5692 goto failed;
5693 ++term->tl_job->jv_refcount;
5694
5695 /* behave like the job is already finished */
5696 term->tl_job->jv_status = JOB_FINISHED;
5697
5698 channel = add_channel();
5699 if (channel == NULL)
5700 goto failed;
5701 term->tl_job->jv_channel = channel;
5702 channel->ch_keep_open = TRUE;
5703 channel->ch_named_pipe = TRUE;
5704
5705 channel_set_pipes(channel,
5706 (sock_T)hPipeIn,
5707 (sock_T)hPipeOut,
5708 (sock_T)hPipeOut);
5709 channel_set_job(channel, term->tl_job, options);
5710 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5711 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5712
5713 return OK;
5714
5715failed:
5716 if (hPipeIn != NULL)
5717 CloseHandle(hPipeIn);
5718 if (hPipeOut != NULL)
5719 CloseHandle(hPipeOut);
5720 return FAIL;
5721}
5722
5723/*
5724 * Free the terminal emulator part of "term".
5725 */
5726 static void
5727term_free_vterm(term_T *term)
5728{
5729 if (term->tl_winpty != NULL)
5730 winpty_free(term->tl_winpty);
5731 term->tl_winpty = NULL;
5732 if (term->tl_winpty_config != NULL)
5733 winpty_config_free(term->tl_winpty_config);
5734 term->tl_winpty_config = NULL;
5735 if (term->tl_vterm != NULL)
5736 vterm_free(term->tl_vterm);
5737 term->tl_vterm = NULL;
5738}
5739
5740/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005741 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005742 */
5743 static void
5744term_report_winsize(term_T *term, int rows, int cols)
5745{
5746 if (term->tl_winpty)
5747 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5748}
5749
5750 int
5751terminal_enabled(void)
5752{
5753 return dyn_winpty_init(FALSE) == OK;
5754}
5755
5756# else
5757
5758/**************************************
5759 * 3. Unix-like implementation.
5760 */
5761
5762/*
5763 * Create a new terminal of "rows" by "cols" cells.
5764 * Start job for "cmd".
5765 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005766 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005767 * Return OK or FAIL.
5768 */
5769 static int
5770term_and_job_init(
5771 term_T *term,
5772 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005773 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005774 jobopt_T *opt,
5775 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005776{
5777 create_vterm(term, term->tl_rows, term->tl_cols);
5778
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005779#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5780 if (opt->jo_set2 & JO2_ANSI_COLORS)
5781 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5782 else
5783 init_vterm_ansi_colors(term->tl_vterm);
5784#endif
5785
Bram Moolenaar13568252018-03-16 20:46:58 +01005786 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02005787 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005788 if (term->tl_job != NULL)
5789 ++term->tl_job->jv_refcount;
5790
5791 return term->tl_job != NULL
5792 && term->tl_job->jv_channel != NULL
5793 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5794}
5795
5796 static int
5797create_pty_only(term_T *term, jobopt_T *opt)
5798{
5799 create_vterm(term, term->tl_rows, term->tl_cols);
5800
5801 term->tl_job = job_alloc();
5802 if (term->tl_job == NULL)
5803 return FAIL;
5804 ++term->tl_job->jv_refcount;
5805
5806 /* behave like the job is already finished */
5807 term->tl_job->jv_status = JOB_FINISHED;
5808
5809 return mch_create_pty_channel(term->tl_job, opt);
5810}
5811
5812/*
5813 * Free the terminal emulator part of "term".
5814 */
5815 static void
5816term_free_vterm(term_T *term)
5817{
5818 if (term->tl_vterm != NULL)
5819 vterm_free(term->tl_vterm);
5820 term->tl_vterm = NULL;
5821}
5822
5823/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005824 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005825 */
5826 static void
5827term_report_winsize(term_T *term, int rows, int cols)
5828{
5829 /* Use an ioctl() to report the new window size to the job. */
5830 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5831 {
5832 int fd = -1;
5833 int part;
5834
5835 for (part = PART_OUT; part < PART_COUNT; ++part)
5836 {
5837 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5838 if (isatty(fd))
5839 break;
5840 }
5841 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5842 mch_signal_job(term->tl_job, (char_u *)"winch");
5843 }
5844}
5845
5846# endif
5847
5848#endif /* FEAT_TERMINAL */