blob: 4e62253d5476ea00db3d88ef313d2677b2bd295c [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);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200532 // Avoid that 'buftype' is reset when this buffer is entered.
533 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200534
535 /* Mark the buffer as not modifiable. It can only be made modifiable after
536 * the job finished. */
537 curbuf->b_p_ma = FALSE;
538
539 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200540#ifdef WIN3264
541 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
542#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200543 setup_job_options(opt, term->tl_rows, term->tl_cols);
544
Bram Moolenaar13568252018-03-16 20:46:58 +0100545 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100546 return curbuf;
547
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100548#if defined(FEAT_SESSION)
549 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100550 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100551 {
552 term->tl_command = vim_strsave((char_u *)"NONE");
553 }
554 else if (argvar->v_type == VAR_STRING)
555 {
556 char_u *cmd = argvar->vval.v_string;
557
558 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
559 term->tl_command = vim_strsave(cmd);
560 }
561 else if (argvar->v_type == VAR_LIST
562 && argvar->vval.v_list != NULL
563 && argvar->vval.v_list->lv_len > 0)
564 {
565 garray_T ga;
566 listitem_T *item;
567
568 ga_init2(&ga, 1, 100);
569 for (item = argvar->vval.v_list->lv_first;
570 item != NULL; item = item->li_next)
571 {
572 char_u *s = get_tv_string_chk(&item->li_tv);
573 char_u *p;
574
575 if (s == NULL)
576 break;
577 p = vim_strsave_fnameescape(s, FALSE);
578 if (p == NULL)
579 break;
580 ga_concat(&ga, p);
581 vim_free(p);
582 ga_append(&ga, ' ');
583 }
584 if (item == NULL)
585 {
586 ga_append(&ga, NUL);
587 term->tl_command = ga.ga_data;
588 }
589 else
590 ga_clear(&ga);
591 }
592#endif
593
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100594 if (opt->jo_term_kill != NULL)
595 {
596 char_u *p = skiptowhite(opt->jo_term_kill);
597
598 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
599 }
600
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200601 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100602 if (argv == NULL
603 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200604 && argvar->vval.v_string != NULL
605 && STRCMP(argvar->vval.v_string, "NONE") == 0)
606 res = create_pty_only(term, opt);
607 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200608 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200609
610 newbuf = curbuf;
611 if (res == OK)
612 {
613 /* Get and remember the size we ended up with. Update the pty. */
614 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
615 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100616#ifdef FEAT_GUI
617 if (term->tl_system)
618 {
619 /* display first line below typed command */
620 term->tl_toprow = msg_row + 1;
621 term->tl_dirty_row_end = 0;
622 }
623#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200624
625 /* Make sure we don't get stuck on sending keys to the job, it leads to
626 * a deadlock if the job is waiting for Vim to read. */
627 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
628
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200629 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200630 {
631 --curbuf->b_nwindows;
632 curbuf = old_curbuf;
633 curwin->w_buffer = curbuf;
634 ++curbuf->b_nwindows;
635 }
636 }
637 else
638 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100639 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200640 return NULL;
641 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100642
Bram Moolenaar13568252018-03-16 20:46:58 +0100643 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200644 return newbuf;
645}
646
647/*
648 * ":terminal": open a terminal window and execute a job in it.
649 */
650 void
651ex_terminal(exarg_T *eap)
652{
653 typval_T argvar[2];
654 jobopt_T opt;
655 char_u *cmd;
656 char_u *tofree = NULL;
657
658 init_job_options(&opt);
659
660 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100661 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200662 {
663 char_u *p, *ep;
664
665 cmd += 2;
666 p = skiptowhite(cmd);
667 ep = vim_strchr(cmd, '=');
668 if (ep != NULL && ep < p)
669 p = ep;
670
671 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
672 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100673 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
674 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200675 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
676 opt.jo_term_finish = 'o';
677 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
678 opt.jo_curwin = 1;
679 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
680 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100681 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
682 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100683 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
684 && ep != NULL)
685 {
686 opt.jo_set2 |= JO2_TERM_KILL;
687 opt.jo_term_kill = ep + 1;
688 p = skiptowhite(cmd);
689 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200690 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
691 && ep != NULL && isdigit(ep[1]))
692 {
693 opt.jo_set2 |= JO2_TERM_ROWS;
694 opt.jo_term_rows = atoi((char *)ep + 1);
695 p = skiptowhite(cmd);
696 }
697 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
698 && ep != NULL && isdigit(ep[1]))
699 {
700 opt.jo_set2 |= JO2_TERM_COLS;
701 opt.jo_term_cols = atoi((char *)ep + 1);
702 p = skiptowhite(cmd);
703 }
704 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
705 && ep != NULL)
706 {
707 char_u *buf = NULL;
708 char_u *keys;
709
710 p = skiptowhite(cmd);
711 *p = NUL;
712 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
713 opt.jo_set2 |= JO2_EOF_CHARS;
714 opt.jo_eof_chars = vim_strsave(keys);
715 vim_free(buf);
716 *p = ' ';
717 }
718 else
719 {
720 if (*p)
721 *p = NUL;
722 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100723 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200724 }
725 cmd = skipwhite(p);
726 }
727 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100728 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200729 /* Make a copy of 'shell', an autocommand may change the option. */
730 tofree = cmd = vim_strsave(p_sh);
731
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100732 /* default to close when the shell exits */
733 if (opt.jo_term_finish == NUL)
734 opt.jo_term_finish = 'c';
735 }
736
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200737 if (eap->addr_count > 0)
738 {
739 /* Write lines from current buffer to the job. */
740 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
741 opt.jo_io[PART_IN] = JIO_BUFFER;
742 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
743 opt.jo_in_top = eap->line1;
744 opt.jo_in_bot = eap->line2;
745 }
746
747 argvar[0].v_type = VAR_STRING;
748 argvar[0].vval.v_string = cmd;
749 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100750 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200751 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100752
753theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200754 vim_free(opt.jo_eof_chars);
755}
756
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100757#if defined(FEAT_SESSION) || defined(PROTO)
758/*
759 * Write a :terminal command to the session file to restore the terminal in
760 * window "wp".
761 * Return FAIL if writing fails.
762 */
763 int
764term_write_session(FILE *fd, win_T *wp)
765{
766 term_T *term = wp->w_buffer->b_term;
767
768 /* Create the terminal and run the command. This is not without
769 * risk, but let's assume the user only creates a session when this
770 * will be OK. */
771 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
772 term->tl_cols, term->tl_rows) < 0)
773 return FAIL;
774 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
775 return FAIL;
776
777 return put_eol(fd);
778}
779
780/*
781 * Return TRUE if "buf" has a terminal that should be restored.
782 */
783 int
784term_should_restore(buf_T *buf)
785{
786 term_T *term = buf->b_term;
787
788 return term != NULL && (term->tl_command == NULL
789 || STRCMP(term->tl_command, "NONE") != 0);
790}
791#endif
792
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200793/*
794 * Free the scrollback buffer for "term".
795 */
796 static void
797free_scrollback(term_T *term)
798{
799 int i;
800
801 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
802 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
803 ga_clear(&term->tl_scrollback);
804}
805
806/*
807 * Free a terminal and everything it refers to.
808 * Kills the job if there is one.
809 * Called when wiping out a buffer.
810 */
811 void
812free_terminal(buf_T *buf)
813{
814 term_T *term = buf->b_term;
815 term_T *tp;
816
817 if (term == NULL)
818 return;
819 if (first_term == term)
820 first_term = term->tl_next;
821 else
822 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
823 if (tp->tl_next == term)
824 {
825 tp->tl_next = term->tl_next;
826 break;
827 }
828
829 if (term->tl_job != NULL)
830 {
831 if (term->tl_job->jv_status != JOB_ENDED
832 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100833 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200834 job_stop(term->tl_job, NULL, "kill");
835 job_unref(term->tl_job);
836 }
837
838 free_scrollback(term);
839
840 term_free_vterm(term);
841 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100842#ifdef FEAT_SESSION
843 vim_free(term->tl_command);
844#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100845 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200846 vim_free(term->tl_status_text);
847 vim_free(term->tl_opencmd);
848 vim_free(term->tl_eof_chars);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200849#ifdef WIN3264
850 if (term->tl_out_fd != NULL)
851 fclose(term->tl_out_fd);
852#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200853 vim_free(term->tl_cursor_color);
854 vim_free(term);
855 buf->b_term = NULL;
856 if (in_terminal_loop == term)
857 in_terminal_loop = NULL;
858}
859
860/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100861 * Get the part that is connected to the tty. Normally this is PART_IN, but
862 * when writing buffer lines to the job it can be another. This makes it
863 * possible to do "1,5term vim -".
864 */
865 static ch_part_T
866get_tty_part(term_T *term)
867{
868#ifdef UNIX
869 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
870 int i;
871
872 for (i = 0; i < 3; ++i)
873 {
874 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
875
876 if (isatty(fd))
877 return parts[i];
878 }
879#endif
880 return PART_IN;
881}
882
883/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200884 * Write job output "msg[len]" to the vterm.
885 */
886 static void
887term_write_job_output(term_T *term, char_u *msg, size_t len)
888{
889 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100890 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200891
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100892 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200893
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100894 /* flush vterm buffer when vterm responded to control sequence */
895 if (prevlen != vterm_output_get_buffer_current(vterm))
896 {
897 char buf[KEY_BUF_LEN];
898 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
899
900 if (curlen > 0)
901 channel_send(term->tl_job->jv_channel, get_tty_part(term),
902 (char_u *)buf, (int)curlen, NULL);
903 }
904
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200905 /* this invokes the damage callbacks */
906 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
907}
908
909 static void
910update_cursor(term_T *term, int redraw)
911{
912 if (term->tl_normal_mode)
913 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100914#ifdef FEAT_GUI
915 if (term->tl_system)
916 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
917 term->tl_cursor_pos.col);
918 else
919#endif
920 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200921 if (redraw)
922 {
923 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
924 cursor_on();
925 out_flush();
926#ifdef FEAT_GUI
927 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100928 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200929 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100930 gui_mch_flush();
931 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200932#endif
933 }
934}
935
936/*
937 * Invoked when "msg" output from a job was received. Write it to the terminal
938 * of "buffer".
939 */
940 void
941write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
942{
943 size_t len = STRLEN(msg);
944 term_T *term = buffer->b_term;
945
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200946#ifdef WIN3264
947 /* Win32: Cannot redirect output of the job, intercept it here and write to
948 * the file. */
949 if (term->tl_out_fd != NULL)
950 {
951 ch_log(channel, "Writing %d bytes to output file", (int)len);
952 fwrite(msg, len, 1, term->tl_out_fd);
953 return;
954 }
955#endif
956
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200957 if (term->tl_vterm == NULL)
958 {
959 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
960 return;
961 }
962 ch_log(channel, "writing %d bytes to terminal", (int)len);
963 term_write_job_output(term, msg, len);
964
Bram Moolenaar13568252018-03-16 20:46:58 +0100965#ifdef FEAT_GUI
966 if (term->tl_system)
967 {
968 /* show system output, scrolling up the screen as needed */
969 update_system_term(term);
970 update_cursor(term, TRUE);
971 }
972 else
973#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200974 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
975 * contents, thus no screen update is needed. */
976 if (!term->tl_normal_mode)
977 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +0200978 // Don't use update_screen() when editing the command line, it gets
979 // cleared.
980 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200981 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +0200982 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200983 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +0200984 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +0200985 /* update_screen() can be slow, check the terminal wasn't closed
986 * already */
987 if (buffer == curbuf && curbuf->b_term != NULL)
988 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200989 }
990 else
991 redraw_after_callback(TRUE);
992 }
993}
994
995/*
996 * Send a mouse position and click to the vterm
997 */
998 static int
999term_send_mouse(VTerm *vterm, int button, int pressed)
1000{
1001 VTermModifier mod = VTERM_MOD_NONE;
1002
1003 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001004 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001005 if (button != 0)
1006 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001007 return TRUE;
1008}
1009
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001010static int enter_mouse_col = -1;
1011static int enter_mouse_row = -1;
1012
1013/*
1014 * Handle a mouse click, drag or release.
1015 * Return TRUE when a mouse event is sent to the terminal.
1016 */
1017 static int
1018term_mouse_click(VTerm *vterm, int key)
1019{
1020#if defined(FEAT_CLIPBOARD)
1021 /* For modeless selection mouse drag and release events are ignored, unless
1022 * they are preceded with a mouse down event */
1023 static int ignore_drag_release = TRUE;
1024 VTermMouseState mouse_state;
1025
1026 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1027 if (mouse_state.flags == 0)
1028 {
1029 /* Terminal is not using the mouse, use modeless selection. */
1030 switch (key)
1031 {
1032 case K_LEFTDRAG:
1033 case K_LEFTRELEASE:
1034 case K_RIGHTDRAG:
1035 case K_RIGHTRELEASE:
1036 /* Ignore drag and release events when the button-down wasn't
1037 * seen before. */
1038 if (ignore_drag_release)
1039 {
1040 int save_mouse_col, save_mouse_row;
1041
1042 if (enter_mouse_col < 0)
1043 break;
1044
1045 /* mouse click in the window gave us focus, handle that
1046 * click now */
1047 save_mouse_col = mouse_col;
1048 save_mouse_row = mouse_row;
1049 mouse_col = enter_mouse_col;
1050 mouse_row = enter_mouse_row;
1051 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1052 mouse_col = save_mouse_col;
1053 mouse_row = save_mouse_row;
1054 }
1055 /* FALLTHROUGH */
1056 case K_LEFTMOUSE:
1057 case K_RIGHTMOUSE:
1058 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1059 ignore_drag_release = TRUE;
1060 else
1061 ignore_drag_release = FALSE;
1062 /* Should we call mouse_has() here? */
1063 if (clip_star.available)
1064 {
1065 int button, is_click, is_drag;
1066
1067 button = get_mouse_button(KEY2TERMCAP1(key),
1068 &is_click, &is_drag);
1069 if (mouse_model_popup() && button == MOUSE_LEFT
1070 && (mod_mask & MOD_MASK_SHIFT))
1071 {
1072 /* Translate shift-left to right button. */
1073 button = MOUSE_RIGHT;
1074 mod_mask &= ~MOD_MASK_SHIFT;
1075 }
1076 clip_modeless(button, is_click, is_drag);
1077 }
1078 break;
1079
1080 case K_MIDDLEMOUSE:
1081 if (clip_star.available)
1082 insert_reg('*', TRUE);
1083 break;
1084 }
1085 enter_mouse_col = -1;
1086 return FALSE;
1087 }
1088#endif
1089 enter_mouse_col = -1;
1090
1091 switch (key)
1092 {
1093 case K_LEFTMOUSE:
1094 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1095 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1096 case K_LEFTRELEASE:
1097 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1098 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1099 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1100 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1101 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1102 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1103 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1104 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1105 }
1106 return TRUE;
1107}
1108
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001109/*
1110 * Convert typed key "c" into bytes to send to the job.
1111 * Return the number of bytes in "buf".
1112 */
1113 static int
1114term_convert_key(term_T *term, int c, char *buf)
1115{
1116 VTerm *vterm = term->tl_vterm;
1117 VTermKey key = VTERM_KEY_NONE;
1118 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001119 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001120
1121 switch (c)
1122 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001123 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1124
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001125 /* don't use VTERM_KEY_BACKSPACE, it always
1126 * becomes 0x7f DEL */
1127 case K_BS: c = term_backspace_char; break;
1128
1129 case ESC: key = VTERM_KEY_ESCAPE; break;
1130 case K_DEL: key = VTERM_KEY_DEL; break;
1131 case K_DOWN: key = VTERM_KEY_DOWN; break;
1132 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1133 key = VTERM_KEY_DOWN; break;
1134 case K_END: key = VTERM_KEY_END; break;
1135 case K_S_END: mod = VTERM_MOD_SHIFT;
1136 key = VTERM_KEY_END; break;
1137 case K_C_END: mod = VTERM_MOD_CTRL;
1138 key = VTERM_KEY_END; break;
1139 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1140 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1141 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1142 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1143 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1144 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1145 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1146 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1147 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1148 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1149 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1150 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1151 case K_HOME: key = VTERM_KEY_HOME; break;
1152 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1153 key = VTERM_KEY_HOME; break;
1154 case K_C_HOME: mod = VTERM_MOD_CTRL;
1155 key = VTERM_KEY_HOME; break;
1156 case K_INS: key = VTERM_KEY_INS; break;
1157 case K_K0: key = VTERM_KEY_KP_0; break;
1158 case K_K1: key = VTERM_KEY_KP_1; break;
1159 case K_K2: key = VTERM_KEY_KP_2; break;
1160 case K_K3: key = VTERM_KEY_KP_3; break;
1161 case K_K4: key = VTERM_KEY_KP_4; break;
1162 case K_K5: key = VTERM_KEY_KP_5; break;
1163 case K_K6: key = VTERM_KEY_KP_6; break;
1164 case K_K7: key = VTERM_KEY_KP_7; break;
1165 case K_K8: key = VTERM_KEY_KP_8; break;
1166 case K_K9: key = VTERM_KEY_KP_9; break;
1167 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1168 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1169 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1170 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1171 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1172 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1173 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1174 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1175 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1176 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1177 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1178 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1179 case K_LEFT: key = VTERM_KEY_LEFT; break;
1180 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1181 key = VTERM_KEY_LEFT; break;
1182 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1183 key = VTERM_KEY_LEFT; break;
1184 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1185 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1186 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1187 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1188 key = VTERM_KEY_RIGHT; break;
1189 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1190 key = VTERM_KEY_RIGHT; break;
1191 case K_UP: key = VTERM_KEY_UP; break;
1192 case K_S_UP: mod = VTERM_MOD_SHIFT;
1193 key = VTERM_KEY_UP; break;
1194 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001195 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1196 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001197
Bram Moolenaara42ad572017-11-16 13:08:04 +01001198 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1199 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001200 case K_MOUSELEFT: /* TODO */ return 0;
1201 case K_MOUSERIGHT: /* TODO */ return 0;
1202
1203 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001204 case K_LEFTMOUSE_NM:
1205 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001206 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001207 case K_LEFTRELEASE_NM:
1208 case K_MOUSEMOVE:
1209 case K_MIDDLEMOUSE:
1210 case K_MIDDLEDRAG:
1211 case K_MIDDLERELEASE:
1212 case K_RIGHTMOUSE:
1213 case K_RIGHTDRAG:
1214 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1215 return 0;
1216 other = TRUE;
1217 break;
1218
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001219 case K_X1MOUSE: /* TODO */ return 0;
1220 case K_X1DRAG: /* TODO */ return 0;
1221 case K_X1RELEASE: /* TODO */ return 0;
1222 case K_X2MOUSE: /* TODO */ return 0;
1223 case K_X2DRAG: /* TODO */ return 0;
1224 case K_X2RELEASE: /* TODO */ return 0;
1225
1226 case K_IGNORE: return 0;
1227 case K_NOP: return 0;
1228 case K_UNDO: return 0;
1229 case K_HELP: return 0;
1230 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1231 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1232 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1233 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1234 case K_SELECT: return 0;
1235#ifdef FEAT_GUI
1236 case K_VER_SCROLLBAR: return 0;
1237 case K_HOR_SCROLLBAR: return 0;
1238#endif
1239#ifdef FEAT_GUI_TABLINE
1240 case K_TABLINE: return 0;
1241 case K_TABMENU: return 0;
1242#endif
1243#ifdef FEAT_NETBEANS_INTG
1244 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1245#endif
1246#ifdef FEAT_DND
1247 case K_DROP: return 0;
1248#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001249 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001250 case K_PS: vterm_keyboard_start_paste(vterm);
1251 other = TRUE;
1252 break;
1253 case K_PE: vterm_keyboard_end_paste(vterm);
1254 other = TRUE;
1255 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001256 }
1257
1258 /*
1259 * Convert special keys to vterm keys:
1260 * - Write keys to vterm: vterm_keyboard_key()
1261 * - Write output to channel.
1262 * TODO: use mod_mask
1263 */
1264 if (key != VTERM_KEY_NONE)
1265 /* Special key, let vterm convert it. */
1266 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001267 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001268 /* Normal character, let vterm convert it. */
1269 vterm_keyboard_unichar(vterm, c, mod);
1270
1271 /* Read back the converted escape sequence. */
1272 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1273}
1274
1275/*
1276 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001277 * If "check_job_status" is TRUE update the job status.
1278 */
1279 static int
1280term_job_running_check(term_T *term, int check_job_status)
1281{
1282 /* Also consider the job finished when the channel is closed, to avoid a
1283 * race condition when updating the title. */
1284 if (term != NULL
1285 && term->tl_job != NULL
1286 && channel_is_open(term->tl_job->jv_channel))
1287 {
1288 if (check_job_status)
1289 job_status(term->tl_job);
1290 return (term->tl_job->jv_status == JOB_STARTED
1291 || term->tl_job->jv_channel->ch_keep_open);
1292 }
1293 return FALSE;
1294}
1295
1296/*
1297 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001298 */
1299 int
1300term_job_running(term_T *term)
1301{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001302 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001303}
1304
1305/*
1306 * Return TRUE if "term" has an active channel and used ":term NONE".
1307 */
1308 int
1309term_none_open(term_T *term)
1310{
1311 /* Also consider the job finished when the channel is closed, to avoid a
1312 * race condition when updating the title. */
1313 return term != NULL
1314 && term->tl_job != NULL
1315 && channel_is_open(term->tl_job->jv_channel)
1316 && term->tl_job->jv_channel->ch_keep_open;
1317}
1318
1319/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001320 * Used when exiting: kill the job in "buf" if so desired.
1321 * Return OK when the job finished.
1322 * Return FAIL when the job is still running.
1323 */
1324 int
1325term_try_stop_job(buf_T *buf)
1326{
1327 int count;
1328 char *how = (char *)buf->b_term->tl_kill;
1329
1330#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1331 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1332 {
1333 char_u buff[DIALOG_MSG_SIZE];
1334 int ret;
1335
1336 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1337 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1338 if (ret == VIM_YES)
1339 how = "kill";
1340 else if (ret == VIM_CANCEL)
1341 return FAIL;
1342 }
1343#endif
1344 if (how == NULL || *how == NUL)
1345 return FAIL;
1346
1347 job_stop(buf->b_term->tl_job, NULL, how);
1348
1349 /* wait for up to a second for the job to die */
1350 for (count = 0; count < 100; ++count)
1351 {
1352 /* buffer, terminal and job may be cleaned up while waiting */
1353 if (!buf_valid(buf)
1354 || buf->b_term == NULL
1355 || buf->b_term->tl_job == NULL)
1356 return OK;
1357
1358 /* call job_status() to update jv_status */
1359 job_status(buf->b_term->tl_job);
1360 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1361 return OK;
1362 ui_delay(10L, FALSE);
1363 mch_check_messages();
1364 parse_queued_messages();
1365 }
1366 return FAIL;
1367}
1368
1369/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001370 * Add the last line of the scrollback buffer to the buffer in the window.
1371 */
1372 static void
1373add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1374{
1375 buf_T *buf = term->tl_buffer;
1376 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1377 linenr_T lnum = buf->b_ml.ml_line_count;
1378
1379#ifdef WIN3264
1380 if (!enc_utf8 && enc_codepage > 0)
1381 {
1382 WCHAR *ret = NULL;
1383 int length = 0;
1384
1385 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1386 &ret, &length);
1387 if (ret != NULL)
1388 {
1389 WideCharToMultiByte_alloc(enc_codepage, 0,
1390 ret, length, (char **)&text, &len, 0, 0);
1391 vim_free(ret);
1392 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1393 vim_free(text);
1394 }
1395 }
1396 else
1397#endif
1398 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1399 if (empty)
1400 {
1401 /* Delete the empty line that was in the empty buffer. */
1402 curbuf = buf;
1403 ml_delete(1, FALSE);
1404 curbuf = curwin->w_buffer;
1405 }
1406}
1407
1408 static void
1409cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1410{
1411 attr->width = cell->width;
1412 attr->attrs = cell->attrs;
1413 attr->fg = cell->fg;
1414 attr->bg = cell->bg;
1415}
1416
1417 static int
1418equal_celattr(cellattr_T *a, cellattr_T *b)
1419{
1420 /* Comparing the colors should be sufficient. */
1421 return a->fg.red == b->fg.red
1422 && a->fg.green == b->fg.green
1423 && a->fg.blue == b->fg.blue
1424 && a->bg.red == b->bg.red
1425 && a->bg.green == b->bg.green
1426 && a->bg.blue == b->bg.blue;
1427}
1428
Bram Moolenaard96ff162018-02-18 22:13:29 +01001429/*
1430 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1431 * line at this position. Otherwise at the end.
1432 */
1433 static int
1434add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1435{
1436 if (ga_grow(&term->tl_scrollback, 1) == OK)
1437 {
1438 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1439 + term->tl_scrollback.ga_len;
1440
1441 if (lnum > 0)
1442 {
1443 int i;
1444
1445 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1446 {
1447 *line = *(line - 1);
1448 --line;
1449 }
1450 }
1451 line->sb_cols = 0;
1452 line->sb_cells = NULL;
1453 line->sb_fill_attr = *fill_attr;
1454 ++term->tl_scrollback.ga_len;
1455 return OK;
1456 }
1457 return FALSE;
1458}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001459
1460/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001461 * Remove the terminal contents from the scrollback and the buffer.
1462 * Used before adding a new scrollback line or updating the buffer for lines
1463 * displayed in the terminal.
1464 */
1465 static void
1466cleanup_scrollback(term_T *term)
1467{
1468 sb_line_T *line;
1469 garray_T *gap;
1470
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001471 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001472 gap = &term->tl_scrollback;
1473 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1474 && gap->ga_len > 0)
1475 {
1476 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1477 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1478 vim_free(line->sb_cells);
1479 --gap->ga_len;
1480 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001481 curbuf = curwin->w_buffer;
1482 if (curbuf == term->tl_buffer)
1483 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001484}
1485
1486/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001487 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001488 */
1489 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001490update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001491{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001492 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001493 int len;
1494 int lines_skipped = 0;
1495 VTermPos pos;
1496 VTermScreenCell cell;
1497 cellattr_T fill_attr, new_fill_attr;
1498 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001499
1500 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1501 "Adding terminal window snapshot to buffer");
1502
1503 /* First remove the lines that were appended before, they might be
1504 * outdated. */
1505 cleanup_scrollback(term);
1506
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001507 screen = vterm_obtain_screen(term->tl_vterm);
1508 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001509 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1510 {
1511 len = 0;
1512 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1513 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1514 && cell.chars[0] != NUL)
1515 {
1516 len = pos.col + 1;
1517 new_fill_attr = term->tl_default_color;
1518 }
1519 else
1520 /* Assume the last attr is the filler attr. */
1521 cell2cellattr(&cell, &new_fill_attr);
1522
1523 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1524 ++lines_skipped;
1525 else
1526 {
1527 while (lines_skipped > 0)
1528 {
1529 /* Line was skipped, add an empty line. */
1530 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001531 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001532 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001533 }
1534
1535 if (len == 0)
1536 p = NULL;
1537 else
1538 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1539 if ((p != NULL || len == 0)
1540 && ga_grow(&term->tl_scrollback, 1) == OK)
1541 {
1542 garray_T ga;
1543 int width;
1544 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1545 + term->tl_scrollback.ga_len;
1546
1547 ga_init2(&ga, 1, 100);
1548 for (pos.col = 0; pos.col < len; pos.col += width)
1549 {
1550 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1551 {
1552 width = 1;
1553 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1554 if (ga_grow(&ga, 1) == OK)
1555 ga.ga_len += utf_char2bytes(' ',
1556 (char_u *)ga.ga_data + ga.ga_len);
1557 }
1558 else
1559 {
1560 width = cell.width;
1561
1562 cell2cellattr(&cell, &p[pos.col]);
1563
1564 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1565 {
1566 int i;
1567 int c;
1568
1569 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1570 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1571 (char_u *)ga.ga_data + ga.ga_len);
1572 }
1573 }
1574 }
1575 line->sb_cols = len;
1576 line->sb_cells = p;
1577 line->sb_fill_attr = new_fill_attr;
1578 fill_attr = new_fill_attr;
1579 ++term->tl_scrollback.ga_len;
1580
1581 if (ga_grow(&ga, 1) == FAIL)
1582 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1583 else
1584 {
1585 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1586 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1587 }
1588 ga_clear(&ga);
1589 }
1590 else
1591 vim_free(p);
1592 }
1593 }
1594
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001595 term->tl_dirty_snapshot = FALSE;
1596#ifdef FEAT_TIMERS
1597 term->tl_timer_set = FALSE;
1598#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001599}
1600
1601/*
1602 * If needed, add the current lines of the terminal to scrollback and to the
1603 * buffer. Called after the job has ended and when switching to
1604 * Terminal-Normal mode.
1605 * When "redraw" is TRUE redraw the windows that show the terminal.
1606 */
1607 static void
1608may_move_terminal_to_buffer(term_T *term, int redraw)
1609{
1610 win_T *wp;
1611
1612 if (term->tl_vterm == NULL)
1613 return;
1614
1615 /* Update the snapshot only if something changes or the buffer does not
1616 * have all the lines. */
1617 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1618 <= term->tl_scrollback_scrolled)
1619 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001620
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001621 /* Obtain the current background color. */
1622 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1623 &term->tl_default_color.fg, &term->tl_default_color.bg);
1624
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001625 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001626 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001628 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001629 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001630 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1631 wp->w_cursor.col = 0;
1632 wp->w_valid = 0;
1633 if (wp->w_cursor.lnum >= wp->w_height)
1634 {
1635 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001636
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001637 if (wp->w_topline < min_topline)
1638 wp->w_topline = min_topline;
1639 }
1640 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001641 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001642 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001643}
1644
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001645#if defined(FEAT_TIMERS) || defined(PROTO)
1646/*
1647 * Check if any terminal timer expired. If so, copy text from the terminal to
1648 * the buffer.
1649 * Return the time until the next timer will expire.
1650 */
1651 int
1652term_check_timers(int next_due_arg, proftime_T *now)
1653{
1654 term_T *term;
1655 int next_due = next_due_arg;
1656
1657 for (term = first_term; term != NULL; term = term->tl_next)
1658 {
1659 if (term->tl_timer_set && !term->tl_normal_mode)
1660 {
1661 long this_due = proftime_time_left(&term->tl_timer_due, now);
1662
1663 if (this_due <= 1)
1664 {
1665 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001666 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001667 }
1668 else if (next_due == -1 || next_due > this_due)
1669 next_due = this_due;
1670 }
1671 }
1672
1673 return next_due;
1674}
1675#endif
1676
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001677 static void
1678set_terminal_mode(term_T *term, int normal_mode)
1679{
1680 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001681 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001682 if (term->tl_buffer == curbuf)
1683 maketitle();
1684}
1685
1686/*
1687 * Called after the job if finished and Terminal mode is not active:
1688 * Move the vterm contents into the scrollback buffer and free the vterm.
1689 */
1690 static void
1691cleanup_vterm(term_T *term)
1692{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001693 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001694 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001695 term_free_vterm(term);
1696 set_terminal_mode(term, FALSE);
1697}
1698
1699/*
1700 * Switch from Terminal-Job mode to Terminal-Normal mode.
1701 * Suspends updating the terminal window.
1702 */
1703 static void
1704term_enter_normal_mode(void)
1705{
1706 term_T *term = curbuf->b_term;
1707
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001708 set_terminal_mode(term, TRUE);
1709
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001710 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001711 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001712
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001713 /* Move the window cursor to the position of the cursor in the
1714 * terminal. */
1715 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1716 + term->tl_cursor_pos.row + 1;
1717 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001718 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1719 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001720
1721 /* Display the same lines as in the terminal. */
1722 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1723}
1724
1725/*
1726 * Returns TRUE if the current window contains a terminal and we are in
1727 * Terminal-Normal mode.
1728 */
1729 int
1730term_in_normal_mode(void)
1731{
1732 term_T *term = curbuf->b_term;
1733
1734 return term != NULL && term->tl_normal_mode;
1735}
1736
1737/*
1738 * Switch from Terminal-Normal mode to Terminal-Job mode.
1739 * Restores updating the terminal window.
1740 */
1741 void
1742term_enter_job_mode()
1743{
1744 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001745
1746 set_terminal_mode(term, FALSE);
1747
1748 if (term->tl_channel_closed)
1749 cleanup_vterm(term);
1750 redraw_buf_and_status_later(curbuf, NOT_VALID);
1751}
1752
1753/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001754 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001755 * Note: while waiting a terminal may be closed and freed if the channel is
1756 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001757 */
1758 static int
1759term_vgetc()
1760{
1761 int c;
1762 int save_State = State;
1763
1764 State = TERMINAL;
1765 got_int = FALSE;
1766#ifdef WIN3264
1767 ctrl_break_was_pressed = FALSE;
1768#endif
1769 c = vgetc();
1770 got_int = FALSE;
1771 State = save_State;
1772 return c;
1773}
1774
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001775static int mouse_was_outside = FALSE;
1776
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001777/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001778 * Send keys to terminal.
1779 * Return FAIL when the key needs to be handled in Normal mode.
1780 * Return OK when the key was dropped or sent to the terminal.
1781 */
1782 int
1783send_keys_to_term(term_T *term, int c, int typed)
1784{
1785 char msg[KEY_BUF_LEN];
1786 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001787 int dragging_outside = FALSE;
1788
1789 /* Catch keys that need to be handled as in Normal mode. */
1790 switch (c)
1791 {
1792 case NUL:
1793 case K_ZERO:
1794 if (typed)
1795 stuffcharReadbuff(c);
1796 return FAIL;
1797
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001798 case K_TABLINE:
1799 stuffcharReadbuff(c);
1800 return FAIL;
1801
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001802 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001803 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001804 return FAIL;
1805
1806 case K_LEFTDRAG:
1807 case K_MIDDLEDRAG:
1808 case K_RIGHTDRAG:
1809 case K_X1DRAG:
1810 case K_X2DRAG:
1811 dragging_outside = mouse_was_outside;
1812 /* FALLTHROUGH */
1813 case K_LEFTMOUSE:
1814 case K_LEFTMOUSE_NM:
1815 case K_LEFTRELEASE:
1816 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001817 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001818 case K_MIDDLEMOUSE:
1819 case K_MIDDLERELEASE:
1820 case K_RIGHTMOUSE:
1821 case K_RIGHTRELEASE:
1822 case K_X1MOUSE:
1823 case K_X1RELEASE:
1824 case K_X2MOUSE:
1825 case K_X2RELEASE:
1826
1827 case K_MOUSEUP:
1828 case K_MOUSEDOWN:
1829 case K_MOUSELEFT:
1830 case K_MOUSERIGHT:
1831 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001832 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001833 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001834 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001835 || dragging_outside)
1836 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001837 /* click or scroll outside the current window or on status line
1838 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001839 if (typed)
1840 {
1841 stuffcharReadbuff(c);
1842 mouse_was_outside = TRUE;
1843 }
1844 return FAIL;
1845 }
1846 }
1847 if (typed)
1848 mouse_was_outside = FALSE;
1849
1850 /* Convert the typed key to a sequence of bytes for the job. */
1851 len = term_convert_key(term, c, msg);
1852 if (len > 0)
1853 /* TODO: if FAIL is returned, stop? */
1854 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1855 (char_u *)msg, (int)len, NULL);
1856
1857 return OK;
1858}
1859
1860 static void
1861position_cursor(win_T *wp, VTermPos *pos)
1862{
1863 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1864 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1865 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1866}
1867
1868/*
1869 * Handle CTRL-W "": send register contents to the job.
1870 */
1871 static void
1872term_paste_register(int prev_c UNUSED)
1873{
1874 int c;
1875 list_T *l;
1876 listitem_T *item;
1877 long reglen = 0;
1878 int type;
1879
1880#ifdef FEAT_CMDL_INFO
1881 if (add_to_showcmd(prev_c))
1882 if (add_to_showcmd('"'))
1883 out_flush();
1884#endif
1885 c = term_vgetc();
1886#ifdef FEAT_CMDL_INFO
1887 clear_showcmd();
1888#endif
1889 if (!term_use_loop())
1890 /* job finished while waiting for a character */
1891 return;
1892
1893 /* CTRL-W "= prompt for expression to evaluate. */
1894 if (c == '=' && get_expr_register() != '=')
1895 return;
1896 if (!term_use_loop())
1897 /* job finished while waiting for a character */
1898 return;
1899
1900 l = (list_T *)get_reg_contents(c, GREG_LIST);
1901 if (l != NULL)
1902 {
1903 type = get_reg_type(c, &reglen);
1904 for (item = l->lv_first; item != NULL; item = item->li_next)
1905 {
1906 char_u *s = get_tv_string(&item->li_tv);
1907#ifdef WIN3264
1908 char_u *tmp = s;
1909
1910 if (!enc_utf8 && enc_codepage > 0)
1911 {
1912 WCHAR *ret = NULL;
1913 int length = 0;
1914
1915 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1916 (int)STRLEN(s), &ret, &length);
1917 if (ret != NULL)
1918 {
1919 WideCharToMultiByte_alloc(CP_UTF8, 0,
1920 ret, length, (char **)&s, &length, 0, 0);
1921 vim_free(ret);
1922 }
1923 }
1924#endif
1925 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1926 s, (int)STRLEN(s), NULL);
1927#ifdef WIN3264
1928 if (tmp != s)
1929 vim_free(s);
1930#endif
1931
1932 if (item->li_next != NULL || type == MLINE)
1933 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1934 (char_u *)"\r", 1, NULL);
1935 }
1936 list_free(l);
1937 }
1938}
1939
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001940/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001941 * Return TRUE when waiting for a character in the terminal, the cursor of the
1942 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001943 */
1944 int
1945terminal_is_active()
1946{
1947 return in_terminal_loop != NULL;
1948}
1949
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001950#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001951 cursorentry_T *
1952term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1953{
1954 term_T *term = in_terminal_loop;
1955 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02001956 int id;
1957 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001958
1959 vim_memset(&entry, 0, sizeof(entry));
1960 entry.shape = entry.mshape =
1961 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1962 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1963 SHAPE_BLOCK;
1964 entry.percentage = 20;
1965 if (term->tl_cursor_blink)
1966 {
1967 entry.blinkwait = 700;
1968 entry.blinkon = 400;
1969 entry.blinkoff = 250;
1970 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02001971
1972 /* The "Terminal" highlight group overrules the defaults. */
1973 id = syn_name2id((char_u *)"Terminal");
1974 if (id != 0)
1975 {
1976 syn_id2colors(id, &term_fg, &term_bg);
1977 *fg = term_bg;
1978 }
1979 else
1980 *fg = gui.back_pixel;
1981
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001982 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02001983 {
1984 if (id != 0)
1985 *bg = term_fg;
1986 else
1987 *bg = gui.norm_pixel;
1988 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001989 else
1990 *bg = color_name2handle(term->tl_cursor_color);
1991 entry.name = "n";
1992 entry.used_for = SHAPE_CURSOR;
1993
1994 return &entry;
1995}
1996#endif
1997
Bram Moolenaard317b382018-02-08 22:33:31 +01001998 static void
1999may_output_cursor_props(void)
2000{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002001 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002002 || last_set_cursor_shape != desired_cursor_shape
2003 || last_set_cursor_blink != desired_cursor_blink)
2004 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002005 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002006 last_set_cursor_shape = desired_cursor_shape;
2007 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002008 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002009 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2010 /* this will restore the initial cursor style, if possible */
2011 ui_cursor_shape_forced(TRUE);
2012 else
2013 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2014 }
2015}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016
Bram Moolenaard317b382018-02-08 22:33:31 +01002017/*
2018 * Set the cursor color and shape, if not last set to these.
2019 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002020 static void
2021may_set_cursor_props(term_T *term)
2022{
2023#ifdef FEAT_GUI
2024 /* For the GUI the cursor properties are obtained with
2025 * term_get_cursor_shape(). */
2026 if (gui.in_use)
2027 return;
2028#endif
2029 if (in_terminal_loop == term)
2030 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002031 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002032 desired_cursor_shape = term->tl_cursor_shape;
2033 desired_cursor_blink = term->tl_cursor_blink;
2034 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002035 }
2036}
2037
Bram Moolenaard317b382018-02-08 22:33:31 +01002038/*
2039 * Reset the desired cursor properties and restore them when needed.
2040 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002041 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002042prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002043{
2044#ifdef FEAT_GUI
2045 if (gui.in_use)
2046 return;
2047#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002048 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002049 desired_cursor_shape = -1;
2050 desired_cursor_blink = -1;
2051 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002052}
2053
2054/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002055 * Returns TRUE if the current window contains a terminal and we are sending
2056 * keys to the job.
2057 * If "check_job_status" is TRUE update the job status.
2058 */
2059 static int
2060term_use_loop_check(int check_job_status)
2061{
2062 term_T *term = curbuf->b_term;
2063
2064 return term != NULL
2065 && !term->tl_normal_mode
2066 && term->tl_vterm != NULL
2067 && term_job_running_check(term, check_job_status);
2068}
2069
2070/*
2071 * Returns TRUE if the current window contains a terminal and we are sending
2072 * keys to the job.
2073 */
2074 int
2075term_use_loop(void)
2076{
2077 return term_use_loop_check(FALSE);
2078}
2079
2080/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002081 * Called when entering a window with the mouse. If this is a terminal window
2082 * we may want to change state.
2083 */
2084 void
2085term_win_entered()
2086{
2087 term_T *term = curbuf->b_term;
2088
2089 if (term != NULL)
2090 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002091 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002092 {
2093 reset_VIsual_and_resel();
2094 if (State & INSERT)
2095 stop_insert_mode = TRUE;
2096 }
2097 mouse_was_outside = FALSE;
2098 enter_mouse_col = mouse_col;
2099 enter_mouse_row = mouse_row;
2100 }
2101}
2102
2103/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002104 * Wait for input and send it to the job.
2105 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2106 * when there is no more typahead.
2107 * Return when the start of a CTRL-W command is typed or anything else that
2108 * should be handled as a Normal mode command.
2109 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2110 * the terminal was closed.
2111 */
2112 int
2113terminal_loop(int blocking)
2114{
2115 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002116 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002117 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002118#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002119 int tty_fd = curbuf->b_term->tl_job->jv_channel
2120 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002121#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002122 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002123
2124 /* Remember the terminal we are sending keys to. However, the terminal
2125 * might be closed while waiting for a character, e.g. typing "exit" in a
2126 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2127 * stored reference. */
2128 in_terminal_loop = curbuf->b_term;
2129
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002130 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002131 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002132 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002133 if (termwinkey == Ctrl_W)
2134 termwinkey = 0;
2135 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002136 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2137 may_set_cursor_props(curbuf->b_term);
2138
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002139 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002140 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002141#ifdef FEAT_GUI
2142 if (!curbuf->b_term->tl_system)
2143#endif
2144 /* TODO: skip screen update when handling a sequence of keys. */
2145 /* Repeat redrawing in case a message is received while redrawing.
2146 */
2147 while (must_redraw != 0)
2148 if (update_screen(0) == FAIL)
2149 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002150 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002151 /* job finished while redrawing */
2152 break;
2153
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002154 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002155 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002156
2157 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002158 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002159 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002160 /* Job finished while waiting for a character. Push back the
2161 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002162 if (c != K_IGNORE)
2163 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002164 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002165 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166 if (c == K_IGNORE)
2167 continue;
2168
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002169#ifdef UNIX
2170 /*
2171 * The shell or another program may change the tty settings. Getting
2172 * them for every typed character is a bit of overhead, but it's needed
2173 * for the first character typed, e.g. when Vim starts in a shell.
2174 */
2175 if (isatty(tty_fd))
2176 {
2177 ttyinfo_T info;
2178
2179 /* Get the current backspace character of the pty. */
2180 if (get_tty_info(tty_fd, &info) == OK)
2181 term_backspace_char = info.backspace;
2182 }
2183#endif
2184
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002185#ifdef WIN3264
2186 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2187 * Use CTRL-BREAK to kill the job. */
2188 if (ctrl_break_was_pressed)
2189 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2190#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002191 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002192 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002193 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002194#ifdef FEAT_GUI
2195 && !curbuf->b_term->tl_system
2196#endif
2197 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002198 {
2199 int prev_c = c;
2200
2201#ifdef FEAT_CMDL_INFO
2202 if (add_to_showcmd(c))
2203 out_flush();
2204#endif
2205 c = term_vgetc();
2206#ifdef FEAT_CMDL_INFO
2207 clear_showcmd();
2208#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002209 if (!term_use_loop_check(TRUE)
2210 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002211 /* job finished while waiting for a character */
2212 break;
2213
2214 if (prev_c == Ctrl_BSL)
2215 {
2216 if (c == Ctrl_N)
2217 {
2218 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2219 term_enter_normal_mode();
2220 ret = FAIL;
2221 goto theend;
2222 }
2223 /* Send both keys to the terminal. */
2224 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2225 }
2226 else if (c == Ctrl_C)
2227 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002228 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002229 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2230 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002231 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002232 {
2233 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002234 /* "'termwinkey' .": send 'termwinkey' to the job */
2235 c = termwinkey == 0 ? Ctrl_W : termwinkey;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002237 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002238 {
2239 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2240 c = Ctrl_BSL;
2241 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002242 else if (c == 'N')
2243 {
2244 /* CTRL-W N : go to Terminal-Normal mode. */
2245 term_enter_normal_mode();
2246 ret = FAIL;
2247 goto theend;
2248 }
2249 else if (c == '"')
2250 {
2251 term_paste_register(prev_c);
2252 continue;
2253 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002254 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002255 {
2256 stuffcharReadbuff(Ctrl_W);
2257 stuffcharReadbuff(c);
2258 ret = OK;
2259 goto theend;
2260 }
2261 }
2262# ifdef WIN3264
2263 if (!enc_utf8 && has_mbyte && c >= 0x80)
2264 {
2265 WCHAR wc;
2266 char_u mb[3];
2267
2268 mb[0] = (unsigned)c >> 8;
2269 mb[1] = c;
2270 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2271 c = wc;
2272 }
2273# endif
2274 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2275 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002276 if (c == K_MOUSEMOVE)
2277 /* We are sure to come back here, don't reset the cursor color
2278 * and shape to avoid flickering. */
2279 restore_cursor = FALSE;
2280
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002281 ret = OK;
2282 goto theend;
2283 }
2284 }
2285 ret = FAIL;
2286
2287theend:
2288 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002289 if (restore_cursor)
2290 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002291
2292 /* Move a snapshot of the screen contents to the buffer, so that completion
2293 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002294 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2295 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002296
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002297 return ret;
2298}
2299
2300/*
2301 * Called when a job has finished.
2302 * This updates the title and status, but does not close the vterm, because
2303 * there might still be pending output in the channel.
2304 */
2305 void
2306term_job_ended(job_T *job)
2307{
2308 term_T *term;
2309 int did_one = FALSE;
2310
2311 for (term = first_term; term != NULL; term = term->tl_next)
2312 if (term->tl_job == job)
2313 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002314 VIM_CLEAR(term->tl_title);
2315 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002316 redraw_buf_and_status_later(term->tl_buffer, VALID);
2317 did_one = TRUE;
2318 }
2319 if (did_one)
2320 redraw_statuslines();
2321 if (curbuf->b_term != NULL)
2322 {
2323 if (curbuf->b_term->tl_job == job)
2324 maketitle();
2325 update_cursor(curbuf->b_term, TRUE);
2326 }
2327}
2328
2329 static void
2330may_toggle_cursor(term_T *term)
2331{
2332 if (in_terminal_loop == term)
2333 {
2334 if (term->tl_cursor_visible)
2335 cursor_on();
2336 else
2337 cursor_off();
2338 }
2339}
2340
2341/*
2342 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002343 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002344 */
2345 static int
2346color2index(VTermColor *color, int fg, int *boldp)
2347{
2348 int red = color->red;
2349 int blue = color->blue;
2350 int green = color->green;
2351
Bram Moolenaar46359e12017-11-29 22:33:38 +01002352 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002353 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002354 /* First 16 colors and default: use the ANSI index, because these
2355 * colors can be redefined. */
2356 if (t_colors >= 16)
2357 return color->ansi_index;
2358 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002359 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002360 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002361 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002362 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2363 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2364 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002365 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002366 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2367 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2368 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2369 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2370 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2371 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2372 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2373 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2374 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2375 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2376 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002377 }
2378 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002379
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002380 if (t_colors >= 256)
2381 {
2382 if (red == blue && red == green)
2383 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002384 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002385 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002386 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2387 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2388 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002389 int i;
2390
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002391 if (red < 5)
2392 return 17; /* 00/00/00 */
2393 if (red > 245) /* ff/ff/ff */
2394 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002395 for (i = 0; i < 23; ++i)
2396 if (red < cutoff[i])
2397 return i + 233;
2398 return 256;
2399 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002400 {
2401 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2402 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002403
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002404 /* 216-color cube */
2405 for (ri = 0; ri < 5; ++ri)
2406 if (red < cutoff[ri])
2407 break;
2408 for (gi = 0; gi < 5; ++gi)
2409 if (green < cutoff[gi])
2410 break;
2411 for (bi = 0; bi < 5; ++bi)
2412 if (blue < cutoff[bi])
2413 break;
2414 return 17 + ri * 36 + gi * 6 + bi;
2415 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002416 }
2417 return 0;
2418}
2419
2420/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002421 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002422 */
2423 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002424vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002425{
2426 int attr = 0;
2427
2428 if (cellattrs.bold)
2429 attr |= HL_BOLD;
2430 if (cellattrs.underline)
2431 attr |= HL_UNDERLINE;
2432 if (cellattrs.italic)
2433 attr |= HL_ITALIC;
2434 if (cellattrs.strike)
2435 attr |= HL_STRIKETHROUGH;
2436 if (cellattrs.reverse)
2437 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002438 return attr;
2439}
2440
2441/*
2442 * Store Vterm attributes in "cell" from highlight flags.
2443 */
2444 static void
2445hl2vtermAttr(int attr, cellattr_T *cell)
2446{
2447 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2448 if (attr & HL_BOLD)
2449 cell->attrs.bold = 1;
2450 if (attr & HL_UNDERLINE)
2451 cell->attrs.underline = 1;
2452 if (attr & HL_ITALIC)
2453 cell->attrs.italic = 1;
2454 if (attr & HL_STRIKETHROUGH)
2455 cell->attrs.strike = 1;
2456 if (attr & HL_INVERSE)
2457 cell->attrs.reverse = 1;
2458}
2459
2460/*
2461 * Convert the attributes of a vterm cell into an attribute index.
2462 */
2463 static int
2464cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2465{
2466 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002467
2468#ifdef FEAT_GUI
2469 if (gui.in_use)
2470 {
2471 guicolor_T fg, bg;
2472
2473 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2474 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2475 return get_gui_attr_idx(attr, fg, bg);
2476 }
2477 else
2478#endif
2479#ifdef FEAT_TERMGUICOLORS
2480 if (p_tgc)
2481 {
2482 guicolor_T fg, bg;
2483
2484 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2485 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2486
2487 return get_tgc_attr_idx(attr, fg, bg);
2488 }
2489 else
2490#endif
2491 {
2492 int bold = MAYBE;
2493 int fg = color2index(&cellfg, TRUE, &bold);
2494 int bg = color2index(&cellbg, FALSE, &bold);
2495
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002496 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002497 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002498 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002499 if (fg == 0 && term_default_cterm_fg >= 0)
2500 fg = term_default_cterm_fg + 1;
2501 if (bg == 0 && term_default_cterm_bg >= 0)
2502 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002503 }
2504
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002505 /* with 8 colors set the bold attribute to get a bright foreground */
2506 if (bold == TRUE)
2507 attr |= HL_BOLD;
2508 return get_cterm_attr_idx(attr, fg, bg);
2509 }
2510 return 0;
2511}
2512
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002513 static void
2514set_dirty_snapshot(term_T *term)
2515{
2516 term->tl_dirty_snapshot = TRUE;
2517#ifdef FEAT_TIMERS
2518 if (!term->tl_normal_mode)
2519 {
2520 /* Update the snapshot after 100 msec of not getting updates. */
2521 profile_setlimit(100L, &term->tl_timer_due);
2522 term->tl_timer_set = TRUE;
2523 }
2524#endif
2525}
2526
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002527 static int
2528handle_damage(VTermRect rect, void *user)
2529{
2530 term_T *term = (term_T *)user;
2531
2532 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2533 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002534 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002535 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002536 return 1;
2537}
2538
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002539 static void
2540term_scroll_up(term_T *term, int start_row, int count)
2541{
2542 win_T *wp;
2543 VTermColor fg, bg;
2544 VTermScreenCellAttrs attr;
2545 int clear_attr;
2546
2547 /* Set the color to clear lines with. */
2548 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2549 &fg, &bg);
2550 vim_memset(&attr, 0, sizeof(attr));
2551 clear_attr = cell2attr(attr, fg, bg);
2552
2553 FOR_ALL_WINDOWS(wp)
2554 {
2555 if (wp->w_buffer == term->tl_buffer)
2556 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2557 }
2558}
2559
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002560 static int
2561handle_moverect(VTermRect dest, VTermRect src, void *user)
2562{
2563 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002564 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002565
2566 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002567 * redrawing the text. But avoid doing this multiple times, postpone until
2568 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002569 if (dest.start_col == src.start_col
2570 && dest.end_col == src.end_col
2571 && dest.start_row < src.start_row)
2572 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002573 if (dest.start_row == 0)
2574 term->tl_postponed_scroll += count;
2575 else
2576 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002577 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002578
2579 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2580 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002581 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002582
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002583 /* Note sure if the scrolling will work correctly, let's do a complete
2584 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002585 redraw_buf_later(term->tl_buffer, NOT_VALID);
2586 return 1;
2587}
2588
2589 static int
2590handle_movecursor(
2591 VTermPos pos,
2592 VTermPos oldpos UNUSED,
2593 int visible,
2594 void *user)
2595{
2596 term_T *term = (term_T *)user;
2597 win_T *wp;
2598
2599 term->tl_cursor_pos = pos;
2600 term->tl_cursor_visible = visible;
2601
2602 FOR_ALL_WINDOWS(wp)
2603 {
2604 if (wp->w_buffer == term->tl_buffer)
2605 position_cursor(wp, &pos);
2606 }
2607 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2608 {
2609 may_toggle_cursor(term);
2610 update_cursor(term, term->tl_cursor_visible);
2611 }
2612
2613 return 1;
2614}
2615
2616 static int
2617handle_settermprop(
2618 VTermProp prop,
2619 VTermValue *value,
2620 void *user)
2621{
2622 term_T *term = (term_T *)user;
2623
2624 switch (prop)
2625 {
2626 case VTERM_PROP_TITLE:
2627 vim_free(term->tl_title);
2628 /* a blank title isn't useful, make it empty, so that "running" is
2629 * displayed */
2630 if (*skipwhite((char_u *)value->string) == NUL)
2631 term->tl_title = NULL;
2632#ifdef WIN3264
2633 else if (!enc_utf8 && enc_codepage > 0)
2634 {
2635 WCHAR *ret = NULL;
2636 int length = 0;
2637
2638 MultiByteToWideChar_alloc(CP_UTF8, 0,
2639 (char*)value->string, (int)STRLEN(value->string),
2640 &ret, &length);
2641 if (ret != NULL)
2642 {
2643 WideCharToMultiByte_alloc(enc_codepage, 0,
2644 ret, length, (char**)&term->tl_title,
2645 &length, 0, 0);
2646 vim_free(ret);
2647 }
2648 }
2649#endif
2650 else
2651 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002652 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002653 if (term == curbuf->b_term)
2654 maketitle();
2655 break;
2656
2657 case VTERM_PROP_CURSORVISIBLE:
2658 term->tl_cursor_visible = value->boolean;
2659 may_toggle_cursor(term);
2660 out_flush();
2661 break;
2662
2663 case VTERM_PROP_CURSORBLINK:
2664 term->tl_cursor_blink = value->boolean;
2665 may_set_cursor_props(term);
2666 break;
2667
2668 case VTERM_PROP_CURSORSHAPE:
2669 term->tl_cursor_shape = value->number;
2670 may_set_cursor_props(term);
2671 break;
2672
2673 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002674 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002675 may_set_cursor_props(term);
2676 break;
2677
2678 case VTERM_PROP_ALTSCREEN:
2679 /* TODO: do anything else? */
2680 term->tl_using_altscreen = value->boolean;
2681 break;
2682
2683 default:
2684 break;
2685 }
2686 /* Always return 1, otherwise vterm doesn't store the value internally. */
2687 return 1;
2688}
2689
2690/*
2691 * The job running in the terminal resized the terminal.
2692 */
2693 static int
2694handle_resize(int rows, int cols, void *user)
2695{
2696 term_T *term = (term_T *)user;
2697 win_T *wp;
2698
2699 term->tl_rows = rows;
2700 term->tl_cols = cols;
2701 if (term->tl_vterm_size_changed)
2702 /* Size was set by vterm_set_size(), don't set the window size. */
2703 term->tl_vterm_size_changed = FALSE;
2704 else
2705 {
2706 FOR_ALL_WINDOWS(wp)
2707 {
2708 if (wp->w_buffer == term->tl_buffer)
2709 {
2710 win_setheight_win(rows, wp);
2711 win_setwidth_win(cols, wp);
2712 }
2713 }
2714 redraw_buf_later(term->tl_buffer, NOT_VALID);
2715 }
2716 return 1;
2717}
2718
2719/*
2720 * Handle a line that is pushed off the top of the screen.
2721 */
2722 static int
2723handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2724{
2725 term_T *term = (term_T *)user;
2726
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002727 /* First remove the lines that were appended before, the pushed line goes
2728 * above it. */
2729 cleanup_scrollback(term);
2730
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002731 /* If the number of lines that are stored goes over 'termscrollback' then
2732 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002733 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002734 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002735 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002736 int i;
2737
2738 curbuf = term->tl_buffer;
2739 for (i = 0; i < todo; ++i)
2740 {
2741 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2742 ml_delete(1, FALSE);
2743 }
2744 curbuf = curwin->w_buffer;
2745
2746 term->tl_scrollback.ga_len -= todo;
2747 mch_memmove(term->tl_scrollback.ga_data,
2748 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2749 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
Bram Moolenaar4d6cd292018-05-15 23:53:26 +02002750 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002751 }
2752
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002753 if (ga_grow(&term->tl_scrollback, 1) == OK)
2754 {
2755 cellattr_T *p = NULL;
2756 int len = 0;
2757 int i;
2758 int c;
2759 int col;
2760 sb_line_T *line;
2761 garray_T ga;
2762 cellattr_T fill_attr = term->tl_default_color;
2763
2764 /* do not store empty cells at the end */
2765 for (i = 0; i < cols; ++i)
2766 if (cells[i].chars[0] != 0)
2767 len = i + 1;
2768 else
2769 cell2cellattr(&cells[i], &fill_attr);
2770
2771 ga_init2(&ga, 1, 100);
2772 if (len > 0)
2773 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2774 if (p != NULL)
2775 {
2776 for (col = 0; col < len; col += cells[col].width)
2777 {
2778 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2779 {
2780 ga.ga_len = 0;
2781 break;
2782 }
2783 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2784 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2785 (char_u *)ga.ga_data + ga.ga_len);
2786 cell2cellattr(&cells[col], &p[col]);
2787 }
2788 }
2789 if (ga_grow(&ga, 1) == FAIL)
2790 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2791 else
2792 {
2793 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2794 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2795 }
2796 ga_clear(&ga);
2797
2798 line = (sb_line_T *)term->tl_scrollback.ga_data
2799 + term->tl_scrollback.ga_len;
2800 line->sb_cols = len;
2801 line->sb_cells = p;
2802 line->sb_fill_attr = fill_attr;
2803 ++term->tl_scrollback.ga_len;
2804 ++term->tl_scrollback_scrolled;
2805 }
2806 return 0; /* ignored */
2807}
2808
2809static VTermScreenCallbacks screen_callbacks = {
2810 handle_damage, /* damage */
2811 handle_moverect, /* moverect */
2812 handle_movecursor, /* movecursor */
2813 handle_settermprop, /* settermprop */
2814 NULL, /* bell */
2815 handle_resize, /* resize */
2816 handle_pushline, /* sb_pushline */
2817 NULL /* sb_popline */
2818};
2819
2820/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002821 * Do the work after the channel of a terminal was closed.
2822 * Must be called only when updating_screen is FALSE.
2823 * Returns TRUE when a buffer was closed (list of terminals may have changed).
2824 */
2825 static int
2826term_after_channel_closed(term_T *term)
2827{
2828 /* Unless in Terminal-Normal mode: clear the vterm. */
2829 if (!term->tl_normal_mode)
2830 {
2831 int fnum = term->tl_buffer->b_fnum;
2832
2833 cleanup_vterm(term);
2834
2835 if (term->tl_finish == TL_FINISH_CLOSE)
2836 {
2837 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002838 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002839
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002840 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002841 ch_log(NULL, "terminal job finished, closing window");
2842 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002843 // Avoid closing the window if we temporarily use it.
2844 if (do_set_w_closing)
2845 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002846 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002847 if (do_set_w_closing)
2848 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002849 aucmd_restbuf(&aco);
2850 return TRUE;
2851 }
2852 if (term->tl_finish == TL_FINISH_OPEN
2853 && term->tl_buffer->b_nwindows == 0)
2854 {
2855 char buf[50];
2856
2857 /* TODO: use term_opencmd */
2858 ch_log(NULL, "terminal job finished, opening window");
2859 vim_snprintf(buf, sizeof(buf),
2860 term->tl_opencmd == NULL
2861 ? "botright sbuf %d"
2862 : (char *)term->tl_opencmd, fnum);
2863 do_cmdline_cmd((char_u *)buf);
2864 }
2865 else
2866 ch_log(NULL, "terminal job finished");
2867 }
2868
2869 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2870 return FALSE;
2871}
2872
2873/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002874 * Called when a channel has been closed.
2875 * If this was a channel for a terminal window then finish it up.
2876 */
2877 void
2878term_channel_closed(channel_T *ch)
2879{
2880 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002881 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002882 int did_one = FALSE;
2883
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002884 for (term = first_term; term != NULL; term = next_term)
2885 {
2886 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002887 if (term->tl_job == ch->ch_job)
2888 {
2889 term->tl_channel_closed = TRUE;
2890 did_one = TRUE;
2891
Bram Moolenaard23a8232018-02-10 18:45:26 +01002892 VIM_CLEAR(term->tl_title);
2893 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002894#ifdef WIN3264
2895 if (term->tl_out_fd != NULL)
2896 {
2897 fclose(term->tl_out_fd);
2898 term->tl_out_fd = NULL;
2899 }
2900#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002901
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002902 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002903 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002904 /* Cannot open or close windows now. Can happen when
2905 * 'lazyredraw' is set. */
2906 term->tl_channel_recently_closed = TRUE;
2907 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002908 }
2909
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002910 if (term_after_channel_closed(term))
2911 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002912 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002913 }
2914
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002915 if (did_one)
2916 {
2917 redraw_statuslines();
2918
2919 /* Need to break out of vgetc(). */
2920 ins_char_typebuf(K_IGNORE);
2921 typebuf_was_filled = TRUE;
2922
2923 term = curbuf->b_term;
2924 if (term != NULL)
2925 {
2926 if (term->tl_job == ch->ch_job)
2927 maketitle();
2928 update_cursor(term, term->tl_cursor_visible);
2929 }
2930 }
2931}
2932
2933/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002934 * To be called after resetting updating_screen: handle any terminal where the
2935 * channel was closed.
2936 */
2937 void
2938term_check_channel_closed_recently()
2939{
2940 term_T *term;
2941 term_T *next_term;
2942
2943 for (term = first_term; term != NULL; term = next_term)
2944 {
2945 next_term = term->tl_next;
2946 if (term->tl_channel_recently_closed)
2947 {
2948 term->tl_channel_recently_closed = FALSE;
2949 if (term_after_channel_closed(term))
2950 // start over, the list may have changed
2951 next_term = first_term;
2952 }
2953 }
2954}
2955
2956/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002957 * Fill one screen line from a line of the terminal.
2958 * Advances "pos" to past the last column.
2959 */
2960 static void
2961term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2962{
2963 int off = screen_get_current_line_off();
2964
2965 for (pos->col = 0; pos->col < max_col; )
2966 {
2967 VTermScreenCell cell;
2968 int c;
2969
2970 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2971 vim_memset(&cell, 0, sizeof(cell));
2972
2973 c = cell.chars[0];
2974 if (c == NUL)
2975 {
2976 ScreenLines[off] = ' ';
2977 if (enc_utf8)
2978 ScreenLinesUC[off] = NUL;
2979 }
2980 else
2981 {
2982 if (enc_utf8)
2983 {
2984 int i;
2985
2986 /* composing chars */
2987 for (i = 0; i < Screen_mco
2988 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2989 {
2990 ScreenLinesC[i][off] = cell.chars[i + 1];
2991 if (cell.chars[i + 1] == 0)
2992 break;
2993 }
2994 if (c >= 0x80 || (Screen_mco > 0
2995 && ScreenLinesC[0][off] != 0))
2996 {
2997 ScreenLines[off] = ' ';
2998 ScreenLinesUC[off] = c;
2999 }
3000 else
3001 {
3002 ScreenLines[off] = c;
3003 ScreenLinesUC[off] = NUL;
3004 }
3005 }
3006#ifdef WIN3264
3007 else if (has_mbyte && c >= 0x80)
3008 {
3009 char_u mb[MB_MAXBYTES+1];
3010 WCHAR wc = c;
3011
3012 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3013 (char*)mb, 2, 0, 0) > 1)
3014 {
3015 ScreenLines[off] = mb[0];
3016 ScreenLines[off + 1] = mb[1];
3017 cell.width = mb_ptr2cells(mb);
3018 }
3019 else
3020 ScreenLines[off] = c;
3021 }
3022#endif
3023 else
3024 ScreenLines[off] = c;
3025 }
3026 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3027
3028 ++pos->col;
3029 ++off;
3030 if (cell.width == 2)
3031 {
3032 if (enc_utf8)
3033 ScreenLinesUC[off] = NUL;
3034
3035 /* don't set the second byte to NUL for a DBCS encoding, it
3036 * has been set above */
3037 if (enc_utf8 || !has_mbyte)
3038 ScreenLines[off] = NUL;
3039
3040 ++pos->col;
3041 ++off;
3042 }
3043 }
3044}
3045
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003046#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003047 static void
3048update_system_term(term_T *term)
3049{
3050 VTermPos pos;
3051 VTermScreen *screen;
3052
3053 if (term->tl_vterm == NULL)
3054 return;
3055 screen = vterm_obtain_screen(term->tl_vterm);
3056
3057 /* Scroll up to make more room for terminal lines if needed. */
3058 while (term->tl_toprow > 0
3059 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3060 {
3061 int save_p_more = p_more;
3062
3063 p_more = FALSE;
3064 msg_row = Rows - 1;
3065 msg_puts((char_u *)"\n");
3066 p_more = save_p_more;
3067 --term->tl_toprow;
3068 }
3069
3070 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3071 && pos.row < Rows; ++pos.row)
3072 {
3073 if (pos.row < term->tl_rows)
3074 {
3075 int max_col = MIN(Columns, term->tl_cols);
3076
3077 term_line2screenline(screen, &pos, max_col);
3078 }
3079 else
3080 pos.col = 0;
3081
3082 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
3083 }
3084
3085 term->tl_dirty_row_start = MAX_ROW;
3086 term->tl_dirty_row_end = 0;
3087 update_cursor(term, TRUE);
3088}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003089#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003090
3091/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003092 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3093 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003094 * Terminal-Normal mode.
3095 */
3096 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003097term_do_update_window(win_T *wp)
3098{
3099 term_T *term = wp->w_buffer->b_term;
3100
3101 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3102}
3103
3104/*
3105 * Called to update a window that contains an active terminal.
3106 */
3107 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003108term_update_window(win_T *wp)
3109{
3110 term_T *term = wp->w_buffer->b_term;
3111 VTerm *vterm;
3112 VTermScreen *screen;
3113 VTermState *state;
3114 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003115 int rows, cols;
3116 int newrows, newcols;
3117 int minsize;
3118 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003119
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003120 vterm = term->tl_vterm;
3121 screen = vterm_obtain_screen(vterm);
3122 state = vterm_obtain_state(vterm);
3123
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003124 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3125 * SOME_VALID only redraw what was marked dirty. */
3126 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003127 {
3128 term->tl_dirty_row_start = 0;
3129 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003130
3131 if (term->tl_postponed_scroll > 0
3132 && term->tl_postponed_scroll < term->tl_rows / 3)
3133 /* Scrolling is usually faster than redrawing, when there are only
3134 * a few lines to scroll. */
3135 term_scroll_up(term, 0, term->tl_postponed_scroll);
3136 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003137 }
3138
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003139 /*
3140 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003141 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003142 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003143 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003144
Bram Moolenaar498c2562018-04-15 23:45:15 +02003145 newrows = 99999;
3146 newcols = 99999;
3147 FOR_ALL_WINDOWS(twp)
3148 {
3149 /* When more than one window shows the same terminal, use the
3150 * smallest size. */
3151 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003152 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003153 newrows = MIN(newrows, twp->w_height);
3154 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003155 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003156 }
3157 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3158 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3159
3160 if (term->tl_rows != newrows || term->tl_cols != newcols)
3161 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003162 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003163 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003164 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003165 newrows);
3166 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003167
3168 // Updating the terminal size will cause the snapshot to be cleared.
3169 // When not in terminal_loop() we need to restore it.
3170 if (term != in_terminal_loop)
3171 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003172 }
3173
3174 /* The cursor may have been moved when resizing. */
3175 vterm_state_get_cursorpos(state, &pos);
3176 position_cursor(wp, &pos);
3177
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003178 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3179 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003180 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003181 if (pos.row < term->tl_rows)
3182 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003183 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003184
Bram Moolenaar13568252018-03-16 20:46:58 +01003185 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003186 }
3187 else
3188 pos.col = 0;
3189
Bram Moolenaarf118d482018-03-13 13:14:00 +01003190 screen_line(wp->w_winrow + pos.row
3191#ifdef FEAT_MENU
3192 + winbar_height(wp)
3193#endif
3194 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003195 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003196 term->tl_dirty_row_start = MAX_ROW;
3197 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003198}
3199
3200/*
3201 * Return TRUE if "wp" is a terminal window where the job has finished.
3202 */
3203 int
3204term_is_finished(buf_T *buf)
3205{
3206 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3207}
3208
3209/*
3210 * Return TRUE if "wp" is a terminal window where the job has finished or we
3211 * are in Terminal-Normal mode, thus we show the buffer contents.
3212 */
3213 int
3214term_show_buffer(buf_T *buf)
3215{
3216 term_T *term = buf->b_term;
3217
3218 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3219}
3220
3221/*
3222 * The current buffer is going to be changed. If there is terminal
3223 * highlighting remove it now.
3224 */
3225 void
3226term_change_in_curbuf(void)
3227{
3228 term_T *term = curbuf->b_term;
3229
3230 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3231 {
3232 free_scrollback(term);
3233 redraw_buf_later(term->tl_buffer, NOT_VALID);
3234
3235 /* The buffer is now like a normal buffer, it cannot be easily
3236 * abandoned when changed. */
3237 set_string_option_direct((char_u *)"buftype", -1,
3238 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3239 }
3240}
3241
3242/*
3243 * Get the screen attribute for a position in the buffer.
3244 * Use a negative "col" to get the filler background color.
3245 */
3246 int
3247term_get_attr(buf_T *buf, linenr_T lnum, int col)
3248{
3249 term_T *term = buf->b_term;
3250 sb_line_T *line;
3251 cellattr_T *cellattr;
3252
3253 if (lnum > term->tl_scrollback.ga_len)
3254 cellattr = &term->tl_default_color;
3255 else
3256 {
3257 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3258 if (col < 0 || col >= line->sb_cols)
3259 cellattr = &line->sb_fill_attr;
3260 else
3261 cellattr = line->sb_cells + col;
3262 }
3263 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3264}
3265
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003266/*
3267 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003268 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003269 */
3270 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003271cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003272{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003273 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003274}
3275
3276/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003277 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003278 */
3279 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003280init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003281{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003282 VTermColor *fg, *bg;
3283 int fgval, bgval;
3284 int id;
3285
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003286 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3287 term->tl_default_color.width = 1;
3288 fg = &term->tl_default_color.fg;
3289 bg = &term->tl_default_color.bg;
3290
3291 /* Vterm uses a default black background. Set it to white when
3292 * 'background' is "light". */
3293 if (*p_bg == 'l')
3294 {
3295 fgval = 0;
3296 bgval = 255;
3297 }
3298 else
3299 {
3300 fgval = 255;
3301 bgval = 0;
3302 }
3303 fg->red = fg->green = fg->blue = fgval;
3304 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003305 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003306
3307 /* The "Terminal" highlight group overrules the defaults. */
3308 id = syn_name2id((char_u *)"Terminal");
3309
Bram Moolenaar46359e12017-11-29 22:33:38 +01003310 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003311#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3312 if (0
3313# ifdef FEAT_GUI
3314 || gui.in_use
3315# endif
3316# ifdef FEAT_TERMGUICOLORS
3317 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003318# ifdef FEAT_VTP
3319 /* Finally get INVALCOLOR on this execution path */
3320 || (!p_tgc && t_colors >= 256)
3321# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003322# endif
3323 )
3324 {
3325 guicolor_T fg_rgb = INVALCOLOR;
3326 guicolor_T bg_rgb = INVALCOLOR;
3327
3328 if (id != 0)
3329 syn_id2colors(id, &fg_rgb, &bg_rgb);
3330
3331# ifdef FEAT_GUI
3332 if (gui.in_use)
3333 {
3334 if (fg_rgb == INVALCOLOR)
3335 fg_rgb = gui.norm_pixel;
3336 if (bg_rgb == INVALCOLOR)
3337 bg_rgb = gui.back_pixel;
3338 }
3339# ifdef FEAT_TERMGUICOLORS
3340 else
3341# endif
3342# endif
3343# ifdef FEAT_TERMGUICOLORS
3344 {
3345 if (fg_rgb == INVALCOLOR)
3346 fg_rgb = cterm_normal_fg_gui_color;
3347 if (bg_rgb == INVALCOLOR)
3348 bg_rgb = cterm_normal_bg_gui_color;
3349 }
3350# endif
3351 if (fg_rgb != INVALCOLOR)
3352 {
3353 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3354
3355 fg->red = (unsigned)(rgb >> 16);
3356 fg->green = (unsigned)(rgb >> 8) & 255;
3357 fg->blue = (unsigned)rgb & 255;
3358 }
3359 if (bg_rgb != INVALCOLOR)
3360 {
3361 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3362
3363 bg->red = (unsigned)(rgb >> 16);
3364 bg->green = (unsigned)(rgb >> 8) & 255;
3365 bg->blue = (unsigned)rgb & 255;
3366 }
3367 }
3368 else
3369#endif
3370 if (id != 0 && t_colors >= 16)
3371 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003372 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003373 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003374 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003375 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003376 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003377 else
3378 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003379#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003380 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003381#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003382
3383 /* In an MS-Windows console we know the normal colors. */
3384 if (cterm_normal_fg_color > 0)
3385 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003386 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003387# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003388 tmp = fg->red;
3389 fg->red = fg->blue;
3390 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003391# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003392 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003393# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003394 else
3395 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003396# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003397
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003398 if (cterm_normal_bg_color > 0)
3399 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003400 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003401# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003402 tmp = bg->red;
3403 bg->red = bg->blue;
3404 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003405# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003406 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003407# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003408 else
3409 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003410# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003411 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003412}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003413
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003414#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3415/*
3416 * Set the 16 ANSI colors from array of RGB values
3417 */
3418 static void
3419set_vterm_palette(VTerm *vterm, long_u *rgb)
3420{
3421 int index = 0;
3422 VTermState *state = vterm_obtain_state(vterm);
3423 for (; index < 16; index++)
3424 {
3425 VTermColor color;
3426 color.red = (unsigned)(rgb[index] >> 16);
3427 color.green = (unsigned)(rgb[index] >> 8) & 255;
3428 color.blue = (unsigned)rgb[index] & 255;
3429 vterm_state_set_palette_color(state, index, &color);
3430 }
3431}
3432
3433/*
3434 * Set the ANSI color palette from a list of colors
3435 */
3436 static int
3437set_ansi_colors_list(VTerm *vterm, list_T *list)
3438{
3439 int n = 0;
3440 long_u rgb[16];
3441 listitem_T *li = list->lv_first;
3442
3443 for (; li != NULL && n < 16; li = li->li_next, n++)
3444 {
3445 char_u *color_name;
3446 guicolor_T guicolor;
3447
3448 color_name = get_tv_string_chk(&li->li_tv);
3449 if (color_name == NULL)
3450 return FAIL;
3451
3452 guicolor = GUI_GET_COLOR(color_name);
3453 if (guicolor == INVALCOLOR)
3454 return FAIL;
3455
3456 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3457 }
3458
3459 if (n != 16 || li != NULL)
3460 return FAIL;
3461
3462 set_vterm_palette(vterm, rgb);
3463
3464 return OK;
3465}
3466
3467/*
3468 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3469 */
3470 static void
3471init_vterm_ansi_colors(VTerm *vterm)
3472{
3473 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3474
3475 if (var != NULL
3476 && (var->di_tv.v_type != VAR_LIST
3477 || var->di_tv.vval.v_list == NULL
3478 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3479 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3480}
3481#endif
3482
Bram Moolenaar52acb112018-03-18 19:20:22 +01003483/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003484 * Handles a "drop" command from the job in the terminal.
3485 * "item" is the file name, "item->li_next" may have options.
3486 */
3487 static void
3488handle_drop_command(listitem_T *item)
3489{
3490 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003491 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003492 int bufnr;
3493 win_T *wp;
3494 tabpage_T *tp;
3495 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003496 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003497
3498 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3499 FOR_ALL_TAB_WINDOWS(tp, wp)
3500 {
3501 if (wp->w_buffer->b_fnum == bufnr)
3502 {
3503 /* buffer is in a window already, go there */
3504 goto_tabpage_win(tp, wp);
3505 return;
3506 }
3507 }
3508
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003509 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003510
3511 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3512 && opt_item->li_tv.vval.v_dict != NULL)
3513 {
3514 dict_T *dict = opt_item->li_tv.vval.v_dict;
3515 char_u *p;
3516
3517 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3518 if (p == NULL)
3519 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3520 if (p != NULL)
3521 {
3522 if (check_ff_value(p) == FAIL)
3523 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3524 else
3525 ea.force_ff = *p;
3526 }
3527 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3528 if (p == NULL)
3529 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3530 if (p != NULL)
3531 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003532 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003533 if (ea.cmd != NULL)
3534 {
3535 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3536 ea.force_enc = 11;
3537 tofree = ea.cmd;
3538 }
3539 }
3540
3541 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3542 if (p != NULL)
3543 get_bad_opt(p, &ea);
3544
3545 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3546 ea.force_bin = FORCE_BIN;
3547 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3548 ea.force_bin = FORCE_BIN;
3549 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3550 ea.force_bin = FORCE_NOBIN;
3551 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3552 ea.force_bin = FORCE_NOBIN;
3553 }
3554
3555 /* open in new window, like ":split fname" */
3556 if (ea.cmd == NULL)
3557 ea.cmd = (char_u *)"split";
3558 ea.arg = fname;
3559 ea.cmdidx = CMD_split;
3560 ex_splitview(&ea);
3561
3562 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003563}
3564
3565/*
3566 * Handles a function call from the job running in a terminal.
3567 * "item" is the function name, "item->li_next" has the arguments.
3568 */
3569 static void
3570handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3571{
3572 char_u *func;
3573 typval_T argvars[2];
3574 typval_T rettv;
3575 int doesrange;
3576
3577 if (item->li_next == NULL)
3578 {
3579 ch_log(channel, "Missing function arguments for call");
3580 return;
3581 }
3582 func = get_tv_string(&item->li_tv);
3583
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003584 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003585 {
3586 ch_log(channel, "Invalid function name: %s", func);
3587 return;
3588 }
3589
3590 argvars[0].v_type = VAR_NUMBER;
3591 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3592 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003593 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003594 2, argvars, /* argv_func */ NULL,
3595 /* firstline */ 1, /* lastline */ 1,
3596 &doesrange, /* evaluate */ TRUE,
3597 /* partial */ NULL, /* selfdict */ NULL) == OK)
3598 {
3599 clear_tv(&rettv);
3600 ch_log(channel, "Function %s called", func);
3601 }
3602 else
3603 ch_log(channel, "Calling function %s failed", func);
3604}
3605
3606/*
3607 * Called by libvterm when it cannot recognize an OSC sequence.
3608 * We recognize a terminal API command.
3609 */
3610 static int
3611parse_osc(const char *command, size_t cmdlen, void *user)
3612{
3613 term_T *term = (term_T *)user;
3614 js_read_T reader;
3615 typval_T tv;
3616 channel_T *channel = term->tl_job == NULL ? NULL
3617 : term->tl_job->jv_channel;
3618
3619 /* We recognize only OSC 5 1 ; {command} */
3620 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3621 return 0; /* not handled */
3622
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003623 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003624 if (reader.js_buf == NULL)
3625 return 1;
3626 reader.js_fill = NULL;
3627 reader.js_used = 0;
3628 if (json_decode(&reader, &tv, 0) == OK
3629 && tv.v_type == VAR_LIST
3630 && tv.vval.v_list != NULL)
3631 {
3632 listitem_T *item = tv.vval.v_list->lv_first;
3633
3634 if (item == NULL)
3635 ch_log(channel, "Missing command");
3636 else
3637 {
3638 char_u *cmd = get_tv_string(&item->li_tv);
3639
Bram Moolenaara997b452018-04-17 23:24:06 +02003640 /* Make sure an invoked command doesn't delete the buffer (and the
3641 * terminal) under our fingers. */
3642 ++term->tl_buffer->b_locked;
3643
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003644 item = item->li_next;
3645 if (item == NULL)
3646 ch_log(channel, "Missing argument for %s", cmd);
3647 else if (STRCMP(cmd, "drop") == 0)
3648 handle_drop_command(item);
3649 else if (STRCMP(cmd, "call") == 0)
3650 handle_call_command(term, channel, item);
3651 else
3652 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003653 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003654 }
3655 }
3656 else
3657 ch_log(channel, "Invalid JSON received");
3658
3659 vim_free(reader.js_buf);
3660 clear_tv(&tv);
3661 return 1;
3662}
3663
3664static VTermParserCallbacks parser_fallbacks = {
3665 NULL, /* text */
3666 NULL, /* control */
3667 NULL, /* escape */
3668 NULL, /* csi */
3669 parse_osc, /* osc */
3670 NULL, /* dcs */
3671 NULL /* resize */
3672};
3673
3674/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003675 * Use Vim's allocation functions for vterm so profiling works.
3676 */
3677 static void *
3678vterm_malloc(size_t size, void *data UNUSED)
3679{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003680 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003681}
3682
3683 static void
3684vterm_memfree(void *ptr, void *data UNUSED)
3685{
3686 vim_free(ptr);
3687}
3688
3689static VTermAllocatorFunctions vterm_allocator = {
3690 &vterm_malloc,
3691 &vterm_memfree
3692};
3693
3694/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003695 * Create a new vterm and initialize it.
3696 */
3697 static void
3698create_vterm(term_T *term, int rows, int cols)
3699{
3700 VTerm *vterm;
3701 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003702 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003703 VTermValue value;
3704
Bram Moolenaar756ef112018-04-10 12:04:27 +02003705 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003706 term->tl_vterm = vterm;
3707 screen = vterm_obtain_screen(vterm);
3708 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3709 /* TODO: depends on 'encoding'. */
3710 vterm_set_utf8(vterm, 1);
3711
3712 init_default_colors(term);
3713
3714 vterm_state_set_default_colors(
3715 vterm_obtain_state(vterm),
3716 &term->tl_default_color.fg,
3717 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003718
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003719 if (t_colors >= 16)
3720 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3721
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003722 /* Required to initialize most things. */
3723 vterm_screen_reset(screen, 1 /* hard */);
3724
3725 /* Allow using alternate screen. */
3726 vterm_screen_enable_altscreen(screen, 1);
3727
3728 /* For unix do not use a blinking cursor. In an xterm this causes the
3729 * cursor to blink if it's blinking in the xterm.
3730 * For Windows we respect the system wide setting. */
3731#ifdef WIN3264
3732 if (GetCaretBlinkTime() == INFINITE)
3733 value.boolean = 0;
3734 else
3735 value.boolean = 1;
3736#else
3737 value.boolean = 0;
3738#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003739 state = vterm_obtain_state(vterm);
3740 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3741 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003742}
3743
3744/*
3745 * Return the text to show for the buffer name and status.
3746 */
3747 char_u *
3748term_get_status_text(term_T *term)
3749{
3750 if (term->tl_status_text == NULL)
3751 {
3752 char_u *txt;
3753 size_t len;
3754
3755 if (term->tl_normal_mode)
3756 {
3757 if (term_job_running(term))
3758 txt = (char_u *)_("Terminal");
3759 else
3760 txt = (char_u *)_("Terminal-finished");
3761 }
3762 else if (term->tl_title != NULL)
3763 txt = term->tl_title;
3764 else if (term_none_open(term))
3765 txt = (char_u *)_("active");
3766 else if (term_job_running(term))
3767 txt = (char_u *)_("running");
3768 else
3769 txt = (char_u *)_("finished");
3770 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3771 term->tl_status_text = alloc((int)len);
3772 if (term->tl_status_text != NULL)
3773 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3774 term->tl_buffer->b_fname, txt);
3775 }
3776 return term->tl_status_text;
3777}
3778
3779/*
3780 * Mark references in jobs of terminals.
3781 */
3782 int
3783set_ref_in_term(int copyID)
3784{
3785 int abort = FALSE;
3786 term_T *term;
3787 typval_T tv;
3788
3789 for (term = first_term; term != NULL; term = term->tl_next)
3790 if (term->tl_job != NULL)
3791 {
3792 tv.v_type = VAR_JOB;
3793 tv.vval.v_job = term->tl_job;
3794 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3795 }
3796 return abort;
3797}
3798
3799/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003800 * Cache "Terminal" highlight group colors.
3801 */
3802 void
3803set_terminal_default_colors(int cterm_fg, int cterm_bg)
3804{
3805 term_default_cterm_fg = cterm_fg - 1;
3806 term_default_cterm_bg = cterm_bg - 1;
3807}
3808
3809/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003810 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003811 * Returns NULL when the buffer is not for a terminal window and logs a message
3812 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003813 */
3814 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003815term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003816{
3817 buf_T *buf;
3818
3819 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3820 ++emsg_off;
3821 buf = get_buf_tv(&argvars[0], FALSE);
3822 --emsg_off;
3823 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003824 {
3825 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003826 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003827 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003828 return buf;
3829}
3830
Bram Moolenaard96ff162018-02-18 22:13:29 +01003831 static int
3832same_color(VTermColor *a, VTermColor *b)
3833{
3834 return a->red == b->red
3835 && a->green == b->green
3836 && a->blue == b->blue
3837 && a->ansi_index == b->ansi_index;
3838}
3839
3840 static void
3841dump_term_color(FILE *fd, VTermColor *color)
3842{
3843 fprintf(fd, "%02x%02x%02x%d",
3844 (int)color->red, (int)color->green, (int)color->blue,
3845 (int)color->ansi_index);
3846}
3847
3848/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003849 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003850 *
3851 * Each screen cell in full is:
3852 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3853 * {characters} is a space for an empty cell
3854 * For a double-width character "+" is changed to "*" and the next cell is
3855 * skipped.
3856 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3857 * when "&" use the same as the previous cell.
3858 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3859 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3860 * {color-idx} is a number from 0 to 255
3861 *
3862 * Screen cell with same width, attributes and color as the previous one:
3863 * |{characters}
3864 *
3865 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3866 *
3867 * Repeating the previous screen cell:
3868 * @{count}
3869 */
3870 void
3871f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3872{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003873 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003874 term_T *term;
3875 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003876 int max_height = 0;
3877 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003878 stat_T st;
3879 FILE *fd;
3880 VTermPos pos;
3881 VTermScreen *screen;
3882 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003883 VTermState *state;
3884 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003885
3886 if (check_restricted() || check_secure())
3887 return;
3888 if (buf == NULL)
3889 return;
3890 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02003891 if (term->tl_vterm == NULL)
3892 {
3893 EMSG(_("E958: Job already finished"));
3894 return;
3895 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003896
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003897 if (argvars[2].v_type != VAR_UNKNOWN)
3898 {
3899 dict_T *d;
3900
3901 if (argvars[2].v_type != VAR_DICT)
3902 {
3903 EMSG(_(e_dictreq));
3904 return;
3905 }
3906 d = argvars[2].vval.v_dict;
3907 if (d != NULL)
3908 {
3909 max_height = get_dict_number(d, (char_u *)"rows");
3910 max_width = get_dict_number(d, (char_u *)"columns");
3911 }
3912 }
3913
Bram Moolenaard96ff162018-02-18 22:13:29 +01003914 fname = get_tv_string_chk(&argvars[1]);
3915 if (fname == NULL)
3916 return;
3917 if (mch_stat((char *)fname, &st) >= 0)
3918 {
3919 EMSG2(_("E953: File exists: %s"), fname);
3920 return;
3921 }
3922
Bram Moolenaard96ff162018-02-18 22:13:29 +01003923 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3924 {
3925 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3926 return;
3927 }
3928
3929 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3930
3931 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003932 state = vterm_obtain_state(term->tl_vterm);
3933 vterm_state_get_cursorpos(state, &cursor_pos);
3934
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003935 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3936 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003937 {
3938 int repeat = 0;
3939
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003940 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3941 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003942 {
3943 VTermScreenCell cell;
3944 int same_attr;
3945 int same_chars = TRUE;
3946 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003947 int is_cursor_pos = (pos.col == cursor_pos.col
3948 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003949
3950 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3951 vim_memset(&cell, 0, sizeof(cell));
3952
3953 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3954 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003955 int c = cell.chars[i];
3956 int pc = prev_cell.chars[i];
3957
3958 /* For the first character NUL is the same as space. */
3959 if (i == 0)
3960 {
3961 c = (c == NUL) ? ' ' : c;
3962 pc = (pc == NUL) ? ' ' : pc;
3963 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02003964 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003965 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02003966 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003967 break;
3968 }
3969 same_attr = vtermAttr2hl(cell.attrs)
3970 == vtermAttr2hl(prev_cell.attrs)
3971 && same_color(&cell.fg, &prev_cell.fg)
3972 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003973 if (same_chars && cell.width == prev_cell.width && same_attr
3974 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003975 {
3976 ++repeat;
3977 }
3978 else
3979 {
3980 if (repeat > 0)
3981 {
3982 fprintf(fd, "@%d", repeat);
3983 repeat = 0;
3984 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003985 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003986
3987 if (cell.chars[0] == NUL)
3988 fputs(" ", fd);
3989 else
3990 {
3991 char_u charbuf[10];
3992 int len;
3993
3994 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3995 && cell.chars[i] != NUL; ++i)
3996 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003997 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003998 fwrite(charbuf, len, 1, fd);
3999 }
4000 }
4001
4002 /* When only the characters differ we don't write anything, the
4003 * following "|", "@" or NL will indicate using the same
4004 * attributes. */
4005 if (cell.width != prev_cell.width || !same_attr)
4006 {
4007 if (cell.width == 2)
4008 {
4009 fputs("*", fd);
4010 ++pos.col;
4011 }
4012 else
4013 fputs("+", fd);
4014
4015 if (same_attr)
4016 {
4017 fputs("&", fd);
4018 }
4019 else
4020 {
4021 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4022 if (same_color(&cell.fg, &prev_cell.fg))
4023 fputs("&", fd);
4024 else
4025 {
4026 fputs("#", fd);
4027 dump_term_color(fd, &cell.fg);
4028 }
4029 if (same_color(&cell.bg, &prev_cell.bg))
4030 fputs("&", fd);
4031 else
4032 {
4033 fputs("#", fd);
4034 dump_term_color(fd, &cell.bg);
4035 }
4036 }
4037 }
4038
4039 prev_cell = cell;
4040 }
4041 }
4042 if (repeat > 0)
4043 fprintf(fd, "@%d", repeat);
4044 fputs("\n", fd);
4045 }
4046
4047 fclose(fd);
4048}
4049
4050/*
4051 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4052 */
4053 static void
4054dump_is_corrupt(garray_T *gap)
4055{
4056 ga_concat(gap, (char_u *)"CORRUPT");
4057}
4058
4059 static void
4060append_cell(garray_T *gap, cellattr_T *cell)
4061{
4062 if (ga_grow(gap, 1) == OK)
4063 {
4064 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4065 ++gap->ga_len;
4066 }
4067}
4068
4069/*
4070 * Read the dump file from "fd" and append lines to the current buffer.
4071 * Return the cell width of the longest line.
4072 */
4073 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004074read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004075{
4076 int c;
4077 garray_T ga_text;
4078 garray_T ga_cell;
4079 char_u *prev_char = NULL;
4080 int attr = 0;
4081 cellattr_T cell;
4082 term_T *term = curbuf->b_term;
4083 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004084 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004085
4086 ga_init2(&ga_text, 1, 90);
4087 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4088 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004089 cursor_pos->row = -1;
4090 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004091
4092 c = fgetc(fd);
4093 for (;;)
4094 {
4095 if (c == EOF)
4096 break;
4097 if (c == '\n')
4098 {
4099 /* End of a line: append it to the buffer. */
4100 if (ga_text.ga_data == NULL)
4101 dump_is_corrupt(&ga_text);
4102 if (ga_grow(&term->tl_scrollback, 1) == OK)
4103 {
4104 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4105 + term->tl_scrollback.ga_len;
4106
4107 if (max_cells < ga_cell.ga_len)
4108 max_cells = ga_cell.ga_len;
4109 line->sb_cols = ga_cell.ga_len;
4110 line->sb_cells = ga_cell.ga_data;
4111 line->sb_fill_attr = term->tl_default_color;
4112 ++term->tl_scrollback.ga_len;
4113 ga_init(&ga_cell);
4114
4115 ga_append(&ga_text, NUL);
4116 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4117 ga_text.ga_len, FALSE);
4118 }
4119 else
4120 ga_clear(&ga_cell);
4121 ga_text.ga_len = 0;
4122
4123 c = fgetc(fd);
4124 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004125 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004126 {
4127 int prev_len = ga_text.ga_len;
4128
Bram Moolenaar9271d052018-02-25 21:39:46 +01004129 if (c == '>')
4130 {
4131 if (cursor_pos->row != -1)
4132 dump_is_corrupt(&ga_text); /* duplicate cursor */
4133 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4134 cursor_pos->col = ga_cell.ga_len;
4135 }
4136
Bram Moolenaard96ff162018-02-18 22:13:29 +01004137 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4138 c = fgetc(fd);
4139 if (c != EOF)
4140 ga_append(&ga_text, c);
4141 for (;;)
4142 {
4143 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004144 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004145 || c == EOF || c == '\n')
4146 break;
4147 ga_append(&ga_text, c);
4148 }
4149
4150 /* save the character for repeating it */
4151 vim_free(prev_char);
4152 if (ga_text.ga_data != NULL)
4153 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4154 ga_text.ga_len - prev_len);
4155
Bram Moolenaar9271d052018-02-25 21:39:46 +01004156 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004157 {
4158 /* use all attributes from previous cell */
4159 }
4160 else if (c == '+' || c == '*')
4161 {
4162 int is_bg;
4163
4164 cell.width = c == '+' ? 1 : 2;
4165
4166 c = fgetc(fd);
4167 if (c == '&')
4168 {
4169 /* use same attr as previous cell */
4170 c = fgetc(fd);
4171 }
4172 else if (isdigit(c))
4173 {
4174 /* get the decimal attribute */
4175 attr = 0;
4176 while (isdigit(c))
4177 {
4178 attr = attr * 10 + (c - '0');
4179 c = fgetc(fd);
4180 }
4181 hl2vtermAttr(attr, &cell);
4182 }
4183 else
4184 dump_is_corrupt(&ga_text);
4185
4186 /* is_bg == 0: fg, is_bg == 1: bg */
4187 for (is_bg = 0; is_bg <= 1; ++is_bg)
4188 {
4189 if (c == '&')
4190 {
4191 /* use same color as previous cell */
4192 c = fgetc(fd);
4193 }
4194 else if (c == '#')
4195 {
4196 int red, green, blue, index = 0;
4197
4198 c = fgetc(fd);
4199 red = hex2nr(c);
4200 c = fgetc(fd);
4201 red = (red << 4) + hex2nr(c);
4202 c = fgetc(fd);
4203 green = hex2nr(c);
4204 c = fgetc(fd);
4205 green = (green << 4) + hex2nr(c);
4206 c = fgetc(fd);
4207 blue = hex2nr(c);
4208 c = fgetc(fd);
4209 blue = (blue << 4) + hex2nr(c);
4210 c = fgetc(fd);
4211 if (!isdigit(c))
4212 dump_is_corrupt(&ga_text);
4213 while (isdigit(c))
4214 {
4215 index = index * 10 + (c - '0');
4216 c = fgetc(fd);
4217 }
4218
4219 if (is_bg)
4220 {
4221 cell.bg.red = red;
4222 cell.bg.green = green;
4223 cell.bg.blue = blue;
4224 cell.bg.ansi_index = index;
4225 }
4226 else
4227 {
4228 cell.fg.red = red;
4229 cell.fg.green = green;
4230 cell.fg.blue = blue;
4231 cell.fg.ansi_index = index;
4232 }
4233 }
4234 else
4235 dump_is_corrupt(&ga_text);
4236 }
4237 }
4238 else
4239 dump_is_corrupt(&ga_text);
4240
4241 append_cell(&ga_cell, &cell);
4242 }
4243 else if (c == '@')
4244 {
4245 if (prev_char == NULL)
4246 dump_is_corrupt(&ga_text);
4247 else
4248 {
4249 int count = 0;
4250
4251 /* repeat previous character, get the count */
4252 for (;;)
4253 {
4254 c = fgetc(fd);
4255 if (!isdigit(c))
4256 break;
4257 count = count * 10 + (c - '0');
4258 }
4259
4260 while (count-- > 0)
4261 {
4262 ga_concat(&ga_text, prev_char);
4263 append_cell(&ga_cell, &cell);
4264 }
4265 }
4266 }
4267 else
4268 {
4269 dump_is_corrupt(&ga_text);
4270 c = fgetc(fd);
4271 }
4272 }
4273
4274 if (ga_text.ga_len > 0)
4275 {
4276 /* trailing characters after last NL */
4277 dump_is_corrupt(&ga_text);
4278 ga_append(&ga_text, NUL);
4279 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4280 ga_text.ga_len, FALSE);
4281 }
4282
4283 ga_clear(&ga_text);
4284 vim_free(prev_char);
4285
4286 return max_cells;
4287}
4288
4289/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004290 * Return an allocated string with at least "text_width" "=" characters and
4291 * "fname" inserted in the middle.
4292 */
4293 static char_u *
4294get_separator(int text_width, char_u *fname)
4295{
4296 int width = MAX(text_width, curwin->w_width);
4297 char_u *textline;
4298 int fname_size;
4299 char_u *p = fname;
4300 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004301 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004302
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004303 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004304 if (textline == NULL)
4305 return NULL;
4306
4307 fname_size = vim_strsize(fname);
4308 if (fname_size < width - 8)
4309 {
4310 /* enough room, don't use the full window width */
4311 width = MAX(text_width, fname_size + 8);
4312 }
4313 else if (fname_size > width - 8)
4314 {
4315 /* full name doesn't fit, use only the tail */
4316 p = gettail(fname);
4317 fname_size = vim_strsize(p);
4318 }
4319 /* skip characters until the name fits */
4320 while (fname_size > width - 8)
4321 {
4322 p += (*mb_ptr2len)(p);
4323 fname_size = vim_strsize(p);
4324 }
4325
4326 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4327 textline[i] = '=';
4328 textline[i++] = ' ';
4329
4330 STRCPY(textline + i, p);
4331 off = STRLEN(textline);
4332 textline[off] = ' ';
4333 for (i = 1; i < (width - fname_size) / 2; ++i)
4334 textline[off + i] = '=';
4335 textline[off + i] = NUL;
4336
4337 return textline;
4338}
4339
4340/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004341 * Common for "term_dumpdiff()" and "term_dumpload()".
4342 */
4343 static void
4344term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4345{
4346 jobopt_T opt;
4347 buf_T *buf;
4348 char_u buf1[NUMBUFLEN];
4349 char_u buf2[NUMBUFLEN];
4350 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004351 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004352 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004353 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004354 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004355 char_u *textline = NULL;
4356
4357 /* First open the files. If this fails bail out. */
4358 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4359 if (do_diff)
4360 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4361 if (fname1 == NULL || (do_diff && fname2 == NULL))
4362 {
4363 EMSG(_(e_invarg));
4364 return;
4365 }
4366 fd1 = mch_fopen((char *)fname1, READBIN);
4367 if (fd1 == NULL)
4368 {
4369 EMSG2(_(e_notread), fname1);
4370 return;
4371 }
4372 if (do_diff)
4373 {
4374 fd2 = mch_fopen((char *)fname2, READBIN);
4375 if (fd2 == NULL)
4376 {
4377 fclose(fd1);
4378 EMSG2(_(e_notread), fname2);
4379 return;
4380 }
4381 }
4382
4383 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004384 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4385 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4386 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4387 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4388 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004389
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004390 if (opt.jo_term_name == NULL)
4391 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004392 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004393
Bram Moolenaarb571c632018-03-21 22:27:59 +01004394 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004395 if (fname_tofree != NULL)
4396 {
4397 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4398 opt.jo_term_name = fname_tofree;
4399 }
4400 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004401
Bram Moolenaar13568252018-03-16 20:46:58 +01004402 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004403 if (buf != NULL && buf->b_term != NULL)
4404 {
4405 int i;
4406 linenr_T bot_lnum;
4407 linenr_T lnum;
4408 term_T *term = buf->b_term;
4409 int width;
4410 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004411 VTermPos cursor_pos1;
4412 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004413
Bram Moolenaar52acb112018-03-18 19:20:22 +01004414 init_default_colors(term);
4415
Bram Moolenaard96ff162018-02-18 22:13:29 +01004416 rettv->vval.v_number = buf->b_fnum;
4417
4418 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004419 width = read_dump_file(fd1, &cursor_pos1);
4420
4421 /* position the cursor */
4422 if (cursor_pos1.row >= 0)
4423 {
4424 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4425 coladvance(cursor_pos1.col);
4426 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004427
4428 /* Delete the empty line that was in the empty buffer. */
4429 ml_delete(1, FALSE);
4430
4431 /* For term_dumpload() we are done here. */
4432 if (!do_diff)
4433 goto theend;
4434
4435 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4436
Bram Moolenaar4a696342018-04-05 18:45:26 +02004437 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004438 if (textline == NULL)
4439 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004440 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4441 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4442 vim_free(textline);
4443
4444 textline = get_separator(width, fname2);
4445 if (textline == NULL)
4446 goto theend;
4447 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4448 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004449 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004450
4451 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004452 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004453 if (width2 > width)
4454 {
4455 vim_free(textline);
4456 textline = alloc(width2 + 1);
4457 if (textline == NULL)
4458 goto theend;
4459 width = width2;
4460 textline[width] = NUL;
4461 }
4462 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4463
4464 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4465 {
4466 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4467 {
4468 /* bottom part has fewer rows, fill with "-" */
4469 for (i = 0; i < width; ++i)
4470 textline[i] = '-';
4471 }
4472 else
4473 {
4474 char_u *line1;
4475 char_u *line2;
4476 char_u *p1;
4477 char_u *p2;
4478 int col;
4479 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4480 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4481 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4482 ->sb_cells;
4483
4484 /* Make a copy, getting the second line will invalidate it. */
4485 line1 = vim_strsave(ml_get(lnum));
4486 if (line1 == NULL)
4487 break;
4488 p1 = line1;
4489
4490 line2 = ml_get(lnum + bot_lnum);
4491 p2 = line2;
4492 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4493 {
4494 int len1 = utfc_ptr2len(p1);
4495 int len2 = utfc_ptr2len(p2);
4496
4497 textline[col] = ' ';
4498 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004499 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004500 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004501 else if (lnum == cursor_pos1.row + 1
4502 && col == cursor_pos1.col
4503 && (cursor_pos1.row != cursor_pos2.row
4504 || cursor_pos1.col != cursor_pos2.col))
4505 /* cursor in first but not in second */
4506 textline[col] = '>';
4507 else if (lnum == cursor_pos2.row + 1
4508 && col == cursor_pos2.col
4509 && (cursor_pos1.row != cursor_pos2.row
4510 || cursor_pos1.col != cursor_pos2.col))
4511 /* cursor in second but not in first */
4512 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004513 else if (cellattr1 != NULL && cellattr2 != NULL)
4514 {
4515 if ((cellattr1 + col)->width
4516 != (cellattr2 + col)->width)
4517 textline[col] = 'w';
4518 else if (!same_color(&(cellattr1 + col)->fg,
4519 &(cellattr2 + col)->fg))
4520 textline[col] = 'f';
4521 else if (!same_color(&(cellattr1 + col)->bg,
4522 &(cellattr2 + col)->bg))
4523 textline[col] = 'b';
4524 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4525 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4526 textline[col] = 'a';
4527 }
4528 p1 += len1;
4529 p2 += len2;
4530 /* TODO: handle different width */
4531 }
4532 vim_free(line1);
4533
4534 while (col < width)
4535 {
4536 if (*p1 == NUL && *p2 == NUL)
4537 textline[col] = '?';
4538 else if (*p1 == NUL)
4539 {
4540 textline[col] = '+';
4541 p2 += utfc_ptr2len(p2);
4542 }
4543 else
4544 {
4545 textline[col] = '-';
4546 p1 += utfc_ptr2len(p1);
4547 }
4548 ++col;
4549 }
4550 }
4551 if (add_empty_scrollback(term, &term->tl_default_color,
4552 term->tl_top_diff_rows) == OK)
4553 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4554 ++bot_lnum;
4555 }
4556
4557 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4558 {
4559 /* bottom part has more rows, fill with "+" */
4560 for (i = 0; i < width; ++i)
4561 textline[i] = '+';
4562 if (add_empty_scrollback(term, &term->tl_default_color,
4563 term->tl_top_diff_rows) == OK)
4564 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4565 ++lnum;
4566 ++bot_lnum;
4567 }
4568
4569 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004570
4571 /* looks better without wrapping */
4572 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004573 }
4574
4575theend:
4576 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004577 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004578 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004579 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004580 fclose(fd2);
4581}
4582
4583/*
4584 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4585 * bottom files.
4586 * Return FAIL when this is not possible.
4587 */
4588 int
4589term_swap_diff()
4590{
4591 term_T *term = curbuf->b_term;
4592 linenr_T line_count;
4593 linenr_T top_rows;
4594 linenr_T bot_rows;
4595 linenr_T bot_start;
4596 linenr_T lnum;
4597 char_u *p;
4598 sb_line_T *sb_line;
4599
4600 if (term == NULL
4601 || !term_is_finished(curbuf)
4602 || term->tl_top_diff_rows == 0
4603 || term->tl_scrollback.ga_len == 0)
4604 return FAIL;
4605
4606 line_count = curbuf->b_ml.ml_line_count;
4607 top_rows = term->tl_top_diff_rows;
4608 bot_rows = term->tl_bot_diff_rows;
4609 bot_start = line_count - bot_rows;
4610 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4611
4612 /* move lines from top to above the bottom part */
4613 for (lnum = 1; lnum <= top_rows; ++lnum)
4614 {
4615 p = vim_strsave(ml_get(1));
4616 if (p == NULL)
4617 return OK;
4618 ml_append(bot_start, p, 0, FALSE);
4619 ml_delete(1, FALSE);
4620 vim_free(p);
4621 }
4622
4623 /* move lines from bottom to the top */
4624 for (lnum = 1; lnum <= bot_rows; ++lnum)
4625 {
4626 p = vim_strsave(ml_get(bot_start + lnum));
4627 if (p == NULL)
4628 return OK;
4629 ml_delete(bot_start + lnum, FALSE);
4630 ml_append(lnum - 1, p, 0, FALSE);
4631 vim_free(p);
4632 }
4633
4634 if (top_rows == bot_rows)
4635 {
4636 /* rows counts are equal, can swap cell properties */
4637 for (lnum = 0; lnum < top_rows; ++lnum)
4638 {
4639 sb_line_T temp;
4640
4641 temp = *(sb_line + lnum);
4642 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4643 *(sb_line + bot_start + lnum) = temp;
4644 }
4645 }
4646 else
4647 {
4648 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4649 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4650
4651 /* need to copy cell properties into temp memory */
4652 if (temp != NULL)
4653 {
4654 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4655 mch_memmove(term->tl_scrollback.ga_data,
4656 temp + bot_start,
4657 sizeof(sb_line_T) * bot_rows);
4658 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4659 temp + top_rows,
4660 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4661 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4662 + line_count - top_rows,
4663 temp,
4664 sizeof(sb_line_T) * top_rows);
4665 vim_free(temp);
4666 }
4667 }
4668
4669 term->tl_top_diff_rows = bot_rows;
4670 term->tl_bot_diff_rows = top_rows;
4671
4672 update_screen(NOT_VALID);
4673 return OK;
4674}
4675
4676/*
4677 * "term_dumpdiff(filename, filename, options)" function
4678 */
4679 void
4680f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4681{
4682 term_load_dump(argvars, rettv, TRUE);
4683}
4684
4685/*
4686 * "term_dumpload(filename, options)" function
4687 */
4688 void
4689f_term_dumpload(typval_T *argvars, typval_T *rettv)
4690{
4691 term_load_dump(argvars, rettv, FALSE);
4692}
4693
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004694/*
4695 * "term_getaltscreen(buf)" function
4696 */
4697 void
4698f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4699{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004700 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004701
4702 if (buf == NULL)
4703 return;
4704 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4705}
4706
4707/*
4708 * "term_getattr(attr, name)" function
4709 */
4710 void
4711f_term_getattr(typval_T *argvars, typval_T *rettv)
4712{
4713 int attr;
4714 size_t i;
4715 char_u *name;
4716
4717 static struct {
4718 char *name;
4719 int attr;
4720 } attrs[] = {
4721 {"bold", HL_BOLD},
4722 {"italic", HL_ITALIC},
4723 {"underline", HL_UNDERLINE},
4724 {"strike", HL_STRIKETHROUGH},
4725 {"reverse", HL_INVERSE},
4726 };
4727
4728 attr = get_tv_number(&argvars[0]);
4729 name = get_tv_string_chk(&argvars[1]);
4730 if (name == NULL)
4731 return;
4732
4733 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4734 if (STRCMP(name, attrs[i].name) == 0)
4735 {
4736 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4737 break;
4738 }
4739}
4740
4741/*
4742 * "term_getcursor(buf)" function
4743 */
4744 void
4745f_term_getcursor(typval_T *argvars, typval_T *rettv)
4746{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004747 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004748 term_T *term;
4749 list_T *l;
4750 dict_T *d;
4751
4752 if (rettv_list_alloc(rettv) == FAIL)
4753 return;
4754 if (buf == NULL)
4755 return;
4756 term = buf->b_term;
4757
4758 l = rettv->vval.v_list;
4759 list_append_number(l, term->tl_cursor_pos.row + 1);
4760 list_append_number(l, term->tl_cursor_pos.col + 1);
4761
4762 d = dict_alloc();
4763 if (d != NULL)
4764 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02004765 dict_add_number(d, "visible", term->tl_cursor_visible);
4766 dict_add_number(d, "blink", blink_state_is_inverted()
4767 ? !term->tl_cursor_blink : term->tl_cursor_blink);
4768 dict_add_number(d, "shape", term->tl_cursor_shape);
4769 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004770 list_append_dict(l, d);
4771 }
4772}
4773
4774/*
4775 * "term_getjob(buf)" function
4776 */
4777 void
4778f_term_getjob(typval_T *argvars, typval_T *rettv)
4779{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004780 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004781
4782 rettv->v_type = VAR_JOB;
4783 rettv->vval.v_job = NULL;
4784 if (buf == NULL)
4785 return;
4786
4787 rettv->vval.v_job = buf->b_term->tl_job;
4788 if (rettv->vval.v_job != NULL)
4789 ++rettv->vval.v_job->jv_refcount;
4790}
4791
4792 static int
4793get_row_number(typval_T *tv, term_T *term)
4794{
4795 if (tv->v_type == VAR_STRING
4796 && tv->vval.v_string != NULL
4797 && STRCMP(tv->vval.v_string, ".") == 0)
4798 return term->tl_cursor_pos.row;
4799 return (int)get_tv_number(tv) - 1;
4800}
4801
4802/*
4803 * "term_getline(buf, row)" function
4804 */
4805 void
4806f_term_getline(typval_T *argvars, typval_T *rettv)
4807{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004808 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004809 term_T *term;
4810 int row;
4811
4812 rettv->v_type = VAR_STRING;
4813 if (buf == NULL)
4814 return;
4815 term = buf->b_term;
4816 row = get_row_number(&argvars[1], term);
4817
4818 if (term->tl_vterm == NULL)
4819 {
4820 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4821
4822 /* vterm is finished, get the text from the buffer */
4823 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4824 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4825 }
4826 else
4827 {
4828 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4829 VTermRect rect;
4830 int len;
4831 char_u *p;
4832
4833 if (row < 0 || row >= term->tl_rows)
4834 return;
4835 len = term->tl_cols * MB_MAXBYTES + 1;
4836 p = alloc(len);
4837 if (p == NULL)
4838 return;
4839 rettv->vval.v_string = p;
4840
4841 rect.start_col = 0;
4842 rect.end_col = term->tl_cols;
4843 rect.start_row = row;
4844 rect.end_row = row + 1;
4845 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4846 }
4847}
4848
4849/*
4850 * "term_getscrolled(buf)" function
4851 */
4852 void
4853f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4854{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004855 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004856
4857 if (buf == NULL)
4858 return;
4859 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4860}
4861
4862/*
4863 * "term_getsize(buf)" function
4864 */
4865 void
4866f_term_getsize(typval_T *argvars, typval_T *rettv)
4867{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004868 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004869 list_T *l;
4870
4871 if (rettv_list_alloc(rettv) == FAIL)
4872 return;
4873 if (buf == NULL)
4874 return;
4875
4876 l = rettv->vval.v_list;
4877 list_append_number(l, buf->b_term->tl_rows);
4878 list_append_number(l, buf->b_term->tl_cols);
4879}
4880
4881/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004882 * "term_setsize(buf, rows, cols)" function
4883 */
4884 void
4885f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4886{
4887 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4888 term_T *term;
4889 varnumber_T rows, cols;
4890
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004891 if (buf == NULL)
4892 {
4893 EMSG(_("E955: Not a terminal buffer"));
4894 return;
4895 }
4896 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004897 return;
4898 term = buf->b_term;
4899 rows = get_tv_number(&argvars[1]);
4900 rows = rows <= 0 ? term->tl_rows : rows;
4901 cols = get_tv_number(&argvars[2]);
4902 cols = cols <= 0 ? term->tl_cols : cols;
4903 vterm_set_size(term->tl_vterm, rows, cols);
4904 /* handle_resize() will resize the windows */
4905
4906 /* Get and remember the size we ended up with. Update the pty. */
4907 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4908 term_report_winsize(term, term->tl_rows, term->tl_cols);
4909}
4910
4911/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004912 * "term_getstatus(buf)" function
4913 */
4914 void
4915f_term_getstatus(typval_T *argvars, typval_T *rettv)
4916{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004917 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004918 term_T *term;
4919 char_u val[100];
4920
4921 rettv->v_type = VAR_STRING;
4922 if (buf == NULL)
4923 return;
4924 term = buf->b_term;
4925
4926 if (term_job_running(term))
4927 STRCPY(val, "running");
4928 else
4929 STRCPY(val, "finished");
4930 if (term->tl_normal_mode)
4931 STRCAT(val, ",normal");
4932 rettv->vval.v_string = vim_strsave(val);
4933}
4934
4935/*
4936 * "term_gettitle(buf)" function
4937 */
4938 void
4939f_term_gettitle(typval_T *argvars, typval_T *rettv)
4940{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004941 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004942
4943 rettv->v_type = VAR_STRING;
4944 if (buf == NULL)
4945 return;
4946
4947 if (buf->b_term->tl_title != NULL)
4948 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4949}
4950
4951/*
4952 * "term_gettty(buf)" function
4953 */
4954 void
4955f_term_gettty(typval_T *argvars, typval_T *rettv)
4956{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004957 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02004958 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004959 int num = 0;
4960
4961 rettv->v_type = VAR_STRING;
4962 if (buf == NULL)
4963 return;
4964 if (argvars[1].v_type != VAR_UNKNOWN)
4965 num = get_tv_number(&argvars[1]);
4966
4967 switch (num)
4968 {
4969 case 0:
4970 if (buf->b_term->tl_job != NULL)
4971 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004972 break;
4973 case 1:
4974 if (buf->b_term->tl_job != NULL)
4975 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004976 break;
4977 default:
4978 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4979 return;
4980 }
4981 if (p != NULL)
4982 rettv->vval.v_string = vim_strsave(p);
4983}
4984
4985/*
4986 * "term_list()" function
4987 */
4988 void
4989f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4990{
4991 term_T *tp;
4992 list_T *l;
4993
4994 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4995 return;
4996
4997 l = rettv->vval.v_list;
4998 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4999 if (tp != NULL && tp->tl_buffer != NULL)
5000 if (list_append_number(l,
5001 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5002 return;
5003}
5004
5005/*
5006 * "term_scrape(buf, row)" function
5007 */
5008 void
5009f_term_scrape(typval_T *argvars, typval_T *rettv)
5010{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005011 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005012 VTermScreen *screen = NULL;
5013 VTermPos pos;
5014 list_T *l;
5015 term_T *term;
5016 char_u *p;
5017 sb_line_T *line;
5018
5019 if (rettv_list_alloc(rettv) == FAIL)
5020 return;
5021 if (buf == NULL)
5022 return;
5023 term = buf->b_term;
5024
5025 l = rettv->vval.v_list;
5026 pos.row = get_row_number(&argvars[1], term);
5027
5028 if (term->tl_vterm != NULL)
5029 {
5030 screen = vterm_obtain_screen(term->tl_vterm);
5031 p = NULL;
5032 line = NULL;
5033 }
5034 else
5035 {
5036 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5037
5038 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5039 return;
5040 p = ml_get_buf(buf, lnum + 1, FALSE);
5041 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5042 }
5043
5044 for (pos.col = 0; pos.col < term->tl_cols; )
5045 {
5046 dict_T *dcell;
5047 int width;
5048 VTermScreenCellAttrs attrs;
5049 VTermColor fg, bg;
5050 char_u rgb[8];
5051 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5052 int off = 0;
5053 int i;
5054
5055 if (screen == NULL)
5056 {
5057 cellattr_T *cellattr;
5058 int len;
5059
5060 /* vterm has finished, get the cell from scrollback */
5061 if (pos.col >= line->sb_cols)
5062 break;
5063 cellattr = line->sb_cells + pos.col;
5064 width = cellattr->width;
5065 attrs = cellattr->attrs;
5066 fg = cellattr->fg;
5067 bg = cellattr->bg;
5068 len = MB_PTR2LEN(p);
5069 mch_memmove(mbs, p, len);
5070 mbs[len] = NUL;
5071 p += len;
5072 }
5073 else
5074 {
5075 VTermScreenCell cell;
5076 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5077 break;
5078 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5079 {
5080 if (cell.chars[i] == 0)
5081 break;
5082 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5083 }
5084 mbs[off] = NUL;
5085 width = cell.width;
5086 attrs = cell.attrs;
5087 fg = cell.fg;
5088 bg = cell.bg;
5089 }
5090 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005091 if (dcell == NULL)
5092 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005093 list_append_dict(l, dcell);
5094
Bram Moolenaare0be1672018-07-08 16:50:37 +02005095 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005096
5097 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5098 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005099 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005100 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5101 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005102 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005103
Bram Moolenaare0be1672018-07-08 16:50:37 +02005104 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5105 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005106
5107 ++pos.col;
5108 if (width == 2)
5109 ++pos.col;
5110 }
5111}
5112
5113/*
5114 * "term_sendkeys(buf, keys)" function
5115 */
5116 void
5117f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5118{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005119 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005120 char_u *msg;
5121 term_T *term;
5122
5123 rettv->v_type = VAR_UNKNOWN;
5124 if (buf == NULL)
5125 return;
5126
5127 msg = get_tv_string_chk(&argvars[1]);
5128 if (msg == NULL)
5129 return;
5130 term = buf->b_term;
5131 if (term->tl_vterm == NULL)
5132 return;
5133
5134 while (*msg != NUL)
5135 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005136 int c;
5137
5138 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5139 {
5140 c = TO_SPECIAL(msg[1], msg[2]);
5141 msg += 3;
5142 }
5143 else
5144 {
5145 c = PTR2CHAR(msg);
5146 msg += MB_CPTR2LEN(msg);
5147 }
5148 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005149 }
5150}
5151
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005152#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5153/*
5154 * "term_getansicolors(buf)" function
5155 */
5156 void
5157f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5158{
5159 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5160 term_T *term;
5161 VTermState *state;
5162 VTermColor color;
5163 char_u hexbuf[10];
5164 int index;
5165 list_T *list;
5166
5167 if (rettv_list_alloc(rettv) == FAIL)
5168 return;
5169
5170 if (buf == NULL)
5171 return;
5172 term = buf->b_term;
5173 if (term->tl_vterm == NULL)
5174 return;
5175
5176 list = rettv->vval.v_list;
5177 state = vterm_obtain_state(term->tl_vterm);
5178 for (index = 0; index < 16; index++)
5179 {
5180 vterm_state_get_palette_color(state, index, &color);
5181 sprintf((char *)hexbuf, "#%02x%02x%02x",
5182 color.red, color.green, color.blue);
5183 if (list_append_string(list, hexbuf, 7) == FAIL)
5184 return;
5185 }
5186}
5187
5188/*
5189 * "term_setansicolors(buf, list)" function
5190 */
5191 void
5192f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5193{
5194 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5195 term_T *term;
5196
5197 if (buf == NULL)
5198 return;
5199 term = buf->b_term;
5200 if (term->tl_vterm == NULL)
5201 return;
5202
5203 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5204 {
5205 EMSG(_(e_listreq));
5206 return;
5207 }
5208
5209 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
5210 EMSG(_(e_invarg));
5211}
5212#endif
5213
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005214/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005215 * "term_setrestore(buf, command)" function
5216 */
5217 void
5218f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5219{
5220#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005221 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005222 term_T *term;
5223 char_u *cmd;
5224
5225 if (buf == NULL)
5226 return;
5227 term = buf->b_term;
5228 vim_free(term->tl_command);
5229 cmd = get_tv_string_chk(&argvars[1]);
5230 if (cmd != NULL)
5231 term->tl_command = vim_strsave(cmd);
5232 else
5233 term->tl_command = NULL;
5234#endif
5235}
5236
5237/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005238 * "term_setkill(buf, how)" function
5239 */
5240 void
5241f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5242{
5243 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5244 term_T *term;
5245 char_u *how;
5246
5247 if (buf == NULL)
5248 return;
5249 term = buf->b_term;
5250 vim_free(term->tl_kill);
5251 how = get_tv_string_chk(&argvars[1]);
5252 if (how != NULL)
5253 term->tl_kill = vim_strsave(how);
5254 else
5255 term->tl_kill = NULL;
5256}
5257
5258/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005259 * "term_start(command, options)" function
5260 */
5261 void
5262f_term_start(typval_T *argvars, typval_T *rettv)
5263{
5264 jobopt_T opt;
5265 buf_T *buf;
5266
5267 init_job_options(&opt);
5268 if (argvars[1].v_type != VAR_UNKNOWN
5269 && get_job_options(&argvars[1], &opt,
5270 JO_TIMEOUT_ALL + JO_STOPONEXIT
5271 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5272 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5273 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5274 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005275 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005276 + JO2_NORESTORE + JO2_TERM_KILL
5277 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005278 return;
5279
Bram Moolenaar13568252018-03-16 20:46:58 +01005280 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005281
5282 if (buf != NULL && buf->b_term != NULL)
5283 rettv->vval.v_number = buf->b_fnum;
5284}
5285
5286/*
5287 * "term_wait" function
5288 */
5289 void
5290f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5291{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005292 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005293
5294 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005295 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005296 if (buf->b_term->tl_job == NULL)
5297 {
5298 ch_log(NULL, "term_wait(): no job to wait for");
5299 return;
5300 }
5301 if (buf->b_term->tl_job->jv_channel == NULL)
5302 /* channel is closed, nothing to do */
5303 return;
5304
5305 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005306 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005307 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5308 {
5309 /* The job is dead, keep reading channel I/O until the channel is
5310 * closed. buf->b_term may become NULL if the terminal was closed while
5311 * waiting. */
5312 ch_log(NULL, "term_wait(): waiting for channel to close");
5313 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5314 {
5315 mch_check_messages();
5316 parse_queued_messages();
Bram Moolenaard45aa552018-05-21 22:50:29 +02005317 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005318 if (!buf_valid(buf))
5319 /* If the terminal is closed when the channel is closed the
5320 * buffer disappears. */
5321 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005322 }
5323 mch_check_messages();
5324 parse_queued_messages();
5325 }
5326 else
5327 {
5328 long wait = 10L;
5329
5330 mch_check_messages();
5331 parse_queued_messages();
5332
5333 /* Wait for some time for any channel I/O. */
5334 if (argvars[1].v_type != VAR_UNKNOWN)
5335 wait = get_tv_number(&argvars[1]);
5336 ui_delay(wait, TRUE);
5337 mch_check_messages();
5338
5339 /* Flushing messages on channels is hopefully sufficient.
5340 * TODO: is there a better way? */
5341 parse_queued_messages();
5342 }
5343}
5344
5345/*
5346 * Called when a channel has sent all the lines to a terminal.
5347 * Send a CTRL-D to mark the end of the text.
5348 */
5349 void
5350term_send_eof(channel_T *ch)
5351{
5352 term_T *term;
5353
5354 for (term = first_term; term != NULL; term = term->tl_next)
5355 if (term->tl_job == ch->ch_job)
5356 {
5357 if (term->tl_eof_chars != NULL)
5358 {
5359 channel_send(ch, PART_IN, term->tl_eof_chars,
5360 (int)STRLEN(term->tl_eof_chars), NULL);
5361 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5362 }
5363# ifdef WIN3264
5364 else
5365 /* Default: CTRL-D */
5366 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5367# endif
5368 }
5369}
5370
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005371 job_T *
5372term_getjob(term_T *term)
5373{
5374 return term != NULL ? term->tl_job : NULL;
5375}
5376
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005377# if defined(WIN3264) || defined(PROTO)
5378
5379/**************************************
5380 * 2. MS-Windows implementation.
5381 */
5382
5383# ifndef PROTO
5384
5385#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5386#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005387#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005388
5389void* (*winpty_config_new)(UINT64, void*);
5390void* (*winpty_open)(void*, void*);
5391void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5392BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5393void (*winpty_config_set_mouse_mode)(void*, int);
5394void (*winpty_config_set_initial_size)(void*, int, int);
5395LPCWSTR (*winpty_conin_name)(void*);
5396LPCWSTR (*winpty_conout_name)(void*);
5397LPCWSTR (*winpty_conerr_name)(void*);
5398void (*winpty_free)(void*);
5399void (*winpty_config_free)(void*);
5400void (*winpty_spawn_config_free)(void*);
5401void (*winpty_error_free)(void*);
5402LPCWSTR (*winpty_error_msg)(void*);
5403BOOL (*winpty_set_size)(void*, int, int, void*);
5404HANDLE (*winpty_agent_process)(void*);
5405
5406#define WINPTY_DLL "winpty.dll"
5407
5408static HINSTANCE hWinPtyDLL = NULL;
5409# endif
5410
5411 static int
5412dyn_winpty_init(int verbose)
5413{
5414 int i;
5415 static struct
5416 {
5417 char *name;
5418 FARPROC *ptr;
5419 } winpty_entry[] =
5420 {
5421 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5422 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5423 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5424 {"winpty_config_set_mouse_mode",
5425 (FARPROC*)&winpty_config_set_mouse_mode},
5426 {"winpty_config_set_initial_size",
5427 (FARPROC*)&winpty_config_set_initial_size},
5428 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5429 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5430 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5431 {"winpty_free", (FARPROC*)&winpty_free},
5432 {"winpty_open", (FARPROC*)&winpty_open},
5433 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5434 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5435 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5436 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5437 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5438 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5439 {NULL, NULL}
5440 };
5441
5442 /* No need to initialize twice. */
5443 if (hWinPtyDLL)
5444 return OK;
5445 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5446 * winpty.dll. */
5447 if (*p_winptydll != NUL)
5448 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5449 if (!hWinPtyDLL)
5450 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5451 if (!hWinPtyDLL)
5452 {
5453 if (verbose)
5454 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5455 : (char_u *)WINPTY_DLL);
5456 return FAIL;
5457 }
5458 for (i = 0; winpty_entry[i].name != NULL
5459 && winpty_entry[i].ptr != NULL; ++i)
5460 {
5461 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5462 winpty_entry[i].name)) == NULL)
5463 {
5464 if (verbose)
5465 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5466 return FAIL;
5467 }
5468 }
5469
5470 return OK;
5471}
5472
5473/*
5474 * Create a new terminal of "rows" by "cols" cells.
5475 * Store a reference in "term".
5476 * Return OK or FAIL.
5477 */
5478 static int
5479term_and_job_init(
5480 term_T *term,
5481 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005482 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005483 jobopt_T *opt,
5484 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005485{
5486 WCHAR *cmd_wchar = NULL;
5487 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005488 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005489 channel_T *channel = NULL;
5490 job_T *job = NULL;
5491 DWORD error;
5492 HANDLE jo = NULL;
5493 HANDLE child_process_handle;
5494 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005495 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005496 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005497 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005498 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005499
5500 if (dyn_winpty_init(TRUE) == FAIL)
5501 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005502 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5503 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005504
5505 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005506 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005507 cmd = argvar->vval.v_string;
5508 }
5509 else if (argvar->v_type == VAR_LIST)
5510 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005511 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005512 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005513 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005514 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005515 if (cmd == NULL || *cmd == NUL)
5516 {
5517 EMSG(_(e_invarg));
5518 goto failed;
5519 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005520
5521 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005522 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005523 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005524 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005525 if (opt->jo_cwd != NULL)
5526 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005527
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005528 win32_build_env(opt->jo_env, &ga_env, TRUE);
5529 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005530
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005531 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5532 if (term->tl_winpty_config == NULL)
5533 goto failed;
5534
5535 winpty_config_set_mouse_mode(term->tl_winpty_config,
5536 WINPTY_MOUSE_MODE_FORCE);
5537 winpty_config_set_initial_size(term->tl_winpty_config,
5538 term->tl_cols, term->tl_rows);
5539 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5540 if (term->tl_winpty == NULL)
5541 goto failed;
5542
5543 spawn_config = winpty_spawn_config_new(
5544 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5545 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5546 NULL,
5547 cmd_wchar,
5548 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005549 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005550 &winpty_err);
5551 if (spawn_config == NULL)
5552 goto failed;
5553
5554 channel = add_channel();
5555 if (channel == NULL)
5556 goto failed;
5557
5558 job = job_alloc();
5559 if (job == NULL)
5560 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005561 if (argvar->v_type == VAR_STRING)
5562 {
5563 int argc;
5564
5565 build_argv_from_string(cmd, &job->jv_argv, &argc);
5566 }
5567 else
5568 {
5569 int argc;
5570
5571 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5572 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005573
5574 if (opt->jo_set & JO_IN_BUF)
5575 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5576
5577 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5578 &child_thread_handle, &error, &winpty_err))
5579 goto failed;
5580
5581 channel_set_pipes(channel,
5582 (sock_T)CreateFileW(
5583 winpty_conin_name(term->tl_winpty),
5584 GENERIC_WRITE, 0, NULL,
5585 OPEN_EXISTING, 0, NULL),
5586 (sock_T)CreateFileW(
5587 winpty_conout_name(term->tl_winpty),
5588 GENERIC_READ, 0, NULL,
5589 OPEN_EXISTING, 0, NULL),
5590 (sock_T)CreateFileW(
5591 winpty_conerr_name(term->tl_winpty),
5592 GENERIC_READ, 0, NULL,
5593 OPEN_EXISTING, 0, NULL));
5594
5595 /* Write lines with CR instead of NL. */
5596 channel->ch_write_text_mode = TRUE;
5597
5598 jo = CreateJobObject(NULL, NULL);
5599 if (jo == NULL)
5600 goto failed;
5601
5602 if (!AssignProcessToJobObject(jo, child_process_handle))
5603 {
5604 /* Failed, switch the way to terminate process with TerminateProcess. */
5605 CloseHandle(jo);
5606 jo = NULL;
5607 }
5608
5609 winpty_spawn_config_free(spawn_config);
5610 vim_free(cmd_wchar);
5611 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005612 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005613
5614 create_vterm(term, term->tl_rows, term->tl_cols);
5615
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005616#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5617 if (opt->jo_set2 & JO2_ANSI_COLORS)
5618 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5619 else
5620 init_vterm_ansi_colors(term->tl_vterm);
5621#endif
5622
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005623 channel_set_job(channel, job, opt);
5624 job_set_options(job, opt);
5625
5626 job->jv_channel = channel;
5627 job->jv_proc_info.hProcess = child_process_handle;
5628 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5629 job->jv_job_object = jo;
5630 job->jv_status = JOB_STARTED;
5631 job->jv_tty_in = utf16_to_enc(
5632 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5633 job->jv_tty_out = utf16_to_enc(
5634 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5635 ++job->jv_refcount;
5636 term->tl_job = job;
5637
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005638 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5639 * open the file here and handle it in. opt->jo_io was changed in
5640 * setup_job_options(), use the original flags here. */
5641 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5642 {
5643 char_u *fname = opt->jo_io_name[PART_OUT];
5644
5645 ch_log(channel, "Opening output file %s", fname);
5646 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5647 if (term->tl_out_fd == NULL)
5648 EMSG2(_(e_notopen), fname);
5649 }
5650
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005651 return OK;
5652
5653failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005654 ga_clear(&ga_cmd);
5655 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005656 vim_free(cmd_wchar);
5657 vim_free(cwd_wchar);
5658 if (spawn_config != NULL)
5659 winpty_spawn_config_free(spawn_config);
5660 if (channel != NULL)
5661 channel_clear(channel);
5662 if (job != NULL)
5663 {
5664 job->jv_channel = NULL;
5665 job_cleanup(job);
5666 }
5667 term->tl_job = NULL;
5668 if (jo != NULL)
5669 CloseHandle(jo);
5670 if (term->tl_winpty != NULL)
5671 winpty_free(term->tl_winpty);
5672 term->tl_winpty = NULL;
5673 if (term->tl_winpty_config != NULL)
5674 winpty_config_free(term->tl_winpty_config);
5675 term->tl_winpty_config = NULL;
5676 if (winpty_err != NULL)
5677 {
5678 char_u *msg = utf16_to_enc(
5679 (short_u *)winpty_error_msg(winpty_err), NULL);
5680
5681 EMSG(msg);
5682 winpty_error_free(winpty_err);
5683 }
5684 return FAIL;
5685}
5686
5687 static int
5688create_pty_only(term_T *term, jobopt_T *options)
5689{
5690 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5691 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5692 char in_name[80], out_name[80];
5693 channel_T *channel = NULL;
5694
5695 create_vterm(term, term->tl_rows, term->tl_cols);
5696
5697 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5698 GetCurrentProcessId(),
5699 curbuf->b_fnum);
5700 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5701 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5702 PIPE_UNLIMITED_INSTANCES,
5703 0, 0, NMPWAIT_NOWAIT, NULL);
5704 if (hPipeIn == INVALID_HANDLE_VALUE)
5705 goto failed;
5706
5707 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5708 GetCurrentProcessId(),
5709 curbuf->b_fnum);
5710 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5711 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5712 PIPE_UNLIMITED_INSTANCES,
5713 0, 0, 0, NULL);
5714 if (hPipeOut == INVALID_HANDLE_VALUE)
5715 goto failed;
5716
5717 ConnectNamedPipe(hPipeIn, NULL);
5718 ConnectNamedPipe(hPipeOut, NULL);
5719
5720 term->tl_job = job_alloc();
5721 if (term->tl_job == NULL)
5722 goto failed;
5723 ++term->tl_job->jv_refcount;
5724
5725 /* behave like the job is already finished */
5726 term->tl_job->jv_status = JOB_FINISHED;
5727
5728 channel = add_channel();
5729 if (channel == NULL)
5730 goto failed;
5731 term->tl_job->jv_channel = channel;
5732 channel->ch_keep_open = TRUE;
5733 channel->ch_named_pipe = TRUE;
5734
5735 channel_set_pipes(channel,
5736 (sock_T)hPipeIn,
5737 (sock_T)hPipeOut,
5738 (sock_T)hPipeOut);
5739 channel_set_job(channel, term->tl_job, options);
5740 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5741 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5742
5743 return OK;
5744
5745failed:
5746 if (hPipeIn != NULL)
5747 CloseHandle(hPipeIn);
5748 if (hPipeOut != NULL)
5749 CloseHandle(hPipeOut);
5750 return FAIL;
5751}
5752
5753/*
5754 * Free the terminal emulator part of "term".
5755 */
5756 static void
5757term_free_vterm(term_T *term)
5758{
5759 if (term->tl_winpty != NULL)
5760 winpty_free(term->tl_winpty);
5761 term->tl_winpty = NULL;
5762 if (term->tl_winpty_config != NULL)
5763 winpty_config_free(term->tl_winpty_config);
5764 term->tl_winpty_config = NULL;
5765 if (term->tl_vterm != NULL)
5766 vterm_free(term->tl_vterm);
5767 term->tl_vterm = NULL;
5768}
5769
5770/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005771 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005772 */
5773 static void
5774term_report_winsize(term_T *term, int rows, int cols)
5775{
5776 if (term->tl_winpty)
5777 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5778}
5779
5780 int
5781terminal_enabled(void)
5782{
5783 return dyn_winpty_init(FALSE) == OK;
5784}
5785
5786# else
5787
5788/**************************************
5789 * 3. Unix-like implementation.
5790 */
5791
5792/*
5793 * Create a new terminal of "rows" by "cols" cells.
5794 * Start job for "cmd".
5795 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005796 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005797 * Return OK or FAIL.
5798 */
5799 static int
5800term_and_job_init(
5801 term_T *term,
5802 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005803 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005804 jobopt_T *opt,
5805 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005806{
5807 create_vterm(term, term->tl_rows, term->tl_cols);
5808
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005809#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5810 if (opt->jo_set2 & JO2_ANSI_COLORS)
5811 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5812 else
5813 init_vterm_ansi_colors(term->tl_vterm);
5814#endif
5815
Bram Moolenaar13568252018-03-16 20:46:58 +01005816 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02005817 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005818 if (term->tl_job != NULL)
5819 ++term->tl_job->jv_refcount;
5820
5821 return term->tl_job != NULL
5822 && term->tl_job->jv_channel != NULL
5823 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5824}
5825
5826 static int
5827create_pty_only(term_T *term, jobopt_T *opt)
5828{
5829 create_vterm(term, term->tl_rows, term->tl_cols);
5830
5831 term->tl_job = job_alloc();
5832 if (term->tl_job == NULL)
5833 return FAIL;
5834 ++term->tl_job->jv_refcount;
5835
5836 /* behave like the job is already finished */
5837 term->tl_job->jv_status = JOB_FINISHED;
5838
5839 return mch_create_pty_channel(term->tl_job, opt);
5840}
5841
5842/*
5843 * Free the terminal emulator part of "term".
5844 */
5845 static void
5846term_free_vterm(term_T *term)
5847{
5848 if (term->tl_vterm != NULL)
5849 vterm_free(term->tl_vterm);
5850 term->tl_vterm = NULL;
5851}
5852
5853/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005854 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005855 */
5856 static void
5857term_report_winsize(term_T *term, int rows, int cols)
5858{
5859 /* Use an ioctl() to report the new window size to the job. */
5860 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5861 {
5862 int fd = -1;
5863 int part;
5864
5865 for (part = PART_OUT; part < PART_COUNT; ++part)
5866 {
5867 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5868 if (isatty(fd))
5869 break;
5870 }
5871 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5872 mch_signal_job(term->tl_job, (char_u *)"winch");
5873 }
5874}
5875
5876# endif
5877
5878#endif /* FEAT_TERMINAL */