blob: dea902f3a4bada53d5aa73e0e64b092ae6d70a98 [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 Moolenaar4f7fd562018-05-21 14:55:28 +0200186 static void
187cursor_color_copy(char_u** to_color, char_u* from_color)
188{
189 vim_free(*to_color);
190 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
191}
192
193 static int
194cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
195{
196 if (lhs_color != NULL && rhs_color != NULL)
197 return STRCMP(lhs_color, rhs_color) == 0;
198 return lhs_color == NULL && rhs_color == NULL;
199}
200
201 static char_u *
202cursor_color_get(char_u *color)
203{
204 return (color == NULL) ? (char_u *)"" : color;
205}
206
207
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200208/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200209 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200210 * current window.
211 * Sets "rows" and/or "cols" to zero when it should follow the window size.
212 * Return TRUE if the size is the minimum size: "24*80".
213 */
214 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200215parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200216{
217 int minsize = FALSE;
218
219 *rows = 0;
220 *cols = 0;
221
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200222 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200223 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200224 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200225
226 /* Syntax of value was already checked when it's set. */
227 if (p == NULL)
228 {
229 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200230 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200231 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200232 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200233 *cols = atoi((char *)p + 1);
234 }
235 return minsize;
236}
237
238/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200239 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200240 */
241 static void
242set_term_and_win_size(term_T *term)
243{
Bram Moolenaar13568252018-03-16 20:46:58 +0100244#ifdef FEAT_GUI
245 if (term->tl_system)
246 {
247 /* Use the whole screen for the system command. However, it will start
248 * at the command line and scroll up as needed, using tl_toprow. */
249 term->tl_rows = Rows;
250 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200251 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100252 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100253#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200254 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200255 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200256 if (term->tl_rows != 0)
257 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
258 if (term->tl_cols != 0)
259 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200260 }
261 if (term->tl_rows == 0)
262 term->tl_rows = curwin->w_height;
263 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200264 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200265 if (term->tl_cols == 0)
266 term->tl_cols = curwin->w_width;
267 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200268 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200269}
270
271/*
272 * Initialize job options for a terminal job.
273 * Caller may overrule some of them.
274 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100275 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200276init_job_options(jobopt_T *opt)
277{
278 clear_job_options(opt);
279
280 opt->jo_mode = MODE_RAW;
281 opt->jo_out_mode = MODE_RAW;
282 opt->jo_err_mode = MODE_RAW;
283 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
284}
285
286/*
287 * Set job options mandatory for a terminal job.
288 */
289 static void
290setup_job_options(jobopt_T *opt, int rows, int cols)
291{
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200292#ifndef WIN3264
293 /* Win32: Redirecting the job output won't work, thus always connect stdout
294 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200295 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200296#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200297 {
298 /* Connect stdout to the terminal. */
299 opt->jo_io[PART_OUT] = JIO_BUFFER;
300 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
301 opt->jo_modifiable[PART_OUT] = 0;
302 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
303 }
304
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200305#ifndef WIN3264
306 /* Win32: Redirecting the job output won't work, thus always connect stderr
307 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200308 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200309#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200310 {
311 /* Connect stderr to the terminal. */
312 opt->jo_io[PART_ERR] = JIO_BUFFER;
313 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
314 opt->jo_modifiable[PART_ERR] = 0;
315 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
316 }
317
318 opt->jo_pty = TRUE;
319 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
320 opt->jo_term_rows = rows;
321 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
322 opt->jo_term_cols = cols;
323}
324
325/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100326 * Close a terminal buffer (and its window). Used when creating the terminal
327 * fails.
328 */
329 static void
330term_close_buffer(buf_T *buf, buf_T *old_curbuf)
331{
332 free_terminal(buf);
333 if (old_curbuf != NULL)
334 {
335 --curbuf->b_nwindows;
336 curbuf = old_curbuf;
337 curwin->w_buffer = curbuf;
338 ++curbuf->b_nwindows;
339 }
340
341 /* Wiping out the buffer will also close the window and call
342 * free_terminal(). */
343 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
344}
345
346/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200347 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100348 * Use either "argvar" or "argv", the other must be NULL.
349 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
350 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200351 * Returns NULL when failed.
352 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100353 buf_T *
354term_start(
355 typval_T *argvar,
356 char **argv,
357 jobopt_T *opt,
358 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200359{
360 exarg_T split_ea;
361 win_T *old_curwin = curwin;
362 term_T *term;
363 buf_T *old_curbuf = NULL;
364 int res;
365 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100366 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200367 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200368
369 if (check_restricted() || check_secure())
370 return NULL;
371
372 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
373 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
374 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
375 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
376 {
377 EMSG(_(e_invarg));
378 return NULL;
379 }
380
381 term = (term_T *)alloc_clear(sizeof(term_T));
382 if (term == NULL)
383 return NULL;
384 term->tl_dirty_row_end = MAX_ROW;
385 term->tl_cursor_visible = TRUE;
386 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
387 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100388#ifdef FEAT_GUI
389 term->tl_system = (flags & TERM_START_SYSTEM);
390#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200391 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
392
393 vim_memset(&split_ea, 0, sizeof(split_ea));
394 if (opt->jo_curwin)
395 {
396 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100397 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200398 {
399 no_write_message();
400 vim_free(term);
401 return NULL;
402 }
403 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100404 ECMD_HIDE
405 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
406 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200407 {
408 vim_free(term);
409 return NULL;
410 }
411 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100412 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200413 {
414 buf_T *buf;
415
416 /* Create a new buffer without a window. Make it the current buffer for
417 * a moment to be able to do the initialisations. */
418 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
419 BLN_NEW | BLN_LISTED);
420 if (buf == NULL || ml_open(buf) == FAIL)
421 {
422 vim_free(term);
423 return NULL;
424 }
425 old_curbuf = curbuf;
426 --curbuf->b_nwindows;
427 curbuf = buf;
428 curwin->w_buffer = buf;
429 ++curbuf->b_nwindows;
430 }
431 else
432 {
433 /* Open a new window or tab. */
434 split_ea.cmdidx = CMD_new;
435 split_ea.cmd = (char_u *)"new";
436 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100437 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200438 {
439 split_ea.line2 = opt->jo_term_rows;
440 split_ea.addr_count = 1;
441 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100442 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200443 {
444 split_ea.line2 = opt->jo_term_cols;
445 split_ea.addr_count = 1;
446 }
447
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100448 if (vertical)
449 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200450 ex_splitview(&split_ea);
451 if (curwin == old_curwin)
452 {
453 /* split failed */
454 vim_free(term);
455 return NULL;
456 }
457 }
458 term->tl_buffer = curbuf;
459 curbuf->b_term = term;
460
461 if (!opt->jo_hidden)
462 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100463 /* Only one size was taken care of with :new, do the other one. With
464 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100465 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200466 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100467 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200468 win_setwidth(opt->jo_term_cols);
469 }
470
471 /* Link the new terminal in the list of active terminals. */
472 term->tl_next = first_term;
473 first_term = term;
474
475 if (opt->jo_term_name != NULL)
476 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100477 else if (argv != NULL)
478 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200479 else
480 {
481 int i;
482 size_t len;
483 char_u *cmd, *p;
484
485 if (argvar->v_type == VAR_STRING)
486 {
487 cmd = argvar->vval.v_string;
488 if (cmd == NULL)
489 cmd = (char_u *)"";
490 else if (STRCMP(cmd, "NONE") == 0)
491 cmd = (char_u *)"pty";
492 }
493 else if (argvar->v_type != VAR_LIST
494 || argvar->vval.v_list == NULL
495 || argvar->vval.v_list->lv_len < 1
496 || (cmd = get_tv_string_chk(
497 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
498 cmd = (char_u*)"";
499
500 len = STRLEN(cmd) + 10;
501 p = alloc((int)len);
502
503 for (i = 0; p != NULL; ++i)
504 {
505 /* Prepend a ! to the command name to avoid the buffer name equals
506 * the executable, otherwise ":w!" would overwrite it. */
507 if (i == 0)
508 vim_snprintf((char *)p, len, "!%s", cmd);
509 else
510 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
511 if (buflist_findname(p) == NULL)
512 {
513 vim_free(curbuf->b_ffname);
514 curbuf->b_ffname = p;
515 break;
516 }
517 }
518 }
519 curbuf->b_fname = curbuf->b_ffname;
520
521 if (opt->jo_term_opencmd != NULL)
522 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
523
524 if (opt->jo_eof_chars != NULL)
525 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
526
527 set_string_option_direct((char_u *)"buftype", -1,
528 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
529
530 /* Mark the buffer as not modifiable. It can only be made modifiable after
531 * the job finished. */
532 curbuf->b_p_ma = FALSE;
533
534 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200535#ifdef WIN3264
536 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
537#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200538 setup_job_options(opt, term->tl_rows, term->tl_cols);
539
Bram Moolenaar13568252018-03-16 20:46:58 +0100540 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100541 return curbuf;
542
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100543#if defined(FEAT_SESSION)
544 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100545 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100546 {
547 term->tl_command = vim_strsave((char_u *)"NONE");
548 }
549 else if (argvar->v_type == VAR_STRING)
550 {
551 char_u *cmd = argvar->vval.v_string;
552
553 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
554 term->tl_command = vim_strsave(cmd);
555 }
556 else if (argvar->v_type == VAR_LIST
557 && argvar->vval.v_list != NULL
558 && argvar->vval.v_list->lv_len > 0)
559 {
560 garray_T ga;
561 listitem_T *item;
562
563 ga_init2(&ga, 1, 100);
564 for (item = argvar->vval.v_list->lv_first;
565 item != NULL; item = item->li_next)
566 {
567 char_u *s = get_tv_string_chk(&item->li_tv);
568 char_u *p;
569
570 if (s == NULL)
571 break;
572 p = vim_strsave_fnameescape(s, FALSE);
573 if (p == NULL)
574 break;
575 ga_concat(&ga, p);
576 vim_free(p);
577 ga_append(&ga, ' ');
578 }
579 if (item == NULL)
580 {
581 ga_append(&ga, NUL);
582 term->tl_command = ga.ga_data;
583 }
584 else
585 ga_clear(&ga);
586 }
587#endif
588
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100589 if (opt->jo_term_kill != NULL)
590 {
591 char_u *p = skiptowhite(opt->jo_term_kill);
592
593 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
594 }
595
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200596 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100597 if (argv == NULL
598 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200599 && argvar->vval.v_string != NULL
600 && STRCMP(argvar->vval.v_string, "NONE") == 0)
601 res = create_pty_only(term, opt);
602 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200603 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200604
605 newbuf = curbuf;
606 if (res == OK)
607 {
608 /* Get and remember the size we ended up with. Update the pty. */
609 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
610 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100611#ifdef FEAT_GUI
612 if (term->tl_system)
613 {
614 /* display first line below typed command */
615 term->tl_toprow = msg_row + 1;
616 term->tl_dirty_row_end = 0;
617 }
618#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200619
620 /* Make sure we don't get stuck on sending keys to the job, it leads to
621 * a deadlock if the job is waiting for Vim to read. */
622 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
623
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200624 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200625 {
626 --curbuf->b_nwindows;
627 curbuf = old_curbuf;
628 curwin->w_buffer = curbuf;
629 ++curbuf->b_nwindows;
630 }
631 }
632 else
633 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100634 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200635 return NULL;
636 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100637
Bram Moolenaar13568252018-03-16 20:46:58 +0100638 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200639 return newbuf;
640}
641
642/*
643 * ":terminal": open a terminal window and execute a job in it.
644 */
645 void
646ex_terminal(exarg_T *eap)
647{
648 typval_T argvar[2];
649 jobopt_T opt;
650 char_u *cmd;
651 char_u *tofree = NULL;
652
653 init_job_options(&opt);
654
655 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100656 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200657 {
658 char_u *p, *ep;
659
660 cmd += 2;
661 p = skiptowhite(cmd);
662 ep = vim_strchr(cmd, '=');
663 if (ep != NULL && ep < p)
664 p = ep;
665
666 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
667 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100668 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
669 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200670 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
671 opt.jo_term_finish = 'o';
672 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
673 opt.jo_curwin = 1;
674 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
675 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100676 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
677 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100678 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
679 && ep != NULL)
680 {
681 opt.jo_set2 |= JO2_TERM_KILL;
682 opt.jo_term_kill = ep + 1;
683 p = skiptowhite(cmd);
684 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200685 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
686 && ep != NULL && isdigit(ep[1]))
687 {
688 opt.jo_set2 |= JO2_TERM_ROWS;
689 opt.jo_term_rows = atoi((char *)ep + 1);
690 p = skiptowhite(cmd);
691 }
692 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
693 && ep != NULL && isdigit(ep[1]))
694 {
695 opt.jo_set2 |= JO2_TERM_COLS;
696 opt.jo_term_cols = atoi((char *)ep + 1);
697 p = skiptowhite(cmd);
698 }
699 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
700 && ep != NULL)
701 {
702 char_u *buf = NULL;
703 char_u *keys;
704
705 p = skiptowhite(cmd);
706 *p = NUL;
707 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
708 opt.jo_set2 |= JO2_EOF_CHARS;
709 opt.jo_eof_chars = vim_strsave(keys);
710 vim_free(buf);
711 *p = ' ';
712 }
713 else
714 {
715 if (*p)
716 *p = NUL;
717 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100718 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200719 }
720 cmd = skipwhite(p);
721 }
722 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100723 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200724 /* Make a copy of 'shell', an autocommand may change the option. */
725 tofree = cmd = vim_strsave(p_sh);
726
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100727 /* default to close when the shell exits */
728 if (opt.jo_term_finish == NUL)
729 opt.jo_term_finish = 'c';
730 }
731
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200732 if (eap->addr_count > 0)
733 {
734 /* Write lines from current buffer to the job. */
735 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
736 opt.jo_io[PART_IN] = JIO_BUFFER;
737 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
738 opt.jo_in_top = eap->line1;
739 opt.jo_in_bot = eap->line2;
740 }
741
742 argvar[0].v_type = VAR_STRING;
743 argvar[0].vval.v_string = cmd;
744 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100745 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200746 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100747
748theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200749 vim_free(opt.jo_eof_chars);
750}
751
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100752#if defined(FEAT_SESSION) || defined(PROTO)
753/*
754 * Write a :terminal command to the session file to restore the terminal in
755 * window "wp".
756 * Return FAIL if writing fails.
757 */
758 int
759term_write_session(FILE *fd, win_T *wp)
760{
761 term_T *term = wp->w_buffer->b_term;
762
763 /* Create the terminal and run the command. This is not without
764 * risk, but let's assume the user only creates a session when this
765 * will be OK. */
766 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
767 term->tl_cols, term->tl_rows) < 0)
768 return FAIL;
769 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
770 return FAIL;
771
772 return put_eol(fd);
773}
774
775/*
776 * Return TRUE if "buf" has a terminal that should be restored.
777 */
778 int
779term_should_restore(buf_T *buf)
780{
781 term_T *term = buf->b_term;
782
783 return term != NULL && (term->tl_command == NULL
784 || STRCMP(term->tl_command, "NONE") != 0);
785}
786#endif
787
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788/*
789 * Free the scrollback buffer for "term".
790 */
791 static void
792free_scrollback(term_T *term)
793{
794 int i;
795
796 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
797 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
798 ga_clear(&term->tl_scrollback);
799}
800
801/*
802 * Free a terminal and everything it refers to.
803 * Kills the job if there is one.
804 * Called when wiping out a buffer.
805 */
806 void
807free_terminal(buf_T *buf)
808{
809 term_T *term = buf->b_term;
810 term_T *tp;
811
812 if (term == NULL)
813 return;
814 if (first_term == term)
815 first_term = term->tl_next;
816 else
817 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
818 if (tp->tl_next == term)
819 {
820 tp->tl_next = term->tl_next;
821 break;
822 }
823
824 if (term->tl_job != NULL)
825 {
826 if (term->tl_job->jv_status != JOB_ENDED
827 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100828 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200829 job_stop(term->tl_job, NULL, "kill");
830 job_unref(term->tl_job);
831 }
832
833 free_scrollback(term);
834
835 term_free_vterm(term);
836 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100837#ifdef FEAT_SESSION
838 vim_free(term->tl_command);
839#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100840 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200841 vim_free(term->tl_status_text);
842 vim_free(term->tl_opencmd);
843 vim_free(term->tl_eof_chars);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200844#ifdef WIN3264
845 if (term->tl_out_fd != NULL)
846 fclose(term->tl_out_fd);
847#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200848 vim_free(term->tl_cursor_color);
849 vim_free(term);
850 buf->b_term = NULL;
851 if (in_terminal_loop == term)
852 in_terminal_loop = NULL;
853}
854
855/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100856 * Get the part that is connected to the tty. Normally this is PART_IN, but
857 * when writing buffer lines to the job it can be another. This makes it
858 * possible to do "1,5term vim -".
859 */
860 static ch_part_T
861get_tty_part(term_T *term)
862{
863#ifdef UNIX
864 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
865 int i;
866
867 for (i = 0; i < 3; ++i)
868 {
869 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
870
871 if (isatty(fd))
872 return parts[i];
873 }
874#endif
875 return PART_IN;
876}
877
878/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200879 * Write job output "msg[len]" to the vterm.
880 */
881 static void
882term_write_job_output(term_T *term, char_u *msg, size_t len)
883{
884 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100885 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200886
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100887 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200888
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100889 /* flush vterm buffer when vterm responded to control sequence */
890 if (prevlen != vterm_output_get_buffer_current(vterm))
891 {
892 char buf[KEY_BUF_LEN];
893 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
894
895 if (curlen > 0)
896 channel_send(term->tl_job->jv_channel, get_tty_part(term),
897 (char_u *)buf, (int)curlen, NULL);
898 }
899
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200900 /* this invokes the damage callbacks */
901 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
902}
903
904 static void
905update_cursor(term_T *term, int redraw)
906{
907 if (term->tl_normal_mode)
908 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100909#ifdef FEAT_GUI
910 if (term->tl_system)
911 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
912 term->tl_cursor_pos.col);
913 else
914#endif
915 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200916 if (redraw)
917 {
918 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
919 cursor_on();
920 out_flush();
921#ifdef FEAT_GUI
922 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100923 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200924 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100925 gui_mch_flush();
926 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200927#endif
928 }
929}
930
931/*
932 * Invoked when "msg" output from a job was received. Write it to the terminal
933 * of "buffer".
934 */
935 void
936write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
937{
938 size_t len = STRLEN(msg);
939 term_T *term = buffer->b_term;
940
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200941#ifdef WIN3264
942 /* Win32: Cannot redirect output of the job, intercept it here and write to
943 * the file. */
944 if (term->tl_out_fd != NULL)
945 {
946 ch_log(channel, "Writing %d bytes to output file", (int)len);
947 fwrite(msg, len, 1, term->tl_out_fd);
948 return;
949 }
950#endif
951
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200952 if (term->tl_vterm == NULL)
953 {
954 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
955 return;
956 }
957 ch_log(channel, "writing %d bytes to terminal", (int)len);
958 term_write_job_output(term, msg, len);
959
Bram Moolenaar13568252018-03-16 20:46:58 +0100960#ifdef FEAT_GUI
961 if (term->tl_system)
962 {
963 /* show system output, scrolling up the screen as needed */
964 update_system_term(term);
965 update_cursor(term, TRUE);
966 }
967 else
968#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200969 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
970 * contents, thus no screen update is needed. */
971 if (!term->tl_normal_mode)
972 {
973 /* TODO: only update once in a while. */
974 ch_log(term->tl_job->jv_channel, "updating screen");
975 if (buffer == curbuf)
976 {
977 update_screen(0);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +0200978 /* update_screen() can be slow, check the terminal wasn't closed
979 * already */
980 if (buffer == curbuf && curbuf->b_term != NULL)
981 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200982 }
983 else
984 redraw_after_callback(TRUE);
985 }
986}
987
988/*
989 * Send a mouse position and click to the vterm
990 */
991 static int
992term_send_mouse(VTerm *vterm, int button, int pressed)
993{
994 VTermModifier mod = VTERM_MOD_NONE;
995
996 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200997 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100998 if (button != 0)
999 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001000 return TRUE;
1001}
1002
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001003static int enter_mouse_col = -1;
1004static int enter_mouse_row = -1;
1005
1006/*
1007 * Handle a mouse click, drag or release.
1008 * Return TRUE when a mouse event is sent to the terminal.
1009 */
1010 static int
1011term_mouse_click(VTerm *vterm, int key)
1012{
1013#if defined(FEAT_CLIPBOARD)
1014 /* For modeless selection mouse drag and release events are ignored, unless
1015 * they are preceded with a mouse down event */
1016 static int ignore_drag_release = TRUE;
1017 VTermMouseState mouse_state;
1018
1019 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1020 if (mouse_state.flags == 0)
1021 {
1022 /* Terminal is not using the mouse, use modeless selection. */
1023 switch (key)
1024 {
1025 case K_LEFTDRAG:
1026 case K_LEFTRELEASE:
1027 case K_RIGHTDRAG:
1028 case K_RIGHTRELEASE:
1029 /* Ignore drag and release events when the button-down wasn't
1030 * seen before. */
1031 if (ignore_drag_release)
1032 {
1033 int save_mouse_col, save_mouse_row;
1034
1035 if (enter_mouse_col < 0)
1036 break;
1037
1038 /* mouse click in the window gave us focus, handle that
1039 * click now */
1040 save_mouse_col = mouse_col;
1041 save_mouse_row = mouse_row;
1042 mouse_col = enter_mouse_col;
1043 mouse_row = enter_mouse_row;
1044 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1045 mouse_col = save_mouse_col;
1046 mouse_row = save_mouse_row;
1047 }
1048 /* FALLTHROUGH */
1049 case K_LEFTMOUSE:
1050 case K_RIGHTMOUSE:
1051 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1052 ignore_drag_release = TRUE;
1053 else
1054 ignore_drag_release = FALSE;
1055 /* Should we call mouse_has() here? */
1056 if (clip_star.available)
1057 {
1058 int button, is_click, is_drag;
1059
1060 button = get_mouse_button(KEY2TERMCAP1(key),
1061 &is_click, &is_drag);
1062 if (mouse_model_popup() && button == MOUSE_LEFT
1063 && (mod_mask & MOD_MASK_SHIFT))
1064 {
1065 /* Translate shift-left to right button. */
1066 button = MOUSE_RIGHT;
1067 mod_mask &= ~MOD_MASK_SHIFT;
1068 }
1069 clip_modeless(button, is_click, is_drag);
1070 }
1071 break;
1072
1073 case K_MIDDLEMOUSE:
1074 if (clip_star.available)
1075 insert_reg('*', TRUE);
1076 break;
1077 }
1078 enter_mouse_col = -1;
1079 return FALSE;
1080 }
1081#endif
1082 enter_mouse_col = -1;
1083
1084 switch (key)
1085 {
1086 case K_LEFTMOUSE:
1087 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1088 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1089 case K_LEFTRELEASE:
1090 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1091 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1092 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1093 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1094 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1095 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1096 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1097 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1098 }
1099 return TRUE;
1100}
1101
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001102/*
1103 * Convert typed key "c" into bytes to send to the job.
1104 * Return the number of bytes in "buf".
1105 */
1106 static int
1107term_convert_key(term_T *term, int c, char *buf)
1108{
1109 VTerm *vterm = term->tl_vterm;
1110 VTermKey key = VTERM_KEY_NONE;
1111 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001112 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001113
1114 switch (c)
1115 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001116 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1117
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001118 /* don't use VTERM_KEY_BACKSPACE, it always
1119 * becomes 0x7f DEL */
1120 case K_BS: c = term_backspace_char; break;
1121
1122 case ESC: key = VTERM_KEY_ESCAPE; break;
1123 case K_DEL: key = VTERM_KEY_DEL; break;
1124 case K_DOWN: key = VTERM_KEY_DOWN; break;
1125 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1126 key = VTERM_KEY_DOWN; break;
1127 case K_END: key = VTERM_KEY_END; break;
1128 case K_S_END: mod = VTERM_MOD_SHIFT;
1129 key = VTERM_KEY_END; break;
1130 case K_C_END: mod = VTERM_MOD_CTRL;
1131 key = VTERM_KEY_END; break;
1132 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1133 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1134 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1135 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1136 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1137 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1138 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1139 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1140 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1141 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1142 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1143 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1144 case K_HOME: key = VTERM_KEY_HOME; break;
1145 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1146 key = VTERM_KEY_HOME; break;
1147 case K_C_HOME: mod = VTERM_MOD_CTRL;
1148 key = VTERM_KEY_HOME; break;
1149 case K_INS: key = VTERM_KEY_INS; break;
1150 case K_K0: key = VTERM_KEY_KP_0; break;
1151 case K_K1: key = VTERM_KEY_KP_1; break;
1152 case K_K2: key = VTERM_KEY_KP_2; break;
1153 case K_K3: key = VTERM_KEY_KP_3; break;
1154 case K_K4: key = VTERM_KEY_KP_4; break;
1155 case K_K5: key = VTERM_KEY_KP_5; break;
1156 case K_K6: key = VTERM_KEY_KP_6; break;
1157 case K_K7: key = VTERM_KEY_KP_7; break;
1158 case K_K8: key = VTERM_KEY_KP_8; break;
1159 case K_K9: key = VTERM_KEY_KP_9; break;
1160 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1161 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1162 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1163 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1164 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1165 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1166 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1167 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1168 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1169 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1170 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1171 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1172 case K_LEFT: key = VTERM_KEY_LEFT; break;
1173 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1174 key = VTERM_KEY_LEFT; break;
1175 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1176 key = VTERM_KEY_LEFT; break;
1177 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1178 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1179 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1180 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1181 key = VTERM_KEY_RIGHT; break;
1182 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1183 key = VTERM_KEY_RIGHT; break;
1184 case K_UP: key = VTERM_KEY_UP; break;
1185 case K_S_UP: mod = VTERM_MOD_SHIFT;
1186 key = VTERM_KEY_UP; break;
1187 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001188 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1189 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001190
Bram Moolenaara42ad572017-11-16 13:08:04 +01001191 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1192 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001193 case K_MOUSELEFT: /* TODO */ return 0;
1194 case K_MOUSERIGHT: /* TODO */ return 0;
1195
1196 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001197 case K_LEFTMOUSE_NM:
1198 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001199 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001200 case K_LEFTRELEASE_NM:
1201 case K_MOUSEMOVE:
1202 case K_MIDDLEMOUSE:
1203 case K_MIDDLEDRAG:
1204 case K_MIDDLERELEASE:
1205 case K_RIGHTMOUSE:
1206 case K_RIGHTDRAG:
1207 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1208 return 0;
1209 other = TRUE;
1210 break;
1211
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001212 case K_X1MOUSE: /* TODO */ return 0;
1213 case K_X1DRAG: /* TODO */ return 0;
1214 case K_X1RELEASE: /* TODO */ return 0;
1215 case K_X2MOUSE: /* TODO */ return 0;
1216 case K_X2DRAG: /* TODO */ return 0;
1217 case K_X2RELEASE: /* TODO */ return 0;
1218
1219 case K_IGNORE: return 0;
1220 case K_NOP: return 0;
1221 case K_UNDO: return 0;
1222 case K_HELP: return 0;
1223 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1224 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1225 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1226 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1227 case K_SELECT: return 0;
1228#ifdef FEAT_GUI
1229 case K_VER_SCROLLBAR: return 0;
1230 case K_HOR_SCROLLBAR: return 0;
1231#endif
1232#ifdef FEAT_GUI_TABLINE
1233 case K_TABLINE: return 0;
1234 case K_TABMENU: return 0;
1235#endif
1236#ifdef FEAT_NETBEANS_INTG
1237 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1238#endif
1239#ifdef FEAT_DND
1240 case K_DROP: return 0;
1241#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001242 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001243 case K_PS: vterm_keyboard_start_paste(vterm);
1244 other = TRUE;
1245 break;
1246 case K_PE: vterm_keyboard_end_paste(vterm);
1247 other = TRUE;
1248 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001249 }
1250
1251 /*
1252 * Convert special keys to vterm keys:
1253 * - Write keys to vterm: vterm_keyboard_key()
1254 * - Write output to channel.
1255 * TODO: use mod_mask
1256 */
1257 if (key != VTERM_KEY_NONE)
1258 /* Special key, let vterm convert it. */
1259 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001260 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001261 /* Normal character, let vterm convert it. */
1262 vterm_keyboard_unichar(vterm, c, mod);
1263
1264 /* Read back the converted escape sequence. */
1265 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1266}
1267
1268/*
1269 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001270 * If "check_job_status" is TRUE update the job status.
1271 */
1272 static int
1273term_job_running_check(term_T *term, int check_job_status)
1274{
1275 /* Also consider the job finished when the channel is closed, to avoid a
1276 * race condition when updating the title. */
1277 if (term != NULL
1278 && term->tl_job != NULL
1279 && channel_is_open(term->tl_job->jv_channel))
1280 {
1281 if (check_job_status)
1282 job_status(term->tl_job);
1283 return (term->tl_job->jv_status == JOB_STARTED
1284 || term->tl_job->jv_channel->ch_keep_open);
1285 }
1286 return FALSE;
1287}
1288
1289/*
1290 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001291 */
1292 int
1293term_job_running(term_T *term)
1294{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001295 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001296}
1297
1298/*
1299 * Return TRUE if "term" has an active channel and used ":term NONE".
1300 */
1301 int
1302term_none_open(term_T *term)
1303{
1304 /* Also consider the job finished when the channel is closed, to avoid a
1305 * race condition when updating the title. */
1306 return term != NULL
1307 && term->tl_job != NULL
1308 && channel_is_open(term->tl_job->jv_channel)
1309 && term->tl_job->jv_channel->ch_keep_open;
1310}
1311
1312/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001313 * Used when exiting: kill the job in "buf" if so desired.
1314 * Return OK when the job finished.
1315 * Return FAIL when the job is still running.
1316 */
1317 int
1318term_try_stop_job(buf_T *buf)
1319{
1320 int count;
1321 char *how = (char *)buf->b_term->tl_kill;
1322
1323#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1324 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1325 {
1326 char_u buff[DIALOG_MSG_SIZE];
1327 int ret;
1328
1329 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1330 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1331 if (ret == VIM_YES)
1332 how = "kill";
1333 else if (ret == VIM_CANCEL)
1334 return FAIL;
1335 }
1336#endif
1337 if (how == NULL || *how == NUL)
1338 return FAIL;
1339
1340 job_stop(buf->b_term->tl_job, NULL, how);
1341
1342 /* wait for up to a second for the job to die */
1343 for (count = 0; count < 100; ++count)
1344 {
1345 /* buffer, terminal and job may be cleaned up while waiting */
1346 if (!buf_valid(buf)
1347 || buf->b_term == NULL
1348 || buf->b_term->tl_job == NULL)
1349 return OK;
1350
1351 /* call job_status() to update jv_status */
1352 job_status(buf->b_term->tl_job);
1353 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1354 return OK;
1355 ui_delay(10L, FALSE);
1356 mch_check_messages();
1357 parse_queued_messages();
1358 }
1359 return FAIL;
1360}
1361
1362/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001363 * Add the last line of the scrollback buffer to the buffer in the window.
1364 */
1365 static void
1366add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1367{
1368 buf_T *buf = term->tl_buffer;
1369 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1370 linenr_T lnum = buf->b_ml.ml_line_count;
1371
1372#ifdef WIN3264
1373 if (!enc_utf8 && enc_codepage > 0)
1374 {
1375 WCHAR *ret = NULL;
1376 int length = 0;
1377
1378 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1379 &ret, &length);
1380 if (ret != NULL)
1381 {
1382 WideCharToMultiByte_alloc(enc_codepage, 0,
1383 ret, length, (char **)&text, &len, 0, 0);
1384 vim_free(ret);
1385 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1386 vim_free(text);
1387 }
1388 }
1389 else
1390#endif
1391 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1392 if (empty)
1393 {
1394 /* Delete the empty line that was in the empty buffer. */
1395 curbuf = buf;
1396 ml_delete(1, FALSE);
1397 curbuf = curwin->w_buffer;
1398 }
1399}
1400
1401 static void
1402cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1403{
1404 attr->width = cell->width;
1405 attr->attrs = cell->attrs;
1406 attr->fg = cell->fg;
1407 attr->bg = cell->bg;
1408}
1409
1410 static int
1411equal_celattr(cellattr_T *a, cellattr_T *b)
1412{
1413 /* Comparing the colors should be sufficient. */
1414 return a->fg.red == b->fg.red
1415 && a->fg.green == b->fg.green
1416 && a->fg.blue == b->fg.blue
1417 && a->bg.red == b->bg.red
1418 && a->bg.green == b->bg.green
1419 && a->bg.blue == b->bg.blue;
1420}
1421
Bram Moolenaard96ff162018-02-18 22:13:29 +01001422/*
1423 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1424 * line at this position. Otherwise at the end.
1425 */
1426 static int
1427add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1428{
1429 if (ga_grow(&term->tl_scrollback, 1) == OK)
1430 {
1431 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1432 + term->tl_scrollback.ga_len;
1433
1434 if (lnum > 0)
1435 {
1436 int i;
1437
1438 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1439 {
1440 *line = *(line - 1);
1441 --line;
1442 }
1443 }
1444 line->sb_cols = 0;
1445 line->sb_cells = NULL;
1446 line->sb_fill_attr = *fill_attr;
1447 ++term->tl_scrollback.ga_len;
1448 return OK;
1449 }
1450 return FALSE;
1451}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001452
1453/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001454 * Remove the terminal contents from the scrollback and the buffer.
1455 * Used before adding a new scrollback line or updating the buffer for lines
1456 * displayed in the terminal.
1457 */
1458 static void
1459cleanup_scrollback(term_T *term)
1460{
1461 sb_line_T *line;
1462 garray_T *gap;
1463
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001464 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001465 gap = &term->tl_scrollback;
1466 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1467 && gap->ga_len > 0)
1468 {
1469 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1470 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1471 vim_free(line->sb_cells);
1472 --gap->ga_len;
1473 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001474 curbuf = curwin->w_buffer;
1475 if (curbuf == term->tl_buffer)
1476 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001477}
1478
1479/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001480 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001481 */
1482 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001483update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001484{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001485 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001486 int len;
1487 int lines_skipped = 0;
1488 VTermPos pos;
1489 VTermScreenCell cell;
1490 cellattr_T fill_attr, new_fill_attr;
1491 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001492
1493 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1494 "Adding terminal window snapshot to buffer");
1495
1496 /* First remove the lines that were appended before, they might be
1497 * outdated. */
1498 cleanup_scrollback(term);
1499
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001500 screen = vterm_obtain_screen(term->tl_vterm);
1501 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001502 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1503 {
1504 len = 0;
1505 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1506 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1507 && cell.chars[0] != NUL)
1508 {
1509 len = pos.col + 1;
1510 new_fill_attr = term->tl_default_color;
1511 }
1512 else
1513 /* Assume the last attr is the filler attr. */
1514 cell2cellattr(&cell, &new_fill_attr);
1515
1516 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1517 ++lines_skipped;
1518 else
1519 {
1520 while (lines_skipped > 0)
1521 {
1522 /* Line was skipped, add an empty line. */
1523 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001524 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001525 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001526 }
1527
1528 if (len == 0)
1529 p = NULL;
1530 else
1531 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1532 if ((p != NULL || len == 0)
1533 && ga_grow(&term->tl_scrollback, 1) == OK)
1534 {
1535 garray_T ga;
1536 int width;
1537 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1538 + term->tl_scrollback.ga_len;
1539
1540 ga_init2(&ga, 1, 100);
1541 for (pos.col = 0; pos.col < len; pos.col += width)
1542 {
1543 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1544 {
1545 width = 1;
1546 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1547 if (ga_grow(&ga, 1) == OK)
1548 ga.ga_len += utf_char2bytes(' ',
1549 (char_u *)ga.ga_data + ga.ga_len);
1550 }
1551 else
1552 {
1553 width = cell.width;
1554
1555 cell2cellattr(&cell, &p[pos.col]);
1556
1557 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1558 {
1559 int i;
1560 int c;
1561
1562 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1563 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1564 (char_u *)ga.ga_data + ga.ga_len);
1565 }
1566 }
1567 }
1568 line->sb_cols = len;
1569 line->sb_cells = p;
1570 line->sb_fill_attr = new_fill_attr;
1571 fill_attr = new_fill_attr;
1572 ++term->tl_scrollback.ga_len;
1573
1574 if (ga_grow(&ga, 1) == FAIL)
1575 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1576 else
1577 {
1578 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1579 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1580 }
1581 ga_clear(&ga);
1582 }
1583 else
1584 vim_free(p);
1585 }
1586 }
1587
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001588 term->tl_dirty_snapshot = FALSE;
1589#ifdef FEAT_TIMERS
1590 term->tl_timer_set = FALSE;
1591#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001592}
1593
1594/*
1595 * If needed, add the current lines of the terminal to scrollback and to the
1596 * buffer. Called after the job has ended and when switching to
1597 * Terminal-Normal mode.
1598 * When "redraw" is TRUE redraw the windows that show the terminal.
1599 */
1600 static void
1601may_move_terminal_to_buffer(term_T *term, int redraw)
1602{
1603 win_T *wp;
1604
1605 if (term->tl_vterm == NULL)
1606 return;
1607
1608 /* Update the snapshot only if something changes or the buffer does not
1609 * have all the lines. */
1610 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1611 <= term->tl_scrollback_scrolled)
1612 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001613
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001614 /* Obtain the current background color. */
1615 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1616 &term->tl_default_color.fg, &term->tl_default_color.bg);
1617
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001618 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001619 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001620 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001621 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001622 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001623 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1624 wp->w_cursor.col = 0;
1625 wp->w_valid = 0;
1626 if (wp->w_cursor.lnum >= wp->w_height)
1627 {
1628 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001629
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001630 if (wp->w_topline < min_topline)
1631 wp->w_topline = min_topline;
1632 }
1633 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001634 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001635 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001636}
1637
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001638#if defined(FEAT_TIMERS) || defined(PROTO)
1639/*
1640 * Check if any terminal timer expired. If so, copy text from the terminal to
1641 * the buffer.
1642 * Return the time until the next timer will expire.
1643 */
1644 int
1645term_check_timers(int next_due_arg, proftime_T *now)
1646{
1647 term_T *term;
1648 int next_due = next_due_arg;
1649
1650 for (term = first_term; term != NULL; term = term->tl_next)
1651 {
1652 if (term->tl_timer_set && !term->tl_normal_mode)
1653 {
1654 long this_due = proftime_time_left(&term->tl_timer_due, now);
1655
1656 if (this_due <= 1)
1657 {
1658 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001659 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001660 }
1661 else if (next_due == -1 || next_due > this_due)
1662 next_due = this_due;
1663 }
1664 }
1665
1666 return next_due;
1667}
1668#endif
1669
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001670 static void
1671set_terminal_mode(term_T *term, int normal_mode)
1672{
1673 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001674 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001675 if (term->tl_buffer == curbuf)
1676 maketitle();
1677}
1678
1679/*
1680 * Called after the job if finished and Terminal mode is not active:
1681 * Move the vterm contents into the scrollback buffer and free the vterm.
1682 */
1683 static void
1684cleanup_vterm(term_T *term)
1685{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001686 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001687 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001688 term_free_vterm(term);
1689 set_terminal_mode(term, FALSE);
1690}
1691
1692/*
1693 * Switch from Terminal-Job mode to Terminal-Normal mode.
1694 * Suspends updating the terminal window.
1695 */
1696 static void
1697term_enter_normal_mode(void)
1698{
1699 term_T *term = curbuf->b_term;
1700
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001701 set_terminal_mode(term, TRUE);
1702
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001703 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001704 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001705
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001706 /* Move the window cursor to the position of the cursor in the
1707 * terminal. */
1708 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1709 + term->tl_cursor_pos.row + 1;
1710 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001711 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1712 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001713
1714 /* Display the same lines as in the terminal. */
1715 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1716}
1717
1718/*
1719 * Returns TRUE if the current window contains a terminal and we are in
1720 * Terminal-Normal mode.
1721 */
1722 int
1723term_in_normal_mode(void)
1724{
1725 term_T *term = curbuf->b_term;
1726
1727 return term != NULL && term->tl_normal_mode;
1728}
1729
1730/*
1731 * Switch from Terminal-Normal mode to Terminal-Job mode.
1732 * Restores updating the terminal window.
1733 */
1734 void
1735term_enter_job_mode()
1736{
1737 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001738
1739 set_terminal_mode(term, FALSE);
1740
1741 if (term->tl_channel_closed)
1742 cleanup_vterm(term);
1743 redraw_buf_and_status_later(curbuf, NOT_VALID);
1744}
1745
1746/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001747 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001748 * Note: while waiting a terminal may be closed and freed if the channel is
1749 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001750 */
1751 static int
1752term_vgetc()
1753{
1754 int c;
1755 int save_State = State;
1756
1757 State = TERMINAL;
1758 got_int = FALSE;
1759#ifdef WIN3264
1760 ctrl_break_was_pressed = FALSE;
1761#endif
1762 c = vgetc();
1763 got_int = FALSE;
1764 State = save_State;
1765 return c;
1766}
1767
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001768static int mouse_was_outside = FALSE;
1769
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001770/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001771 * Send keys to terminal.
1772 * Return FAIL when the key needs to be handled in Normal mode.
1773 * Return OK when the key was dropped or sent to the terminal.
1774 */
1775 int
1776send_keys_to_term(term_T *term, int c, int typed)
1777{
1778 char msg[KEY_BUF_LEN];
1779 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001780 int dragging_outside = FALSE;
1781
1782 /* Catch keys that need to be handled as in Normal mode. */
1783 switch (c)
1784 {
1785 case NUL:
1786 case K_ZERO:
1787 if (typed)
1788 stuffcharReadbuff(c);
1789 return FAIL;
1790
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001791 case K_TABLINE:
1792 stuffcharReadbuff(c);
1793 return FAIL;
1794
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001795 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001796 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001797 return FAIL;
1798
1799 case K_LEFTDRAG:
1800 case K_MIDDLEDRAG:
1801 case K_RIGHTDRAG:
1802 case K_X1DRAG:
1803 case K_X2DRAG:
1804 dragging_outside = mouse_was_outside;
1805 /* FALLTHROUGH */
1806 case K_LEFTMOUSE:
1807 case K_LEFTMOUSE_NM:
1808 case K_LEFTRELEASE:
1809 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001810 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001811 case K_MIDDLEMOUSE:
1812 case K_MIDDLERELEASE:
1813 case K_RIGHTMOUSE:
1814 case K_RIGHTRELEASE:
1815 case K_X1MOUSE:
1816 case K_X1RELEASE:
1817 case K_X2MOUSE:
1818 case K_X2RELEASE:
1819
1820 case K_MOUSEUP:
1821 case K_MOUSEDOWN:
1822 case K_MOUSELEFT:
1823 case K_MOUSERIGHT:
1824 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001825 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001826 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001827 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001828 || dragging_outside)
1829 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001830 /* click or scroll outside the current window or on status line
1831 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001832 if (typed)
1833 {
1834 stuffcharReadbuff(c);
1835 mouse_was_outside = TRUE;
1836 }
1837 return FAIL;
1838 }
1839 }
1840 if (typed)
1841 mouse_was_outside = FALSE;
1842
1843 /* Convert the typed key to a sequence of bytes for the job. */
1844 len = term_convert_key(term, c, msg);
1845 if (len > 0)
1846 /* TODO: if FAIL is returned, stop? */
1847 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1848 (char_u *)msg, (int)len, NULL);
1849
1850 return OK;
1851}
1852
1853 static void
1854position_cursor(win_T *wp, VTermPos *pos)
1855{
1856 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1857 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1858 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1859}
1860
1861/*
1862 * Handle CTRL-W "": send register contents to the job.
1863 */
1864 static void
1865term_paste_register(int prev_c UNUSED)
1866{
1867 int c;
1868 list_T *l;
1869 listitem_T *item;
1870 long reglen = 0;
1871 int type;
1872
1873#ifdef FEAT_CMDL_INFO
1874 if (add_to_showcmd(prev_c))
1875 if (add_to_showcmd('"'))
1876 out_flush();
1877#endif
1878 c = term_vgetc();
1879#ifdef FEAT_CMDL_INFO
1880 clear_showcmd();
1881#endif
1882 if (!term_use_loop())
1883 /* job finished while waiting for a character */
1884 return;
1885
1886 /* CTRL-W "= prompt for expression to evaluate. */
1887 if (c == '=' && get_expr_register() != '=')
1888 return;
1889 if (!term_use_loop())
1890 /* job finished while waiting for a character */
1891 return;
1892
1893 l = (list_T *)get_reg_contents(c, GREG_LIST);
1894 if (l != NULL)
1895 {
1896 type = get_reg_type(c, &reglen);
1897 for (item = l->lv_first; item != NULL; item = item->li_next)
1898 {
1899 char_u *s = get_tv_string(&item->li_tv);
1900#ifdef WIN3264
1901 char_u *tmp = s;
1902
1903 if (!enc_utf8 && enc_codepage > 0)
1904 {
1905 WCHAR *ret = NULL;
1906 int length = 0;
1907
1908 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1909 (int)STRLEN(s), &ret, &length);
1910 if (ret != NULL)
1911 {
1912 WideCharToMultiByte_alloc(CP_UTF8, 0,
1913 ret, length, (char **)&s, &length, 0, 0);
1914 vim_free(ret);
1915 }
1916 }
1917#endif
1918 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1919 s, (int)STRLEN(s), NULL);
1920#ifdef WIN3264
1921 if (tmp != s)
1922 vim_free(s);
1923#endif
1924
1925 if (item->li_next != NULL || type == MLINE)
1926 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1927 (char_u *)"\r", 1, NULL);
1928 }
1929 list_free(l);
1930 }
1931}
1932
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001933/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001934 * Return TRUE when waiting for a character in the terminal, the cursor of the
1935 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001936 */
1937 int
1938terminal_is_active()
1939{
1940 return in_terminal_loop != NULL;
1941}
1942
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001943#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001944 cursorentry_T *
1945term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1946{
1947 term_T *term = in_terminal_loop;
1948 static cursorentry_T entry;
1949
1950 vim_memset(&entry, 0, sizeof(entry));
1951 entry.shape = entry.mshape =
1952 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1953 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1954 SHAPE_BLOCK;
1955 entry.percentage = 20;
1956 if (term->tl_cursor_blink)
1957 {
1958 entry.blinkwait = 700;
1959 entry.blinkon = 400;
1960 entry.blinkoff = 250;
1961 }
1962 *fg = gui.back_pixel;
1963 if (term->tl_cursor_color == NULL)
1964 *bg = gui.norm_pixel;
1965 else
1966 *bg = color_name2handle(term->tl_cursor_color);
1967 entry.name = "n";
1968 entry.used_for = SHAPE_CURSOR;
1969
1970 return &entry;
1971}
1972#endif
1973
Bram Moolenaard317b382018-02-08 22:33:31 +01001974 static void
1975may_output_cursor_props(void)
1976{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02001977 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01001978 || last_set_cursor_shape != desired_cursor_shape
1979 || last_set_cursor_blink != desired_cursor_blink)
1980 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02001981 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01001982 last_set_cursor_shape = desired_cursor_shape;
1983 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02001984 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01001985 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1986 /* this will restore the initial cursor style, if possible */
1987 ui_cursor_shape_forced(TRUE);
1988 else
1989 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1990 }
1991}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001992
Bram Moolenaard317b382018-02-08 22:33:31 +01001993/*
1994 * Set the cursor color and shape, if not last set to these.
1995 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001996 static void
1997may_set_cursor_props(term_T *term)
1998{
1999#ifdef FEAT_GUI
2000 /* For the GUI the cursor properties are obtained with
2001 * term_get_cursor_shape(). */
2002 if (gui.in_use)
2003 return;
2004#endif
2005 if (in_terminal_loop == term)
2006 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002007 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002008 desired_cursor_shape = term->tl_cursor_shape;
2009 desired_cursor_blink = term->tl_cursor_blink;
2010 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 }
2012}
2013
Bram Moolenaard317b382018-02-08 22:33:31 +01002014/*
2015 * Reset the desired cursor properties and restore them when needed.
2016 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002017 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002018prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002019{
2020#ifdef FEAT_GUI
2021 if (gui.in_use)
2022 return;
2023#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002024 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002025 desired_cursor_shape = -1;
2026 desired_cursor_blink = -1;
2027 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028}
2029
2030/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002031 * Returns TRUE if the current window contains a terminal and we are sending
2032 * keys to the job.
2033 * If "check_job_status" is TRUE update the job status.
2034 */
2035 static int
2036term_use_loop_check(int check_job_status)
2037{
2038 term_T *term = curbuf->b_term;
2039
2040 return term != NULL
2041 && !term->tl_normal_mode
2042 && term->tl_vterm != NULL
2043 && term_job_running_check(term, check_job_status);
2044}
2045
2046/*
2047 * Returns TRUE if the current window contains a terminal and we are sending
2048 * keys to the job.
2049 */
2050 int
2051term_use_loop(void)
2052{
2053 return term_use_loop_check(FALSE);
2054}
2055
2056/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002057 * Called when entering a window with the mouse. If this is a terminal window
2058 * we may want to change state.
2059 */
2060 void
2061term_win_entered()
2062{
2063 term_T *term = curbuf->b_term;
2064
2065 if (term != NULL)
2066 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002067 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002068 {
2069 reset_VIsual_and_resel();
2070 if (State & INSERT)
2071 stop_insert_mode = TRUE;
2072 }
2073 mouse_was_outside = FALSE;
2074 enter_mouse_col = mouse_col;
2075 enter_mouse_row = mouse_row;
2076 }
2077}
2078
2079/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002080 * Wait for input and send it to the job.
2081 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2082 * when there is no more typahead.
2083 * Return when the start of a CTRL-W command is typed or anything else that
2084 * should be handled as a Normal mode command.
2085 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2086 * the terminal was closed.
2087 */
2088 int
2089terminal_loop(int blocking)
2090{
2091 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002092 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002093 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002094#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002095 int tty_fd = curbuf->b_term->tl_job->jv_channel
2096 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002097#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002098 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002099
2100 /* Remember the terminal we are sending keys to. However, the terminal
2101 * might be closed while waiting for a character, e.g. typing "exit" in a
2102 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2103 * stored reference. */
2104 in_terminal_loop = curbuf->b_term;
2105
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002106 if (*curwin->w_p_twk != NUL)
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002107 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002108 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2109 may_set_cursor_props(curbuf->b_term);
2110
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002111 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002112 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002113#ifdef FEAT_GUI
2114 if (!curbuf->b_term->tl_system)
2115#endif
2116 /* TODO: skip screen update when handling a sequence of keys. */
2117 /* Repeat redrawing in case a message is received while redrawing.
2118 */
2119 while (must_redraw != 0)
2120 if (update_screen(0) == FAIL)
2121 break;
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002122 if (!term_use_loop_check(TRUE))
2123 /* job finished while redrawing */
2124 break;
2125
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002126 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002127 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002128
2129 c = term_vgetc();
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002130 if (!term_use_loop_check(TRUE))
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002131 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002132 /* Job finished while waiting for a character. Push back the
2133 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002134 if (c != K_IGNORE)
2135 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002136 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002137 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002138 if (c == K_IGNORE)
2139 continue;
2140
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002141#ifdef UNIX
2142 /*
2143 * The shell or another program may change the tty settings. Getting
2144 * them for every typed character is a bit of overhead, but it's needed
2145 * for the first character typed, e.g. when Vim starts in a shell.
2146 */
2147 if (isatty(tty_fd))
2148 {
2149 ttyinfo_T info;
2150
2151 /* Get the current backspace character of the pty. */
2152 if (get_tty_info(tty_fd, &info) == OK)
2153 term_backspace_char = info.backspace;
2154 }
2155#endif
2156
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002157#ifdef WIN3264
2158 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2159 * Use CTRL-BREAK to kill the job. */
2160 if (ctrl_break_was_pressed)
2161 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2162#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002163 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002164 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002165 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002166#ifdef FEAT_GUI
2167 && !curbuf->b_term->tl_system
2168#endif
2169 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002170 {
2171 int prev_c = c;
2172
2173#ifdef FEAT_CMDL_INFO
2174 if (add_to_showcmd(c))
2175 out_flush();
2176#endif
2177 c = term_vgetc();
2178#ifdef FEAT_CMDL_INFO
2179 clear_showcmd();
2180#endif
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002181 if (!term_use_loop_check(TRUE))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002182 /* job finished while waiting for a character */
2183 break;
2184
2185 if (prev_c == Ctrl_BSL)
2186 {
2187 if (c == Ctrl_N)
2188 {
2189 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2190 term_enter_normal_mode();
2191 ret = FAIL;
2192 goto theend;
2193 }
2194 /* Send both keys to the terminal. */
2195 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2196 }
2197 else if (c == Ctrl_C)
2198 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002199 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002200 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2201 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002202 else if (termwinkey == 0 && c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002203 {
2204 /* "CTRL-W .": send CTRL-W to the job */
2205 c = Ctrl_W;
2206 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002207 else if (termwinkey == 0 && c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002208 {
2209 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2210 c = Ctrl_BSL;
2211 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002212 else if (c == 'N')
2213 {
2214 /* CTRL-W N : go to Terminal-Normal mode. */
2215 term_enter_normal_mode();
2216 ret = FAIL;
2217 goto theend;
2218 }
2219 else if (c == '"')
2220 {
2221 term_paste_register(prev_c);
2222 continue;
2223 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002224 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002225 {
2226 stuffcharReadbuff(Ctrl_W);
2227 stuffcharReadbuff(c);
2228 ret = OK;
2229 goto theend;
2230 }
2231 }
2232# ifdef WIN3264
2233 if (!enc_utf8 && has_mbyte && c >= 0x80)
2234 {
2235 WCHAR wc;
2236 char_u mb[3];
2237
2238 mb[0] = (unsigned)c >> 8;
2239 mb[1] = c;
2240 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2241 c = wc;
2242 }
2243# endif
2244 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2245 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002246 if (c == K_MOUSEMOVE)
2247 /* We are sure to come back here, don't reset the cursor color
2248 * and shape to avoid flickering. */
2249 restore_cursor = FALSE;
2250
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002251 ret = OK;
2252 goto theend;
2253 }
2254 }
2255 ret = FAIL;
2256
2257theend:
2258 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002259 if (restore_cursor)
2260 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002261
2262 /* Move a snapshot of the screen contents to the buffer, so that completion
2263 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002264 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2265 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002266
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002267 return ret;
2268}
2269
2270/*
2271 * Called when a job has finished.
2272 * This updates the title and status, but does not close the vterm, because
2273 * there might still be pending output in the channel.
2274 */
2275 void
2276term_job_ended(job_T *job)
2277{
2278 term_T *term;
2279 int did_one = FALSE;
2280
2281 for (term = first_term; term != NULL; term = term->tl_next)
2282 if (term->tl_job == job)
2283 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002284 VIM_CLEAR(term->tl_title);
2285 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002286 redraw_buf_and_status_later(term->tl_buffer, VALID);
2287 did_one = TRUE;
2288 }
2289 if (did_one)
2290 redraw_statuslines();
2291 if (curbuf->b_term != NULL)
2292 {
2293 if (curbuf->b_term->tl_job == job)
2294 maketitle();
2295 update_cursor(curbuf->b_term, TRUE);
2296 }
2297}
2298
2299 static void
2300may_toggle_cursor(term_T *term)
2301{
2302 if (in_terminal_loop == term)
2303 {
2304 if (term->tl_cursor_visible)
2305 cursor_on();
2306 else
2307 cursor_off();
2308 }
2309}
2310
2311/*
2312 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002313 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002314 */
2315 static int
2316color2index(VTermColor *color, int fg, int *boldp)
2317{
2318 int red = color->red;
2319 int blue = color->blue;
2320 int green = color->green;
2321
Bram Moolenaar46359e12017-11-29 22:33:38 +01002322 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002323 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002324 /* First 16 colors and default: use the ANSI index, because these
2325 * colors can be redefined. */
2326 if (t_colors >= 16)
2327 return color->ansi_index;
2328 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002329 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002330 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002331 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002332 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2333 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2334 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002335 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002336 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2337 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2338 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2339 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2340 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2341 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2342 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2343 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2344 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2345 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2346 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002347 }
2348 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002349
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002350 if (t_colors >= 256)
2351 {
2352 if (red == blue && red == green)
2353 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002354 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002355 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002356 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2357 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2358 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002359 int i;
2360
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002361 if (red < 5)
2362 return 17; /* 00/00/00 */
2363 if (red > 245) /* ff/ff/ff */
2364 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002365 for (i = 0; i < 23; ++i)
2366 if (red < cutoff[i])
2367 return i + 233;
2368 return 256;
2369 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002370 {
2371 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2372 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002373
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002374 /* 216-color cube */
2375 for (ri = 0; ri < 5; ++ri)
2376 if (red < cutoff[ri])
2377 break;
2378 for (gi = 0; gi < 5; ++gi)
2379 if (green < cutoff[gi])
2380 break;
2381 for (bi = 0; bi < 5; ++bi)
2382 if (blue < cutoff[bi])
2383 break;
2384 return 17 + ri * 36 + gi * 6 + bi;
2385 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002386 }
2387 return 0;
2388}
2389
2390/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002391 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002392 */
2393 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002394vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002395{
2396 int attr = 0;
2397
2398 if (cellattrs.bold)
2399 attr |= HL_BOLD;
2400 if (cellattrs.underline)
2401 attr |= HL_UNDERLINE;
2402 if (cellattrs.italic)
2403 attr |= HL_ITALIC;
2404 if (cellattrs.strike)
2405 attr |= HL_STRIKETHROUGH;
2406 if (cellattrs.reverse)
2407 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002408 return attr;
2409}
2410
2411/*
2412 * Store Vterm attributes in "cell" from highlight flags.
2413 */
2414 static void
2415hl2vtermAttr(int attr, cellattr_T *cell)
2416{
2417 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2418 if (attr & HL_BOLD)
2419 cell->attrs.bold = 1;
2420 if (attr & HL_UNDERLINE)
2421 cell->attrs.underline = 1;
2422 if (attr & HL_ITALIC)
2423 cell->attrs.italic = 1;
2424 if (attr & HL_STRIKETHROUGH)
2425 cell->attrs.strike = 1;
2426 if (attr & HL_INVERSE)
2427 cell->attrs.reverse = 1;
2428}
2429
2430/*
2431 * Convert the attributes of a vterm cell into an attribute index.
2432 */
2433 static int
2434cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2435{
2436 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002437
2438#ifdef FEAT_GUI
2439 if (gui.in_use)
2440 {
2441 guicolor_T fg, bg;
2442
2443 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2444 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2445 return get_gui_attr_idx(attr, fg, bg);
2446 }
2447 else
2448#endif
2449#ifdef FEAT_TERMGUICOLORS
2450 if (p_tgc)
2451 {
2452 guicolor_T fg, bg;
2453
2454 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2455 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2456
2457 return get_tgc_attr_idx(attr, fg, bg);
2458 }
2459 else
2460#endif
2461 {
2462 int bold = MAYBE;
2463 int fg = color2index(&cellfg, TRUE, &bold);
2464 int bg = color2index(&cellbg, FALSE, &bold);
2465
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002466 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002467 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002468 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002469 if (fg == 0 && term_default_cterm_fg >= 0)
2470 fg = term_default_cterm_fg + 1;
2471 if (bg == 0 && term_default_cterm_bg >= 0)
2472 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002473 }
2474
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002475 /* with 8 colors set the bold attribute to get a bright foreground */
2476 if (bold == TRUE)
2477 attr |= HL_BOLD;
2478 return get_cterm_attr_idx(attr, fg, bg);
2479 }
2480 return 0;
2481}
2482
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002483 static void
2484set_dirty_snapshot(term_T *term)
2485{
2486 term->tl_dirty_snapshot = TRUE;
2487#ifdef FEAT_TIMERS
2488 if (!term->tl_normal_mode)
2489 {
2490 /* Update the snapshot after 100 msec of not getting updates. */
2491 profile_setlimit(100L, &term->tl_timer_due);
2492 term->tl_timer_set = TRUE;
2493 }
2494#endif
2495}
2496
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002497 static int
2498handle_damage(VTermRect rect, void *user)
2499{
2500 term_T *term = (term_T *)user;
2501
2502 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2503 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002504 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002505 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002506 return 1;
2507}
2508
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002509 static void
2510term_scroll_up(term_T *term, int start_row, int count)
2511{
2512 win_T *wp;
2513 VTermColor fg, bg;
2514 VTermScreenCellAttrs attr;
2515 int clear_attr;
2516
2517 /* Set the color to clear lines with. */
2518 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2519 &fg, &bg);
2520 vim_memset(&attr, 0, sizeof(attr));
2521 clear_attr = cell2attr(attr, fg, bg);
2522
2523 FOR_ALL_WINDOWS(wp)
2524 {
2525 if (wp->w_buffer == term->tl_buffer)
2526 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2527 }
2528}
2529
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002530 static int
2531handle_moverect(VTermRect dest, VTermRect src, void *user)
2532{
2533 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002534 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002535
2536 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002537 * redrawing the text. But avoid doing this multiple times, postpone until
2538 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539 if (dest.start_col == src.start_col
2540 && dest.end_col == src.end_col
2541 && dest.start_row < src.start_row)
2542 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002543 if (dest.start_row == 0)
2544 term->tl_postponed_scroll += count;
2545 else
2546 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002547 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002548
2549 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2550 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002551 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002552
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002553 /* Note sure if the scrolling will work correctly, let's do a complete
2554 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002555 redraw_buf_later(term->tl_buffer, NOT_VALID);
2556 return 1;
2557}
2558
2559 static int
2560handle_movecursor(
2561 VTermPos pos,
2562 VTermPos oldpos UNUSED,
2563 int visible,
2564 void *user)
2565{
2566 term_T *term = (term_T *)user;
2567 win_T *wp;
2568
2569 term->tl_cursor_pos = pos;
2570 term->tl_cursor_visible = visible;
2571
2572 FOR_ALL_WINDOWS(wp)
2573 {
2574 if (wp->w_buffer == term->tl_buffer)
2575 position_cursor(wp, &pos);
2576 }
2577 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2578 {
2579 may_toggle_cursor(term);
2580 update_cursor(term, term->tl_cursor_visible);
2581 }
2582
2583 return 1;
2584}
2585
2586 static int
2587handle_settermprop(
2588 VTermProp prop,
2589 VTermValue *value,
2590 void *user)
2591{
2592 term_T *term = (term_T *)user;
2593
2594 switch (prop)
2595 {
2596 case VTERM_PROP_TITLE:
2597 vim_free(term->tl_title);
2598 /* a blank title isn't useful, make it empty, so that "running" is
2599 * displayed */
2600 if (*skipwhite((char_u *)value->string) == NUL)
2601 term->tl_title = NULL;
2602#ifdef WIN3264
2603 else if (!enc_utf8 && enc_codepage > 0)
2604 {
2605 WCHAR *ret = NULL;
2606 int length = 0;
2607
2608 MultiByteToWideChar_alloc(CP_UTF8, 0,
2609 (char*)value->string, (int)STRLEN(value->string),
2610 &ret, &length);
2611 if (ret != NULL)
2612 {
2613 WideCharToMultiByte_alloc(enc_codepage, 0,
2614 ret, length, (char**)&term->tl_title,
2615 &length, 0, 0);
2616 vim_free(ret);
2617 }
2618 }
2619#endif
2620 else
2621 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002622 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002623 if (term == curbuf->b_term)
2624 maketitle();
2625 break;
2626
2627 case VTERM_PROP_CURSORVISIBLE:
2628 term->tl_cursor_visible = value->boolean;
2629 may_toggle_cursor(term);
2630 out_flush();
2631 break;
2632
2633 case VTERM_PROP_CURSORBLINK:
2634 term->tl_cursor_blink = value->boolean;
2635 may_set_cursor_props(term);
2636 break;
2637
2638 case VTERM_PROP_CURSORSHAPE:
2639 term->tl_cursor_shape = value->number;
2640 may_set_cursor_props(term);
2641 break;
2642
2643 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002644 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002645 may_set_cursor_props(term);
2646 break;
2647
2648 case VTERM_PROP_ALTSCREEN:
2649 /* TODO: do anything else? */
2650 term->tl_using_altscreen = value->boolean;
2651 break;
2652
2653 default:
2654 break;
2655 }
2656 /* Always return 1, otherwise vterm doesn't store the value internally. */
2657 return 1;
2658}
2659
2660/*
2661 * The job running in the terminal resized the terminal.
2662 */
2663 static int
2664handle_resize(int rows, int cols, void *user)
2665{
2666 term_T *term = (term_T *)user;
2667 win_T *wp;
2668
2669 term->tl_rows = rows;
2670 term->tl_cols = cols;
2671 if (term->tl_vterm_size_changed)
2672 /* Size was set by vterm_set_size(), don't set the window size. */
2673 term->tl_vterm_size_changed = FALSE;
2674 else
2675 {
2676 FOR_ALL_WINDOWS(wp)
2677 {
2678 if (wp->w_buffer == term->tl_buffer)
2679 {
2680 win_setheight_win(rows, wp);
2681 win_setwidth_win(cols, wp);
2682 }
2683 }
2684 redraw_buf_later(term->tl_buffer, NOT_VALID);
2685 }
2686 return 1;
2687}
2688
2689/*
2690 * Handle a line that is pushed off the top of the screen.
2691 */
2692 static int
2693handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2694{
2695 term_T *term = (term_T *)user;
2696
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002697 /* First remove the lines that were appended before, the pushed line goes
2698 * above it. */
2699 cleanup_scrollback(term);
2700
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002701 /* If the number of lines that are stored goes over 'termscrollback' then
2702 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002703 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002704 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002705 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002706 int i;
2707
2708 curbuf = term->tl_buffer;
2709 for (i = 0; i < todo; ++i)
2710 {
2711 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2712 ml_delete(1, FALSE);
2713 }
2714 curbuf = curwin->w_buffer;
2715
2716 term->tl_scrollback.ga_len -= todo;
2717 mch_memmove(term->tl_scrollback.ga_data,
2718 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2719 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
Bram Moolenaar4d6cd292018-05-15 23:53:26 +02002720 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002721 }
2722
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002723 if (ga_grow(&term->tl_scrollback, 1) == OK)
2724 {
2725 cellattr_T *p = NULL;
2726 int len = 0;
2727 int i;
2728 int c;
2729 int col;
2730 sb_line_T *line;
2731 garray_T ga;
2732 cellattr_T fill_attr = term->tl_default_color;
2733
2734 /* do not store empty cells at the end */
2735 for (i = 0; i < cols; ++i)
2736 if (cells[i].chars[0] != 0)
2737 len = i + 1;
2738 else
2739 cell2cellattr(&cells[i], &fill_attr);
2740
2741 ga_init2(&ga, 1, 100);
2742 if (len > 0)
2743 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2744 if (p != NULL)
2745 {
2746 for (col = 0; col < len; col += cells[col].width)
2747 {
2748 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2749 {
2750 ga.ga_len = 0;
2751 break;
2752 }
2753 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2754 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2755 (char_u *)ga.ga_data + ga.ga_len);
2756 cell2cellattr(&cells[col], &p[col]);
2757 }
2758 }
2759 if (ga_grow(&ga, 1) == FAIL)
2760 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2761 else
2762 {
2763 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2764 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2765 }
2766 ga_clear(&ga);
2767
2768 line = (sb_line_T *)term->tl_scrollback.ga_data
2769 + term->tl_scrollback.ga_len;
2770 line->sb_cols = len;
2771 line->sb_cells = p;
2772 line->sb_fill_attr = fill_attr;
2773 ++term->tl_scrollback.ga_len;
2774 ++term->tl_scrollback_scrolled;
2775 }
2776 return 0; /* ignored */
2777}
2778
2779static VTermScreenCallbacks screen_callbacks = {
2780 handle_damage, /* damage */
2781 handle_moverect, /* moverect */
2782 handle_movecursor, /* movecursor */
2783 handle_settermprop, /* settermprop */
2784 NULL, /* bell */
2785 handle_resize, /* resize */
2786 handle_pushline, /* sb_pushline */
2787 NULL /* sb_popline */
2788};
2789
2790/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002791 * Do the work after the channel of a terminal was closed.
2792 * Must be called only when updating_screen is FALSE.
2793 * Returns TRUE when a buffer was closed (list of terminals may have changed).
2794 */
2795 static int
2796term_after_channel_closed(term_T *term)
2797{
2798 /* Unless in Terminal-Normal mode: clear the vterm. */
2799 if (!term->tl_normal_mode)
2800 {
2801 int fnum = term->tl_buffer->b_fnum;
2802
2803 cleanup_vterm(term);
2804
2805 if (term->tl_finish == TL_FINISH_CLOSE)
2806 {
2807 aco_save_T aco;
2808
2809 /* ++close or term_finish == "close" */
2810 ch_log(NULL, "terminal job finished, closing window");
2811 aucmd_prepbuf(&aco, term->tl_buffer);
2812 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
2813 aucmd_restbuf(&aco);
2814 return TRUE;
2815 }
2816 if (term->tl_finish == TL_FINISH_OPEN
2817 && term->tl_buffer->b_nwindows == 0)
2818 {
2819 char buf[50];
2820
2821 /* TODO: use term_opencmd */
2822 ch_log(NULL, "terminal job finished, opening window");
2823 vim_snprintf(buf, sizeof(buf),
2824 term->tl_opencmd == NULL
2825 ? "botright sbuf %d"
2826 : (char *)term->tl_opencmd, fnum);
2827 do_cmdline_cmd((char_u *)buf);
2828 }
2829 else
2830 ch_log(NULL, "terminal job finished");
2831 }
2832
2833 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2834 return FALSE;
2835}
2836
2837/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002838 * Called when a channel has been closed.
2839 * If this was a channel for a terminal window then finish it up.
2840 */
2841 void
2842term_channel_closed(channel_T *ch)
2843{
2844 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002845 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002846 int did_one = FALSE;
2847
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002848 for (term = first_term; term != NULL; term = next_term)
2849 {
2850 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002851 if (term->tl_job == ch->ch_job)
2852 {
2853 term->tl_channel_closed = TRUE;
2854 did_one = TRUE;
2855
Bram Moolenaard23a8232018-02-10 18:45:26 +01002856 VIM_CLEAR(term->tl_title);
2857 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002858#ifdef WIN3264
2859 if (term->tl_out_fd != NULL)
2860 {
2861 fclose(term->tl_out_fd);
2862 term->tl_out_fd = NULL;
2863 }
2864#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002865
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002866 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002867 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002868 /* Cannot open or close windows now. Can happen when
2869 * 'lazyredraw' is set. */
2870 term->tl_channel_recently_closed = TRUE;
2871 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002872 }
2873
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002874 if (term_after_channel_closed(term))
2875 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002876 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002877 }
2878
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002879 if (did_one)
2880 {
2881 redraw_statuslines();
2882
2883 /* Need to break out of vgetc(). */
2884 ins_char_typebuf(K_IGNORE);
2885 typebuf_was_filled = TRUE;
2886
2887 term = curbuf->b_term;
2888 if (term != NULL)
2889 {
2890 if (term->tl_job == ch->ch_job)
2891 maketitle();
2892 update_cursor(term, term->tl_cursor_visible);
2893 }
2894 }
2895}
2896
2897/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002898 * To be called after resetting updating_screen: handle any terminal where the
2899 * channel was closed.
2900 */
2901 void
2902term_check_channel_closed_recently()
2903{
2904 term_T *term;
2905 term_T *next_term;
2906
2907 for (term = first_term; term != NULL; term = next_term)
2908 {
2909 next_term = term->tl_next;
2910 if (term->tl_channel_recently_closed)
2911 {
2912 term->tl_channel_recently_closed = FALSE;
2913 if (term_after_channel_closed(term))
2914 // start over, the list may have changed
2915 next_term = first_term;
2916 }
2917 }
2918}
2919
2920/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002921 * Fill one screen line from a line of the terminal.
2922 * Advances "pos" to past the last column.
2923 */
2924 static void
2925term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2926{
2927 int off = screen_get_current_line_off();
2928
2929 for (pos->col = 0; pos->col < max_col; )
2930 {
2931 VTermScreenCell cell;
2932 int c;
2933
2934 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2935 vim_memset(&cell, 0, sizeof(cell));
2936
2937 c = cell.chars[0];
2938 if (c == NUL)
2939 {
2940 ScreenLines[off] = ' ';
2941 if (enc_utf8)
2942 ScreenLinesUC[off] = NUL;
2943 }
2944 else
2945 {
2946 if (enc_utf8)
2947 {
2948 int i;
2949
2950 /* composing chars */
2951 for (i = 0; i < Screen_mco
2952 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2953 {
2954 ScreenLinesC[i][off] = cell.chars[i + 1];
2955 if (cell.chars[i + 1] == 0)
2956 break;
2957 }
2958 if (c >= 0x80 || (Screen_mco > 0
2959 && ScreenLinesC[0][off] != 0))
2960 {
2961 ScreenLines[off] = ' ';
2962 ScreenLinesUC[off] = c;
2963 }
2964 else
2965 {
2966 ScreenLines[off] = c;
2967 ScreenLinesUC[off] = NUL;
2968 }
2969 }
2970#ifdef WIN3264
2971 else if (has_mbyte && c >= 0x80)
2972 {
2973 char_u mb[MB_MAXBYTES+1];
2974 WCHAR wc = c;
2975
2976 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2977 (char*)mb, 2, 0, 0) > 1)
2978 {
2979 ScreenLines[off] = mb[0];
2980 ScreenLines[off + 1] = mb[1];
2981 cell.width = mb_ptr2cells(mb);
2982 }
2983 else
2984 ScreenLines[off] = c;
2985 }
2986#endif
2987 else
2988 ScreenLines[off] = c;
2989 }
2990 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2991
2992 ++pos->col;
2993 ++off;
2994 if (cell.width == 2)
2995 {
2996 if (enc_utf8)
2997 ScreenLinesUC[off] = NUL;
2998
2999 /* don't set the second byte to NUL for a DBCS encoding, it
3000 * has been set above */
3001 if (enc_utf8 || !has_mbyte)
3002 ScreenLines[off] = NUL;
3003
3004 ++pos->col;
3005 ++off;
3006 }
3007 }
3008}
3009
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003010#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003011 static void
3012update_system_term(term_T *term)
3013{
3014 VTermPos pos;
3015 VTermScreen *screen;
3016
3017 if (term->tl_vterm == NULL)
3018 return;
3019 screen = vterm_obtain_screen(term->tl_vterm);
3020
3021 /* Scroll up to make more room for terminal lines if needed. */
3022 while (term->tl_toprow > 0
3023 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3024 {
3025 int save_p_more = p_more;
3026
3027 p_more = FALSE;
3028 msg_row = Rows - 1;
3029 msg_puts((char_u *)"\n");
3030 p_more = save_p_more;
3031 --term->tl_toprow;
3032 }
3033
3034 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3035 && pos.row < Rows; ++pos.row)
3036 {
3037 if (pos.row < term->tl_rows)
3038 {
3039 int max_col = MIN(Columns, term->tl_cols);
3040
3041 term_line2screenline(screen, &pos, max_col);
3042 }
3043 else
3044 pos.col = 0;
3045
3046 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
3047 }
3048
3049 term->tl_dirty_row_start = MAX_ROW;
3050 term->tl_dirty_row_end = 0;
3051 update_cursor(term, TRUE);
3052}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003053#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003054
3055/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003056 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3057 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003058 * Terminal-Normal mode.
3059 */
3060 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003061term_do_update_window(win_T *wp)
3062{
3063 term_T *term = wp->w_buffer->b_term;
3064
3065 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3066}
3067
3068/*
3069 * Called to update a window that contains an active terminal.
3070 */
3071 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003072term_update_window(win_T *wp)
3073{
3074 term_T *term = wp->w_buffer->b_term;
3075 VTerm *vterm;
3076 VTermScreen *screen;
3077 VTermState *state;
3078 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003079 int rows, cols;
3080 int newrows, newcols;
3081 int minsize;
3082 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003083
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003084 vterm = term->tl_vterm;
3085 screen = vterm_obtain_screen(vterm);
3086 state = vterm_obtain_state(vterm);
3087
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003088 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3089 * SOME_VALID only redraw what was marked dirty. */
3090 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003091 {
3092 term->tl_dirty_row_start = 0;
3093 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003094
3095 if (term->tl_postponed_scroll > 0
3096 && term->tl_postponed_scroll < term->tl_rows / 3)
3097 /* Scrolling is usually faster than redrawing, when there are only
3098 * a few lines to scroll. */
3099 term_scroll_up(term, 0, term->tl_postponed_scroll);
3100 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003101 }
3102
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003103 /*
3104 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003105 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003106 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003107 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003108
Bram Moolenaar498c2562018-04-15 23:45:15 +02003109 newrows = 99999;
3110 newcols = 99999;
3111 FOR_ALL_WINDOWS(twp)
3112 {
3113 /* When more than one window shows the same terminal, use the
3114 * smallest size. */
3115 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003116 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003117 newrows = MIN(newrows, twp->w_height);
3118 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003119 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003120 }
3121 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3122 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3123
3124 if (term->tl_rows != newrows || term->tl_cols != newcols)
3125 {
3126
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003127
3128 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003129 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003131 newrows);
3132 term_report_winsize(term, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003133 }
3134
3135 /* The cursor may have been moved when resizing. */
3136 vterm_state_get_cursorpos(state, &pos);
3137 position_cursor(wp, &pos);
3138
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003139 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3140 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003141 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003142 if (pos.row < term->tl_rows)
3143 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003144 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003145
Bram Moolenaar13568252018-03-16 20:46:58 +01003146 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003147 }
3148 else
3149 pos.col = 0;
3150
Bram Moolenaarf118d482018-03-13 13:14:00 +01003151 screen_line(wp->w_winrow + pos.row
3152#ifdef FEAT_MENU
3153 + winbar_height(wp)
3154#endif
3155 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003157 term->tl_dirty_row_start = MAX_ROW;
3158 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003159}
3160
3161/*
3162 * Return TRUE if "wp" is a terminal window where the job has finished.
3163 */
3164 int
3165term_is_finished(buf_T *buf)
3166{
3167 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3168}
3169
3170/*
3171 * Return TRUE if "wp" is a terminal window where the job has finished or we
3172 * are in Terminal-Normal mode, thus we show the buffer contents.
3173 */
3174 int
3175term_show_buffer(buf_T *buf)
3176{
3177 term_T *term = buf->b_term;
3178
3179 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3180}
3181
3182/*
3183 * The current buffer is going to be changed. If there is terminal
3184 * highlighting remove it now.
3185 */
3186 void
3187term_change_in_curbuf(void)
3188{
3189 term_T *term = curbuf->b_term;
3190
3191 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3192 {
3193 free_scrollback(term);
3194 redraw_buf_later(term->tl_buffer, NOT_VALID);
3195
3196 /* The buffer is now like a normal buffer, it cannot be easily
3197 * abandoned when changed. */
3198 set_string_option_direct((char_u *)"buftype", -1,
3199 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3200 }
3201}
3202
3203/*
3204 * Get the screen attribute for a position in the buffer.
3205 * Use a negative "col" to get the filler background color.
3206 */
3207 int
3208term_get_attr(buf_T *buf, linenr_T lnum, int col)
3209{
3210 term_T *term = buf->b_term;
3211 sb_line_T *line;
3212 cellattr_T *cellattr;
3213
3214 if (lnum > term->tl_scrollback.ga_len)
3215 cellattr = &term->tl_default_color;
3216 else
3217 {
3218 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3219 if (col < 0 || col >= line->sb_cols)
3220 cellattr = &line->sb_fill_attr;
3221 else
3222 cellattr = line->sb_cells + col;
3223 }
3224 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3225}
3226
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003227/*
3228 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003229 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003230 */
3231 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003232cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003233{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003234 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003235}
3236
3237/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003238 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003239 */
3240 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003241init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003242{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003243 VTermColor *fg, *bg;
3244 int fgval, bgval;
3245 int id;
3246
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003247 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3248 term->tl_default_color.width = 1;
3249 fg = &term->tl_default_color.fg;
3250 bg = &term->tl_default_color.bg;
3251
3252 /* Vterm uses a default black background. Set it to white when
3253 * 'background' is "light". */
3254 if (*p_bg == 'l')
3255 {
3256 fgval = 0;
3257 bgval = 255;
3258 }
3259 else
3260 {
3261 fgval = 255;
3262 bgval = 0;
3263 }
3264 fg->red = fg->green = fg->blue = fgval;
3265 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003266 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003267
3268 /* The "Terminal" highlight group overrules the defaults. */
3269 id = syn_name2id((char_u *)"Terminal");
3270
Bram Moolenaar46359e12017-11-29 22:33:38 +01003271 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003272#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3273 if (0
3274# ifdef FEAT_GUI
3275 || gui.in_use
3276# endif
3277# ifdef FEAT_TERMGUICOLORS
3278 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003279# ifdef FEAT_VTP
3280 /* Finally get INVALCOLOR on this execution path */
3281 || (!p_tgc && t_colors >= 256)
3282# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003283# endif
3284 )
3285 {
3286 guicolor_T fg_rgb = INVALCOLOR;
3287 guicolor_T bg_rgb = INVALCOLOR;
3288
3289 if (id != 0)
3290 syn_id2colors(id, &fg_rgb, &bg_rgb);
3291
3292# ifdef FEAT_GUI
3293 if (gui.in_use)
3294 {
3295 if (fg_rgb == INVALCOLOR)
3296 fg_rgb = gui.norm_pixel;
3297 if (bg_rgb == INVALCOLOR)
3298 bg_rgb = gui.back_pixel;
3299 }
3300# ifdef FEAT_TERMGUICOLORS
3301 else
3302# endif
3303# endif
3304# ifdef FEAT_TERMGUICOLORS
3305 {
3306 if (fg_rgb == INVALCOLOR)
3307 fg_rgb = cterm_normal_fg_gui_color;
3308 if (bg_rgb == INVALCOLOR)
3309 bg_rgb = cterm_normal_bg_gui_color;
3310 }
3311# endif
3312 if (fg_rgb != INVALCOLOR)
3313 {
3314 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3315
3316 fg->red = (unsigned)(rgb >> 16);
3317 fg->green = (unsigned)(rgb >> 8) & 255;
3318 fg->blue = (unsigned)rgb & 255;
3319 }
3320 if (bg_rgb != INVALCOLOR)
3321 {
3322 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3323
3324 bg->red = (unsigned)(rgb >> 16);
3325 bg->green = (unsigned)(rgb >> 8) & 255;
3326 bg->blue = (unsigned)rgb & 255;
3327 }
3328 }
3329 else
3330#endif
3331 if (id != 0 && t_colors >= 16)
3332 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003333 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003334 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003335 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003336 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003337 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003338 else
3339 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003340#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003341 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003342#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003343
3344 /* In an MS-Windows console we know the normal colors. */
3345 if (cterm_normal_fg_color > 0)
3346 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003347 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003348# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003349 tmp = fg->red;
3350 fg->red = fg->blue;
3351 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003352# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003353 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003354# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003355 else
3356 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003357# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003358
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003359 if (cterm_normal_bg_color > 0)
3360 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003361 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003362# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003363 tmp = bg->red;
3364 bg->red = bg->blue;
3365 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003366# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003367 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003368# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003369 else
3370 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003371# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003372 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003373}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003374
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003375#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3376/*
3377 * Set the 16 ANSI colors from array of RGB values
3378 */
3379 static void
3380set_vterm_palette(VTerm *vterm, long_u *rgb)
3381{
3382 int index = 0;
3383 VTermState *state = vterm_obtain_state(vterm);
3384 for (; index < 16; index++)
3385 {
3386 VTermColor color;
3387 color.red = (unsigned)(rgb[index] >> 16);
3388 color.green = (unsigned)(rgb[index] >> 8) & 255;
3389 color.blue = (unsigned)rgb[index] & 255;
3390 vterm_state_set_palette_color(state, index, &color);
3391 }
3392}
3393
3394/*
3395 * Set the ANSI color palette from a list of colors
3396 */
3397 static int
3398set_ansi_colors_list(VTerm *vterm, list_T *list)
3399{
3400 int n = 0;
3401 long_u rgb[16];
3402 listitem_T *li = list->lv_first;
3403
3404 for (; li != NULL && n < 16; li = li->li_next, n++)
3405 {
3406 char_u *color_name;
3407 guicolor_T guicolor;
3408
3409 color_name = get_tv_string_chk(&li->li_tv);
3410 if (color_name == NULL)
3411 return FAIL;
3412
3413 guicolor = GUI_GET_COLOR(color_name);
3414 if (guicolor == INVALCOLOR)
3415 return FAIL;
3416
3417 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3418 }
3419
3420 if (n != 16 || li != NULL)
3421 return FAIL;
3422
3423 set_vterm_palette(vterm, rgb);
3424
3425 return OK;
3426}
3427
3428/*
3429 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3430 */
3431 static void
3432init_vterm_ansi_colors(VTerm *vterm)
3433{
3434 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3435
3436 if (var != NULL
3437 && (var->di_tv.v_type != VAR_LIST
3438 || var->di_tv.vval.v_list == NULL
3439 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3440 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3441}
3442#endif
3443
Bram Moolenaar52acb112018-03-18 19:20:22 +01003444/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003445 * Handles a "drop" command from the job in the terminal.
3446 * "item" is the file name, "item->li_next" may have options.
3447 */
3448 static void
3449handle_drop_command(listitem_T *item)
3450{
3451 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003452 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003453 int bufnr;
3454 win_T *wp;
3455 tabpage_T *tp;
3456 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003457 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003458
3459 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3460 FOR_ALL_TAB_WINDOWS(tp, wp)
3461 {
3462 if (wp->w_buffer->b_fnum == bufnr)
3463 {
3464 /* buffer is in a window already, go there */
3465 goto_tabpage_win(tp, wp);
3466 return;
3467 }
3468 }
3469
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003470 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003471
3472 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3473 && opt_item->li_tv.vval.v_dict != NULL)
3474 {
3475 dict_T *dict = opt_item->li_tv.vval.v_dict;
3476 char_u *p;
3477
3478 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3479 if (p == NULL)
3480 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3481 if (p != NULL)
3482 {
3483 if (check_ff_value(p) == FAIL)
3484 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3485 else
3486 ea.force_ff = *p;
3487 }
3488 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3489 if (p == NULL)
3490 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3491 if (p != NULL)
3492 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003493 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003494 if (ea.cmd != NULL)
3495 {
3496 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3497 ea.force_enc = 11;
3498 tofree = ea.cmd;
3499 }
3500 }
3501
3502 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3503 if (p != NULL)
3504 get_bad_opt(p, &ea);
3505
3506 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3507 ea.force_bin = FORCE_BIN;
3508 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3509 ea.force_bin = FORCE_BIN;
3510 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3511 ea.force_bin = FORCE_NOBIN;
3512 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3513 ea.force_bin = FORCE_NOBIN;
3514 }
3515
3516 /* open in new window, like ":split fname" */
3517 if (ea.cmd == NULL)
3518 ea.cmd = (char_u *)"split";
3519 ea.arg = fname;
3520 ea.cmdidx = CMD_split;
3521 ex_splitview(&ea);
3522
3523 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003524}
3525
3526/*
3527 * Handles a function call from the job running in a terminal.
3528 * "item" is the function name, "item->li_next" has the arguments.
3529 */
3530 static void
3531handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3532{
3533 char_u *func;
3534 typval_T argvars[2];
3535 typval_T rettv;
3536 int doesrange;
3537
3538 if (item->li_next == NULL)
3539 {
3540 ch_log(channel, "Missing function arguments for call");
3541 return;
3542 }
3543 func = get_tv_string(&item->li_tv);
3544
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003545 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003546 {
3547 ch_log(channel, "Invalid function name: %s", func);
3548 return;
3549 }
3550
3551 argvars[0].v_type = VAR_NUMBER;
3552 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3553 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003554 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003555 2, argvars, /* argv_func */ NULL,
3556 /* firstline */ 1, /* lastline */ 1,
3557 &doesrange, /* evaluate */ TRUE,
3558 /* partial */ NULL, /* selfdict */ NULL) == OK)
3559 {
3560 clear_tv(&rettv);
3561 ch_log(channel, "Function %s called", func);
3562 }
3563 else
3564 ch_log(channel, "Calling function %s failed", func);
3565}
3566
3567/*
3568 * Called by libvterm when it cannot recognize an OSC sequence.
3569 * We recognize a terminal API command.
3570 */
3571 static int
3572parse_osc(const char *command, size_t cmdlen, void *user)
3573{
3574 term_T *term = (term_T *)user;
3575 js_read_T reader;
3576 typval_T tv;
3577 channel_T *channel = term->tl_job == NULL ? NULL
3578 : term->tl_job->jv_channel;
3579
3580 /* We recognize only OSC 5 1 ; {command} */
3581 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3582 return 0; /* not handled */
3583
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003584 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003585 if (reader.js_buf == NULL)
3586 return 1;
3587 reader.js_fill = NULL;
3588 reader.js_used = 0;
3589 if (json_decode(&reader, &tv, 0) == OK
3590 && tv.v_type == VAR_LIST
3591 && tv.vval.v_list != NULL)
3592 {
3593 listitem_T *item = tv.vval.v_list->lv_first;
3594
3595 if (item == NULL)
3596 ch_log(channel, "Missing command");
3597 else
3598 {
3599 char_u *cmd = get_tv_string(&item->li_tv);
3600
Bram Moolenaara997b452018-04-17 23:24:06 +02003601 /* Make sure an invoked command doesn't delete the buffer (and the
3602 * terminal) under our fingers. */
3603 ++term->tl_buffer->b_locked;
3604
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003605 item = item->li_next;
3606 if (item == NULL)
3607 ch_log(channel, "Missing argument for %s", cmd);
3608 else if (STRCMP(cmd, "drop") == 0)
3609 handle_drop_command(item);
3610 else if (STRCMP(cmd, "call") == 0)
3611 handle_call_command(term, channel, item);
3612 else
3613 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003614 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003615 }
3616 }
3617 else
3618 ch_log(channel, "Invalid JSON received");
3619
3620 vim_free(reader.js_buf);
3621 clear_tv(&tv);
3622 return 1;
3623}
3624
3625static VTermParserCallbacks parser_fallbacks = {
3626 NULL, /* text */
3627 NULL, /* control */
3628 NULL, /* escape */
3629 NULL, /* csi */
3630 parse_osc, /* osc */
3631 NULL, /* dcs */
3632 NULL /* resize */
3633};
3634
3635/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003636 * Use Vim's allocation functions for vterm so profiling works.
3637 */
3638 static void *
3639vterm_malloc(size_t size, void *data UNUSED)
3640{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003641 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003642}
3643
3644 static void
3645vterm_memfree(void *ptr, void *data UNUSED)
3646{
3647 vim_free(ptr);
3648}
3649
3650static VTermAllocatorFunctions vterm_allocator = {
3651 &vterm_malloc,
3652 &vterm_memfree
3653};
3654
3655/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003656 * Create a new vterm and initialize it.
3657 */
3658 static void
3659create_vterm(term_T *term, int rows, int cols)
3660{
3661 VTerm *vterm;
3662 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003663 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003664 VTermValue value;
3665
Bram Moolenaar756ef112018-04-10 12:04:27 +02003666 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003667 term->tl_vterm = vterm;
3668 screen = vterm_obtain_screen(vterm);
3669 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3670 /* TODO: depends on 'encoding'. */
3671 vterm_set_utf8(vterm, 1);
3672
3673 init_default_colors(term);
3674
3675 vterm_state_set_default_colors(
3676 vterm_obtain_state(vterm),
3677 &term->tl_default_color.fg,
3678 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003679
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003680 if (t_colors >= 16)
3681 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3682
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003683 /* Required to initialize most things. */
3684 vterm_screen_reset(screen, 1 /* hard */);
3685
3686 /* Allow using alternate screen. */
3687 vterm_screen_enable_altscreen(screen, 1);
3688
3689 /* For unix do not use a blinking cursor. In an xterm this causes the
3690 * cursor to blink if it's blinking in the xterm.
3691 * For Windows we respect the system wide setting. */
3692#ifdef WIN3264
3693 if (GetCaretBlinkTime() == INFINITE)
3694 value.boolean = 0;
3695 else
3696 value.boolean = 1;
3697#else
3698 value.boolean = 0;
3699#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003700 state = vterm_obtain_state(vterm);
3701 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3702 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003703}
3704
3705/*
3706 * Return the text to show for the buffer name and status.
3707 */
3708 char_u *
3709term_get_status_text(term_T *term)
3710{
3711 if (term->tl_status_text == NULL)
3712 {
3713 char_u *txt;
3714 size_t len;
3715
3716 if (term->tl_normal_mode)
3717 {
3718 if (term_job_running(term))
3719 txt = (char_u *)_("Terminal");
3720 else
3721 txt = (char_u *)_("Terminal-finished");
3722 }
3723 else if (term->tl_title != NULL)
3724 txt = term->tl_title;
3725 else if (term_none_open(term))
3726 txt = (char_u *)_("active");
3727 else if (term_job_running(term))
3728 txt = (char_u *)_("running");
3729 else
3730 txt = (char_u *)_("finished");
3731 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3732 term->tl_status_text = alloc((int)len);
3733 if (term->tl_status_text != NULL)
3734 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3735 term->tl_buffer->b_fname, txt);
3736 }
3737 return term->tl_status_text;
3738}
3739
3740/*
3741 * Mark references in jobs of terminals.
3742 */
3743 int
3744set_ref_in_term(int copyID)
3745{
3746 int abort = FALSE;
3747 term_T *term;
3748 typval_T tv;
3749
3750 for (term = first_term; term != NULL; term = term->tl_next)
3751 if (term->tl_job != NULL)
3752 {
3753 tv.v_type = VAR_JOB;
3754 tv.vval.v_job = term->tl_job;
3755 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3756 }
3757 return abort;
3758}
3759
3760/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003761 * Cache "Terminal" highlight group colors.
3762 */
3763 void
3764set_terminal_default_colors(int cterm_fg, int cterm_bg)
3765{
3766 term_default_cterm_fg = cterm_fg - 1;
3767 term_default_cterm_bg = cterm_bg - 1;
3768}
3769
3770/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003771 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003772 * Returns NULL when the buffer is not for a terminal window and logs a message
3773 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003774 */
3775 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003776term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003777{
3778 buf_T *buf;
3779
3780 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3781 ++emsg_off;
3782 buf = get_buf_tv(&argvars[0], FALSE);
3783 --emsg_off;
3784 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003785 {
3786 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003787 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003788 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003789 return buf;
3790}
3791
Bram Moolenaard96ff162018-02-18 22:13:29 +01003792 static int
3793same_color(VTermColor *a, VTermColor *b)
3794{
3795 return a->red == b->red
3796 && a->green == b->green
3797 && a->blue == b->blue
3798 && a->ansi_index == b->ansi_index;
3799}
3800
3801 static void
3802dump_term_color(FILE *fd, VTermColor *color)
3803{
3804 fprintf(fd, "%02x%02x%02x%d",
3805 (int)color->red, (int)color->green, (int)color->blue,
3806 (int)color->ansi_index);
3807}
3808
3809/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003810 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003811 *
3812 * Each screen cell in full is:
3813 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3814 * {characters} is a space for an empty cell
3815 * For a double-width character "+" is changed to "*" and the next cell is
3816 * skipped.
3817 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3818 * when "&" use the same as the previous cell.
3819 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3820 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3821 * {color-idx} is a number from 0 to 255
3822 *
3823 * Screen cell with same width, attributes and color as the previous one:
3824 * |{characters}
3825 *
3826 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3827 *
3828 * Repeating the previous screen cell:
3829 * @{count}
3830 */
3831 void
3832f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3833{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003834 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003835 term_T *term;
3836 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003837 int max_height = 0;
3838 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003839 stat_T st;
3840 FILE *fd;
3841 VTermPos pos;
3842 VTermScreen *screen;
3843 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003844 VTermState *state;
3845 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003846
3847 if (check_restricted() || check_secure())
3848 return;
3849 if (buf == NULL)
3850 return;
3851 term = buf->b_term;
3852
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003853 if (argvars[2].v_type != VAR_UNKNOWN)
3854 {
3855 dict_T *d;
3856
3857 if (argvars[2].v_type != VAR_DICT)
3858 {
3859 EMSG(_(e_dictreq));
3860 return;
3861 }
3862 d = argvars[2].vval.v_dict;
3863 if (d != NULL)
3864 {
3865 max_height = get_dict_number(d, (char_u *)"rows");
3866 max_width = get_dict_number(d, (char_u *)"columns");
3867 }
3868 }
3869
Bram Moolenaard96ff162018-02-18 22:13:29 +01003870 fname = get_tv_string_chk(&argvars[1]);
3871 if (fname == NULL)
3872 return;
3873 if (mch_stat((char *)fname, &st) >= 0)
3874 {
3875 EMSG2(_("E953: File exists: %s"), fname);
3876 return;
3877 }
3878
Bram Moolenaard96ff162018-02-18 22:13:29 +01003879 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3880 {
3881 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3882 return;
3883 }
3884
3885 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3886
3887 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003888 state = vterm_obtain_state(term->tl_vterm);
3889 vterm_state_get_cursorpos(state, &cursor_pos);
3890
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003891 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3892 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003893 {
3894 int repeat = 0;
3895
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003896 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3897 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003898 {
3899 VTermScreenCell cell;
3900 int same_attr;
3901 int same_chars = TRUE;
3902 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003903 int is_cursor_pos = (pos.col == cursor_pos.col
3904 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003905
3906 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3907 vim_memset(&cell, 0, sizeof(cell));
3908
3909 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3910 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003911 int c = cell.chars[i];
3912 int pc = prev_cell.chars[i];
3913
3914 /* For the first character NUL is the same as space. */
3915 if (i == 0)
3916 {
3917 c = (c == NUL) ? ' ' : c;
3918 pc = (pc == NUL) ? ' ' : pc;
3919 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003920 if (cell.chars[i] != prev_cell.chars[i])
3921 same_chars = FALSE;
3922 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3923 break;
3924 }
3925 same_attr = vtermAttr2hl(cell.attrs)
3926 == vtermAttr2hl(prev_cell.attrs)
3927 && same_color(&cell.fg, &prev_cell.fg)
3928 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003929 if (same_chars && cell.width == prev_cell.width && same_attr
3930 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003931 {
3932 ++repeat;
3933 }
3934 else
3935 {
3936 if (repeat > 0)
3937 {
3938 fprintf(fd, "@%d", repeat);
3939 repeat = 0;
3940 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003941 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003942
3943 if (cell.chars[0] == NUL)
3944 fputs(" ", fd);
3945 else
3946 {
3947 char_u charbuf[10];
3948 int len;
3949
3950 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3951 && cell.chars[i] != NUL; ++i)
3952 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003953 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003954 fwrite(charbuf, len, 1, fd);
3955 }
3956 }
3957
3958 /* When only the characters differ we don't write anything, the
3959 * following "|", "@" or NL will indicate using the same
3960 * attributes. */
3961 if (cell.width != prev_cell.width || !same_attr)
3962 {
3963 if (cell.width == 2)
3964 {
3965 fputs("*", fd);
3966 ++pos.col;
3967 }
3968 else
3969 fputs("+", fd);
3970
3971 if (same_attr)
3972 {
3973 fputs("&", fd);
3974 }
3975 else
3976 {
3977 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3978 if (same_color(&cell.fg, &prev_cell.fg))
3979 fputs("&", fd);
3980 else
3981 {
3982 fputs("#", fd);
3983 dump_term_color(fd, &cell.fg);
3984 }
3985 if (same_color(&cell.bg, &prev_cell.bg))
3986 fputs("&", fd);
3987 else
3988 {
3989 fputs("#", fd);
3990 dump_term_color(fd, &cell.bg);
3991 }
3992 }
3993 }
3994
3995 prev_cell = cell;
3996 }
3997 }
3998 if (repeat > 0)
3999 fprintf(fd, "@%d", repeat);
4000 fputs("\n", fd);
4001 }
4002
4003 fclose(fd);
4004}
4005
4006/*
4007 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4008 */
4009 static void
4010dump_is_corrupt(garray_T *gap)
4011{
4012 ga_concat(gap, (char_u *)"CORRUPT");
4013}
4014
4015 static void
4016append_cell(garray_T *gap, cellattr_T *cell)
4017{
4018 if (ga_grow(gap, 1) == OK)
4019 {
4020 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4021 ++gap->ga_len;
4022 }
4023}
4024
4025/*
4026 * Read the dump file from "fd" and append lines to the current buffer.
4027 * Return the cell width of the longest line.
4028 */
4029 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004030read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004031{
4032 int c;
4033 garray_T ga_text;
4034 garray_T ga_cell;
4035 char_u *prev_char = NULL;
4036 int attr = 0;
4037 cellattr_T cell;
4038 term_T *term = curbuf->b_term;
4039 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004040 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004041
4042 ga_init2(&ga_text, 1, 90);
4043 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4044 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004045 cursor_pos->row = -1;
4046 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004047
4048 c = fgetc(fd);
4049 for (;;)
4050 {
4051 if (c == EOF)
4052 break;
4053 if (c == '\n')
4054 {
4055 /* End of a line: append it to the buffer. */
4056 if (ga_text.ga_data == NULL)
4057 dump_is_corrupt(&ga_text);
4058 if (ga_grow(&term->tl_scrollback, 1) == OK)
4059 {
4060 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4061 + term->tl_scrollback.ga_len;
4062
4063 if (max_cells < ga_cell.ga_len)
4064 max_cells = ga_cell.ga_len;
4065 line->sb_cols = ga_cell.ga_len;
4066 line->sb_cells = ga_cell.ga_data;
4067 line->sb_fill_attr = term->tl_default_color;
4068 ++term->tl_scrollback.ga_len;
4069 ga_init(&ga_cell);
4070
4071 ga_append(&ga_text, NUL);
4072 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4073 ga_text.ga_len, FALSE);
4074 }
4075 else
4076 ga_clear(&ga_cell);
4077 ga_text.ga_len = 0;
4078
4079 c = fgetc(fd);
4080 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004081 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004082 {
4083 int prev_len = ga_text.ga_len;
4084
Bram Moolenaar9271d052018-02-25 21:39:46 +01004085 if (c == '>')
4086 {
4087 if (cursor_pos->row != -1)
4088 dump_is_corrupt(&ga_text); /* duplicate cursor */
4089 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4090 cursor_pos->col = ga_cell.ga_len;
4091 }
4092
Bram Moolenaard96ff162018-02-18 22:13:29 +01004093 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4094 c = fgetc(fd);
4095 if (c != EOF)
4096 ga_append(&ga_text, c);
4097 for (;;)
4098 {
4099 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004100 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004101 || c == EOF || c == '\n')
4102 break;
4103 ga_append(&ga_text, c);
4104 }
4105
4106 /* save the character for repeating it */
4107 vim_free(prev_char);
4108 if (ga_text.ga_data != NULL)
4109 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4110 ga_text.ga_len - prev_len);
4111
Bram Moolenaar9271d052018-02-25 21:39:46 +01004112 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004113 {
4114 /* use all attributes from previous cell */
4115 }
4116 else if (c == '+' || c == '*')
4117 {
4118 int is_bg;
4119
4120 cell.width = c == '+' ? 1 : 2;
4121
4122 c = fgetc(fd);
4123 if (c == '&')
4124 {
4125 /* use same attr as previous cell */
4126 c = fgetc(fd);
4127 }
4128 else if (isdigit(c))
4129 {
4130 /* get the decimal attribute */
4131 attr = 0;
4132 while (isdigit(c))
4133 {
4134 attr = attr * 10 + (c - '0');
4135 c = fgetc(fd);
4136 }
4137 hl2vtermAttr(attr, &cell);
4138 }
4139 else
4140 dump_is_corrupt(&ga_text);
4141
4142 /* is_bg == 0: fg, is_bg == 1: bg */
4143 for (is_bg = 0; is_bg <= 1; ++is_bg)
4144 {
4145 if (c == '&')
4146 {
4147 /* use same color as previous cell */
4148 c = fgetc(fd);
4149 }
4150 else if (c == '#')
4151 {
4152 int red, green, blue, index = 0;
4153
4154 c = fgetc(fd);
4155 red = hex2nr(c);
4156 c = fgetc(fd);
4157 red = (red << 4) + hex2nr(c);
4158 c = fgetc(fd);
4159 green = hex2nr(c);
4160 c = fgetc(fd);
4161 green = (green << 4) + hex2nr(c);
4162 c = fgetc(fd);
4163 blue = hex2nr(c);
4164 c = fgetc(fd);
4165 blue = (blue << 4) + hex2nr(c);
4166 c = fgetc(fd);
4167 if (!isdigit(c))
4168 dump_is_corrupt(&ga_text);
4169 while (isdigit(c))
4170 {
4171 index = index * 10 + (c - '0');
4172 c = fgetc(fd);
4173 }
4174
4175 if (is_bg)
4176 {
4177 cell.bg.red = red;
4178 cell.bg.green = green;
4179 cell.bg.blue = blue;
4180 cell.bg.ansi_index = index;
4181 }
4182 else
4183 {
4184 cell.fg.red = red;
4185 cell.fg.green = green;
4186 cell.fg.blue = blue;
4187 cell.fg.ansi_index = index;
4188 }
4189 }
4190 else
4191 dump_is_corrupt(&ga_text);
4192 }
4193 }
4194 else
4195 dump_is_corrupt(&ga_text);
4196
4197 append_cell(&ga_cell, &cell);
4198 }
4199 else if (c == '@')
4200 {
4201 if (prev_char == NULL)
4202 dump_is_corrupt(&ga_text);
4203 else
4204 {
4205 int count = 0;
4206
4207 /* repeat previous character, get the count */
4208 for (;;)
4209 {
4210 c = fgetc(fd);
4211 if (!isdigit(c))
4212 break;
4213 count = count * 10 + (c - '0');
4214 }
4215
4216 while (count-- > 0)
4217 {
4218 ga_concat(&ga_text, prev_char);
4219 append_cell(&ga_cell, &cell);
4220 }
4221 }
4222 }
4223 else
4224 {
4225 dump_is_corrupt(&ga_text);
4226 c = fgetc(fd);
4227 }
4228 }
4229
4230 if (ga_text.ga_len > 0)
4231 {
4232 /* trailing characters after last NL */
4233 dump_is_corrupt(&ga_text);
4234 ga_append(&ga_text, NUL);
4235 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4236 ga_text.ga_len, FALSE);
4237 }
4238
4239 ga_clear(&ga_text);
4240 vim_free(prev_char);
4241
4242 return max_cells;
4243}
4244
4245/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004246 * Return an allocated string with at least "text_width" "=" characters and
4247 * "fname" inserted in the middle.
4248 */
4249 static char_u *
4250get_separator(int text_width, char_u *fname)
4251{
4252 int width = MAX(text_width, curwin->w_width);
4253 char_u *textline;
4254 int fname_size;
4255 char_u *p = fname;
4256 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004257 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004258
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004259 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004260 if (textline == NULL)
4261 return NULL;
4262
4263 fname_size = vim_strsize(fname);
4264 if (fname_size < width - 8)
4265 {
4266 /* enough room, don't use the full window width */
4267 width = MAX(text_width, fname_size + 8);
4268 }
4269 else if (fname_size > width - 8)
4270 {
4271 /* full name doesn't fit, use only the tail */
4272 p = gettail(fname);
4273 fname_size = vim_strsize(p);
4274 }
4275 /* skip characters until the name fits */
4276 while (fname_size > width - 8)
4277 {
4278 p += (*mb_ptr2len)(p);
4279 fname_size = vim_strsize(p);
4280 }
4281
4282 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4283 textline[i] = '=';
4284 textline[i++] = ' ';
4285
4286 STRCPY(textline + i, p);
4287 off = STRLEN(textline);
4288 textline[off] = ' ';
4289 for (i = 1; i < (width - fname_size) / 2; ++i)
4290 textline[off + i] = '=';
4291 textline[off + i] = NUL;
4292
4293 return textline;
4294}
4295
4296/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004297 * Common for "term_dumpdiff()" and "term_dumpload()".
4298 */
4299 static void
4300term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4301{
4302 jobopt_T opt;
4303 buf_T *buf;
4304 char_u buf1[NUMBUFLEN];
4305 char_u buf2[NUMBUFLEN];
4306 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004307 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004308 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004309 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004310 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004311 char_u *textline = NULL;
4312
4313 /* First open the files. If this fails bail out. */
4314 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4315 if (do_diff)
4316 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4317 if (fname1 == NULL || (do_diff && fname2 == NULL))
4318 {
4319 EMSG(_(e_invarg));
4320 return;
4321 }
4322 fd1 = mch_fopen((char *)fname1, READBIN);
4323 if (fd1 == NULL)
4324 {
4325 EMSG2(_(e_notread), fname1);
4326 return;
4327 }
4328 if (do_diff)
4329 {
4330 fd2 = mch_fopen((char *)fname2, READBIN);
4331 if (fd2 == NULL)
4332 {
4333 fclose(fd1);
4334 EMSG2(_(e_notread), fname2);
4335 return;
4336 }
4337 }
4338
4339 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004340 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4341 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4342 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4343 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4344 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004345
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004346 if (opt.jo_term_name == NULL)
4347 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004348 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004349
Bram Moolenaarb571c632018-03-21 22:27:59 +01004350 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004351 if (fname_tofree != NULL)
4352 {
4353 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4354 opt.jo_term_name = fname_tofree;
4355 }
4356 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004357
Bram Moolenaar13568252018-03-16 20:46:58 +01004358 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004359 if (buf != NULL && buf->b_term != NULL)
4360 {
4361 int i;
4362 linenr_T bot_lnum;
4363 linenr_T lnum;
4364 term_T *term = buf->b_term;
4365 int width;
4366 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004367 VTermPos cursor_pos1;
4368 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004369
Bram Moolenaar52acb112018-03-18 19:20:22 +01004370 init_default_colors(term);
4371
Bram Moolenaard96ff162018-02-18 22:13:29 +01004372 rettv->vval.v_number = buf->b_fnum;
4373
4374 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004375 width = read_dump_file(fd1, &cursor_pos1);
4376
4377 /* position the cursor */
4378 if (cursor_pos1.row >= 0)
4379 {
4380 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4381 coladvance(cursor_pos1.col);
4382 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004383
4384 /* Delete the empty line that was in the empty buffer. */
4385 ml_delete(1, FALSE);
4386
4387 /* For term_dumpload() we are done here. */
4388 if (!do_diff)
4389 goto theend;
4390
4391 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4392
Bram Moolenaar4a696342018-04-05 18:45:26 +02004393 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004394 if (textline == NULL)
4395 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004396 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4397 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4398 vim_free(textline);
4399
4400 textline = get_separator(width, fname2);
4401 if (textline == NULL)
4402 goto theend;
4403 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4404 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004405 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004406
4407 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004408 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004409 if (width2 > width)
4410 {
4411 vim_free(textline);
4412 textline = alloc(width2 + 1);
4413 if (textline == NULL)
4414 goto theend;
4415 width = width2;
4416 textline[width] = NUL;
4417 }
4418 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4419
4420 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4421 {
4422 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4423 {
4424 /* bottom part has fewer rows, fill with "-" */
4425 for (i = 0; i < width; ++i)
4426 textline[i] = '-';
4427 }
4428 else
4429 {
4430 char_u *line1;
4431 char_u *line2;
4432 char_u *p1;
4433 char_u *p2;
4434 int col;
4435 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4436 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4437 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4438 ->sb_cells;
4439
4440 /* Make a copy, getting the second line will invalidate it. */
4441 line1 = vim_strsave(ml_get(lnum));
4442 if (line1 == NULL)
4443 break;
4444 p1 = line1;
4445
4446 line2 = ml_get(lnum + bot_lnum);
4447 p2 = line2;
4448 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4449 {
4450 int len1 = utfc_ptr2len(p1);
4451 int len2 = utfc_ptr2len(p2);
4452
4453 textline[col] = ' ';
4454 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004455 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004456 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004457 else if (lnum == cursor_pos1.row + 1
4458 && col == cursor_pos1.col
4459 && (cursor_pos1.row != cursor_pos2.row
4460 || cursor_pos1.col != cursor_pos2.col))
4461 /* cursor in first but not in second */
4462 textline[col] = '>';
4463 else if (lnum == cursor_pos2.row + 1
4464 && col == cursor_pos2.col
4465 && (cursor_pos1.row != cursor_pos2.row
4466 || cursor_pos1.col != cursor_pos2.col))
4467 /* cursor in second but not in first */
4468 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004469 else if (cellattr1 != NULL && cellattr2 != NULL)
4470 {
4471 if ((cellattr1 + col)->width
4472 != (cellattr2 + col)->width)
4473 textline[col] = 'w';
4474 else if (!same_color(&(cellattr1 + col)->fg,
4475 &(cellattr2 + col)->fg))
4476 textline[col] = 'f';
4477 else if (!same_color(&(cellattr1 + col)->bg,
4478 &(cellattr2 + col)->bg))
4479 textline[col] = 'b';
4480 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4481 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4482 textline[col] = 'a';
4483 }
4484 p1 += len1;
4485 p2 += len2;
4486 /* TODO: handle different width */
4487 }
4488 vim_free(line1);
4489
4490 while (col < width)
4491 {
4492 if (*p1 == NUL && *p2 == NUL)
4493 textline[col] = '?';
4494 else if (*p1 == NUL)
4495 {
4496 textline[col] = '+';
4497 p2 += utfc_ptr2len(p2);
4498 }
4499 else
4500 {
4501 textline[col] = '-';
4502 p1 += utfc_ptr2len(p1);
4503 }
4504 ++col;
4505 }
4506 }
4507 if (add_empty_scrollback(term, &term->tl_default_color,
4508 term->tl_top_diff_rows) == OK)
4509 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4510 ++bot_lnum;
4511 }
4512
4513 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4514 {
4515 /* bottom part has more rows, fill with "+" */
4516 for (i = 0; i < width; ++i)
4517 textline[i] = '+';
4518 if (add_empty_scrollback(term, &term->tl_default_color,
4519 term->tl_top_diff_rows) == OK)
4520 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4521 ++lnum;
4522 ++bot_lnum;
4523 }
4524
4525 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004526
4527 /* looks better without wrapping */
4528 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004529 }
4530
4531theend:
4532 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004533 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004534 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004535 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004536 fclose(fd2);
4537}
4538
4539/*
4540 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4541 * bottom files.
4542 * Return FAIL when this is not possible.
4543 */
4544 int
4545term_swap_diff()
4546{
4547 term_T *term = curbuf->b_term;
4548 linenr_T line_count;
4549 linenr_T top_rows;
4550 linenr_T bot_rows;
4551 linenr_T bot_start;
4552 linenr_T lnum;
4553 char_u *p;
4554 sb_line_T *sb_line;
4555
4556 if (term == NULL
4557 || !term_is_finished(curbuf)
4558 || term->tl_top_diff_rows == 0
4559 || term->tl_scrollback.ga_len == 0)
4560 return FAIL;
4561
4562 line_count = curbuf->b_ml.ml_line_count;
4563 top_rows = term->tl_top_diff_rows;
4564 bot_rows = term->tl_bot_diff_rows;
4565 bot_start = line_count - bot_rows;
4566 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4567
4568 /* move lines from top to above the bottom part */
4569 for (lnum = 1; lnum <= top_rows; ++lnum)
4570 {
4571 p = vim_strsave(ml_get(1));
4572 if (p == NULL)
4573 return OK;
4574 ml_append(bot_start, p, 0, FALSE);
4575 ml_delete(1, FALSE);
4576 vim_free(p);
4577 }
4578
4579 /* move lines from bottom to the top */
4580 for (lnum = 1; lnum <= bot_rows; ++lnum)
4581 {
4582 p = vim_strsave(ml_get(bot_start + lnum));
4583 if (p == NULL)
4584 return OK;
4585 ml_delete(bot_start + lnum, FALSE);
4586 ml_append(lnum - 1, p, 0, FALSE);
4587 vim_free(p);
4588 }
4589
4590 if (top_rows == bot_rows)
4591 {
4592 /* rows counts are equal, can swap cell properties */
4593 for (lnum = 0; lnum < top_rows; ++lnum)
4594 {
4595 sb_line_T temp;
4596
4597 temp = *(sb_line + lnum);
4598 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4599 *(sb_line + bot_start + lnum) = temp;
4600 }
4601 }
4602 else
4603 {
4604 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4605 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4606
4607 /* need to copy cell properties into temp memory */
4608 if (temp != NULL)
4609 {
4610 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4611 mch_memmove(term->tl_scrollback.ga_data,
4612 temp + bot_start,
4613 sizeof(sb_line_T) * bot_rows);
4614 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4615 temp + top_rows,
4616 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4617 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4618 + line_count - top_rows,
4619 temp,
4620 sizeof(sb_line_T) * top_rows);
4621 vim_free(temp);
4622 }
4623 }
4624
4625 term->tl_top_diff_rows = bot_rows;
4626 term->tl_bot_diff_rows = top_rows;
4627
4628 update_screen(NOT_VALID);
4629 return OK;
4630}
4631
4632/*
4633 * "term_dumpdiff(filename, filename, options)" function
4634 */
4635 void
4636f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4637{
4638 term_load_dump(argvars, rettv, TRUE);
4639}
4640
4641/*
4642 * "term_dumpload(filename, options)" function
4643 */
4644 void
4645f_term_dumpload(typval_T *argvars, typval_T *rettv)
4646{
4647 term_load_dump(argvars, rettv, FALSE);
4648}
4649
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004650/*
4651 * "term_getaltscreen(buf)" function
4652 */
4653 void
4654f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4655{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004656 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004657
4658 if (buf == NULL)
4659 return;
4660 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4661}
4662
4663/*
4664 * "term_getattr(attr, name)" function
4665 */
4666 void
4667f_term_getattr(typval_T *argvars, typval_T *rettv)
4668{
4669 int attr;
4670 size_t i;
4671 char_u *name;
4672
4673 static struct {
4674 char *name;
4675 int attr;
4676 } attrs[] = {
4677 {"bold", HL_BOLD},
4678 {"italic", HL_ITALIC},
4679 {"underline", HL_UNDERLINE},
4680 {"strike", HL_STRIKETHROUGH},
4681 {"reverse", HL_INVERSE},
4682 };
4683
4684 attr = get_tv_number(&argvars[0]);
4685 name = get_tv_string_chk(&argvars[1]);
4686 if (name == NULL)
4687 return;
4688
4689 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4690 if (STRCMP(name, attrs[i].name) == 0)
4691 {
4692 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4693 break;
4694 }
4695}
4696
4697/*
4698 * "term_getcursor(buf)" function
4699 */
4700 void
4701f_term_getcursor(typval_T *argvars, typval_T *rettv)
4702{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004703 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004704 term_T *term;
4705 list_T *l;
4706 dict_T *d;
4707
4708 if (rettv_list_alloc(rettv) == FAIL)
4709 return;
4710 if (buf == NULL)
4711 return;
4712 term = buf->b_term;
4713
4714 l = rettv->vval.v_list;
4715 list_append_number(l, term->tl_cursor_pos.row + 1);
4716 list_append_number(l, term->tl_cursor_pos.col + 1);
4717
4718 d = dict_alloc();
4719 if (d != NULL)
4720 {
4721 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4722 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4723 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4724 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02004725 dict_add_nr_str(d, "color", 0L, cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004726 list_append_dict(l, d);
4727 }
4728}
4729
4730/*
4731 * "term_getjob(buf)" function
4732 */
4733 void
4734f_term_getjob(typval_T *argvars, typval_T *rettv)
4735{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004736 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004737
4738 rettv->v_type = VAR_JOB;
4739 rettv->vval.v_job = NULL;
4740 if (buf == NULL)
4741 return;
4742
4743 rettv->vval.v_job = buf->b_term->tl_job;
4744 if (rettv->vval.v_job != NULL)
4745 ++rettv->vval.v_job->jv_refcount;
4746}
4747
4748 static int
4749get_row_number(typval_T *tv, term_T *term)
4750{
4751 if (tv->v_type == VAR_STRING
4752 && tv->vval.v_string != NULL
4753 && STRCMP(tv->vval.v_string, ".") == 0)
4754 return term->tl_cursor_pos.row;
4755 return (int)get_tv_number(tv) - 1;
4756}
4757
4758/*
4759 * "term_getline(buf, row)" function
4760 */
4761 void
4762f_term_getline(typval_T *argvars, typval_T *rettv)
4763{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004764 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004765 term_T *term;
4766 int row;
4767
4768 rettv->v_type = VAR_STRING;
4769 if (buf == NULL)
4770 return;
4771 term = buf->b_term;
4772 row = get_row_number(&argvars[1], term);
4773
4774 if (term->tl_vterm == NULL)
4775 {
4776 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4777
4778 /* vterm is finished, get the text from the buffer */
4779 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4780 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4781 }
4782 else
4783 {
4784 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4785 VTermRect rect;
4786 int len;
4787 char_u *p;
4788
4789 if (row < 0 || row >= term->tl_rows)
4790 return;
4791 len = term->tl_cols * MB_MAXBYTES + 1;
4792 p = alloc(len);
4793 if (p == NULL)
4794 return;
4795 rettv->vval.v_string = p;
4796
4797 rect.start_col = 0;
4798 rect.end_col = term->tl_cols;
4799 rect.start_row = row;
4800 rect.end_row = row + 1;
4801 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4802 }
4803}
4804
4805/*
4806 * "term_getscrolled(buf)" function
4807 */
4808 void
4809f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4810{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004811 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004812
4813 if (buf == NULL)
4814 return;
4815 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4816}
4817
4818/*
4819 * "term_getsize(buf)" function
4820 */
4821 void
4822f_term_getsize(typval_T *argvars, typval_T *rettv)
4823{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004824 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004825 list_T *l;
4826
4827 if (rettv_list_alloc(rettv) == FAIL)
4828 return;
4829 if (buf == NULL)
4830 return;
4831
4832 l = rettv->vval.v_list;
4833 list_append_number(l, buf->b_term->tl_rows);
4834 list_append_number(l, buf->b_term->tl_cols);
4835}
4836
4837/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004838 * "term_setsize(buf, rows, cols)" function
4839 */
4840 void
4841f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4842{
4843 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4844 term_T *term;
4845 varnumber_T rows, cols;
4846
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004847 if (buf == NULL)
4848 {
4849 EMSG(_("E955: Not a terminal buffer"));
4850 return;
4851 }
4852 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004853 return;
4854 term = buf->b_term;
4855 rows = get_tv_number(&argvars[1]);
4856 rows = rows <= 0 ? term->tl_rows : rows;
4857 cols = get_tv_number(&argvars[2]);
4858 cols = cols <= 0 ? term->tl_cols : cols;
4859 vterm_set_size(term->tl_vterm, rows, cols);
4860 /* handle_resize() will resize the windows */
4861
4862 /* Get and remember the size we ended up with. Update the pty. */
4863 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4864 term_report_winsize(term, term->tl_rows, term->tl_cols);
4865}
4866
4867/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004868 * "term_getstatus(buf)" function
4869 */
4870 void
4871f_term_getstatus(typval_T *argvars, typval_T *rettv)
4872{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004873 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004874 term_T *term;
4875 char_u val[100];
4876
4877 rettv->v_type = VAR_STRING;
4878 if (buf == NULL)
4879 return;
4880 term = buf->b_term;
4881
4882 if (term_job_running(term))
4883 STRCPY(val, "running");
4884 else
4885 STRCPY(val, "finished");
4886 if (term->tl_normal_mode)
4887 STRCAT(val, ",normal");
4888 rettv->vval.v_string = vim_strsave(val);
4889}
4890
4891/*
4892 * "term_gettitle(buf)" function
4893 */
4894 void
4895f_term_gettitle(typval_T *argvars, typval_T *rettv)
4896{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004897 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004898
4899 rettv->v_type = VAR_STRING;
4900 if (buf == NULL)
4901 return;
4902
4903 if (buf->b_term->tl_title != NULL)
4904 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4905}
4906
4907/*
4908 * "term_gettty(buf)" function
4909 */
4910 void
4911f_term_gettty(typval_T *argvars, typval_T *rettv)
4912{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004913 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02004914 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004915 int num = 0;
4916
4917 rettv->v_type = VAR_STRING;
4918 if (buf == NULL)
4919 return;
4920 if (argvars[1].v_type != VAR_UNKNOWN)
4921 num = get_tv_number(&argvars[1]);
4922
4923 switch (num)
4924 {
4925 case 0:
4926 if (buf->b_term->tl_job != NULL)
4927 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004928 break;
4929 case 1:
4930 if (buf->b_term->tl_job != NULL)
4931 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004932 break;
4933 default:
4934 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4935 return;
4936 }
4937 if (p != NULL)
4938 rettv->vval.v_string = vim_strsave(p);
4939}
4940
4941/*
4942 * "term_list()" function
4943 */
4944 void
4945f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4946{
4947 term_T *tp;
4948 list_T *l;
4949
4950 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4951 return;
4952
4953 l = rettv->vval.v_list;
4954 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4955 if (tp != NULL && tp->tl_buffer != NULL)
4956 if (list_append_number(l,
4957 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4958 return;
4959}
4960
4961/*
4962 * "term_scrape(buf, row)" function
4963 */
4964 void
4965f_term_scrape(typval_T *argvars, typval_T *rettv)
4966{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004967 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004968 VTermScreen *screen = NULL;
4969 VTermPos pos;
4970 list_T *l;
4971 term_T *term;
4972 char_u *p;
4973 sb_line_T *line;
4974
4975 if (rettv_list_alloc(rettv) == FAIL)
4976 return;
4977 if (buf == NULL)
4978 return;
4979 term = buf->b_term;
4980
4981 l = rettv->vval.v_list;
4982 pos.row = get_row_number(&argvars[1], term);
4983
4984 if (term->tl_vterm != NULL)
4985 {
4986 screen = vterm_obtain_screen(term->tl_vterm);
4987 p = NULL;
4988 line = NULL;
4989 }
4990 else
4991 {
4992 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4993
4994 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4995 return;
4996 p = ml_get_buf(buf, lnum + 1, FALSE);
4997 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4998 }
4999
5000 for (pos.col = 0; pos.col < term->tl_cols; )
5001 {
5002 dict_T *dcell;
5003 int width;
5004 VTermScreenCellAttrs attrs;
5005 VTermColor fg, bg;
5006 char_u rgb[8];
5007 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5008 int off = 0;
5009 int i;
5010
5011 if (screen == NULL)
5012 {
5013 cellattr_T *cellattr;
5014 int len;
5015
5016 /* vterm has finished, get the cell from scrollback */
5017 if (pos.col >= line->sb_cols)
5018 break;
5019 cellattr = line->sb_cells + pos.col;
5020 width = cellattr->width;
5021 attrs = cellattr->attrs;
5022 fg = cellattr->fg;
5023 bg = cellattr->bg;
5024 len = MB_PTR2LEN(p);
5025 mch_memmove(mbs, p, len);
5026 mbs[len] = NUL;
5027 p += len;
5028 }
5029 else
5030 {
5031 VTermScreenCell cell;
5032 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5033 break;
5034 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5035 {
5036 if (cell.chars[i] == 0)
5037 break;
5038 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5039 }
5040 mbs[off] = NUL;
5041 width = cell.width;
5042 attrs = cell.attrs;
5043 fg = cell.fg;
5044 bg = cell.bg;
5045 }
5046 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005047 if (dcell == NULL)
5048 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005049 list_append_dict(l, dcell);
5050
5051 dict_add_nr_str(dcell, "chars", 0, mbs);
5052
5053 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5054 fg.red, fg.green, fg.blue);
5055 dict_add_nr_str(dcell, "fg", 0, rgb);
5056 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5057 bg.red, bg.green, bg.blue);
5058 dict_add_nr_str(dcell, "bg", 0, rgb);
5059
5060 dict_add_nr_str(dcell, "attr",
5061 cell2attr(attrs, fg, bg), NULL);
5062 dict_add_nr_str(dcell, "width", width, NULL);
5063
5064 ++pos.col;
5065 if (width == 2)
5066 ++pos.col;
5067 }
5068}
5069
5070/*
5071 * "term_sendkeys(buf, keys)" function
5072 */
5073 void
5074f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5075{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005076 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005077 char_u *msg;
5078 term_T *term;
5079
5080 rettv->v_type = VAR_UNKNOWN;
5081 if (buf == NULL)
5082 return;
5083
5084 msg = get_tv_string_chk(&argvars[1]);
5085 if (msg == NULL)
5086 return;
5087 term = buf->b_term;
5088 if (term->tl_vterm == NULL)
5089 return;
5090
5091 while (*msg != NUL)
5092 {
5093 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02005094 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005095 }
5096}
5097
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005098#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5099/*
5100 * "term_getansicolors(buf)" function
5101 */
5102 void
5103f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5104{
5105 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5106 term_T *term;
5107 VTermState *state;
5108 VTermColor color;
5109 char_u hexbuf[10];
5110 int index;
5111 list_T *list;
5112
5113 if (rettv_list_alloc(rettv) == FAIL)
5114 return;
5115
5116 if (buf == NULL)
5117 return;
5118 term = buf->b_term;
5119 if (term->tl_vterm == NULL)
5120 return;
5121
5122 list = rettv->vval.v_list;
5123 state = vterm_obtain_state(term->tl_vterm);
5124 for (index = 0; index < 16; index++)
5125 {
5126 vterm_state_get_palette_color(state, index, &color);
5127 sprintf((char *)hexbuf, "#%02x%02x%02x",
5128 color.red, color.green, color.blue);
5129 if (list_append_string(list, hexbuf, 7) == FAIL)
5130 return;
5131 }
5132}
5133
5134/*
5135 * "term_setansicolors(buf, list)" function
5136 */
5137 void
5138f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5139{
5140 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5141 term_T *term;
5142
5143 if (buf == NULL)
5144 return;
5145 term = buf->b_term;
5146 if (term->tl_vterm == NULL)
5147 return;
5148
5149 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5150 {
5151 EMSG(_(e_listreq));
5152 return;
5153 }
5154
5155 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
5156 EMSG(_(e_invarg));
5157}
5158#endif
5159
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005160/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005161 * "term_setrestore(buf, command)" function
5162 */
5163 void
5164f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5165{
5166#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005167 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005168 term_T *term;
5169 char_u *cmd;
5170
5171 if (buf == NULL)
5172 return;
5173 term = buf->b_term;
5174 vim_free(term->tl_command);
5175 cmd = get_tv_string_chk(&argvars[1]);
5176 if (cmd != NULL)
5177 term->tl_command = vim_strsave(cmd);
5178 else
5179 term->tl_command = NULL;
5180#endif
5181}
5182
5183/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005184 * "term_setkill(buf, how)" function
5185 */
5186 void
5187f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5188{
5189 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5190 term_T *term;
5191 char_u *how;
5192
5193 if (buf == NULL)
5194 return;
5195 term = buf->b_term;
5196 vim_free(term->tl_kill);
5197 how = get_tv_string_chk(&argvars[1]);
5198 if (how != NULL)
5199 term->tl_kill = vim_strsave(how);
5200 else
5201 term->tl_kill = NULL;
5202}
5203
5204/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005205 * "term_start(command, options)" function
5206 */
5207 void
5208f_term_start(typval_T *argvars, typval_T *rettv)
5209{
5210 jobopt_T opt;
5211 buf_T *buf;
5212
5213 init_job_options(&opt);
5214 if (argvars[1].v_type != VAR_UNKNOWN
5215 && get_job_options(&argvars[1], &opt,
5216 JO_TIMEOUT_ALL + JO_STOPONEXIT
5217 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5218 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5219 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5220 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005221 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005222 + JO2_NORESTORE + JO2_TERM_KILL
5223 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005224 return;
5225
Bram Moolenaar13568252018-03-16 20:46:58 +01005226 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005227
5228 if (buf != NULL && buf->b_term != NULL)
5229 rettv->vval.v_number = buf->b_fnum;
5230}
5231
5232/*
5233 * "term_wait" function
5234 */
5235 void
5236f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5237{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005238 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005239
5240 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005241 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005242 if (buf->b_term->tl_job == NULL)
5243 {
5244 ch_log(NULL, "term_wait(): no job to wait for");
5245 return;
5246 }
5247 if (buf->b_term->tl_job->jv_channel == NULL)
5248 /* channel is closed, nothing to do */
5249 return;
5250
5251 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005252 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005253 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5254 {
5255 /* The job is dead, keep reading channel I/O until the channel is
5256 * closed. buf->b_term may become NULL if the terminal was closed while
5257 * waiting. */
5258 ch_log(NULL, "term_wait(): waiting for channel to close");
5259 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5260 {
5261 mch_check_messages();
5262 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005263 if (!buf_valid(buf))
5264 /* If the terminal is closed when the channel is closed the
5265 * buffer disappears. */
5266 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005267 ui_delay(10L, FALSE);
5268 }
5269 mch_check_messages();
5270 parse_queued_messages();
5271 }
5272 else
5273 {
5274 long wait = 10L;
5275
5276 mch_check_messages();
5277 parse_queued_messages();
5278
5279 /* Wait for some time for any channel I/O. */
5280 if (argvars[1].v_type != VAR_UNKNOWN)
5281 wait = get_tv_number(&argvars[1]);
5282 ui_delay(wait, TRUE);
5283 mch_check_messages();
5284
5285 /* Flushing messages on channels is hopefully sufficient.
5286 * TODO: is there a better way? */
5287 parse_queued_messages();
5288 }
5289}
5290
5291/*
5292 * Called when a channel has sent all the lines to a terminal.
5293 * Send a CTRL-D to mark the end of the text.
5294 */
5295 void
5296term_send_eof(channel_T *ch)
5297{
5298 term_T *term;
5299
5300 for (term = first_term; term != NULL; term = term->tl_next)
5301 if (term->tl_job == ch->ch_job)
5302 {
5303 if (term->tl_eof_chars != NULL)
5304 {
5305 channel_send(ch, PART_IN, term->tl_eof_chars,
5306 (int)STRLEN(term->tl_eof_chars), NULL);
5307 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5308 }
5309# ifdef WIN3264
5310 else
5311 /* Default: CTRL-D */
5312 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5313# endif
5314 }
5315}
5316
5317# if defined(WIN3264) || defined(PROTO)
5318
5319/**************************************
5320 * 2. MS-Windows implementation.
5321 */
5322
5323# ifndef PROTO
5324
5325#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5326#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005327#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005328
5329void* (*winpty_config_new)(UINT64, void*);
5330void* (*winpty_open)(void*, void*);
5331void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5332BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5333void (*winpty_config_set_mouse_mode)(void*, int);
5334void (*winpty_config_set_initial_size)(void*, int, int);
5335LPCWSTR (*winpty_conin_name)(void*);
5336LPCWSTR (*winpty_conout_name)(void*);
5337LPCWSTR (*winpty_conerr_name)(void*);
5338void (*winpty_free)(void*);
5339void (*winpty_config_free)(void*);
5340void (*winpty_spawn_config_free)(void*);
5341void (*winpty_error_free)(void*);
5342LPCWSTR (*winpty_error_msg)(void*);
5343BOOL (*winpty_set_size)(void*, int, int, void*);
5344HANDLE (*winpty_agent_process)(void*);
5345
5346#define WINPTY_DLL "winpty.dll"
5347
5348static HINSTANCE hWinPtyDLL = NULL;
5349# endif
5350
5351 static int
5352dyn_winpty_init(int verbose)
5353{
5354 int i;
5355 static struct
5356 {
5357 char *name;
5358 FARPROC *ptr;
5359 } winpty_entry[] =
5360 {
5361 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5362 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5363 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5364 {"winpty_config_set_mouse_mode",
5365 (FARPROC*)&winpty_config_set_mouse_mode},
5366 {"winpty_config_set_initial_size",
5367 (FARPROC*)&winpty_config_set_initial_size},
5368 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5369 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5370 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5371 {"winpty_free", (FARPROC*)&winpty_free},
5372 {"winpty_open", (FARPROC*)&winpty_open},
5373 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5374 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5375 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5376 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5377 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5378 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5379 {NULL, NULL}
5380 };
5381
5382 /* No need to initialize twice. */
5383 if (hWinPtyDLL)
5384 return OK;
5385 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5386 * winpty.dll. */
5387 if (*p_winptydll != NUL)
5388 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5389 if (!hWinPtyDLL)
5390 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5391 if (!hWinPtyDLL)
5392 {
5393 if (verbose)
5394 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5395 : (char_u *)WINPTY_DLL);
5396 return FAIL;
5397 }
5398 for (i = 0; winpty_entry[i].name != NULL
5399 && winpty_entry[i].ptr != NULL; ++i)
5400 {
5401 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5402 winpty_entry[i].name)) == NULL)
5403 {
5404 if (verbose)
5405 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5406 return FAIL;
5407 }
5408 }
5409
5410 return OK;
5411}
5412
5413/*
5414 * Create a new terminal of "rows" by "cols" cells.
5415 * Store a reference in "term".
5416 * Return OK or FAIL.
5417 */
5418 static int
5419term_and_job_init(
5420 term_T *term,
5421 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005422 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005423 jobopt_T *opt,
5424 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005425{
5426 WCHAR *cmd_wchar = NULL;
5427 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005428 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005429 channel_T *channel = NULL;
5430 job_T *job = NULL;
5431 DWORD error;
5432 HANDLE jo = NULL;
5433 HANDLE child_process_handle;
5434 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005435 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005436 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005437 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005438 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005439
5440 if (dyn_winpty_init(TRUE) == FAIL)
5441 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005442 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5443 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005444
5445 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005446 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005447 cmd = argvar->vval.v_string;
5448 }
5449 else if (argvar->v_type == VAR_LIST)
5450 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005451 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005452 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005453 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005454 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005455 if (cmd == NULL || *cmd == NUL)
5456 {
5457 EMSG(_(e_invarg));
5458 goto failed;
5459 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005460
5461 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005462 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005463 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005464 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005465 if (opt->jo_cwd != NULL)
5466 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005467
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005468 win32_build_env(opt->jo_env, &ga_env, TRUE);
5469 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005470
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005471 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5472 if (term->tl_winpty_config == NULL)
5473 goto failed;
5474
5475 winpty_config_set_mouse_mode(term->tl_winpty_config,
5476 WINPTY_MOUSE_MODE_FORCE);
5477 winpty_config_set_initial_size(term->tl_winpty_config,
5478 term->tl_cols, term->tl_rows);
5479 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5480 if (term->tl_winpty == NULL)
5481 goto failed;
5482
5483 spawn_config = winpty_spawn_config_new(
5484 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5485 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5486 NULL,
5487 cmd_wchar,
5488 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005489 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005490 &winpty_err);
5491 if (spawn_config == NULL)
5492 goto failed;
5493
5494 channel = add_channel();
5495 if (channel == NULL)
5496 goto failed;
5497
5498 job = job_alloc();
5499 if (job == NULL)
5500 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005501 if (argvar->v_type == VAR_STRING)
5502 {
5503 int argc;
5504
5505 build_argv_from_string(cmd, &job->jv_argv, &argc);
5506 }
5507 else
5508 {
5509 int argc;
5510
5511 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5512 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005513
5514 if (opt->jo_set & JO_IN_BUF)
5515 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5516
5517 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5518 &child_thread_handle, &error, &winpty_err))
5519 goto failed;
5520
5521 channel_set_pipes(channel,
5522 (sock_T)CreateFileW(
5523 winpty_conin_name(term->tl_winpty),
5524 GENERIC_WRITE, 0, NULL,
5525 OPEN_EXISTING, 0, NULL),
5526 (sock_T)CreateFileW(
5527 winpty_conout_name(term->tl_winpty),
5528 GENERIC_READ, 0, NULL,
5529 OPEN_EXISTING, 0, NULL),
5530 (sock_T)CreateFileW(
5531 winpty_conerr_name(term->tl_winpty),
5532 GENERIC_READ, 0, NULL,
5533 OPEN_EXISTING, 0, NULL));
5534
5535 /* Write lines with CR instead of NL. */
5536 channel->ch_write_text_mode = TRUE;
5537
5538 jo = CreateJobObject(NULL, NULL);
5539 if (jo == NULL)
5540 goto failed;
5541
5542 if (!AssignProcessToJobObject(jo, child_process_handle))
5543 {
5544 /* Failed, switch the way to terminate process with TerminateProcess. */
5545 CloseHandle(jo);
5546 jo = NULL;
5547 }
5548
5549 winpty_spawn_config_free(spawn_config);
5550 vim_free(cmd_wchar);
5551 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005552 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005553
5554 create_vterm(term, term->tl_rows, term->tl_cols);
5555
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005556#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5557 if (opt->jo_set2 & JO2_ANSI_COLORS)
5558 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5559 else
5560 init_vterm_ansi_colors(term->tl_vterm);
5561#endif
5562
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005563 channel_set_job(channel, job, opt);
5564 job_set_options(job, opt);
5565
5566 job->jv_channel = channel;
5567 job->jv_proc_info.hProcess = child_process_handle;
5568 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5569 job->jv_job_object = jo;
5570 job->jv_status = JOB_STARTED;
5571 job->jv_tty_in = utf16_to_enc(
5572 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5573 job->jv_tty_out = utf16_to_enc(
5574 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5575 ++job->jv_refcount;
5576 term->tl_job = job;
5577
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005578 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5579 * open the file here and handle it in. opt->jo_io was changed in
5580 * setup_job_options(), use the original flags here. */
5581 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5582 {
5583 char_u *fname = opt->jo_io_name[PART_OUT];
5584
5585 ch_log(channel, "Opening output file %s", fname);
5586 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5587 if (term->tl_out_fd == NULL)
5588 EMSG2(_(e_notopen), fname);
5589 }
5590
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005591 return OK;
5592
5593failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005594 ga_clear(&ga_cmd);
5595 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005596 vim_free(cmd_wchar);
5597 vim_free(cwd_wchar);
5598 if (spawn_config != NULL)
5599 winpty_spawn_config_free(spawn_config);
5600 if (channel != NULL)
5601 channel_clear(channel);
5602 if (job != NULL)
5603 {
5604 job->jv_channel = NULL;
5605 job_cleanup(job);
5606 }
5607 term->tl_job = NULL;
5608 if (jo != NULL)
5609 CloseHandle(jo);
5610 if (term->tl_winpty != NULL)
5611 winpty_free(term->tl_winpty);
5612 term->tl_winpty = NULL;
5613 if (term->tl_winpty_config != NULL)
5614 winpty_config_free(term->tl_winpty_config);
5615 term->tl_winpty_config = NULL;
5616 if (winpty_err != NULL)
5617 {
5618 char_u *msg = utf16_to_enc(
5619 (short_u *)winpty_error_msg(winpty_err), NULL);
5620
5621 EMSG(msg);
5622 winpty_error_free(winpty_err);
5623 }
5624 return FAIL;
5625}
5626
5627 static int
5628create_pty_only(term_T *term, jobopt_T *options)
5629{
5630 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5631 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5632 char in_name[80], out_name[80];
5633 channel_T *channel = NULL;
5634
5635 create_vterm(term, term->tl_rows, term->tl_cols);
5636
5637 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5638 GetCurrentProcessId(),
5639 curbuf->b_fnum);
5640 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5641 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5642 PIPE_UNLIMITED_INSTANCES,
5643 0, 0, NMPWAIT_NOWAIT, NULL);
5644 if (hPipeIn == INVALID_HANDLE_VALUE)
5645 goto failed;
5646
5647 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5648 GetCurrentProcessId(),
5649 curbuf->b_fnum);
5650 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5651 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5652 PIPE_UNLIMITED_INSTANCES,
5653 0, 0, 0, NULL);
5654 if (hPipeOut == INVALID_HANDLE_VALUE)
5655 goto failed;
5656
5657 ConnectNamedPipe(hPipeIn, NULL);
5658 ConnectNamedPipe(hPipeOut, NULL);
5659
5660 term->tl_job = job_alloc();
5661 if (term->tl_job == NULL)
5662 goto failed;
5663 ++term->tl_job->jv_refcount;
5664
5665 /* behave like the job is already finished */
5666 term->tl_job->jv_status = JOB_FINISHED;
5667
5668 channel = add_channel();
5669 if (channel == NULL)
5670 goto failed;
5671 term->tl_job->jv_channel = channel;
5672 channel->ch_keep_open = TRUE;
5673 channel->ch_named_pipe = TRUE;
5674
5675 channel_set_pipes(channel,
5676 (sock_T)hPipeIn,
5677 (sock_T)hPipeOut,
5678 (sock_T)hPipeOut);
5679 channel_set_job(channel, term->tl_job, options);
5680 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5681 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5682
5683 return OK;
5684
5685failed:
5686 if (hPipeIn != NULL)
5687 CloseHandle(hPipeIn);
5688 if (hPipeOut != NULL)
5689 CloseHandle(hPipeOut);
5690 return FAIL;
5691}
5692
5693/*
5694 * Free the terminal emulator part of "term".
5695 */
5696 static void
5697term_free_vterm(term_T *term)
5698{
5699 if (term->tl_winpty != NULL)
5700 winpty_free(term->tl_winpty);
5701 term->tl_winpty = NULL;
5702 if (term->tl_winpty_config != NULL)
5703 winpty_config_free(term->tl_winpty_config);
5704 term->tl_winpty_config = NULL;
5705 if (term->tl_vterm != NULL)
5706 vterm_free(term->tl_vterm);
5707 term->tl_vterm = NULL;
5708}
5709
5710/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005711 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005712 */
5713 static void
5714term_report_winsize(term_T *term, int rows, int cols)
5715{
5716 if (term->tl_winpty)
5717 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5718}
5719
5720 int
5721terminal_enabled(void)
5722{
5723 return dyn_winpty_init(FALSE) == OK;
5724}
5725
5726# else
5727
5728/**************************************
5729 * 3. Unix-like implementation.
5730 */
5731
5732/*
5733 * Create a new terminal of "rows" by "cols" cells.
5734 * Start job for "cmd".
5735 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005736 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005737 * Return OK or FAIL.
5738 */
5739 static int
5740term_and_job_init(
5741 term_T *term,
5742 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005743 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005744 jobopt_T *opt,
5745 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005746{
5747 create_vterm(term, term->tl_rows, term->tl_cols);
5748
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005749#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5750 if (opt->jo_set2 & JO2_ANSI_COLORS)
5751 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5752 else
5753 init_vterm_ansi_colors(term->tl_vterm);
5754#endif
5755
Bram Moolenaar13568252018-03-16 20:46:58 +01005756 /* This may change a string in "argvar". */
5757 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005758 if (term->tl_job != NULL)
5759 ++term->tl_job->jv_refcount;
5760
5761 return term->tl_job != NULL
5762 && term->tl_job->jv_channel != NULL
5763 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5764}
5765
5766 static int
5767create_pty_only(term_T *term, jobopt_T *opt)
5768{
5769 create_vterm(term, term->tl_rows, term->tl_cols);
5770
5771 term->tl_job = job_alloc();
5772 if (term->tl_job == NULL)
5773 return FAIL;
5774 ++term->tl_job->jv_refcount;
5775
5776 /* behave like the job is already finished */
5777 term->tl_job->jv_status = JOB_FINISHED;
5778
5779 return mch_create_pty_channel(term->tl_job, opt);
5780}
5781
5782/*
5783 * Free the terminal emulator part of "term".
5784 */
5785 static void
5786term_free_vterm(term_T *term)
5787{
5788 if (term->tl_vterm != NULL)
5789 vterm_free(term->tl_vterm);
5790 term->tl_vterm = NULL;
5791}
5792
5793/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005794 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005795 */
5796 static void
5797term_report_winsize(term_T *term, int rows, int cols)
5798{
5799 /* Use an ioctl() to report the new window size to the job. */
5800 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5801 {
5802 int fd = -1;
5803 int part;
5804
5805 for (part = PART_OUT; part < PART_COUNT; ++part)
5806 {
5807 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5808 if (isatty(fd))
5809 break;
5810 }
5811 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5812 mch_signal_job(term->tl_job, (char_u *)"winch");
5813 }
5814}
5815
5816# endif
5817
5818#endif /* FEAT_TERMINAL */