blob: e2ae2f600fa06100e861ec699bcd2476243a95ad [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 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +010063 int sb_cols; // can differ per line
64 cellattr_T *sb_cells; // allocated
65 cellattr_T sb_fill_attr; // for short line
66 char_u *sb_text; // for tl_scrollback_postponed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067} sb_line_T;
68
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010069#ifdef WIN3264
70# ifndef HPCON
71# define HPCON VOID*
72# endif
73# ifndef EXTENDED_STARTUPINFO_PRESENT
74# define EXTENDED_STARTUPINFO_PRESENT 0x00080000
75# endif
76# ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
77# define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE 0x00020016
78# endif
79typedef struct _DYN_STARTUPINFOEXW
80{
81 STARTUPINFOW StartupInfo;
82 LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
83} DYN_STARTUPINFOEXW, *PDYN_STARTUPINFOEXW;
84#endif
85
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020086/* typedef term_T in structs.h */
87struct terminal_S {
88 term_T *tl_next;
89
90 VTerm *tl_vterm;
91 job_T *tl_job;
92 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010093#if defined(FEAT_GUI)
94 int tl_system; /* when non-zero used for :!cmd output */
95 int tl_toprow; /* row with first line of system terminal */
96#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
98 /* Set when setting the size of a vterm, reset after redrawing. */
99 int tl_vterm_size_changed;
100
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200101 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
102 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200103 int tl_channel_recently_closed; // still need to handle tl_finish
104
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100105 int tl_finish;
106#define TL_FINISH_UNSET NUL
107#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
108#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
109#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200110 char_u *tl_opencmd;
111 char_u *tl_eof_chars;
112
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100113 char_u *tl_arg0_cmd; // To format the status bar
114
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200115#ifdef WIN3264
116 void *tl_winpty_config;
117 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200118
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100119 HPCON tl_conpty;
120 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
121
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200122 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200123#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100124#if defined(FEAT_SESSION)
125 char_u *tl_command;
126#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100127 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200128
129 /* last known vterm size */
130 int tl_rows;
131 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200132
133 char_u *tl_title; /* NULL or allocated */
134 char_u *tl_status_text; /* NULL or allocated */
135
136 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200137 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200138 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200139 int tl_dirty_snapshot; /* text updated after making snapshot */
140#ifdef FEAT_TIMERS
141 int tl_timer_set;
142 proftime_T tl_timer_due;
143#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200144 int tl_postponed_scroll; /* to be scrolled up */
145
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200146 garray_T tl_scrollback;
147 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100148 garray_T tl_scrollback_postponed;
149
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200150 cellattr_T tl_default_color;
151
Bram Moolenaard96ff162018-02-18 22:13:29 +0100152 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
153 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
154
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200155 VTermPos tl_cursor_pos;
156 int tl_cursor_visible;
157 int tl_cursor_blink;
158 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
159 char_u *tl_cursor_color; /* NULL or allocated */
160
161 int tl_using_altscreen;
162};
163
164#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
165#define TMODE_LOOP 2 /* CTRL-W N used */
166
167/*
168 * List of all active terminals.
169 */
170static term_T *first_term = NULL;
171
172/* Terminal active in terminal_loop(). */
173static term_T *in_terminal_loop = NULL;
174
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100175#ifdef WIN3264
176static BOOL has_winpty = FALSE;
177static BOOL has_conpty = FALSE;
178#endif
179
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200180#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
181#define KEY_BUF_LEN 200
182
183/*
184 * Functions with separate implementation for MS-Windows and Unix-like systems.
185 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200186static 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 +0200187static int create_pty_only(term_T *term, jobopt_T *opt);
188static void term_report_winsize(term_T *term, int rows, int cols);
189static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100190#ifdef FEAT_GUI
191static void update_system_term(term_T *term);
192#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100194static void handle_postponed_scrollback(term_T *term);
195
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100196/* The character that we know (or assume) that the terminal expects for the
197 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200198static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200199
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100200/* "Terminal" highlight group colors. */
201static int term_default_cterm_fg = -1;
202static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200203
Bram Moolenaard317b382018-02-08 22:33:31 +0100204/* Store the last set and the desired cursor properties, so that we only update
205 * them when needed. Doing it unnecessary may result in flicker. */
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200206static char_u *last_set_cursor_color = NULL;
207static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100208static int last_set_cursor_shape = -1;
209static int desired_cursor_shape = -1;
210static int last_set_cursor_blink = -1;
211static int desired_cursor_blink = -1;
212
213
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200214/**************************************
215 * 1. Generic code for all systems.
216 */
217
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200218 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200219cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
220{
221 if (lhs_color != NULL && rhs_color != NULL)
222 return STRCMP(lhs_color, rhs_color) == 0;
223 return lhs_color == NULL && rhs_color == NULL;
224}
225
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200226 static void
227cursor_color_copy(char_u **to_color, char_u *from_color)
228{
229 // Avoid a free & alloc if the value is already right.
230 if (cursor_color_equal(*to_color, from_color))
231 return;
232 vim_free(*to_color);
233 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
234}
235
236 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200237cursor_color_get(char_u *color)
238{
239 return (color == NULL) ? (char_u *)"" : color;
240}
241
242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200243/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200244 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200245 * current window.
246 * Sets "rows" and/or "cols" to zero when it should follow the window size.
247 * Return TRUE if the size is the minimum size: "24*80".
248 */
249 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200250parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200251{
252 int minsize = FALSE;
253
254 *rows = 0;
255 *cols = 0;
256
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200257 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200258 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200259 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200260
261 /* Syntax of value was already checked when it's set. */
262 if (p == NULL)
263 {
264 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200265 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200266 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200267 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200268 *cols = atoi((char *)p + 1);
269 }
270 return minsize;
271}
272
273/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200274 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200275 */
276 static void
277set_term_and_win_size(term_T *term)
278{
Bram Moolenaar13568252018-03-16 20:46:58 +0100279#ifdef FEAT_GUI
280 if (term->tl_system)
281 {
282 /* Use the whole screen for the system command. However, it will start
283 * at the command line and scroll up as needed, using tl_toprow. */
284 term->tl_rows = Rows;
285 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200286 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100287 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100288#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200289 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200290 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200291 if (term->tl_rows != 0)
292 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
293 if (term->tl_cols != 0)
294 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200295 }
296 if (term->tl_rows == 0)
297 term->tl_rows = curwin->w_height;
298 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200299 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 if (term->tl_cols == 0)
301 term->tl_cols = curwin->w_width;
302 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200303 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200304}
305
306/*
307 * Initialize job options for a terminal job.
308 * Caller may overrule some of them.
309 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100310 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311init_job_options(jobopt_T *opt)
312{
313 clear_job_options(opt);
314
315 opt->jo_mode = MODE_RAW;
316 opt->jo_out_mode = MODE_RAW;
317 opt->jo_err_mode = MODE_RAW;
318 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
319}
320
321/*
322 * Set job options mandatory for a terminal job.
323 */
324 static void
325setup_job_options(jobopt_T *opt, int rows, int cols)
326{
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200327#ifndef WIN3264
328 /* Win32: Redirecting the job output won't work, thus always connect stdout
329 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200330 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200331#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200332 {
333 /* Connect stdout to the terminal. */
334 opt->jo_io[PART_OUT] = JIO_BUFFER;
335 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
336 opt->jo_modifiable[PART_OUT] = 0;
337 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
338 }
339
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200340#ifndef WIN3264
341 /* Win32: Redirecting the job output won't work, thus always connect stderr
342 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200343 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200344#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200345 {
346 /* Connect stderr to the terminal. */
347 opt->jo_io[PART_ERR] = JIO_BUFFER;
348 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
349 opt->jo_modifiable[PART_ERR] = 0;
350 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
351 }
352
353 opt->jo_pty = TRUE;
354 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
355 opt->jo_term_rows = rows;
356 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
357 opt->jo_term_cols = cols;
358}
359
360/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100361 * Close a terminal buffer (and its window). Used when creating the terminal
362 * fails.
363 */
364 static void
365term_close_buffer(buf_T *buf, buf_T *old_curbuf)
366{
367 free_terminal(buf);
368 if (old_curbuf != NULL)
369 {
370 --curbuf->b_nwindows;
371 curbuf = old_curbuf;
372 curwin->w_buffer = curbuf;
373 ++curbuf->b_nwindows;
374 }
375
376 /* Wiping out the buffer will also close the window and call
377 * free_terminal(). */
378 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
379}
380
381/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200382 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100383 * Use either "argvar" or "argv", the other must be NULL.
384 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
385 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200386 * Returns NULL when failed.
387 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100388 buf_T *
389term_start(
390 typval_T *argvar,
391 char **argv,
392 jobopt_T *opt,
393 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200394{
395 exarg_T split_ea;
396 win_T *old_curwin = curwin;
397 term_T *term;
398 buf_T *old_curbuf = NULL;
399 int res;
400 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100401 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200402 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200403
404 if (check_restricted() || check_secure())
405 return NULL;
406
407 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
408 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
409 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
410 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
411 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100412 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200413 return NULL;
414 }
415
416 term = (term_T *)alloc_clear(sizeof(term_T));
417 if (term == NULL)
418 return NULL;
419 term->tl_dirty_row_end = MAX_ROW;
420 term->tl_cursor_visible = TRUE;
421 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
422 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100423#ifdef FEAT_GUI
424 term->tl_system = (flags & TERM_START_SYSTEM);
425#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200426 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100427 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428
429 vim_memset(&split_ea, 0, sizeof(split_ea));
430 if (opt->jo_curwin)
431 {
432 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100433 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200434 {
435 no_write_message();
436 vim_free(term);
437 return NULL;
438 }
439 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100440 ECMD_HIDE
441 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
442 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200443 {
444 vim_free(term);
445 return NULL;
446 }
447 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100448 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200449 {
450 buf_T *buf;
451
452 /* Create a new buffer without a window. Make it the current buffer for
453 * a moment to be able to do the initialisations. */
454 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
455 BLN_NEW | BLN_LISTED);
456 if (buf == NULL || ml_open(buf) == FAIL)
457 {
458 vim_free(term);
459 return NULL;
460 }
461 old_curbuf = curbuf;
462 --curbuf->b_nwindows;
463 curbuf = buf;
464 curwin->w_buffer = buf;
465 ++curbuf->b_nwindows;
466 }
467 else
468 {
469 /* Open a new window or tab. */
470 split_ea.cmdidx = CMD_new;
471 split_ea.cmd = (char_u *)"new";
472 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100473 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200474 {
475 split_ea.line2 = opt->jo_term_rows;
476 split_ea.addr_count = 1;
477 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100478 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200479 {
480 split_ea.line2 = opt->jo_term_cols;
481 split_ea.addr_count = 1;
482 }
483
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100484 if (vertical)
485 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200486 ex_splitview(&split_ea);
487 if (curwin == old_curwin)
488 {
489 /* split failed */
490 vim_free(term);
491 return NULL;
492 }
493 }
494 term->tl_buffer = curbuf;
495 curbuf->b_term = term;
496
497 if (!opt->jo_hidden)
498 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100499 /* Only one size was taken care of with :new, do the other one. With
500 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100501 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200502 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100503 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200504 win_setwidth(opt->jo_term_cols);
505 }
506
507 /* Link the new terminal in the list of active terminals. */
508 term->tl_next = first_term;
509 first_term = term;
510
511 if (opt->jo_term_name != NULL)
512 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100513 else if (argv != NULL)
514 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200515 else
516 {
517 int i;
518 size_t len;
519 char_u *cmd, *p;
520
521 if (argvar->v_type == VAR_STRING)
522 {
523 cmd = argvar->vval.v_string;
524 if (cmd == NULL)
525 cmd = (char_u *)"";
526 else if (STRCMP(cmd, "NONE") == 0)
527 cmd = (char_u *)"pty";
528 }
529 else if (argvar->v_type != VAR_LIST
530 || argvar->vval.v_list == NULL
531 || argvar->vval.v_list->lv_len < 1
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100532 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200533 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
534 cmd = (char_u*)"";
535
536 len = STRLEN(cmd) + 10;
537 p = alloc((int)len);
538
539 for (i = 0; p != NULL; ++i)
540 {
541 /* Prepend a ! to the command name to avoid the buffer name equals
542 * the executable, otherwise ":w!" would overwrite it. */
543 if (i == 0)
544 vim_snprintf((char *)p, len, "!%s", cmd);
545 else
546 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
547 if (buflist_findname(p) == NULL)
548 {
549 vim_free(curbuf->b_ffname);
550 curbuf->b_ffname = p;
551 break;
552 }
553 }
554 }
555 curbuf->b_fname = curbuf->b_ffname;
556
557 if (opt->jo_term_opencmd != NULL)
558 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
559
560 if (opt->jo_eof_chars != NULL)
561 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
562
563 set_string_option_direct((char_u *)"buftype", -1,
564 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200565 // Avoid that 'buftype' is reset when this buffer is entered.
566 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200567
568 /* Mark the buffer as not modifiable. It can only be made modifiable after
569 * the job finished. */
570 curbuf->b_p_ma = FALSE;
571
572 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200573#ifdef WIN3264
574 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
575#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200576 setup_job_options(opt, term->tl_rows, term->tl_cols);
577
Bram Moolenaar13568252018-03-16 20:46:58 +0100578 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100579 return curbuf;
580
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100581#if defined(FEAT_SESSION)
582 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100583 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100584 {
585 term->tl_command = vim_strsave((char_u *)"NONE");
586 }
587 else if (argvar->v_type == VAR_STRING)
588 {
589 char_u *cmd = argvar->vval.v_string;
590
591 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
592 term->tl_command = vim_strsave(cmd);
593 }
594 else if (argvar->v_type == VAR_LIST
595 && argvar->vval.v_list != NULL
596 && argvar->vval.v_list->lv_len > 0)
597 {
598 garray_T ga;
599 listitem_T *item;
600
601 ga_init2(&ga, 1, 100);
602 for (item = argvar->vval.v_list->lv_first;
603 item != NULL; item = item->li_next)
604 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100605 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100606 char_u *p;
607
608 if (s == NULL)
609 break;
610 p = vim_strsave_fnameescape(s, FALSE);
611 if (p == NULL)
612 break;
613 ga_concat(&ga, p);
614 vim_free(p);
615 ga_append(&ga, ' ');
616 }
617 if (item == NULL)
618 {
619 ga_append(&ga, NUL);
620 term->tl_command = ga.ga_data;
621 }
622 else
623 ga_clear(&ga);
624 }
625#endif
626
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100627 if (opt->jo_term_kill != NULL)
628 {
629 char_u *p = skiptowhite(opt->jo_term_kill);
630
631 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
632 }
633
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200634 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100635 if (argv == NULL
636 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200637 && argvar->vval.v_string != NULL
638 && STRCMP(argvar->vval.v_string, "NONE") == 0)
639 res = create_pty_only(term, opt);
640 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200641 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200642
643 newbuf = curbuf;
644 if (res == OK)
645 {
646 /* Get and remember the size we ended up with. Update the pty. */
647 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
648 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100649#ifdef FEAT_GUI
650 if (term->tl_system)
651 {
652 /* display first line below typed command */
653 term->tl_toprow = msg_row + 1;
654 term->tl_dirty_row_end = 0;
655 }
656#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200657
658 /* Make sure we don't get stuck on sending keys to the job, it leads to
659 * a deadlock if the job is waiting for Vim to read. */
660 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
661
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200662 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200663 {
664 --curbuf->b_nwindows;
665 curbuf = old_curbuf;
666 curwin->w_buffer = curbuf;
667 ++curbuf->b_nwindows;
668 }
669 }
670 else
671 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100672 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200673 return NULL;
674 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100675
Bram Moolenaar13568252018-03-16 20:46:58 +0100676 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200677 return newbuf;
678}
679
680/*
681 * ":terminal": open a terminal window and execute a job in it.
682 */
683 void
684ex_terminal(exarg_T *eap)
685{
686 typval_T argvar[2];
687 jobopt_T opt;
688 char_u *cmd;
689 char_u *tofree = NULL;
690
691 init_job_options(&opt);
692
693 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100694 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200695 {
696 char_u *p, *ep;
697
698 cmd += 2;
699 p = skiptowhite(cmd);
700 ep = vim_strchr(cmd, '=');
701 if (ep != NULL && ep < p)
702 p = ep;
703
704 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
705 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100706 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
707 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200708 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
709 opt.jo_term_finish = 'o';
710 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
711 opt.jo_curwin = 1;
712 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
713 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100714 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
715 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100716 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
717 && ep != NULL)
718 {
719 opt.jo_set2 |= JO2_TERM_KILL;
720 opt.jo_term_kill = ep + 1;
721 p = skiptowhite(cmd);
722 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200723 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
724 && ep != NULL && isdigit(ep[1]))
725 {
726 opt.jo_set2 |= JO2_TERM_ROWS;
727 opt.jo_term_rows = atoi((char *)ep + 1);
728 p = skiptowhite(cmd);
729 }
730 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
731 && ep != NULL && isdigit(ep[1]))
732 {
733 opt.jo_set2 |= JO2_TERM_COLS;
734 opt.jo_term_cols = atoi((char *)ep + 1);
735 p = skiptowhite(cmd);
736 }
737 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
738 && ep != NULL)
739 {
740 char_u *buf = NULL;
741 char_u *keys;
742
743 p = skiptowhite(cmd);
744 *p = NUL;
745 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
746 opt.jo_set2 |= JO2_EOF_CHARS;
747 opt.jo_eof_chars = vim_strsave(keys);
748 vim_free(buf);
749 *p = ' ';
750 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100751#ifdef WIN3264
752 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
753 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100754 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100755 int tty_type = NUL;
756
757 p = skiptowhite(cmd);
758 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
759 tty_type = 'w';
760 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
761 tty_type = 'c';
762 else
763 {
764 semsg(e_invargval, "type");
765 goto theend;
766 }
767 opt.jo_set2 |= JO2_TTY_TYPE;
768 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100769 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100770#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200771 else
772 {
773 if (*p)
774 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100775 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100776 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200777 }
778 cmd = skipwhite(p);
779 }
780 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100781 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200782 /* Make a copy of 'shell', an autocommand may change the option. */
783 tofree = cmd = vim_strsave(p_sh);
784
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100785 /* default to close when the shell exits */
786 if (opt.jo_term_finish == NUL)
787 opt.jo_term_finish = 'c';
788 }
789
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200790 if (eap->addr_count > 0)
791 {
792 /* Write lines from current buffer to the job. */
793 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
794 opt.jo_io[PART_IN] = JIO_BUFFER;
795 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
796 opt.jo_in_top = eap->line1;
797 opt.jo_in_bot = eap->line2;
798 }
799
800 argvar[0].v_type = VAR_STRING;
801 argvar[0].vval.v_string = cmd;
802 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100803 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200804 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100805
806theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200807 vim_free(opt.jo_eof_chars);
808}
809
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100810#if defined(FEAT_SESSION) || defined(PROTO)
811/*
812 * Write a :terminal command to the session file to restore the terminal in
813 * window "wp".
814 * Return FAIL if writing fails.
815 */
816 int
817term_write_session(FILE *fd, win_T *wp)
818{
819 term_T *term = wp->w_buffer->b_term;
820
821 /* Create the terminal and run the command. This is not without
822 * risk, but let's assume the user only creates a session when this
823 * will be OK. */
824 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
825 term->tl_cols, term->tl_rows) < 0)
826 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100827#ifdef WIN3264
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100828 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
829 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100830#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100831 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
832 return FAIL;
833
834 return put_eol(fd);
835}
836
837/*
838 * Return TRUE if "buf" has a terminal that should be restored.
839 */
840 int
841term_should_restore(buf_T *buf)
842{
843 term_T *term = buf->b_term;
844
845 return term != NULL && (term->tl_command == NULL
846 || STRCMP(term->tl_command, "NONE") != 0);
847}
848#endif
849
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200850/*
851 * Free the scrollback buffer for "term".
852 */
853 static void
854free_scrollback(term_T *term)
855{
856 int i;
857
858 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
859 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
860 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100861 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
862 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
863 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200864}
865
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100866
867// Terminals that need to be freed soon.
868term_T *terminals_to_free = NULL;
869
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200870/*
871 * Free a terminal and everything it refers to.
872 * Kills the job if there is one.
873 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100874 * The actual terminal structure is freed later in free_unused_terminals(),
875 * because callbacks may wipe out a buffer while the terminal is still
876 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200877 */
878 void
879free_terminal(buf_T *buf)
880{
881 term_T *term = buf->b_term;
882 term_T *tp;
883
884 if (term == NULL)
885 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100886
887 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200888 if (first_term == term)
889 first_term = term->tl_next;
890 else
891 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
892 if (tp->tl_next == term)
893 {
894 tp->tl_next = term->tl_next;
895 break;
896 }
897
898 if (term->tl_job != NULL)
899 {
900 if (term->tl_job->jv_status != JOB_ENDED
901 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100902 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200903 job_stop(term->tl_job, NULL, "kill");
904 job_unref(term->tl_job);
905 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100906 term->tl_next = terminals_to_free;
907 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200908
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200909 buf->b_term = NULL;
910 if (in_terminal_loop == term)
911 in_terminal_loop = NULL;
912}
913
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100914 void
915free_unused_terminals()
916{
917 while (terminals_to_free != NULL)
918 {
919 term_T *term = terminals_to_free;
920
921 terminals_to_free = term->tl_next;
922
923 free_scrollback(term);
924
925 term_free_vterm(term);
926 vim_free(term->tl_title);
927#ifdef FEAT_SESSION
928 vim_free(term->tl_command);
929#endif
930 vim_free(term->tl_kill);
931 vim_free(term->tl_status_text);
932 vim_free(term->tl_opencmd);
933 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100934 vim_free(term->tl_arg0_cmd);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100935#ifdef WIN3264
936 if (term->tl_out_fd != NULL)
937 fclose(term->tl_out_fd);
938#endif
939 vim_free(term->tl_cursor_color);
940 vim_free(term);
941 }
942}
943
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200944/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100945 * Get the part that is connected to the tty. Normally this is PART_IN, but
946 * when writing buffer lines to the job it can be another. This makes it
947 * possible to do "1,5term vim -".
948 */
949 static ch_part_T
950get_tty_part(term_T *term)
951{
952#ifdef UNIX
953 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
954 int i;
955
956 for (i = 0; i < 3; ++i)
957 {
958 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
959
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +0100960 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100961 return parts[i];
962 }
963#endif
964 return PART_IN;
965}
966
967/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200968 * Write job output "msg[len]" to the vterm.
969 */
970 static void
971term_write_job_output(term_T *term, char_u *msg, size_t len)
972{
973 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100974 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200975
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100976 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200977
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100978 /* flush vterm buffer when vterm responded to control sequence */
979 if (prevlen != vterm_output_get_buffer_current(vterm))
980 {
981 char buf[KEY_BUF_LEN];
982 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
983
984 if (curlen > 0)
985 channel_send(term->tl_job->jv_channel, get_tty_part(term),
986 (char_u *)buf, (int)curlen, NULL);
987 }
988
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200989 /* this invokes the damage callbacks */
990 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
991}
992
993 static void
994update_cursor(term_T *term, int redraw)
995{
996 if (term->tl_normal_mode)
997 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100998#ifdef FEAT_GUI
999 if (term->tl_system)
1000 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1001 term->tl_cursor_pos.col);
1002 else
1003#endif
1004 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001005 if (redraw)
1006 {
1007 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1008 cursor_on();
1009 out_flush();
1010#ifdef FEAT_GUI
1011 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001012 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001013 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001014 gui_mch_flush();
1015 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001016#endif
1017 }
1018}
1019
1020/*
1021 * Invoked when "msg" output from a job was received. Write it to the terminal
1022 * of "buffer".
1023 */
1024 void
1025write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1026{
1027 size_t len = STRLEN(msg);
1028 term_T *term = buffer->b_term;
1029
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001030#ifdef WIN3264
1031 /* Win32: Cannot redirect output of the job, intercept it here and write to
1032 * the file. */
1033 if (term->tl_out_fd != NULL)
1034 {
1035 ch_log(channel, "Writing %d bytes to output file", (int)len);
1036 fwrite(msg, len, 1, term->tl_out_fd);
1037 return;
1038 }
1039#endif
1040
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001041 if (term->tl_vterm == NULL)
1042 {
1043 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1044 return;
1045 }
1046 ch_log(channel, "writing %d bytes to terminal", (int)len);
1047 term_write_job_output(term, msg, len);
1048
Bram Moolenaar13568252018-03-16 20:46:58 +01001049#ifdef FEAT_GUI
1050 if (term->tl_system)
1051 {
1052 /* show system output, scrolling up the screen as needed */
1053 update_system_term(term);
1054 update_cursor(term, TRUE);
1055 }
1056 else
1057#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001058 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
1059 * contents, thus no screen update is needed. */
1060 if (!term->tl_normal_mode)
1061 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001062 // Don't use update_screen() when editing the command line, it gets
1063 // cleared.
1064 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001065 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001066 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001067 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001068 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001069 /* update_screen() can be slow, check the terminal wasn't closed
1070 * already */
1071 if (buffer == curbuf && curbuf->b_term != NULL)
1072 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001073 }
1074 else
1075 redraw_after_callback(TRUE);
1076 }
1077}
1078
1079/*
1080 * Send a mouse position and click to the vterm
1081 */
1082 static int
1083term_send_mouse(VTerm *vterm, int button, int pressed)
1084{
1085 VTermModifier mod = VTERM_MOD_NONE;
1086
1087 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001088 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001089 if (button != 0)
1090 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001091 return TRUE;
1092}
1093
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001094static int enter_mouse_col = -1;
1095static int enter_mouse_row = -1;
1096
1097/*
1098 * Handle a mouse click, drag or release.
1099 * Return TRUE when a mouse event is sent to the terminal.
1100 */
1101 static int
1102term_mouse_click(VTerm *vterm, int key)
1103{
1104#if defined(FEAT_CLIPBOARD)
1105 /* For modeless selection mouse drag and release events are ignored, unless
1106 * they are preceded with a mouse down event */
1107 static int ignore_drag_release = TRUE;
1108 VTermMouseState mouse_state;
1109
1110 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1111 if (mouse_state.flags == 0)
1112 {
1113 /* Terminal is not using the mouse, use modeless selection. */
1114 switch (key)
1115 {
1116 case K_LEFTDRAG:
1117 case K_LEFTRELEASE:
1118 case K_RIGHTDRAG:
1119 case K_RIGHTRELEASE:
1120 /* Ignore drag and release events when the button-down wasn't
1121 * seen before. */
1122 if (ignore_drag_release)
1123 {
1124 int save_mouse_col, save_mouse_row;
1125
1126 if (enter_mouse_col < 0)
1127 break;
1128
1129 /* mouse click in the window gave us focus, handle that
1130 * click now */
1131 save_mouse_col = mouse_col;
1132 save_mouse_row = mouse_row;
1133 mouse_col = enter_mouse_col;
1134 mouse_row = enter_mouse_row;
1135 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1136 mouse_col = save_mouse_col;
1137 mouse_row = save_mouse_row;
1138 }
1139 /* FALLTHROUGH */
1140 case K_LEFTMOUSE:
1141 case K_RIGHTMOUSE:
1142 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1143 ignore_drag_release = TRUE;
1144 else
1145 ignore_drag_release = FALSE;
1146 /* Should we call mouse_has() here? */
1147 if (clip_star.available)
1148 {
1149 int button, is_click, is_drag;
1150
1151 button = get_mouse_button(KEY2TERMCAP1(key),
1152 &is_click, &is_drag);
1153 if (mouse_model_popup() && button == MOUSE_LEFT
1154 && (mod_mask & MOD_MASK_SHIFT))
1155 {
1156 /* Translate shift-left to right button. */
1157 button = MOUSE_RIGHT;
1158 mod_mask &= ~MOD_MASK_SHIFT;
1159 }
1160 clip_modeless(button, is_click, is_drag);
1161 }
1162 break;
1163
1164 case K_MIDDLEMOUSE:
1165 if (clip_star.available)
1166 insert_reg('*', TRUE);
1167 break;
1168 }
1169 enter_mouse_col = -1;
1170 return FALSE;
1171 }
1172#endif
1173 enter_mouse_col = -1;
1174
1175 switch (key)
1176 {
1177 case K_LEFTMOUSE:
1178 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1179 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1180 case K_LEFTRELEASE:
1181 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1182 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1183 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1184 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1185 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1186 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1187 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1188 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1189 }
1190 return TRUE;
1191}
1192
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001193/*
1194 * Convert typed key "c" into bytes to send to the job.
1195 * Return the number of bytes in "buf".
1196 */
1197 static int
1198term_convert_key(term_T *term, int c, char *buf)
1199{
1200 VTerm *vterm = term->tl_vterm;
1201 VTermKey key = VTERM_KEY_NONE;
1202 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001203 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001204
1205 switch (c)
1206 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001207 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1208
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001209 /* don't use VTERM_KEY_BACKSPACE, it always
1210 * becomes 0x7f DEL */
1211 case K_BS: c = term_backspace_char; break;
1212
1213 case ESC: key = VTERM_KEY_ESCAPE; break;
1214 case K_DEL: key = VTERM_KEY_DEL; break;
1215 case K_DOWN: key = VTERM_KEY_DOWN; break;
1216 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1217 key = VTERM_KEY_DOWN; break;
1218 case K_END: key = VTERM_KEY_END; break;
1219 case K_S_END: mod = VTERM_MOD_SHIFT;
1220 key = VTERM_KEY_END; break;
1221 case K_C_END: mod = VTERM_MOD_CTRL;
1222 key = VTERM_KEY_END; break;
1223 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1224 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1225 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1226 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1227 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1228 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1229 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1230 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1231 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1232 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1233 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1234 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1235 case K_HOME: key = VTERM_KEY_HOME; break;
1236 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1237 key = VTERM_KEY_HOME; break;
1238 case K_C_HOME: mod = VTERM_MOD_CTRL;
1239 key = VTERM_KEY_HOME; break;
1240 case K_INS: key = VTERM_KEY_INS; break;
1241 case K_K0: key = VTERM_KEY_KP_0; break;
1242 case K_K1: key = VTERM_KEY_KP_1; break;
1243 case K_K2: key = VTERM_KEY_KP_2; break;
1244 case K_K3: key = VTERM_KEY_KP_3; break;
1245 case K_K4: key = VTERM_KEY_KP_4; break;
1246 case K_K5: key = VTERM_KEY_KP_5; break;
1247 case K_K6: key = VTERM_KEY_KP_6; break;
1248 case K_K7: key = VTERM_KEY_KP_7; break;
1249 case K_K8: key = VTERM_KEY_KP_8; break;
1250 case K_K9: key = VTERM_KEY_KP_9; break;
1251 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1252 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1253 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1254 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1255 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1256 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1257 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1258 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1259 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1260 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1261 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1262 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1263 case K_LEFT: key = VTERM_KEY_LEFT; break;
1264 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1265 key = VTERM_KEY_LEFT; break;
1266 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1267 key = VTERM_KEY_LEFT; break;
1268 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1269 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1270 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1271 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1272 key = VTERM_KEY_RIGHT; break;
1273 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1274 key = VTERM_KEY_RIGHT; break;
1275 case K_UP: key = VTERM_KEY_UP; break;
1276 case K_S_UP: mod = VTERM_MOD_SHIFT;
1277 key = VTERM_KEY_UP; break;
1278 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001279 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1280 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001281
Bram Moolenaara42ad572017-11-16 13:08:04 +01001282 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1283 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001284 case K_MOUSELEFT: /* TODO */ return 0;
1285 case K_MOUSERIGHT: /* TODO */ return 0;
1286
1287 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001288 case K_LEFTMOUSE_NM:
1289 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001290 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001291 case K_LEFTRELEASE_NM:
1292 case K_MOUSEMOVE:
1293 case K_MIDDLEMOUSE:
1294 case K_MIDDLEDRAG:
1295 case K_MIDDLERELEASE:
1296 case K_RIGHTMOUSE:
1297 case K_RIGHTDRAG:
1298 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1299 return 0;
1300 other = TRUE;
1301 break;
1302
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001303 case K_X1MOUSE: /* TODO */ return 0;
1304 case K_X1DRAG: /* TODO */ return 0;
1305 case K_X1RELEASE: /* TODO */ return 0;
1306 case K_X2MOUSE: /* TODO */ return 0;
1307 case K_X2DRAG: /* TODO */ return 0;
1308 case K_X2RELEASE: /* TODO */ return 0;
1309
1310 case K_IGNORE: return 0;
1311 case K_NOP: return 0;
1312 case K_UNDO: return 0;
1313 case K_HELP: return 0;
1314 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1315 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1316 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1317 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1318 case K_SELECT: return 0;
1319#ifdef FEAT_GUI
1320 case K_VER_SCROLLBAR: return 0;
1321 case K_HOR_SCROLLBAR: return 0;
1322#endif
1323#ifdef FEAT_GUI_TABLINE
1324 case K_TABLINE: return 0;
1325 case K_TABMENU: return 0;
1326#endif
1327#ifdef FEAT_NETBEANS_INTG
1328 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1329#endif
1330#ifdef FEAT_DND
1331 case K_DROP: return 0;
1332#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001333 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001334 case K_PS: vterm_keyboard_start_paste(vterm);
1335 other = TRUE;
1336 break;
1337 case K_PE: vterm_keyboard_end_paste(vterm);
1338 other = TRUE;
1339 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001340 }
1341
1342 /*
1343 * Convert special keys to vterm keys:
1344 * - Write keys to vterm: vterm_keyboard_key()
1345 * - Write output to channel.
1346 * TODO: use mod_mask
1347 */
1348 if (key != VTERM_KEY_NONE)
1349 /* Special key, let vterm convert it. */
1350 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001351 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001352 /* Normal character, let vterm convert it. */
1353 vterm_keyboard_unichar(vterm, c, mod);
1354
1355 /* Read back the converted escape sequence. */
1356 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1357}
1358
1359/*
1360 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001361 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001362 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001363 */
1364 static int
1365term_job_running_check(term_T *term, int check_job_status)
1366{
1367 /* Also consider the job finished when the channel is closed, to avoid a
1368 * race condition when updating the title. */
1369 if (term != NULL
1370 && term->tl_job != NULL
1371 && channel_is_open(term->tl_job->jv_channel))
1372 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001373 job_T *job = term->tl_job;
1374
1375 // Careful: Checking the job status may invoked callbacks, which close
1376 // the buffer and terminate "term". However, "job" will not be freed
1377 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001378 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001379 job_status(job);
1380 return (job->jv_status == JOB_STARTED
1381 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001382 }
1383 return FALSE;
1384}
1385
1386/*
1387 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001388 */
1389 int
1390term_job_running(term_T *term)
1391{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001392 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001393}
1394
1395/*
1396 * Return TRUE if "term" has an active channel and used ":term NONE".
1397 */
1398 int
1399term_none_open(term_T *term)
1400{
1401 /* Also consider the job finished when the channel is closed, to avoid a
1402 * race condition when updating the title. */
1403 return term != NULL
1404 && term->tl_job != NULL
1405 && channel_is_open(term->tl_job->jv_channel)
1406 && term->tl_job->jv_channel->ch_keep_open;
1407}
1408
1409/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001410 * Used when exiting: kill the job in "buf" if so desired.
1411 * Return OK when the job finished.
1412 * Return FAIL when the job is still running.
1413 */
1414 int
1415term_try_stop_job(buf_T *buf)
1416{
1417 int count;
1418 char *how = (char *)buf->b_term->tl_kill;
1419
1420#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1421 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1422 {
1423 char_u buff[DIALOG_MSG_SIZE];
1424 int ret;
1425
1426 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1427 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1428 if (ret == VIM_YES)
1429 how = "kill";
1430 else if (ret == VIM_CANCEL)
1431 return FAIL;
1432 }
1433#endif
1434 if (how == NULL || *how == NUL)
1435 return FAIL;
1436
1437 job_stop(buf->b_term->tl_job, NULL, how);
1438
Bram Moolenaar9172d232019-01-29 23:06:54 +01001439 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001440 for (count = 0; count < 100; ++count)
1441 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001442 job_T *job;
1443
1444 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001445 if (!buf_valid(buf)
1446 || buf->b_term == NULL
1447 || buf->b_term->tl_job == NULL)
1448 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001449 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001450
Bram Moolenaar9172d232019-01-29 23:06:54 +01001451 // Call job_status() to update jv_status. It may cause the job to be
1452 // cleaned up but it won't be freed.
1453 job_status(job);
1454 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001455 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001456
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001457 ui_delay(10L, FALSE);
1458 mch_check_messages();
1459 parse_queued_messages();
1460 }
1461 return FAIL;
1462}
1463
1464/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001465 * Add the last line of the scrollback buffer to the buffer in the window.
1466 */
1467 static void
1468add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1469{
1470 buf_T *buf = term->tl_buffer;
1471 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1472 linenr_T lnum = buf->b_ml.ml_line_count;
1473
1474#ifdef WIN3264
1475 if (!enc_utf8 && enc_codepage > 0)
1476 {
1477 WCHAR *ret = NULL;
1478 int length = 0;
1479
1480 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1481 &ret, &length);
1482 if (ret != NULL)
1483 {
1484 WideCharToMultiByte_alloc(enc_codepage, 0,
1485 ret, length, (char **)&text, &len, 0, 0);
1486 vim_free(ret);
1487 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1488 vim_free(text);
1489 }
1490 }
1491 else
1492#endif
1493 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1494 if (empty)
1495 {
1496 /* Delete the empty line that was in the empty buffer. */
1497 curbuf = buf;
1498 ml_delete(1, FALSE);
1499 curbuf = curwin->w_buffer;
1500 }
1501}
1502
1503 static void
1504cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1505{
1506 attr->width = cell->width;
1507 attr->attrs = cell->attrs;
1508 attr->fg = cell->fg;
1509 attr->bg = cell->bg;
1510}
1511
1512 static int
1513equal_celattr(cellattr_T *a, cellattr_T *b)
1514{
1515 /* Comparing the colors should be sufficient. */
1516 return a->fg.red == b->fg.red
1517 && a->fg.green == b->fg.green
1518 && a->fg.blue == b->fg.blue
1519 && a->bg.red == b->bg.red
1520 && a->bg.green == b->bg.green
1521 && a->bg.blue == b->bg.blue;
1522}
1523
Bram Moolenaard96ff162018-02-18 22:13:29 +01001524/*
1525 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1526 * line at this position. Otherwise at the end.
1527 */
1528 static int
1529add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1530{
1531 if (ga_grow(&term->tl_scrollback, 1) == OK)
1532 {
1533 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1534 + term->tl_scrollback.ga_len;
1535
1536 if (lnum > 0)
1537 {
1538 int i;
1539
1540 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1541 {
1542 *line = *(line - 1);
1543 --line;
1544 }
1545 }
1546 line->sb_cols = 0;
1547 line->sb_cells = NULL;
1548 line->sb_fill_attr = *fill_attr;
1549 ++term->tl_scrollback.ga_len;
1550 return OK;
1551 }
1552 return FALSE;
1553}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001554
1555/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001556 * Remove the terminal contents from the scrollback and the buffer.
1557 * Used before adding a new scrollback line or updating the buffer for lines
1558 * displayed in the terminal.
1559 */
1560 static void
1561cleanup_scrollback(term_T *term)
1562{
1563 sb_line_T *line;
1564 garray_T *gap;
1565
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001566 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001567 gap = &term->tl_scrollback;
1568 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1569 && gap->ga_len > 0)
1570 {
1571 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1572 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1573 vim_free(line->sb_cells);
1574 --gap->ga_len;
1575 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001576 curbuf = curwin->w_buffer;
1577 if (curbuf == term->tl_buffer)
1578 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001579}
1580
1581/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001582 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001583 */
1584 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001585update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001586{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001587 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001588 int len;
1589 int lines_skipped = 0;
1590 VTermPos pos;
1591 VTermScreenCell cell;
1592 cellattr_T fill_attr, new_fill_attr;
1593 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001594
1595 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1596 "Adding terminal window snapshot to buffer");
1597
1598 /* First remove the lines that were appended before, they might be
1599 * outdated. */
1600 cleanup_scrollback(term);
1601
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001602 screen = vterm_obtain_screen(term->tl_vterm);
1603 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001604 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1605 {
1606 len = 0;
1607 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1608 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1609 && cell.chars[0] != NUL)
1610 {
1611 len = pos.col + 1;
1612 new_fill_attr = term->tl_default_color;
1613 }
1614 else
1615 /* Assume the last attr is the filler attr. */
1616 cell2cellattr(&cell, &new_fill_attr);
1617
1618 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1619 ++lines_skipped;
1620 else
1621 {
1622 while (lines_skipped > 0)
1623 {
1624 /* Line was skipped, add an empty line. */
1625 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001626 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001628 }
1629
1630 if (len == 0)
1631 p = NULL;
1632 else
1633 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1634 if ((p != NULL || len == 0)
1635 && ga_grow(&term->tl_scrollback, 1) == OK)
1636 {
1637 garray_T ga;
1638 int width;
1639 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1640 + term->tl_scrollback.ga_len;
1641
1642 ga_init2(&ga, 1, 100);
1643 for (pos.col = 0; pos.col < len; pos.col += width)
1644 {
1645 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1646 {
1647 width = 1;
1648 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1649 if (ga_grow(&ga, 1) == OK)
1650 ga.ga_len += utf_char2bytes(' ',
1651 (char_u *)ga.ga_data + ga.ga_len);
1652 }
1653 else
1654 {
1655 width = cell.width;
1656
1657 cell2cellattr(&cell, &p[pos.col]);
1658
Bram Moolenaara79fd562018-12-20 20:47:32 +01001659 // Each character can be up to 6 bytes.
1660 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001661 {
1662 int i;
1663 int c;
1664
1665 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1666 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1667 (char_u *)ga.ga_data + ga.ga_len);
1668 }
1669 }
1670 }
1671 line->sb_cols = len;
1672 line->sb_cells = p;
1673 line->sb_fill_attr = new_fill_attr;
1674 fill_attr = new_fill_attr;
1675 ++term->tl_scrollback.ga_len;
1676
1677 if (ga_grow(&ga, 1) == FAIL)
1678 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1679 else
1680 {
1681 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1682 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1683 }
1684 ga_clear(&ga);
1685 }
1686 else
1687 vim_free(p);
1688 }
1689 }
1690
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001691 // Add trailing empty lines.
1692 for (pos.row = term->tl_scrollback.ga_len;
1693 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1694 ++pos.row)
1695 {
1696 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1697 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1698 }
1699
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001700 term->tl_dirty_snapshot = FALSE;
1701#ifdef FEAT_TIMERS
1702 term->tl_timer_set = FALSE;
1703#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001704}
1705
1706/*
1707 * If needed, add the current lines of the terminal to scrollback and to the
1708 * buffer. Called after the job has ended and when switching to
1709 * Terminal-Normal mode.
1710 * When "redraw" is TRUE redraw the windows that show the terminal.
1711 */
1712 static void
1713may_move_terminal_to_buffer(term_T *term, int redraw)
1714{
1715 win_T *wp;
1716
1717 if (term->tl_vterm == NULL)
1718 return;
1719
1720 /* Update the snapshot only if something changes or the buffer does not
1721 * have all the lines. */
1722 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1723 <= term->tl_scrollback_scrolled)
1724 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001725
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001726 /* Obtain the current background color. */
1727 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1728 &term->tl_default_color.fg, &term->tl_default_color.bg);
1729
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001730 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001731 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001732 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001733 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001735 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1736 wp->w_cursor.col = 0;
1737 wp->w_valid = 0;
1738 if (wp->w_cursor.lnum >= wp->w_height)
1739 {
1740 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001741
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001742 if (wp->w_topline < min_topline)
1743 wp->w_topline = min_topline;
1744 }
1745 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001746 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001747 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001748}
1749
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001750#if defined(FEAT_TIMERS) || defined(PROTO)
1751/*
1752 * Check if any terminal timer expired. If so, copy text from the terminal to
1753 * the buffer.
1754 * Return the time until the next timer will expire.
1755 */
1756 int
1757term_check_timers(int next_due_arg, proftime_T *now)
1758{
1759 term_T *term;
1760 int next_due = next_due_arg;
1761
1762 for (term = first_term; term != NULL; term = term->tl_next)
1763 {
1764 if (term->tl_timer_set && !term->tl_normal_mode)
1765 {
1766 long this_due = proftime_time_left(&term->tl_timer_due, now);
1767
1768 if (this_due <= 1)
1769 {
1770 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001771 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001772 }
1773 else if (next_due == -1 || next_due > this_due)
1774 next_due = this_due;
1775 }
1776 }
1777
1778 return next_due;
1779}
1780#endif
1781
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001782/*
1783 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1784 * otherwise end it.
1785 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001786 static void
1787set_terminal_mode(term_T *term, int normal_mode)
1788{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001789ch_log(NULL, "set_terminal_mode(): %d", normal_mode);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001790 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001791 if (!normal_mode)
1792 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001793 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001794 if (term->tl_buffer == curbuf)
1795 maketitle();
1796}
1797
1798/*
1799 * Called after the job if finished and Terminal mode is not active:
1800 * Move the vterm contents into the scrollback buffer and free the vterm.
1801 */
1802 static void
1803cleanup_vterm(term_T *term)
1804{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001805 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001806 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001807 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001808 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001809}
1810
1811/*
1812 * Switch from Terminal-Job mode to Terminal-Normal mode.
1813 * Suspends updating the terminal window.
1814 */
1815 static void
1816term_enter_normal_mode(void)
1817{
1818 term_T *term = curbuf->b_term;
1819
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001820 set_terminal_mode(term, TRUE);
1821
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001822 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001823 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001825 /* Move the window cursor to the position of the cursor in the
1826 * terminal. */
1827 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1828 + term->tl_cursor_pos.row + 1;
1829 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001830 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1831 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001832
1833 /* Display the same lines as in the terminal. */
1834 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1835}
1836
1837/*
1838 * Returns TRUE if the current window contains a terminal and we are in
1839 * Terminal-Normal mode.
1840 */
1841 int
1842term_in_normal_mode(void)
1843{
1844 term_T *term = curbuf->b_term;
1845
1846 return term != NULL && term->tl_normal_mode;
1847}
1848
1849/*
1850 * Switch from Terminal-Normal mode to Terminal-Job mode.
1851 * Restores updating the terminal window.
1852 */
1853 void
1854term_enter_job_mode()
1855{
1856 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001857
1858 set_terminal_mode(term, FALSE);
1859
1860 if (term->tl_channel_closed)
1861 cleanup_vterm(term);
1862 redraw_buf_and_status_later(curbuf, NOT_VALID);
1863}
1864
1865/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001866 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001867 * Note: while waiting a terminal may be closed and freed if the channel is
1868 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001869 */
1870 static int
1871term_vgetc()
1872{
1873 int c;
1874 int save_State = State;
1875
1876 State = TERMINAL;
1877 got_int = FALSE;
1878#ifdef WIN3264
1879 ctrl_break_was_pressed = FALSE;
1880#endif
1881 c = vgetc();
1882 got_int = FALSE;
1883 State = save_State;
1884 return c;
1885}
1886
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001887static int mouse_was_outside = FALSE;
1888
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001889/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001890 * Send keys to terminal.
1891 * Return FAIL when the key needs to be handled in Normal mode.
1892 * Return OK when the key was dropped or sent to the terminal.
1893 */
1894 int
1895send_keys_to_term(term_T *term, int c, int typed)
1896{
1897 char msg[KEY_BUF_LEN];
1898 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001899 int dragging_outside = FALSE;
1900
1901 /* Catch keys that need to be handled as in Normal mode. */
1902 switch (c)
1903 {
1904 case NUL:
1905 case K_ZERO:
1906 if (typed)
1907 stuffcharReadbuff(c);
1908 return FAIL;
1909
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001910 case K_TABLINE:
1911 stuffcharReadbuff(c);
1912 return FAIL;
1913
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001914 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001915 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001916 return FAIL;
1917
1918 case K_LEFTDRAG:
1919 case K_MIDDLEDRAG:
1920 case K_RIGHTDRAG:
1921 case K_X1DRAG:
1922 case K_X2DRAG:
1923 dragging_outside = mouse_was_outside;
1924 /* FALLTHROUGH */
1925 case K_LEFTMOUSE:
1926 case K_LEFTMOUSE_NM:
1927 case K_LEFTRELEASE:
1928 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001929 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001930 case K_MIDDLEMOUSE:
1931 case K_MIDDLERELEASE:
1932 case K_RIGHTMOUSE:
1933 case K_RIGHTRELEASE:
1934 case K_X1MOUSE:
1935 case K_X1RELEASE:
1936 case K_X2MOUSE:
1937 case K_X2RELEASE:
1938
1939 case K_MOUSEUP:
1940 case K_MOUSEDOWN:
1941 case K_MOUSELEFT:
1942 case K_MOUSERIGHT:
1943 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001944 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001945 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001946 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001947 || dragging_outside)
1948 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001949 /* click or scroll outside the current window or on status line
1950 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001951 if (typed)
1952 {
1953 stuffcharReadbuff(c);
1954 mouse_was_outside = TRUE;
1955 }
1956 return FAIL;
1957 }
1958 }
1959 if (typed)
1960 mouse_was_outside = FALSE;
1961
1962 /* Convert the typed key to a sequence of bytes for the job. */
1963 len = term_convert_key(term, c, msg);
1964 if (len > 0)
1965 /* TODO: if FAIL is returned, stop? */
1966 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1967 (char_u *)msg, (int)len, NULL);
1968
1969 return OK;
1970}
1971
1972 static void
1973position_cursor(win_T *wp, VTermPos *pos)
1974{
1975 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1976 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1977 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1978}
1979
1980/*
1981 * Handle CTRL-W "": send register contents to the job.
1982 */
1983 static void
1984term_paste_register(int prev_c UNUSED)
1985{
1986 int c;
1987 list_T *l;
1988 listitem_T *item;
1989 long reglen = 0;
1990 int type;
1991
1992#ifdef FEAT_CMDL_INFO
1993 if (add_to_showcmd(prev_c))
1994 if (add_to_showcmd('"'))
1995 out_flush();
1996#endif
1997 c = term_vgetc();
1998#ifdef FEAT_CMDL_INFO
1999 clear_showcmd();
2000#endif
2001 if (!term_use_loop())
2002 /* job finished while waiting for a character */
2003 return;
2004
2005 /* CTRL-W "= prompt for expression to evaluate. */
2006 if (c == '=' && get_expr_register() != '=')
2007 return;
2008 if (!term_use_loop())
2009 /* job finished while waiting for a character */
2010 return;
2011
2012 l = (list_T *)get_reg_contents(c, GREG_LIST);
2013 if (l != NULL)
2014 {
2015 type = get_reg_type(c, &reglen);
2016 for (item = l->lv_first; item != NULL; item = item->li_next)
2017 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002018 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002019#ifdef WIN3264
2020 char_u *tmp = s;
2021
2022 if (!enc_utf8 && enc_codepage > 0)
2023 {
2024 WCHAR *ret = NULL;
2025 int length = 0;
2026
2027 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2028 (int)STRLEN(s), &ret, &length);
2029 if (ret != NULL)
2030 {
2031 WideCharToMultiByte_alloc(CP_UTF8, 0,
2032 ret, length, (char **)&s, &length, 0, 0);
2033 vim_free(ret);
2034 }
2035 }
2036#endif
2037 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2038 s, (int)STRLEN(s), NULL);
2039#ifdef WIN3264
2040 if (tmp != s)
2041 vim_free(s);
2042#endif
2043
2044 if (item->li_next != NULL || type == MLINE)
2045 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2046 (char_u *)"\r", 1, NULL);
2047 }
2048 list_free(l);
2049 }
2050}
2051
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002052/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002053 * Return TRUE when waiting for a character in the terminal, the cursor of the
2054 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002055 */
2056 int
2057terminal_is_active()
2058{
2059 return in_terminal_loop != NULL;
2060}
2061
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002062#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002063 cursorentry_T *
2064term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2065{
2066 term_T *term = in_terminal_loop;
2067 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002068 int id;
2069 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002070
2071 vim_memset(&entry, 0, sizeof(entry));
2072 entry.shape = entry.mshape =
2073 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2074 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2075 SHAPE_BLOCK;
2076 entry.percentage = 20;
2077 if (term->tl_cursor_blink)
2078 {
2079 entry.blinkwait = 700;
2080 entry.blinkon = 400;
2081 entry.blinkoff = 250;
2082 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002083
2084 /* The "Terminal" highlight group overrules the defaults. */
2085 id = syn_name2id((char_u *)"Terminal");
2086 if (id != 0)
2087 {
2088 syn_id2colors(id, &term_fg, &term_bg);
2089 *fg = term_bg;
2090 }
2091 else
2092 *fg = gui.back_pixel;
2093
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002094 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002095 {
2096 if (id != 0)
2097 *bg = term_fg;
2098 else
2099 *bg = gui.norm_pixel;
2100 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002101 else
2102 *bg = color_name2handle(term->tl_cursor_color);
2103 entry.name = "n";
2104 entry.used_for = SHAPE_CURSOR;
2105
2106 return &entry;
2107}
2108#endif
2109
Bram Moolenaard317b382018-02-08 22:33:31 +01002110 static void
2111may_output_cursor_props(void)
2112{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002113 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002114 || last_set_cursor_shape != desired_cursor_shape
2115 || last_set_cursor_blink != desired_cursor_blink)
2116 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002117 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002118 last_set_cursor_shape = desired_cursor_shape;
2119 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002120 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002121 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2122 /* this will restore the initial cursor style, if possible */
2123 ui_cursor_shape_forced(TRUE);
2124 else
2125 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2126 }
2127}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002128
Bram Moolenaard317b382018-02-08 22:33:31 +01002129/*
2130 * Set the cursor color and shape, if not last set to these.
2131 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002132 static void
2133may_set_cursor_props(term_T *term)
2134{
2135#ifdef FEAT_GUI
2136 /* For the GUI the cursor properties are obtained with
2137 * term_get_cursor_shape(). */
2138 if (gui.in_use)
2139 return;
2140#endif
2141 if (in_terminal_loop == term)
2142 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002143 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002144 desired_cursor_shape = term->tl_cursor_shape;
2145 desired_cursor_blink = term->tl_cursor_blink;
2146 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002147 }
2148}
2149
Bram Moolenaard317b382018-02-08 22:33:31 +01002150/*
2151 * Reset the desired cursor properties and restore them when needed.
2152 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002153 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002154prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002155{
2156#ifdef FEAT_GUI
2157 if (gui.in_use)
2158 return;
2159#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002160 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002161 desired_cursor_shape = -1;
2162 desired_cursor_blink = -1;
2163 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002164}
2165
2166/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002167 * Returns TRUE if the current window contains a terminal and we are sending
2168 * keys to the job.
2169 * If "check_job_status" is TRUE update the job status.
2170 */
2171 static int
2172term_use_loop_check(int check_job_status)
2173{
2174 term_T *term = curbuf->b_term;
2175
2176 return term != NULL
2177 && !term->tl_normal_mode
2178 && term->tl_vterm != NULL
2179 && term_job_running_check(term, check_job_status);
2180}
2181
2182/*
2183 * Returns TRUE if the current window contains a terminal and we are sending
2184 * keys to the job.
2185 */
2186 int
2187term_use_loop(void)
2188{
2189 return term_use_loop_check(FALSE);
2190}
2191
2192/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002193 * Called when entering a window with the mouse. If this is a terminal window
2194 * we may want to change state.
2195 */
2196 void
2197term_win_entered()
2198{
2199 term_T *term = curbuf->b_term;
2200
2201 if (term != NULL)
2202 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002203 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002204 {
2205 reset_VIsual_and_resel();
2206 if (State & INSERT)
2207 stop_insert_mode = TRUE;
2208 }
2209 mouse_was_outside = FALSE;
2210 enter_mouse_col = mouse_col;
2211 enter_mouse_row = mouse_row;
2212 }
2213}
2214
2215/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002216 * Wait for input and send it to the job.
2217 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2218 * when there is no more typahead.
2219 * Return when the start of a CTRL-W command is typed or anything else that
2220 * should be handled as a Normal mode command.
2221 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2222 * the terminal was closed.
2223 */
2224 int
2225terminal_loop(int blocking)
2226{
2227 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002228 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002229 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002230#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002231 int tty_fd = curbuf->b_term->tl_job->jv_channel
2232 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002233#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002234 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002235
2236 /* Remember the terminal we are sending keys to. However, the terminal
2237 * might be closed while waiting for a character, e.g. typing "exit" in a
2238 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2239 * stored reference. */
2240 in_terminal_loop = curbuf->b_term;
2241
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002242 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002243 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002244 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002245 if (termwinkey == Ctrl_W)
2246 termwinkey = 0;
2247 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002248 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2249 may_set_cursor_props(curbuf->b_term);
2250
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002251 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002252 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002253#ifdef FEAT_GUI
2254 if (!curbuf->b_term->tl_system)
2255#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002256 // TODO: skip screen update when handling a sequence of keys.
2257 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002258 while (must_redraw != 0)
2259 if (update_screen(0) == FAIL)
2260 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002261 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002262 /* job finished while redrawing */
2263 break;
2264
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002265 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002266 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002267
2268 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002269 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002270 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002271 /* Job finished while waiting for a character. Push back the
2272 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002273 if (c != K_IGNORE)
2274 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002275 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002276 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002277 if (c == K_IGNORE)
2278 continue;
2279
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002280#ifdef UNIX
2281 /*
2282 * The shell or another program may change the tty settings. Getting
2283 * them for every typed character is a bit of overhead, but it's needed
2284 * for the first character typed, e.g. when Vim starts in a shell.
2285 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002286 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002287 {
2288 ttyinfo_T info;
2289
2290 /* Get the current backspace character of the pty. */
2291 if (get_tty_info(tty_fd, &info) == OK)
2292 term_backspace_char = info.backspace;
2293 }
2294#endif
2295
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002296#ifdef WIN3264
2297 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2298 * Use CTRL-BREAK to kill the job. */
2299 if (ctrl_break_was_pressed)
2300 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2301#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002302 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002303 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002304 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002305#ifdef FEAT_GUI
2306 && !curbuf->b_term->tl_system
2307#endif
2308 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002309 {
2310 int prev_c = c;
2311
2312#ifdef FEAT_CMDL_INFO
2313 if (add_to_showcmd(c))
2314 out_flush();
2315#endif
2316 c = term_vgetc();
2317#ifdef FEAT_CMDL_INFO
2318 clear_showcmd();
2319#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002320 if (!term_use_loop_check(TRUE)
2321 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002322 /* job finished while waiting for a character */
2323 break;
2324
2325 if (prev_c == Ctrl_BSL)
2326 {
2327 if (c == Ctrl_N)
2328 {
2329 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2330 term_enter_normal_mode();
2331 ret = FAIL;
2332 goto theend;
2333 }
2334 /* Send both keys to the terminal. */
2335 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2336 }
2337 else if (c == Ctrl_C)
2338 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002339 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002340 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2341 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002342 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002343 {
2344 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002345 /* "'termwinkey' .": send 'termwinkey' to the job */
2346 c = termwinkey == 0 ? Ctrl_W : termwinkey;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002347 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002348 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002349 {
2350 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2351 c = Ctrl_BSL;
2352 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002353 else if (c == 'N')
2354 {
2355 /* CTRL-W N : go to Terminal-Normal mode. */
2356 term_enter_normal_mode();
2357 ret = FAIL;
2358 goto theend;
2359 }
2360 else if (c == '"')
2361 {
2362 term_paste_register(prev_c);
2363 continue;
2364 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002365 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002366 {
2367 stuffcharReadbuff(Ctrl_W);
2368 stuffcharReadbuff(c);
2369 ret = OK;
2370 goto theend;
2371 }
2372 }
2373# ifdef WIN3264
2374 if (!enc_utf8 && has_mbyte && c >= 0x80)
2375 {
2376 WCHAR wc;
2377 char_u mb[3];
2378
2379 mb[0] = (unsigned)c >> 8;
2380 mb[1] = c;
2381 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2382 c = wc;
2383 }
2384# endif
2385 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2386 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002387 if (c == K_MOUSEMOVE)
2388 /* We are sure to come back here, don't reset the cursor color
2389 * and shape to avoid flickering. */
2390 restore_cursor = FALSE;
2391
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002392 ret = OK;
2393 goto theend;
2394 }
2395 }
2396 ret = FAIL;
2397
2398theend:
2399 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002400 if (restore_cursor)
2401 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002402
2403 /* Move a snapshot of the screen contents to the buffer, so that completion
2404 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002405 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2406 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002407
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002408 return ret;
2409}
2410
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002411 static void
2412may_toggle_cursor(term_T *term)
2413{
2414 if (in_terminal_loop == term)
2415 {
2416 if (term->tl_cursor_visible)
2417 cursor_on();
2418 else
2419 cursor_off();
2420 }
2421}
2422
2423/*
2424 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002425 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002426 */
2427 static int
2428color2index(VTermColor *color, int fg, int *boldp)
2429{
2430 int red = color->red;
2431 int blue = color->blue;
2432 int green = color->green;
2433
Bram Moolenaar46359e12017-11-29 22:33:38 +01002434 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002435 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002436 /* First 16 colors and default: use the ANSI index, because these
2437 * colors can be redefined. */
2438 if (t_colors >= 16)
2439 return color->ansi_index;
2440 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002441 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002442 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002443 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002444 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2445 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2446 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002447 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002448 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2449 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2450 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2451 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2452 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2453 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2454 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2455 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2456 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2457 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2458 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002459 }
2460 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002461
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002462 if (t_colors >= 256)
2463 {
2464 if (red == blue && red == green)
2465 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002466 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002467 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002468 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2469 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2470 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002471 int i;
2472
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002473 if (red < 5)
2474 return 17; /* 00/00/00 */
2475 if (red > 245) /* ff/ff/ff */
2476 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002477 for (i = 0; i < 23; ++i)
2478 if (red < cutoff[i])
2479 return i + 233;
2480 return 256;
2481 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002482 {
2483 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2484 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002485
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002486 /* 216-color cube */
2487 for (ri = 0; ri < 5; ++ri)
2488 if (red < cutoff[ri])
2489 break;
2490 for (gi = 0; gi < 5; ++gi)
2491 if (green < cutoff[gi])
2492 break;
2493 for (bi = 0; bi < 5; ++bi)
2494 if (blue < cutoff[bi])
2495 break;
2496 return 17 + ri * 36 + gi * 6 + bi;
2497 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002498 }
2499 return 0;
2500}
2501
2502/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002503 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002504 */
2505 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002506vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002507{
2508 int attr = 0;
2509
2510 if (cellattrs.bold)
2511 attr |= HL_BOLD;
2512 if (cellattrs.underline)
2513 attr |= HL_UNDERLINE;
2514 if (cellattrs.italic)
2515 attr |= HL_ITALIC;
2516 if (cellattrs.strike)
2517 attr |= HL_STRIKETHROUGH;
2518 if (cellattrs.reverse)
2519 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002520 return attr;
2521}
2522
2523/*
2524 * Store Vterm attributes in "cell" from highlight flags.
2525 */
2526 static void
2527hl2vtermAttr(int attr, cellattr_T *cell)
2528{
2529 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2530 if (attr & HL_BOLD)
2531 cell->attrs.bold = 1;
2532 if (attr & HL_UNDERLINE)
2533 cell->attrs.underline = 1;
2534 if (attr & HL_ITALIC)
2535 cell->attrs.italic = 1;
2536 if (attr & HL_STRIKETHROUGH)
2537 cell->attrs.strike = 1;
2538 if (attr & HL_INVERSE)
2539 cell->attrs.reverse = 1;
2540}
2541
2542/*
2543 * Convert the attributes of a vterm cell into an attribute index.
2544 */
2545 static int
2546cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2547{
2548 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002549
2550#ifdef FEAT_GUI
2551 if (gui.in_use)
2552 {
2553 guicolor_T fg, bg;
2554
2555 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2556 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2557 return get_gui_attr_idx(attr, fg, bg);
2558 }
2559 else
2560#endif
2561#ifdef FEAT_TERMGUICOLORS
2562 if (p_tgc)
2563 {
2564 guicolor_T fg, bg;
2565
2566 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2567 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2568
2569 return get_tgc_attr_idx(attr, fg, bg);
2570 }
2571 else
2572#endif
2573 {
2574 int bold = MAYBE;
2575 int fg = color2index(&cellfg, TRUE, &bold);
2576 int bg = color2index(&cellbg, FALSE, &bold);
2577
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002578 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002579 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002580 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002581 if (fg == 0 && term_default_cterm_fg >= 0)
2582 fg = term_default_cterm_fg + 1;
2583 if (bg == 0 && term_default_cterm_bg >= 0)
2584 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002585 }
2586
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002587 /* with 8 colors set the bold attribute to get a bright foreground */
2588 if (bold == TRUE)
2589 attr |= HL_BOLD;
2590 return get_cterm_attr_idx(attr, fg, bg);
2591 }
2592 return 0;
2593}
2594
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002595 static void
2596set_dirty_snapshot(term_T *term)
2597{
2598 term->tl_dirty_snapshot = TRUE;
2599#ifdef FEAT_TIMERS
2600 if (!term->tl_normal_mode)
2601 {
2602 /* Update the snapshot after 100 msec of not getting updates. */
2603 profile_setlimit(100L, &term->tl_timer_due);
2604 term->tl_timer_set = TRUE;
2605 }
2606#endif
2607}
2608
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002609 static int
2610handle_damage(VTermRect rect, void *user)
2611{
2612 term_T *term = (term_T *)user;
2613
2614 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2615 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002616 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002617 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002618 return 1;
2619}
2620
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002621 static void
2622term_scroll_up(term_T *term, int start_row, int count)
2623{
2624 win_T *wp;
2625 VTermColor fg, bg;
2626 VTermScreenCellAttrs attr;
2627 int clear_attr;
2628
2629 /* Set the color to clear lines with. */
2630 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2631 &fg, &bg);
2632 vim_memset(&attr, 0, sizeof(attr));
2633 clear_attr = cell2attr(attr, fg, bg);
2634
2635 FOR_ALL_WINDOWS(wp)
2636 {
2637 if (wp->w_buffer == term->tl_buffer)
2638 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2639 }
2640}
2641
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002642 static int
2643handle_moverect(VTermRect dest, VTermRect src, void *user)
2644{
2645 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002646 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002647
2648 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002649 * redrawing the text. But avoid doing this multiple times, postpone until
2650 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002651 if (dest.start_col == src.start_col
2652 && dest.end_col == src.end_col
2653 && dest.start_row < src.start_row)
2654 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002655 if (dest.start_row == 0)
2656 term->tl_postponed_scroll += count;
2657 else
2658 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002659 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002660
2661 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2662 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002663 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002664
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002665 /* Note sure if the scrolling will work correctly, let's do a complete
2666 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002667 redraw_buf_later(term->tl_buffer, NOT_VALID);
2668 return 1;
2669}
2670
2671 static int
2672handle_movecursor(
2673 VTermPos pos,
2674 VTermPos oldpos UNUSED,
2675 int visible,
2676 void *user)
2677{
2678 term_T *term = (term_T *)user;
2679 win_T *wp;
2680
2681 term->tl_cursor_pos = pos;
2682 term->tl_cursor_visible = visible;
2683
2684 FOR_ALL_WINDOWS(wp)
2685 {
2686 if (wp->w_buffer == term->tl_buffer)
2687 position_cursor(wp, &pos);
2688 }
2689 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2690 {
2691 may_toggle_cursor(term);
2692 update_cursor(term, term->tl_cursor_visible);
2693 }
2694
2695 return 1;
2696}
2697
2698 static int
2699handle_settermprop(
2700 VTermProp prop,
2701 VTermValue *value,
2702 void *user)
2703{
2704 term_T *term = (term_T *)user;
2705
2706 switch (prop)
2707 {
2708 case VTERM_PROP_TITLE:
2709 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002710 // a blank title isn't useful, make it empty, so that "running" is
2711 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002712 if (*skipwhite((char_u *)value->string) == NUL)
2713 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002714 // Same as blank
2715 else if (term->tl_arg0_cmd != NULL
2716 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2717 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2718 term->tl_title = NULL;
2719 // Empty corrupted data of winpty
2720 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2721 term->tl_title = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002722#ifdef WIN3264
2723 else if (!enc_utf8 && enc_codepage > 0)
2724 {
2725 WCHAR *ret = NULL;
2726 int length = 0;
2727
2728 MultiByteToWideChar_alloc(CP_UTF8, 0,
2729 (char*)value->string, (int)STRLEN(value->string),
2730 &ret, &length);
2731 if (ret != NULL)
2732 {
2733 WideCharToMultiByte_alloc(enc_codepage, 0,
2734 ret, length, (char**)&term->tl_title,
2735 &length, 0, 0);
2736 vim_free(ret);
2737 }
2738 }
2739#endif
2740 else
2741 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002742 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002743 if (term == curbuf->b_term)
2744 maketitle();
2745 break;
2746
2747 case VTERM_PROP_CURSORVISIBLE:
2748 term->tl_cursor_visible = value->boolean;
2749 may_toggle_cursor(term);
2750 out_flush();
2751 break;
2752
2753 case VTERM_PROP_CURSORBLINK:
2754 term->tl_cursor_blink = value->boolean;
2755 may_set_cursor_props(term);
2756 break;
2757
2758 case VTERM_PROP_CURSORSHAPE:
2759 term->tl_cursor_shape = value->number;
2760 may_set_cursor_props(term);
2761 break;
2762
2763 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002764 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002765 may_set_cursor_props(term);
2766 break;
2767
2768 case VTERM_PROP_ALTSCREEN:
2769 /* TODO: do anything else? */
2770 term->tl_using_altscreen = value->boolean;
2771 break;
2772
2773 default:
2774 break;
2775 }
2776 /* Always return 1, otherwise vterm doesn't store the value internally. */
2777 return 1;
2778}
2779
2780/*
2781 * The job running in the terminal resized the terminal.
2782 */
2783 static int
2784handle_resize(int rows, int cols, void *user)
2785{
2786 term_T *term = (term_T *)user;
2787 win_T *wp;
2788
2789 term->tl_rows = rows;
2790 term->tl_cols = cols;
2791 if (term->tl_vterm_size_changed)
2792 /* Size was set by vterm_set_size(), don't set the window size. */
2793 term->tl_vterm_size_changed = FALSE;
2794 else
2795 {
2796 FOR_ALL_WINDOWS(wp)
2797 {
2798 if (wp->w_buffer == term->tl_buffer)
2799 {
2800 win_setheight_win(rows, wp);
2801 win_setwidth_win(cols, wp);
2802 }
2803 }
2804 redraw_buf_later(term->tl_buffer, NOT_VALID);
2805 }
2806 return 1;
2807}
2808
2809/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002810 * If the number of lines that are stored goes over 'termscrollback' then
2811 * delete the first 10%.
2812 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2813 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002814 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002815 static void
2816limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002817{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002818 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002819 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002820 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002821 int i;
2822
2823 curbuf = term->tl_buffer;
2824 for (i = 0; i < todo; ++i)
2825 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002826 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
2827 if (update_buffer)
2828 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002829 }
2830 curbuf = curwin->w_buffer;
2831
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002832 gap->ga_len -= todo;
2833 mch_memmove(gap->ga_data,
2834 (sb_line_T *)gap->ga_data + todo,
2835 sizeof(sb_line_T) * gap->ga_len);
2836 if (update_buffer)
2837 term->tl_scrollback_scrolled -= todo;
2838 }
2839}
2840
2841/*
2842 * Handle a line that is pushed off the top of the screen.
2843 */
2844 static int
2845handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2846{
2847 term_T *term = (term_T *)user;
2848 garray_T *gap;
2849 int update_buffer;
2850
2851 if (term->tl_normal_mode)
2852 {
2853 // In Terminal-Normal mode the user interacts with the buffer, thus we
2854 // must not change it. Postpone adding the scrollback lines.
2855 gap = &term->tl_scrollback_postponed;
2856 update_buffer = FALSE;
2857ch_log(NULL, "handle_pushline(): add to postponed");
2858 }
2859 else
2860 {
2861 // First remove the lines that were appended before, the pushed line
2862 // goes above it.
2863 cleanup_scrollback(term);
2864 gap = &term->tl_scrollback;
2865 update_buffer = TRUE;
2866ch_log(NULL, "handle_pushline(): add to window");
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002867 }
2868
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002869 limit_scrollback(term, gap, update_buffer);
2870
2871 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002872 {
2873 cellattr_T *p = NULL;
2874 int len = 0;
2875 int i;
2876 int c;
2877 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002878 int text_len;
2879 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880 sb_line_T *line;
2881 garray_T ga;
2882 cellattr_T fill_attr = term->tl_default_color;
2883
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002884 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002885 for (i = 0; i < cols; ++i)
2886 if (cells[i].chars[0] != 0)
2887 len = i + 1;
2888 else
2889 cell2cellattr(&cells[i], &fill_attr);
2890
2891 ga_init2(&ga, 1, 100);
2892 if (len > 0)
2893 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2894 if (p != NULL)
2895 {
2896 for (col = 0; col < len; col += cells[col].width)
2897 {
2898 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2899 {
2900 ga.ga_len = 0;
2901 break;
2902 }
2903 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2904 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2905 (char_u *)ga.ga_data + ga.ga_len);
2906 cell2cellattr(&cells[col], &p[col]);
2907 }
2908 }
2909 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002910 {
2911 if (update_buffer)
2912 text = (char_u *)"";
2913 else
2914 text = vim_strsave((char_u *)"");
2915 text_len = 0;
2916 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002917 else
2918 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002919 text = ga.ga_data;
2920 text_len = ga.ga_len;
2921 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002923 if (update_buffer)
2924 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002926 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002927 line->sb_cols = len;
2928 line->sb_cells = p;
2929 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002930 if (update_buffer)
2931 {
2932 line->sb_text = NULL;
2933 ++term->tl_scrollback_scrolled;
2934 ga_clear(&ga); // free the text
2935 }
2936 else
2937 {
2938 line->sb_text = text;
2939 ga_init(&ga); // text is kept in tl_scrollback_postponed
2940 }
2941 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002942 }
2943 return 0; /* ignored */
2944}
2945
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002946/*
2947 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
2948 * received and stored in tl_scrollback_postponed.
2949 */
2950 static void
2951handle_postponed_scrollback(term_T *term)
2952{
2953 int i;
2954
2955ch_log(NULL, "Moving postponed scrollback to scrollback");
2956 // First remove the lines that were appended before, the pushed lines go
2957 // above it.
2958 cleanup_scrollback(term);
2959
2960 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
2961 {
2962 char_u *text;
2963 sb_line_T *pp_line;
2964 sb_line_T *line;
2965
2966 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
2967 break;
2968 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
2969
2970 text = pp_line->sb_text;
2971 if (text == NULL)
2972 text = (char_u *)"";
2973 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
2974 vim_free(pp_line->sb_text);
2975
2976 line = (sb_line_T *)term->tl_scrollback.ga_data
2977 + term->tl_scrollback.ga_len;
2978 line->sb_cols = pp_line->sb_cols;
2979 line->sb_cells = pp_line->sb_cells;
2980 line->sb_fill_attr = pp_line->sb_fill_attr;
2981 line->sb_text = NULL;
2982 ++term->tl_scrollback_scrolled;
2983 ++term->tl_scrollback.ga_len;
2984 }
2985
2986 ga_clear(&term->tl_scrollback_postponed);
2987 limit_scrollback(term, &term->tl_scrollback, TRUE);
2988}
2989
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002990static VTermScreenCallbacks screen_callbacks = {
2991 handle_damage, /* damage */
2992 handle_moverect, /* moverect */
2993 handle_movecursor, /* movecursor */
2994 handle_settermprop, /* settermprop */
2995 NULL, /* bell */
2996 handle_resize, /* resize */
2997 handle_pushline, /* sb_pushline */
2998 NULL /* sb_popline */
2999};
3000
3001/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003002 * Do the work after the channel of a terminal was closed.
3003 * Must be called only when updating_screen is FALSE.
3004 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3005 */
3006 static int
3007term_after_channel_closed(term_T *term)
3008{
3009 /* Unless in Terminal-Normal mode: clear the vterm. */
3010 if (!term->tl_normal_mode)
3011 {
3012 int fnum = term->tl_buffer->b_fnum;
3013
3014 cleanup_vterm(term);
3015
3016 if (term->tl_finish == TL_FINISH_CLOSE)
3017 {
3018 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003019 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003020
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003021 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003022 ch_log(NULL, "terminal job finished, closing window");
3023 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003024 // Avoid closing the window if we temporarily use it.
3025 if (do_set_w_closing)
3026 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003027 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003028 if (do_set_w_closing)
3029 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003030 aucmd_restbuf(&aco);
3031 return TRUE;
3032 }
3033 if (term->tl_finish == TL_FINISH_OPEN
3034 && term->tl_buffer->b_nwindows == 0)
3035 {
3036 char buf[50];
3037
3038 /* TODO: use term_opencmd */
3039 ch_log(NULL, "terminal job finished, opening window");
3040 vim_snprintf(buf, sizeof(buf),
3041 term->tl_opencmd == NULL
3042 ? "botright sbuf %d"
3043 : (char *)term->tl_opencmd, fnum);
3044 do_cmdline_cmd((char_u *)buf);
3045 }
3046 else
3047 ch_log(NULL, "terminal job finished");
3048 }
3049
3050 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3051 return FALSE;
3052}
3053
3054/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003055 * Called when a channel has been closed.
3056 * If this was a channel for a terminal window then finish it up.
3057 */
3058 void
3059term_channel_closed(channel_T *ch)
3060{
3061 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003062 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003063 int did_one = FALSE;
3064
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003065 for (term = first_term; term != NULL; term = next_term)
3066 {
3067 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003068 if (term->tl_job == ch->ch_job)
3069 {
3070 term->tl_channel_closed = TRUE;
3071 did_one = TRUE;
3072
Bram Moolenaard23a8232018-02-10 18:45:26 +01003073 VIM_CLEAR(term->tl_title);
3074 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02003075#ifdef WIN3264
3076 if (term->tl_out_fd != NULL)
3077 {
3078 fclose(term->tl_out_fd);
3079 term->tl_out_fd = NULL;
3080 }
3081#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003082
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003083 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003084 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003085 /* Cannot open or close windows now. Can happen when
3086 * 'lazyredraw' is set. */
3087 term->tl_channel_recently_closed = TRUE;
3088 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003089 }
3090
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003091 if (term_after_channel_closed(term))
3092 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003093 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003094 }
3095
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003096 if (did_one)
3097 {
3098 redraw_statuslines();
3099
3100 /* Need to break out of vgetc(). */
3101 ins_char_typebuf(K_IGNORE);
3102 typebuf_was_filled = TRUE;
3103
3104 term = curbuf->b_term;
3105 if (term != NULL)
3106 {
3107 if (term->tl_job == ch->ch_job)
3108 maketitle();
3109 update_cursor(term, term->tl_cursor_visible);
3110 }
3111 }
3112}
3113
3114/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003115 * To be called after resetting updating_screen: handle any terminal where the
3116 * channel was closed.
3117 */
3118 void
3119term_check_channel_closed_recently()
3120{
3121 term_T *term;
3122 term_T *next_term;
3123
3124 for (term = first_term; term != NULL; term = next_term)
3125 {
3126 next_term = term->tl_next;
3127 if (term->tl_channel_recently_closed)
3128 {
3129 term->tl_channel_recently_closed = FALSE;
3130 if (term_after_channel_closed(term))
3131 // start over, the list may have changed
3132 next_term = first_term;
3133 }
3134 }
3135}
3136
3137/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003138 * Fill one screen line from a line of the terminal.
3139 * Advances "pos" to past the last column.
3140 */
3141 static void
3142term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3143{
3144 int off = screen_get_current_line_off();
3145
3146 for (pos->col = 0; pos->col < max_col; )
3147 {
3148 VTermScreenCell cell;
3149 int c;
3150
3151 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3152 vim_memset(&cell, 0, sizeof(cell));
3153
3154 c = cell.chars[0];
3155 if (c == NUL)
3156 {
3157 ScreenLines[off] = ' ';
3158 if (enc_utf8)
3159 ScreenLinesUC[off] = NUL;
3160 }
3161 else
3162 {
3163 if (enc_utf8)
3164 {
3165 int i;
3166
3167 /* composing chars */
3168 for (i = 0; i < Screen_mco
3169 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3170 {
3171 ScreenLinesC[i][off] = cell.chars[i + 1];
3172 if (cell.chars[i + 1] == 0)
3173 break;
3174 }
3175 if (c >= 0x80 || (Screen_mco > 0
3176 && ScreenLinesC[0][off] != 0))
3177 {
3178 ScreenLines[off] = ' ';
3179 ScreenLinesUC[off] = c;
3180 }
3181 else
3182 {
3183 ScreenLines[off] = c;
3184 ScreenLinesUC[off] = NUL;
3185 }
3186 }
3187#ifdef WIN3264
3188 else if (has_mbyte && c >= 0x80)
3189 {
3190 char_u mb[MB_MAXBYTES+1];
3191 WCHAR wc = c;
3192
3193 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3194 (char*)mb, 2, 0, 0) > 1)
3195 {
3196 ScreenLines[off] = mb[0];
3197 ScreenLines[off + 1] = mb[1];
3198 cell.width = mb_ptr2cells(mb);
3199 }
3200 else
3201 ScreenLines[off] = c;
3202 }
3203#endif
3204 else
3205 ScreenLines[off] = c;
3206 }
3207 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3208
3209 ++pos->col;
3210 ++off;
3211 if (cell.width == 2)
3212 {
3213 if (enc_utf8)
3214 ScreenLinesUC[off] = NUL;
3215
3216 /* don't set the second byte to NUL for a DBCS encoding, it
3217 * has been set above */
3218 if (enc_utf8 || !has_mbyte)
3219 ScreenLines[off] = NUL;
3220
3221 ++pos->col;
3222 ++off;
3223 }
3224 }
3225}
3226
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003227#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003228 static void
3229update_system_term(term_T *term)
3230{
3231 VTermPos pos;
3232 VTermScreen *screen;
3233
3234 if (term->tl_vterm == NULL)
3235 return;
3236 screen = vterm_obtain_screen(term->tl_vterm);
3237
3238 /* Scroll up to make more room for terminal lines if needed. */
3239 while (term->tl_toprow > 0
3240 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3241 {
3242 int save_p_more = p_more;
3243
3244 p_more = FALSE;
3245 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003246 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003247 p_more = save_p_more;
3248 --term->tl_toprow;
3249 }
3250
3251 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3252 && pos.row < Rows; ++pos.row)
3253 {
3254 if (pos.row < term->tl_rows)
3255 {
3256 int max_col = MIN(Columns, term->tl_cols);
3257
3258 term_line2screenline(screen, &pos, max_col);
3259 }
3260 else
3261 pos.col = 0;
3262
3263 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
3264 }
3265
3266 term->tl_dirty_row_start = MAX_ROW;
3267 term->tl_dirty_row_end = 0;
3268 update_cursor(term, TRUE);
3269}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003270#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003271
3272/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003273 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3274 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003275 * Terminal-Normal mode.
3276 */
3277 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003278term_do_update_window(win_T *wp)
3279{
3280 term_T *term = wp->w_buffer->b_term;
3281
3282 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3283}
3284
3285/*
3286 * Called to update a window that contains an active terminal.
3287 */
3288 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003289term_update_window(win_T *wp)
3290{
3291 term_T *term = wp->w_buffer->b_term;
3292 VTerm *vterm;
3293 VTermScreen *screen;
3294 VTermState *state;
3295 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003296 int rows, cols;
3297 int newrows, newcols;
3298 int minsize;
3299 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003300
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003301 vterm = term->tl_vterm;
3302 screen = vterm_obtain_screen(vterm);
3303 state = vterm_obtain_state(vterm);
3304
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003305 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3306 * SOME_VALID only redraw what was marked dirty. */
3307 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003308 {
3309 term->tl_dirty_row_start = 0;
3310 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003311
3312 if (term->tl_postponed_scroll > 0
3313 && term->tl_postponed_scroll < term->tl_rows / 3)
3314 /* Scrolling is usually faster than redrawing, when there are only
3315 * a few lines to scroll. */
3316 term_scroll_up(term, 0, term->tl_postponed_scroll);
3317 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003318 }
3319
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003320 /*
3321 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003322 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003323 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003324 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003325
Bram Moolenaar498c2562018-04-15 23:45:15 +02003326 newrows = 99999;
3327 newcols = 99999;
3328 FOR_ALL_WINDOWS(twp)
3329 {
3330 /* When more than one window shows the same terminal, use the
3331 * smallest size. */
3332 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003333 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003334 newrows = MIN(newrows, twp->w_height);
3335 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003336 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003337 }
3338 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3339 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3340
3341 if (term->tl_rows != newrows || term->tl_cols != newcols)
3342 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003343 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003344 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003345 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003346 newrows);
3347 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003348
3349 // Updating the terminal size will cause the snapshot to be cleared.
3350 // When not in terminal_loop() we need to restore it.
3351 if (term != in_terminal_loop)
3352 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003353 }
3354
3355 /* The cursor may have been moved when resizing. */
3356 vterm_state_get_cursorpos(state, &pos);
3357 position_cursor(wp, &pos);
3358
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003359 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3360 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003361 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003362 if (pos.row < term->tl_rows)
3363 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003364 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003365
Bram Moolenaar13568252018-03-16 20:46:58 +01003366 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003367 }
3368 else
3369 pos.col = 0;
3370
Bram Moolenaarf118d482018-03-13 13:14:00 +01003371 screen_line(wp->w_winrow + pos.row
3372#ifdef FEAT_MENU
3373 + winbar_height(wp)
3374#endif
3375 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003376 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003377 term->tl_dirty_row_start = MAX_ROW;
3378 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003379}
3380
3381/*
3382 * Return TRUE if "wp" is a terminal window where the job has finished.
3383 */
3384 int
3385term_is_finished(buf_T *buf)
3386{
3387 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3388}
3389
3390/*
3391 * Return TRUE if "wp" is a terminal window where the job has finished or we
3392 * are in Terminal-Normal mode, thus we show the buffer contents.
3393 */
3394 int
3395term_show_buffer(buf_T *buf)
3396{
3397 term_T *term = buf->b_term;
3398
3399 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3400}
3401
3402/*
3403 * The current buffer is going to be changed. If there is terminal
3404 * highlighting remove it now.
3405 */
3406 void
3407term_change_in_curbuf(void)
3408{
3409 term_T *term = curbuf->b_term;
3410
3411 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3412 {
3413 free_scrollback(term);
3414 redraw_buf_later(term->tl_buffer, NOT_VALID);
3415
3416 /* The buffer is now like a normal buffer, it cannot be easily
3417 * abandoned when changed. */
3418 set_string_option_direct((char_u *)"buftype", -1,
3419 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3420 }
3421}
3422
3423/*
3424 * Get the screen attribute for a position in the buffer.
3425 * Use a negative "col" to get the filler background color.
3426 */
3427 int
3428term_get_attr(buf_T *buf, linenr_T lnum, int col)
3429{
3430 term_T *term = buf->b_term;
3431 sb_line_T *line;
3432 cellattr_T *cellattr;
3433
3434 if (lnum > term->tl_scrollback.ga_len)
3435 cellattr = &term->tl_default_color;
3436 else
3437 {
3438 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3439 if (col < 0 || col >= line->sb_cols)
3440 cellattr = &line->sb_fill_attr;
3441 else
3442 cellattr = line->sb_cells + col;
3443 }
3444 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3445}
3446
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003447/*
3448 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003449 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003450 */
3451 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003452cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003453{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003454 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003455}
3456
3457/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003458 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003459 */
3460 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003461init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003462{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003463 VTermColor *fg, *bg;
3464 int fgval, bgval;
3465 int id;
3466
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003467 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3468 term->tl_default_color.width = 1;
3469 fg = &term->tl_default_color.fg;
3470 bg = &term->tl_default_color.bg;
3471
3472 /* Vterm uses a default black background. Set it to white when
3473 * 'background' is "light". */
3474 if (*p_bg == 'l')
3475 {
3476 fgval = 0;
3477 bgval = 255;
3478 }
3479 else
3480 {
3481 fgval = 255;
3482 bgval = 0;
3483 }
3484 fg->red = fg->green = fg->blue = fgval;
3485 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003486 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003487
3488 /* The "Terminal" highlight group overrules the defaults. */
3489 id = syn_name2id((char_u *)"Terminal");
3490
Bram Moolenaar46359e12017-11-29 22:33:38 +01003491 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003492#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3493 if (0
3494# ifdef FEAT_GUI
3495 || gui.in_use
3496# endif
3497# ifdef FEAT_TERMGUICOLORS
3498 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003499# ifdef FEAT_VTP
3500 /* Finally get INVALCOLOR on this execution path */
3501 || (!p_tgc && t_colors >= 256)
3502# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003503# endif
3504 )
3505 {
3506 guicolor_T fg_rgb = INVALCOLOR;
3507 guicolor_T bg_rgb = INVALCOLOR;
3508
3509 if (id != 0)
3510 syn_id2colors(id, &fg_rgb, &bg_rgb);
3511
3512# ifdef FEAT_GUI
3513 if (gui.in_use)
3514 {
3515 if (fg_rgb == INVALCOLOR)
3516 fg_rgb = gui.norm_pixel;
3517 if (bg_rgb == INVALCOLOR)
3518 bg_rgb = gui.back_pixel;
3519 }
3520# ifdef FEAT_TERMGUICOLORS
3521 else
3522# endif
3523# endif
3524# ifdef FEAT_TERMGUICOLORS
3525 {
3526 if (fg_rgb == INVALCOLOR)
3527 fg_rgb = cterm_normal_fg_gui_color;
3528 if (bg_rgb == INVALCOLOR)
3529 bg_rgb = cterm_normal_bg_gui_color;
3530 }
3531# endif
3532 if (fg_rgb != INVALCOLOR)
3533 {
3534 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3535
3536 fg->red = (unsigned)(rgb >> 16);
3537 fg->green = (unsigned)(rgb >> 8) & 255;
3538 fg->blue = (unsigned)rgb & 255;
3539 }
3540 if (bg_rgb != INVALCOLOR)
3541 {
3542 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3543
3544 bg->red = (unsigned)(rgb >> 16);
3545 bg->green = (unsigned)(rgb >> 8) & 255;
3546 bg->blue = (unsigned)rgb & 255;
3547 }
3548 }
3549 else
3550#endif
3551 if (id != 0 && t_colors >= 16)
3552 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003553 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003554 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003555 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003556 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003557 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003558 else
3559 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003560#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003561 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003562#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003563
3564 /* In an MS-Windows console we know the normal colors. */
3565 if (cterm_normal_fg_color > 0)
3566 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003567 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003568# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003569 tmp = fg->red;
3570 fg->red = fg->blue;
3571 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003572# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003573 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003574# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003575 else
3576 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003577# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003578
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003579 if (cterm_normal_bg_color > 0)
3580 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003581 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003582# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003583 tmp = bg->red;
3584 bg->red = bg->blue;
3585 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003586# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003587 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003588# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003589 else
3590 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003591# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003592 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003593}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003594
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003595#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3596/*
3597 * Set the 16 ANSI colors from array of RGB values
3598 */
3599 static void
3600set_vterm_palette(VTerm *vterm, long_u *rgb)
3601{
3602 int index = 0;
3603 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003604
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003605 for (; index < 16; index++)
3606 {
3607 VTermColor color;
3608 color.red = (unsigned)(rgb[index] >> 16);
3609 color.green = (unsigned)(rgb[index] >> 8) & 255;
3610 color.blue = (unsigned)rgb[index] & 255;
3611 vterm_state_set_palette_color(state, index, &color);
3612 }
3613}
3614
3615/*
3616 * Set the ANSI color palette from a list of colors
3617 */
3618 static int
3619set_ansi_colors_list(VTerm *vterm, list_T *list)
3620{
3621 int n = 0;
3622 long_u rgb[16];
3623 listitem_T *li = list->lv_first;
3624
3625 for (; li != NULL && n < 16; li = li->li_next, n++)
3626 {
3627 char_u *color_name;
3628 guicolor_T guicolor;
3629
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003630 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003631 if (color_name == NULL)
3632 return FAIL;
3633
3634 guicolor = GUI_GET_COLOR(color_name);
3635 if (guicolor == INVALCOLOR)
3636 return FAIL;
3637
3638 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3639 }
3640
3641 if (n != 16 || li != NULL)
3642 return FAIL;
3643
3644 set_vterm_palette(vterm, rgb);
3645
3646 return OK;
3647}
3648
3649/*
3650 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3651 */
3652 static void
3653init_vterm_ansi_colors(VTerm *vterm)
3654{
3655 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3656
3657 if (var != NULL
3658 && (var->di_tv.v_type != VAR_LIST
3659 || var->di_tv.vval.v_list == NULL
3660 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003661 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003662}
3663#endif
3664
Bram Moolenaar52acb112018-03-18 19:20:22 +01003665/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003666 * Handles a "drop" command from the job in the terminal.
3667 * "item" is the file name, "item->li_next" may have options.
3668 */
3669 static void
3670handle_drop_command(listitem_T *item)
3671{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003672 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003673 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003674 int bufnr;
3675 win_T *wp;
3676 tabpage_T *tp;
3677 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003678 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003679
3680 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3681 FOR_ALL_TAB_WINDOWS(tp, wp)
3682 {
3683 if (wp->w_buffer->b_fnum == bufnr)
3684 {
3685 /* buffer is in a window already, go there */
3686 goto_tabpage_win(tp, wp);
3687 return;
3688 }
3689 }
3690
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003691 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003692
3693 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3694 && opt_item->li_tv.vval.v_dict != NULL)
3695 {
3696 dict_T *dict = opt_item->li_tv.vval.v_dict;
3697 char_u *p;
3698
Bram Moolenaar8f667172018-12-14 15:38:31 +01003699 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003700 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003701 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003702 if (p != NULL)
3703 {
3704 if (check_ff_value(p) == FAIL)
3705 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3706 else
3707 ea.force_ff = *p;
3708 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003709 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003710 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003711 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003712 if (p != NULL)
3713 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003714 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003715 if (ea.cmd != NULL)
3716 {
3717 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3718 ea.force_enc = 11;
3719 tofree = ea.cmd;
3720 }
3721 }
3722
Bram Moolenaar8f667172018-12-14 15:38:31 +01003723 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003724 if (p != NULL)
3725 get_bad_opt(p, &ea);
3726
3727 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3728 ea.force_bin = FORCE_BIN;
3729 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3730 ea.force_bin = FORCE_BIN;
3731 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3732 ea.force_bin = FORCE_NOBIN;
3733 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3734 ea.force_bin = FORCE_NOBIN;
3735 }
3736
3737 /* open in new window, like ":split fname" */
3738 if (ea.cmd == NULL)
3739 ea.cmd = (char_u *)"split";
3740 ea.arg = fname;
3741 ea.cmdidx = CMD_split;
3742 ex_splitview(&ea);
3743
3744 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003745}
3746
3747/*
3748 * Handles a function call from the job running in a terminal.
3749 * "item" is the function name, "item->li_next" has the arguments.
3750 */
3751 static void
3752handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3753{
3754 char_u *func;
3755 typval_T argvars[2];
3756 typval_T rettv;
3757 int doesrange;
3758
3759 if (item->li_next == NULL)
3760 {
3761 ch_log(channel, "Missing function arguments for call");
3762 return;
3763 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003764 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003765
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003766 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003767 {
3768 ch_log(channel, "Invalid function name: %s", func);
3769 return;
3770 }
3771
3772 argvars[0].v_type = VAR_NUMBER;
3773 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3774 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003775 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003776 2, argvars, /* argv_func */ NULL,
3777 /* firstline */ 1, /* lastline */ 1,
3778 &doesrange, /* evaluate */ TRUE,
3779 /* partial */ NULL, /* selfdict */ NULL) == OK)
3780 {
3781 clear_tv(&rettv);
3782 ch_log(channel, "Function %s called", func);
3783 }
3784 else
3785 ch_log(channel, "Calling function %s failed", func);
3786}
3787
3788/*
3789 * Called by libvterm when it cannot recognize an OSC sequence.
3790 * We recognize a terminal API command.
3791 */
3792 static int
3793parse_osc(const char *command, size_t cmdlen, void *user)
3794{
3795 term_T *term = (term_T *)user;
3796 js_read_T reader;
3797 typval_T tv;
3798 channel_T *channel = term->tl_job == NULL ? NULL
3799 : term->tl_job->jv_channel;
3800
3801 /* We recognize only OSC 5 1 ; {command} */
3802 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3803 return 0; /* not handled */
3804
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003805 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003806 if (reader.js_buf == NULL)
3807 return 1;
3808 reader.js_fill = NULL;
3809 reader.js_used = 0;
3810 if (json_decode(&reader, &tv, 0) == OK
3811 && tv.v_type == VAR_LIST
3812 && tv.vval.v_list != NULL)
3813 {
3814 listitem_T *item = tv.vval.v_list->lv_first;
3815
3816 if (item == NULL)
3817 ch_log(channel, "Missing command");
3818 else
3819 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003820 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003821
Bram Moolenaara997b452018-04-17 23:24:06 +02003822 /* Make sure an invoked command doesn't delete the buffer (and the
3823 * terminal) under our fingers. */
3824 ++term->tl_buffer->b_locked;
3825
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003826 item = item->li_next;
3827 if (item == NULL)
3828 ch_log(channel, "Missing argument for %s", cmd);
3829 else if (STRCMP(cmd, "drop") == 0)
3830 handle_drop_command(item);
3831 else if (STRCMP(cmd, "call") == 0)
3832 handle_call_command(term, channel, item);
3833 else
3834 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003835 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003836 }
3837 }
3838 else
3839 ch_log(channel, "Invalid JSON received");
3840
3841 vim_free(reader.js_buf);
3842 clear_tv(&tv);
3843 return 1;
3844}
3845
3846static VTermParserCallbacks parser_fallbacks = {
3847 NULL, /* text */
3848 NULL, /* control */
3849 NULL, /* escape */
3850 NULL, /* csi */
3851 parse_osc, /* osc */
3852 NULL, /* dcs */
3853 NULL /* resize */
3854};
3855
3856/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003857 * Use Vim's allocation functions for vterm so profiling works.
3858 */
3859 static void *
3860vterm_malloc(size_t size, void *data UNUSED)
3861{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003862 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003863}
3864
3865 static void
3866vterm_memfree(void *ptr, void *data UNUSED)
3867{
3868 vim_free(ptr);
3869}
3870
3871static VTermAllocatorFunctions vterm_allocator = {
3872 &vterm_malloc,
3873 &vterm_memfree
3874};
3875
3876/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003877 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003878 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01003879 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003880 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01003881create_vterm(term_T *term, int rows, int cols)
3882{
3883 VTerm *vterm;
3884 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003885 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003886 VTermValue value;
3887
Bram Moolenaar756ef112018-04-10 12:04:27 +02003888 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003889 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003890 if (vterm == NULL)
3891 return FAIL;
3892
3893 // Allocate screen and state here, so we can bail out if that fails.
3894 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003895 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003896 if (state == NULL || screen == NULL)
3897 {
3898 vterm_free(vterm);
3899 return FAIL;
3900 }
3901
Bram Moolenaar52acb112018-03-18 19:20:22 +01003902 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3903 /* TODO: depends on 'encoding'. */
3904 vterm_set_utf8(vterm, 1);
3905
3906 init_default_colors(term);
3907
3908 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003909 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01003910 &term->tl_default_color.fg,
3911 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003912
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003913 if (t_colors >= 16)
3914 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3915
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003916 /* Required to initialize most things. */
3917 vterm_screen_reset(screen, 1 /* hard */);
3918
3919 /* Allow using alternate screen. */
3920 vterm_screen_enable_altscreen(screen, 1);
3921
3922 /* For unix do not use a blinking cursor. In an xterm this causes the
3923 * cursor to blink if it's blinking in the xterm.
3924 * For Windows we respect the system wide setting. */
3925#ifdef WIN3264
3926 if (GetCaretBlinkTime() == INFINITE)
3927 value.boolean = 0;
3928 else
3929 value.boolean = 1;
3930#else
3931 value.boolean = 0;
3932#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003933 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3934 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003935
3936 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003937}
3938
3939/*
3940 * Return the text to show for the buffer name and status.
3941 */
3942 char_u *
3943term_get_status_text(term_T *term)
3944{
3945 if (term->tl_status_text == NULL)
3946 {
3947 char_u *txt;
3948 size_t len;
3949
3950 if (term->tl_normal_mode)
3951 {
3952 if (term_job_running(term))
3953 txt = (char_u *)_("Terminal");
3954 else
3955 txt = (char_u *)_("Terminal-finished");
3956 }
3957 else if (term->tl_title != NULL)
3958 txt = term->tl_title;
3959 else if (term_none_open(term))
3960 txt = (char_u *)_("active");
3961 else if (term_job_running(term))
3962 txt = (char_u *)_("running");
3963 else
3964 txt = (char_u *)_("finished");
3965 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3966 term->tl_status_text = alloc((int)len);
3967 if (term->tl_status_text != NULL)
3968 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3969 term->tl_buffer->b_fname, txt);
3970 }
3971 return term->tl_status_text;
3972}
3973
3974/*
3975 * Mark references in jobs of terminals.
3976 */
3977 int
3978set_ref_in_term(int copyID)
3979{
3980 int abort = FALSE;
3981 term_T *term;
3982 typval_T tv;
3983
3984 for (term = first_term; term != NULL; term = term->tl_next)
3985 if (term->tl_job != NULL)
3986 {
3987 tv.v_type = VAR_JOB;
3988 tv.vval.v_job = term->tl_job;
3989 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3990 }
3991 return abort;
3992}
3993
3994/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003995 * Cache "Terminal" highlight group colors.
3996 */
3997 void
3998set_terminal_default_colors(int cterm_fg, int cterm_bg)
3999{
4000 term_default_cterm_fg = cterm_fg - 1;
4001 term_default_cterm_bg = cterm_bg - 1;
4002}
4003
4004/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004005 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004006 * Returns NULL when the buffer is not for a terminal window and logs a message
4007 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004008 */
4009 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004010term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004011{
4012 buf_T *buf;
4013
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004014 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004015 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004016 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004017 --emsg_off;
4018 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004019 {
4020 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004021 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004022 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004023 return buf;
4024}
4025
Bram Moolenaard96ff162018-02-18 22:13:29 +01004026 static int
4027same_color(VTermColor *a, VTermColor *b)
4028{
4029 return a->red == b->red
4030 && a->green == b->green
4031 && a->blue == b->blue
4032 && a->ansi_index == b->ansi_index;
4033}
4034
4035 static void
4036dump_term_color(FILE *fd, VTermColor *color)
4037{
4038 fprintf(fd, "%02x%02x%02x%d",
4039 (int)color->red, (int)color->green, (int)color->blue,
4040 (int)color->ansi_index);
4041}
4042
4043/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004044 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004045 *
4046 * Each screen cell in full is:
4047 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4048 * {characters} is a space for an empty cell
4049 * For a double-width character "+" is changed to "*" and the next cell is
4050 * skipped.
4051 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4052 * when "&" use the same as the previous cell.
4053 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4054 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4055 * {color-idx} is a number from 0 to 255
4056 *
4057 * Screen cell with same width, attributes and color as the previous one:
4058 * |{characters}
4059 *
4060 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4061 *
4062 * Repeating the previous screen cell:
4063 * @{count}
4064 */
4065 void
4066f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4067{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004068 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004069 term_T *term;
4070 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004071 int max_height = 0;
4072 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004073 stat_T st;
4074 FILE *fd;
4075 VTermPos pos;
4076 VTermScreen *screen;
4077 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004078 VTermState *state;
4079 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004080
4081 if (check_restricted() || check_secure())
4082 return;
4083 if (buf == NULL)
4084 return;
4085 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004086 if (term->tl_vterm == NULL)
4087 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004088 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004089 return;
4090 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004091
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004092 if (argvars[2].v_type != VAR_UNKNOWN)
4093 {
4094 dict_T *d;
4095
4096 if (argvars[2].v_type != VAR_DICT)
4097 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004098 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004099 return;
4100 }
4101 d = argvars[2].vval.v_dict;
4102 if (d != NULL)
4103 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004104 max_height = dict_get_number(d, (char_u *)"rows");
4105 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004106 }
4107 }
4108
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004109 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004110 if (fname == NULL)
4111 return;
4112 if (mch_stat((char *)fname, &st) >= 0)
4113 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004114 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004115 return;
4116 }
4117
Bram Moolenaard96ff162018-02-18 22:13:29 +01004118 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4119 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004120 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004121 return;
4122 }
4123
4124 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4125
4126 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004127 state = vterm_obtain_state(term->tl_vterm);
4128 vterm_state_get_cursorpos(state, &cursor_pos);
4129
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004130 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4131 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004132 {
4133 int repeat = 0;
4134
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004135 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4136 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004137 {
4138 VTermScreenCell cell;
4139 int same_attr;
4140 int same_chars = TRUE;
4141 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004142 int is_cursor_pos = (pos.col == cursor_pos.col
4143 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004144
4145 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4146 vim_memset(&cell, 0, sizeof(cell));
4147
4148 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4149 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004150 int c = cell.chars[i];
4151 int pc = prev_cell.chars[i];
4152
4153 /* For the first character NUL is the same as space. */
4154 if (i == 0)
4155 {
4156 c = (c == NUL) ? ' ' : c;
4157 pc = (pc == NUL) ? ' ' : pc;
4158 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004159 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004160 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004161 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004162 break;
4163 }
4164 same_attr = vtermAttr2hl(cell.attrs)
4165 == vtermAttr2hl(prev_cell.attrs)
4166 && same_color(&cell.fg, &prev_cell.fg)
4167 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004168 if (same_chars && cell.width == prev_cell.width && same_attr
4169 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004170 {
4171 ++repeat;
4172 }
4173 else
4174 {
4175 if (repeat > 0)
4176 {
4177 fprintf(fd, "@%d", repeat);
4178 repeat = 0;
4179 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004180 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004181
4182 if (cell.chars[0] == NUL)
4183 fputs(" ", fd);
4184 else
4185 {
4186 char_u charbuf[10];
4187 int len;
4188
4189 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4190 && cell.chars[i] != NUL; ++i)
4191 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004192 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004193 fwrite(charbuf, len, 1, fd);
4194 }
4195 }
4196
4197 /* When only the characters differ we don't write anything, the
4198 * following "|", "@" or NL will indicate using the same
4199 * attributes. */
4200 if (cell.width != prev_cell.width || !same_attr)
4201 {
4202 if (cell.width == 2)
4203 {
4204 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004205 }
4206 else
4207 fputs("+", fd);
4208
4209 if (same_attr)
4210 {
4211 fputs("&", fd);
4212 }
4213 else
4214 {
4215 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4216 if (same_color(&cell.fg, &prev_cell.fg))
4217 fputs("&", fd);
4218 else
4219 {
4220 fputs("#", fd);
4221 dump_term_color(fd, &cell.fg);
4222 }
4223 if (same_color(&cell.bg, &prev_cell.bg))
4224 fputs("&", fd);
4225 else
4226 {
4227 fputs("#", fd);
4228 dump_term_color(fd, &cell.bg);
4229 }
4230 }
4231 }
4232
4233 prev_cell = cell;
4234 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004235
4236 if (cell.width == 2)
4237 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004238 }
4239 if (repeat > 0)
4240 fprintf(fd, "@%d", repeat);
4241 fputs("\n", fd);
4242 }
4243
4244 fclose(fd);
4245}
4246
4247/*
4248 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4249 */
4250 static void
4251dump_is_corrupt(garray_T *gap)
4252{
4253 ga_concat(gap, (char_u *)"CORRUPT");
4254}
4255
4256 static void
4257append_cell(garray_T *gap, cellattr_T *cell)
4258{
4259 if (ga_grow(gap, 1) == OK)
4260 {
4261 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4262 ++gap->ga_len;
4263 }
4264}
4265
4266/*
4267 * Read the dump file from "fd" and append lines to the current buffer.
4268 * Return the cell width of the longest line.
4269 */
4270 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004271read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004272{
4273 int c;
4274 garray_T ga_text;
4275 garray_T ga_cell;
4276 char_u *prev_char = NULL;
4277 int attr = 0;
4278 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004279 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004280 term_T *term = curbuf->b_term;
4281 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004282 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004283
4284 ga_init2(&ga_text, 1, 90);
4285 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4286 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004287 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004288 cursor_pos->row = -1;
4289 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004290
4291 c = fgetc(fd);
4292 for (;;)
4293 {
4294 if (c == EOF)
4295 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004296 if (c == '\r')
4297 {
4298 // DOS line endings? Ignore.
4299 c = fgetc(fd);
4300 }
4301 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004302 {
4303 /* End of a line: append it to the buffer. */
4304 if (ga_text.ga_data == NULL)
4305 dump_is_corrupt(&ga_text);
4306 if (ga_grow(&term->tl_scrollback, 1) == OK)
4307 {
4308 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4309 + term->tl_scrollback.ga_len;
4310
4311 if (max_cells < ga_cell.ga_len)
4312 max_cells = ga_cell.ga_len;
4313 line->sb_cols = ga_cell.ga_len;
4314 line->sb_cells = ga_cell.ga_data;
4315 line->sb_fill_attr = term->tl_default_color;
4316 ++term->tl_scrollback.ga_len;
4317 ga_init(&ga_cell);
4318
4319 ga_append(&ga_text, NUL);
4320 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4321 ga_text.ga_len, FALSE);
4322 }
4323 else
4324 ga_clear(&ga_cell);
4325 ga_text.ga_len = 0;
4326
4327 c = fgetc(fd);
4328 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004329 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004330 {
4331 int prev_len = ga_text.ga_len;
4332
Bram Moolenaar9271d052018-02-25 21:39:46 +01004333 if (c == '>')
4334 {
4335 if (cursor_pos->row != -1)
4336 dump_is_corrupt(&ga_text); /* duplicate cursor */
4337 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4338 cursor_pos->col = ga_cell.ga_len;
4339 }
4340
Bram Moolenaard96ff162018-02-18 22:13:29 +01004341 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4342 c = fgetc(fd);
4343 if (c != EOF)
4344 ga_append(&ga_text, c);
4345 for (;;)
4346 {
4347 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004348 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004349 || c == EOF || c == '\n')
4350 break;
4351 ga_append(&ga_text, c);
4352 }
4353
4354 /* save the character for repeating it */
4355 vim_free(prev_char);
4356 if (ga_text.ga_data != NULL)
4357 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4358 ga_text.ga_len - prev_len);
4359
Bram Moolenaar9271d052018-02-25 21:39:46 +01004360 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004361 {
4362 /* use all attributes from previous cell */
4363 }
4364 else if (c == '+' || c == '*')
4365 {
4366 int is_bg;
4367
4368 cell.width = c == '+' ? 1 : 2;
4369
4370 c = fgetc(fd);
4371 if (c == '&')
4372 {
4373 /* use same attr as previous cell */
4374 c = fgetc(fd);
4375 }
4376 else if (isdigit(c))
4377 {
4378 /* get the decimal attribute */
4379 attr = 0;
4380 while (isdigit(c))
4381 {
4382 attr = attr * 10 + (c - '0');
4383 c = fgetc(fd);
4384 }
4385 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004386
4387 /* is_bg == 0: fg, is_bg == 1: bg */
4388 for (is_bg = 0; is_bg <= 1; ++is_bg)
4389 {
4390 if (c == '&')
4391 {
4392 /* use same color as previous cell */
4393 c = fgetc(fd);
4394 }
4395 else if (c == '#')
4396 {
4397 int red, green, blue, index = 0;
4398
4399 c = fgetc(fd);
4400 red = hex2nr(c);
4401 c = fgetc(fd);
4402 red = (red << 4) + hex2nr(c);
4403 c = fgetc(fd);
4404 green = hex2nr(c);
4405 c = fgetc(fd);
4406 green = (green << 4) + hex2nr(c);
4407 c = fgetc(fd);
4408 blue = hex2nr(c);
4409 c = fgetc(fd);
4410 blue = (blue << 4) + hex2nr(c);
4411 c = fgetc(fd);
4412 if (!isdigit(c))
4413 dump_is_corrupt(&ga_text);
4414 while (isdigit(c))
4415 {
4416 index = index * 10 + (c - '0');
4417 c = fgetc(fd);
4418 }
4419
4420 if (is_bg)
4421 {
4422 cell.bg.red = red;
4423 cell.bg.green = green;
4424 cell.bg.blue = blue;
4425 cell.bg.ansi_index = index;
4426 }
4427 else
4428 {
4429 cell.fg.red = red;
4430 cell.fg.green = green;
4431 cell.fg.blue = blue;
4432 cell.fg.ansi_index = index;
4433 }
4434 }
4435 else
4436 dump_is_corrupt(&ga_text);
4437 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004438 }
4439 else
4440 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004441 }
4442 else
4443 dump_is_corrupt(&ga_text);
4444
4445 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004446 if (cell.width == 2)
4447 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004448 }
4449 else if (c == '@')
4450 {
4451 if (prev_char == NULL)
4452 dump_is_corrupt(&ga_text);
4453 else
4454 {
4455 int count = 0;
4456
4457 /* repeat previous character, get the count */
4458 for (;;)
4459 {
4460 c = fgetc(fd);
4461 if (!isdigit(c))
4462 break;
4463 count = count * 10 + (c - '0');
4464 }
4465
4466 while (count-- > 0)
4467 {
4468 ga_concat(&ga_text, prev_char);
4469 append_cell(&ga_cell, &cell);
4470 }
4471 }
4472 }
4473 else
4474 {
4475 dump_is_corrupt(&ga_text);
4476 c = fgetc(fd);
4477 }
4478 }
4479
4480 if (ga_text.ga_len > 0)
4481 {
4482 /* trailing characters after last NL */
4483 dump_is_corrupt(&ga_text);
4484 ga_append(&ga_text, NUL);
4485 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4486 ga_text.ga_len, FALSE);
4487 }
4488
4489 ga_clear(&ga_text);
4490 vim_free(prev_char);
4491
4492 return max_cells;
4493}
4494
4495/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004496 * Return an allocated string with at least "text_width" "=" characters and
4497 * "fname" inserted in the middle.
4498 */
4499 static char_u *
4500get_separator(int text_width, char_u *fname)
4501{
4502 int width = MAX(text_width, curwin->w_width);
4503 char_u *textline;
4504 int fname_size;
4505 char_u *p = fname;
4506 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004507 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004508
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004509 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004510 if (textline == NULL)
4511 return NULL;
4512
4513 fname_size = vim_strsize(fname);
4514 if (fname_size < width - 8)
4515 {
4516 /* enough room, don't use the full window width */
4517 width = MAX(text_width, fname_size + 8);
4518 }
4519 else if (fname_size > width - 8)
4520 {
4521 /* full name doesn't fit, use only the tail */
4522 p = gettail(fname);
4523 fname_size = vim_strsize(p);
4524 }
4525 /* skip characters until the name fits */
4526 while (fname_size > width - 8)
4527 {
4528 p += (*mb_ptr2len)(p);
4529 fname_size = vim_strsize(p);
4530 }
4531
4532 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4533 textline[i] = '=';
4534 textline[i++] = ' ';
4535
4536 STRCPY(textline + i, p);
4537 off = STRLEN(textline);
4538 textline[off] = ' ';
4539 for (i = 1; i < (width - fname_size) / 2; ++i)
4540 textline[off + i] = '=';
4541 textline[off + i] = NUL;
4542
4543 return textline;
4544}
4545
4546/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004547 * Common for "term_dumpdiff()" and "term_dumpload()".
4548 */
4549 static void
4550term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4551{
4552 jobopt_T opt;
4553 buf_T *buf;
4554 char_u buf1[NUMBUFLEN];
4555 char_u buf2[NUMBUFLEN];
4556 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004557 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004558 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004559 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004560 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004561 char_u *textline = NULL;
4562
4563 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004564 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004565 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004566 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004567 if (fname1 == NULL || (do_diff && fname2 == NULL))
4568 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004569 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004570 return;
4571 }
4572 fd1 = mch_fopen((char *)fname1, READBIN);
4573 if (fd1 == NULL)
4574 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004575 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004576 return;
4577 }
4578 if (do_diff)
4579 {
4580 fd2 = mch_fopen((char *)fname2, READBIN);
4581 if (fd2 == NULL)
4582 {
4583 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004584 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004585 return;
4586 }
4587 }
4588
4589 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004590 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4591 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4592 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4593 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4594 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004595
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004596 if (opt.jo_term_name == NULL)
4597 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004598 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004599
Bram Moolenaarb571c632018-03-21 22:27:59 +01004600 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004601 if (fname_tofree != NULL)
4602 {
4603 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4604 opt.jo_term_name = fname_tofree;
4605 }
4606 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004607
Bram Moolenaar13568252018-03-16 20:46:58 +01004608 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004609 if (buf != NULL && buf->b_term != NULL)
4610 {
4611 int i;
4612 linenr_T bot_lnum;
4613 linenr_T lnum;
4614 term_T *term = buf->b_term;
4615 int width;
4616 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004617 VTermPos cursor_pos1;
4618 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004619
Bram Moolenaar52acb112018-03-18 19:20:22 +01004620 init_default_colors(term);
4621
Bram Moolenaard96ff162018-02-18 22:13:29 +01004622 rettv->vval.v_number = buf->b_fnum;
4623
4624 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004625 width = read_dump_file(fd1, &cursor_pos1);
4626
4627 /* position the cursor */
4628 if (cursor_pos1.row >= 0)
4629 {
4630 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4631 coladvance(cursor_pos1.col);
4632 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004633
4634 /* Delete the empty line that was in the empty buffer. */
4635 ml_delete(1, FALSE);
4636
4637 /* For term_dumpload() we are done here. */
4638 if (!do_diff)
4639 goto theend;
4640
4641 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4642
Bram Moolenaar4a696342018-04-05 18:45:26 +02004643 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004644 if (textline == NULL)
4645 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004646 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4647 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4648 vim_free(textline);
4649
4650 textline = get_separator(width, fname2);
4651 if (textline == NULL)
4652 goto theend;
4653 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4654 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004655 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004656
4657 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004658 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004659 if (width2 > width)
4660 {
4661 vim_free(textline);
4662 textline = alloc(width2 + 1);
4663 if (textline == NULL)
4664 goto theend;
4665 width = width2;
4666 textline[width] = NUL;
4667 }
4668 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4669
4670 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4671 {
4672 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4673 {
4674 /* bottom part has fewer rows, fill with "-" */
4675 for (i = 0; i < width; ++i)
4676 textline[i] = '-';
4677 }
4678 else
4679 {
4680 char_u *line1;
4681 char_u *line2;
4682 char_u *p1;
4683 char_u *p2;
4684 int col;
4685 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4686 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4687 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4688 ->sb_cells;
4689
4690 /* Make a copy, getting the second line will invalidate it. */
4691 line1 = vim_strsave(ml_get(lnum));
4692 if (line1 == NULL)
4693 break;
4694 p1 = line1;
4695
4696 line2 = ml_get(lnum + bot_lnum);
4697 p2 = line2;
4698 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4699 {
4700 int len1 = utfc_ptr2len(p1);
4701 int len2 = utfc_ptr2len(p2);
4702
4703 textline[col] = ' ';
4704 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004705 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004706 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004707 else if (lnum == cursor_pos1.row + 1
4708 && col == cursor_pos1.col
4709 && (cursor_pos1.row != cursor_pos2.row
4710 || cursor_pos1.col != cursor_pos2.col))
4711 /* cursor in first but not in second */
4712 textline[col] = '>';
4713 else if (lnum == cursor_pos2.row + 1
4714 && col == cursor_pos2.col
4715 && (cursor_pos1.row != cursor_pos2.row
4716 || cursor_pos1.col != cursor_pos2.col))
4717 /* cursor in second but not in first */
4718 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004719 else if (cellattr1 != NULL && cellattr2 != NULL)
4720 {
4721 if ((cellattr1 + col)->width
4722 != (cellattr2 + col)->width)
4723 textline[col] = 'w';
4724 else if (!same_color(&(cellattr1 + col)->fg,
4725 &(cellattr2 + col)->fg))
4726 textline[col] = 'f';
4727 else if (!same_color(&(cellattr1 + col)->bg,
4728 &(cellattr2 + col)->bg))
4729 textline[col] = 'b';
4730 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4731 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4732 textline[col] = 'a';
4733 }
4734 p1 += len1;
4735 p2 += len2;
4736 /* TODO: handle different width */
4737 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004738
4739 while (col < width)
4740 {
4741 if (*p1 == NUL && *p2 == NUL)
4742 textline[col] = '?';
4743 else if (*p1 == NUL)
4744 {
4745 textline[col] = '+';
4746 p2 += utfc_ptr2len(p2);
4747 }
4748 else
4749 {
4750 textline[col] = '-';
4751 p1 += utfc_ptr2len(p1);
4752 }
4753 ++col;
4754 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004755
4756 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004757 }
4758 if (add_empty_scrollback(term, &term->tl_default_color,
4759 term->tl_top_diff_rows) == OK)
4760 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4761 ++bot_lnum;
4762 }
4763
4764 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4765 {
4766 /* bottom part has more rows, fill with "+" */
4767 for (i = 0; i < width; ++i)
4768 textline[i] = '+';
4769 if (add_empty_scrollback(term, &term->tl_default_color,
4770 term->tl_top_diff_rows) == OK)
4771 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4772 ++lnum;
4773 ++bot_lnum;
4774 }
4775
4776 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004777
4778 /* looks better without wrapping */
4779 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004780 }
4781
4782theend:
4783 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004784 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004785 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004786 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004787 fclose(fd2);
4788}
4789
4790/*
4791 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4792 * bottom files.
4793 * Return FAIL when this is not possible.
4794 */
4795 int
4796term_swap_diff()
4797{
4798 term_T *term = curbuf->b_term;
4799 linenr_T line_count;
4800 linenr_T top_rows;
4801 linenr_T bot_rows;
4802 linenr_T bot_start;
4803 linenr_T lnum;
4804 char_u *p;
4805 sb_line_T *sb_line;
4806
4807 if (term == NULL
4808 || !term_is_finished(curbuf)
4809 || term->tl_top_diff_rows == 0
4810 || term->tl_scrollback.ga_len == 0)
4811 return FAIL;
4812
4813 line_count = curbuf->b_ml.ml_line_count;
4814 top_rows = term->tl_top_diff_rows;
4815 bot_rows = term->tl_bot_diff_rows;
4816 bot_start = line_count - bot_rows;
4817 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4818
4819 /* move lines from top to above the bottom part */
4820 for (lnum = 1; lnum <= top_rows; ++lnum)
4821 {
4822 p = vim_strsave(ml_get(1));
4823 if (p == NULL)
4824 return OK;
4825 ml_append(bot_start, p, 0, FALSE);
4826 ml_delete(1, FALSE);
4827 vim_free(p);
4828 }
4829
4830 /* move lines from bottom to the top */
4831 for (lnum = 1; lnum <= bot_rows; ++lnum)
4832 {
4833 p = vim_strsave(ml_get(bot_start + lnum));
4834 if (p == NULL)
4835 return OK;
4836 ml_delete(bot_start + lnum, FALSE);
4837 ml_append(lnum - 1, p, 0, FALSE);
4838 vim_free(p);
4839 }
4840
4841 if (top_rows == bot_rows)
4842 {
4843 /* rows counts are equal, can swap cell properties */
4844 for (lnum = 0; lnum < top_rows; ++lnum)
4845 {
4846 sb_line_T temp;
4847
4848 temp = *(sb_line + lnum);
4849 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4850 *(sb_line + bot_start + lnum) = temp;
4851 }
4852 }
4853 else
4854 {
4855 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4856 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4857
4858 /* need to copy cell properties into temp memory */
4859 if (temp != NULL)
4860 {
4861 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4862 mch_memmove(term->tl_scrollback.ga_data,
4863 temp + bot_start,
4864 sizeof(sb_line_T) * bot_rows);
4865 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4866 temp + top_rows,
4867 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4868 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4869 + line_count - top_rows,
4870 temp,
4871 sizeof(sb_line_T) * top_rows);
4872 vim_free(temp);
4873 }
4874 }
4875
4876 term->tl_top_diff_rows = bot_rows;
4877 term->tl_bot_diff_rows = top_rows;
4878
4879 update_screen(NOT_VALID);
4880 return OK;
4881}
4882
4883/*
4884 * "term_dumpdiff(filename, filename, options)" function
4885 */
4886 void
4887f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4888{
4889 term_load_dump(argvars, rettv, TRUE);
4890}
4891
4892/*
4893 * "term_dumpload(filename, options)" function
4894 */
4895 void
4896f_term_dumpload(typval_T *argvars, typval_T *rettv)
4897{
4898 term_load_dump(argvars, rettv, FALSE);
4899}
4900
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004901/*
4902 * "term_getaltscreen(buf)" function
4903 */
4904 void
4905f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4906{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004907 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004908
4909 if (buf == NULL)
4910 return;
4911 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4912}
4913
4914/*
4915 * "term_getattr(attr, name)" function
4916 */
4917 void
4918f_term_getattr(typval_T *argvars, typval_T *rettv)
4919{
4920 int attr;
4921 size_t i;
4922 char_u *name;
4923
4924 static struct {
4925 char *name;
4926 int attr;
4927 } attrs[] = {
4928 {"bold", HL_BOLD},
4929 {"italic", HL_ITALIC},
4930 {"underline", HL_UNDERLINE},
4931 {"strike", HL_STRIKETHROUGH},
4932 {"reverse", HL_INVERSE},
4933 };
4934
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004935 attr = tv_get_number(&argvars[0]);
4936 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004937 if (name == NULL)
4938 return;
4939
4940 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4941 if (STRCMP(name, attrs[i].name) == 0)
4942 {
4943 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4944 break;
4945 }
4946}
4947
4948/*
4949 * "term_getcursor(buf)" function
4950 */
4951 void
4952f_term_getcursor(typval_T *argvars, typval_T *rettv)
4953{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004954 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004955 term_T *term;
4956 list_T *l;
4957 dict_T *d;
4958
4959 if (rettv_list_alloc(rettv) == FAIL)
4960 return;
4961 if (buf == NULL)
4962 return;
4963 term = buf->b_term;
4964
4965 l = rettv->vval.v_list;
4966 list_append_number(l, term->tl_cursor_pos.row + 1);
4967 list_append_number(l, term->tl_cursor_pos.col + 1);
4968
4969 d = dict_alloc();
4970 if (d != NULL)
4971 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02004972 dict_add_number(d, "visible", term->tl_cursor_visible);
4973 dict_add_number(d, "blink", blink_state_is_inverted()
4974 ? !term->tl_cursor_blink : term->tl_cursor_blink);
4975 dict_add_number(d, "shape", term->tl_cursor_shape);
4976 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004977 list_append_dict(l, d);
4978 }
4979}
4980
4981/*
4982 * "term_getjob(buf)" function
4983 */
4984 void
4985f_term_getjob(typval_T *argvars, typval_T *rettv)
4986{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004987 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004988
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004989 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01004990 {
4991 rettv->v_type = VAR_SPECIAL;
4992 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004993 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01004994 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004995
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01004996 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004997 rettv->vval.v_job = buf->b_term->tl_job;
4998 if (rettv->vval.v_job != NULL)
4999 ++rettv->vval.v_job->jv_refcount;
5000}
5001
5002 static int
5003get_row_number(typval_T *tv, term_T *term)
5004{
5005 if (tv->v_type == VAR_STRING
5006 && tv->vval.v_string != NULL
5007 && STRCMP(tv->vval.v_string, ".") == 0)
5008 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005009 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005010}
5011
5012/*
5013 * "term_getline(buf, row)" function
5014 */
5015 void
5016f_term_getline(typval_T *argvars, typval_T *rettv)
5017{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005018 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005019 term_T *term;
5020 int row;
5021
5022 rettv->v_type = VAR_STRING;
5023 if (buf == NULL)
5024 return;
5025 term = buf->b_term;
5026 row = get_row_number(&argvars[1], term);
5027
5028 if (term->tl_vterm == NULL)
5029 {
5030 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5031
5032 /* vterm is finished, get the text from the buffer */
5033 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5034 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5035 }
5036 else
5037 {
5038 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5039 VTermRect rect;
5040 int len;
5041 char_u *p;
5042
5043 if (row < 0 || row >= term->tl_rows)
5044 return;
5045 len = term->tl_cols * MB_MAXBYTES + 1;
5046 p = alloc(len);
5047 if (p == NULL)
5048 return;
5049 rettv->vval.v_string = p;
5050
5051 rect.start_col = 0;
5052 rect.end_col = term->tl_cols;
5053 rect.start_row = row;
5054 rect.end_row = row + 1;
5055 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5056 }
5057}
5058
5059/*
5060 * "term_getscrolled(buf)" function
5061 */
5062 void
5063f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5064{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005065 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005066
5067 if (buf == NULL)
5068 return;
5069 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5070}
5071
5072/*
5073 * "term_getsize(buf)" function
5074 */
5075 void
5076f_term_getsize(typval_T *argvars, typval_T *rettv)
5077{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005078 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005079 list_T *l;
5080
5081 if (rettv_list_alloc(rettv) == FAIL)
5082 return;
5083 if (buf == NULL)
5084 return;
5085
5086 l = rettv->vval.v_list;
5087 list_append_number(l, buf->b_term->tl_rows);
5088 list_append_number(l, buf->b_term->tl_cols);
5089}
5090
5091/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005092 * "term_setsize(buf, rows, cols)" function
5093 */
5094 void
5095f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5096{
5097 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5098 term_T *term;
5099 varnumber_T rows, cols;
5100
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005101 if (buf == NULL)
5102 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005103 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005104 return;
5105 }
5106 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005107 return;
5108 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005109 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005110 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005111 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005112 cols = cols <= 0 ? term->tl_cols : cols;
5113 vterm_set_size(term->tl_vterm, rows, cols);
5114 /* handle_resize() will resize the windows */
5115
5116 /* Get and remember the size we ended up with. Update the pty. */
5117 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5118 term_report_winsize(term, term->tl_rows, term->tl_cols);
5119}
5120
5121/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005122 * "term_getstatus(buf)" function
5123 */
5124 void
5125f_term_getstatus(typval_T *argvars, typval_T *rettv)
5126{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005127 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005128 term_T *term;
5129 char_u val[100];
5130
5131 rettv->v_type = VAR_STRING;
5132 if (buf == NULL)
5133 return;
5134 term = buf->b_term;
5135
5136 if (term_job_running(term))
5137 STRCPY(val, "running");
5138 else
5139 STRCPY(val, "finished");
5140 if (term->tl_normal_mode)
5141 STRCAT(val, ",normal");
5142 rettv->vval.v_string = vim_strsave(val);
5143}
5144
5145/*
5146 * "term_gettitle(buf)" function
5147 */
5148 void
5149f_term_gettitle(typval_T *argvars, typval_T *rettv)
5150{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005151 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005152
5153 rettv->v_type = VAR_STRING;
5154 if (buf == NULL)
5155 return;
5156
5157 if (buf->b_term->tl_title != NULL)
5158 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5159}
5160
5161/*
5162 * "term_gettty(buf)" function
5163 */
5164 void
5165f_term_gettty(typval_T *argvars, typval_T *rettv)
5166{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005167 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005168 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005169 int num = 0;
5170
5171 rettv->v_type = VAR_STRING;
5172 if (buf == NULL)
5173 return;
5174 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005175 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005176
5177 switch (num)
5178 {
5179 case 0:
5180 if (buf->b_term->tl_job != NULL)
5181 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005182 break;
5183 case 1:
5184 if (buf->b_term->tl_job != NULL)
5185 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005186 break;
5187 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005188 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005189 return;
5190 }
5191 if (p != NULL)
5192 rettv->vval.v_string = vim_strsave(p);
5193}
5194
5195/*
5196 * "term_list()" function
5197 */
5198 void
5199f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5200{
5201 term_T *tp;
5202 list_T *l;
5203
5204 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5205 return;
5206
5207 l = rettv->vval.v_list;
5208 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5209 if (tp != NULL && tp->tl_buffer != NULL)
5210 if (list_append_number(l,
5211 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5212 return;
5213}
5214
5215/*
5216 * "term_scrape(buf, row)" function
5217 */
5218 void
5219f_term_scrape(typval_T *argvars, typval_T *rettv)
5220{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005221 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005222 VTermScreen *screen = NULL;
5223 VTermPos pos;
5224 list_T *l;
5225 term_T *term;
5226 char_u *p;
5227 sb_line_T *line;
5228
5229 if (rettv_list_alloc(rettv) == FAIL)
5230 return;
5231 if (buf == NULL)
5232 return;
5233 term = buf->b_term;
5234
5235 l = rettv->vval.v_list;
5236 pos.row = get_row_number(&argvars[1], term);
5237
5238 if (term->tl_vterm != NULL)
5239 {
5240 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005241 if (screen == NULL) // can't really happen
5242 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005243 p = NULL;
5244 line = NULL;
5245 }
5246 else
5247 {
5248 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5249
5250 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5251 return;
5252 p = ml_get_buf(buf, lnum + 1, FALSE);
5253 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5254 }
5255
5256 for (pos.col = 0; pos.col < term->tl_cols; )
5257 {
5258 dict_T *dcell;
5259 int width;
5260 VTermScreenCellAttrs attrs;
5261 VTermColor fg, bg;
5262 char_u rgb[8];
5263 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5264 int off = 0;
5265 int i;
5266
5267 if (screen == NULL)
5268 {
5269 cellattr_T *cellattr;
5270 int len;
5271
5272 /* vterm has finished, get the cell from scrollback */
5273 if (pos.col >= line->sb_cols)
5274 break;
5275 cellattr = line->sb_cells + pos.col;
5276 width = cellattr->width;
5277 attrs = cellattr->attrs;
5278 fg = cellattr->fg;
5279 bg = cellattr->bg;
5280 len = MB_PTR2LEN(p);
5281 mch_memmove(mbs, p, len);
5282 mbs[len] = NUL;
5283 p += len;
5284 }
5285 else
5286 {
5287 VTermScreenCell cell;
5288 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5289 break;
5290 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5291 {
5292 if (cell.chars[i] == 0)
5293 break;
5294 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5295 }
5296 mbs[off] = NUL;
5297 width = cell.width;
5298 attrs = cell.attrs;
5299 fg = cell.fg;
5300 bg = cell.bg;
5301 }
5302 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005303 if (dcell == NULL)
5304 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005305 list_append_dict(l, dcell);
5306
Bram Moolenaare0be1672018-07-08 16:50:37 +02005307 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005308
5309 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5310 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005311 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005312 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5313 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005314 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005315
Bram Moolenaare0be1672018-07-08 16:50:37 +02005316 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5317 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005318
5319 ++pos.col;
5320 if (width == 2)
5321 ++pos.col;
5322 }
5323}
5324
5325/*
5326 * "term_sendkeys(buf, keys)" function
5327 */
5328 void
5329f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5330{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005331 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005332 char_u *msg;
5333 term_T *term;
5334
5335 rettv->v_type = VAR_UNKNOWN;
5336 if (buf == NULL)
5337 return;
5338
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005339 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005340 if (msg == NULL)
5341 return;
5342 term = buf->b_term;
5343 if (term->tl_vterm == NULL)
5344 return;
5345
5346 while (*msg != NUL)
5347 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005348 int c;
5349
5350 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5351 {
5352 c = TO_SPECIAL(msg[1], msg[2]);
5353 msg += 3;
5354 }
5355 else
5356 {
5357 c = PTR2CHAR(msg);
5358 msg += MB_CPTR2LEN(msg);
5359 }
5360 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005361 }
5362}
5363
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005364#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5365/*
5366 * "term_getansicolors(buf)" function
5367 */
5368 void
5369f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5370{
5371 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5372 term_T *term;
5373 VTermState *state;
5374 VTermColor color;
5375 char_u hexbuf[10];
5376 int index;
5377 list_T *list;
5378
5379 if (rettv_list_alloc(rettv) == FAIL)
5380 return;
5381
5382 if (buf == NULL)
5383 return;
5384 term = buf->b_term;
5385 if (term->tl_vterm == NULL)
5386 return;
5387
5388 list = rettv->vval.v_list;
5389 state = vterm_obtain_state(term->tl_vterm);
5390 for (index = 0; index < 16; index++)
5391 {
5392 vterm_state_get_palette_color(state, index, &color);
5393 sprintf((char *)hexbuf, "#%02x%02x%02x",
5394 color.red, color.green, color.blue);
5395 if (list_append_string(list, hexbuf, 7) == FAIL)
5396 return;
5397 }
5398}
5399
5400/*
5401 * "term_setansicolors(buf, list)" function
5402 */
5403 void
5404f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5405{
5406 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5407 term_T *term;
5408
5409 if (buf == NULL)
5410 return;
5411 term = buf->b_term;
5412 if (term->tl_vterm == NULL)
5413 return;
5414
5415 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5416 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005417 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005418 return;
5419 }
5420
5421 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005422 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005423}
5424#endif
5425
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005426/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005427 * "term_setrestore(buf, command)" function
5428 */
5429 void
5430f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5431{
5432#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005433 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005434 term_T *term;
5435 char_u *cmd;
5436
5437 if (buf == NULL)
5438 return;
5439 term = buf->b_term;
5440 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005441 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005442 if (cmd != NULL)
5443 term->tl_command = vim_strsave(cmd);
5444 else
5445 term->tl_command = NULL;
5446#endif
5447}
5448
5449/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005450 * "term_setkill(buf, how)" function
5451 */
5452 void
5453f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5454{
5455 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5456 term_T *term;
5457 char_u *how;
5458
5459 if (buf == NULL)
5460 return;
5461 term = buf->b_term;
5462 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005463 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005464 if (how != NULL)
5465 term->tl_kill = vim_strsave(how);
5466 else
5467 term->tl_kill = NULL;
5468}
5469
5470/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005471 * "term_start(command, options)" function
5472 */
5473 void
5474f_term_start(typval_T *argvars, typval_T *rettv)
5475{
5476 jobopt_T opt;
5477 buf_T *buf;
5478
5479 init_job_options(&opt);
5480 if (argvars[1].v_type != VAR_UNKNOWN
5481 && get_job_options(&argvars[1], &opt,
5482 JO_TIMEOUT_ALL + JO_STOPONEXIT
5483 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5484 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5485 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5486 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005487 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005488 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01005489 + JO2_ANSI_COLORS + JO2_TTY_TYPE) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005490 return;
5491
Bram Moolenaar13568252018-03-16 20:46:58 +01005492 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005493
5494 if (buf != NULL && buf->b_term != NULL)
5495 rettv->vval.v_number = buf->b_fnum;
5496}
5497
5498/*
5499 * "term_wait" function
5500 */
5501 void
5502f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5503{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005504 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005505
5506 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005507 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005508 if (buf->b_term->tl_job == NULL)
5509 {
5510 ch_log(NULL, "term_wait(): no job to wait for");
5511 return;
5512 }
5513 if (buf->b_term->tl_job->jv_channel == NULL)
5514 /* channel is closed, nothing to do */
5515 return;
5516
5517 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005518 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005519 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5520 {
5521 /* The job is dead, keep reading channel I/O until the channel is
5522 * closed. buf->b_term may become NULL if the terminal was closed while
5523 * waiting. */
5524 ch_log(NULL, "term_wait(): waiting for channel to close");
5525 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5526 {
5527 mch_check_messages();
5528 parse_queued_messages();
Bram Moolenaard45aa552018-05-21 22:50:29 +02005529 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005530 if (!buf_valid(buf))
5531 /* If the terminal is closed when the channel is closed the
5532 * buffer disappears. */
5533 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005534 }
5535 mch_check_messages();
5536 parse_queued_messages();
5537 }
5538 else
5539 {
5540 long wait = 10L;
5541
5542 mch_check_messages();
5543 parse_queued_messages();
5544
5545 /* Wait for some time for any channel I/O. */
5546 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005547 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005548 ui_delay(wait, TRUE);
5549 mch_check_messages();
5550
5551 /* Flushing messages on channels is hopefully sufficient.
5552 * TODO: is there a better way? */
5553 parse_queued_messages();
5554 }
5555}
5556
5557/*
5558 * Called when a channel has sent all the lines to a terminal.
5559 * Send a CTRL-D to mark the end of the text.
5560 */
5561 void
5562term_send_eof(channel_T *ch)
5563{
5564 term_T *term;
5565
5566 for (term = first_term; term != NULL; term = term->tl_next)
5567 if (term->tl_job == ch->ch_job)
5568 {
5569 if (term->tl_eof_chars != NULL)
5570 {
5571 channel_send(ch, PART_IN, term->tl_eof_chars,
5572 (int)STRLEN(term->tl_eof_chars), NULL);
5573 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5574 }
5575# ifdef WIN3264
5576 else
5577 /* Default: CTRL-D */
5578 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5579# endif
5580 }
5581}
5582
Bram Moolenaar113e1072019-01-20 15:30:40 +01005583#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005584 job_T *
5585term_getjob(term_T *term)
5586{
5587 return term != NULL ? term->tl_job : NULL;
5588}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005589#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005590
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005591# if defined(WIN3264) || defined(PROTO)
5592
5593/**************************************
5594 * 2. MS-Windows implementation.
5595 */
5596
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005597HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5598HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5599HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005600BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5601BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5602void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005603
5604 static int
5605dyn_conpty_init(int verbose)
5606{
5607 static BOOL handled = FALSE;
5608 static int result;
5609 HMODULE hKerneldll;
5610 int i;
5611 static struct
5612 {
5613 char *name;
5614 FARPROC *ptr;
5615 } conpty_entry[] =
5616 {
5617 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5618 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5619 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5620 {"InitializeProcThreadAttributeList",
5621 (FARPROC*)&pInitializeProcThreadAttributeList},
5622 {"UpdateProcThreadAttribute",
5623 (FARPROC*)&pUpdateProcThreadAttribute},
5624 {"DeleteProcThreadAttributeList",
5625 (FARPROC*)&pDeleteProcThreadAttributeList},
5626 {NULL, NULL}
5627 };
5628
5629 if (handled)
5630 return result;
5631
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005632 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005633 {
5634 handled = TRUE;
5635 result = FAIL;
5636 return FAIL;
5637 }
5638
5639 hKerneldll = vimLoadLib("kernel32.dll");
5640 for (i = 0; conpty_entry[i].name != NULL
5641 && conpty_entry[i].ptr != NULL; ++i)
5642 {
5643 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5644 conpty_entry[i].name)) == NULL)
5645 {
5646 if (verbose)
5647 semsg(_(e_loadfunc), conpty_entry[i].name);
5648 return FAIL;
5649 }
5650 }
5651
5652 handled = TRUE;
5653 result = OK;
5654 return OK;
5655}
5656
5657 static int
5658conpty_term_and_job_init(
5659 term_T *term,
5660 typval_T *argvar,
5661 char **argv,
5662 jobopt_T *opt,
5663 jobopt_T *orig_opt)
5664{
5665 WCHAR *cmd_wchar = NULL;
5666 WCHAR *cmd_wchar_copy = NULL;
5667 WCHAR *cwd_wchar = NULL;
5668 WCHAR *env_wchar = NULL;
5669 channel_T *channel = NULL;
5670 job_T *job = NULL;
5671 HANDLE jo = NULL;
5672 garray_T ga_cmd, ga_env;
5673 char_u *cmd = NULL;
5674 HRESULT hr;
5675 COORD consize;
5676 SIZE_T breq;
5677 PROCESS_INFORMATION proc_info;
5678 HANDLE i_theirs = NULL;
5679 HANDLE o_theirs = NULL;
5680 HANDLE i_ours = NULL;
5681 HANDLE o_ours = NULL;
5682
5683 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5684 ga_init2(&ga_env, (int)sizeof(char*), 20);
5685
5686 if (argvar->v_type == VAR_STRING)
5687 {
5688 cmd = argvar->vval.v_string;
5689 }
5690 else if (argvar->v_type == VAR_LIST)
5691 {
5692 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5693 goto failed;
5694 cmd = ga_cmd.ga_data;
5695 }
5696 if (cmd == NULL || *cmd == NUL)
5697 {
5698 emsg(_(e_invarg));
5699 goto failed;
5700 }
5701
5702 term->tl_arg0_cmd = vim_strsave(cmd);
5703
5704 cmd_wchar = enc_to_utf16(cmd, NULL);
5705
5706 if (cmd_wchar != NULL)
5707 {
5708 /* Request by CreateProcessW */
5709 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
5710 cmd_wchar_copy = (PWSTR)alloc((int)(breq * sizeof(WCHAR)));
5711 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5712 }
5713
5714 ga_clear(&ga_cmd);
5715 if (cmd_wchar == NULL)
5716 goto failed;
5717 if (opt->jo_cwd != NULL)
5718 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5719
5720 win32_build_env(opt->jo_env, &ga_env, TRUE);
5721 env_wchar = ga_env.ga_data;
5722
5723 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5724 goto failed;
5725 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5726 goto failed;
5727
5728 consize.X = term->tl_cols;
5729 consize.Y = term->tl_rows;
5730 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
5731 &term->tl_conpty);
5732 if (FAILED(hr))
5733 goto failed;
5734
5735 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
5736
5737 /* Set up pipe inheritance safely: Vista or later. */
5738 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
5739 term->tl_siex.lpAttributeList =
5740 (PPROC_THREAD_ATTRIBUTE_LIST)alloc((int)breq);
5741 if (!term->tl_siex.lpAttributeList)
5742 goto failed;
5743 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
5744 0, &breq))
5745 goto failed;
5746 if (!pUpdateProcThreadAttribute(
5747 term->tl_siex.lpAttributeList, 0,
5748 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
5749 sizeof(HPCON), NULL, NULL))
5750 goto failed;
5751
5752 channel = add_channel();
5753 if (channel == NULL)
5754 goto failed;
5755
5756 job = job_alloc();
5757 if (job == NULL)
5758 goto failed;
5759 if (argvar->v_type == VAR_STRING)
5760 {
5761 int argc;
5762
5763 build_argv_from_string(cmd, &job->jv_argv, &argc);
5764 }
5765 else
5766 {
5767 int argc;
5768
5769 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5770 }
5771
5772 if (opt->jo_set & JO_IN_BUF)
5773 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5774
5775 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
5776 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
5777 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
5778 | CREATE_DEFAULT_ERROR_MODE,
5779 env_wchar, cwd_wchar,
5780 &term->tl_siex.StartupInfo, &proc_info))
5781 goto failed;
5782
5783 CloseHandle(i_theirs);
5784 CloseHandle(o_theirs);
5785
5786 channel_set_pipes(channel,
5787 (sock_T)i_ours,
5788 (sock_T)o_ours,
5789 (sock_T)o_ours);
5790
5791 /* Write lines with CR instead of NL. */
5792 channel->ch_write_text_mode = TRUE;
5793
5794 /* Use to explicitly delete anonymous pipe handle. */
5795 channel->ch_anonymous_pipe = TRUE;
5796
5797 jo = CreateJobObject(NULL, NULL);
5798 if (jo == NULL)
5799 goto failed;
5800
5801 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
5802 {
5803 /* Failed, switch the way to terminate process with TerminateProcess. */
5804 CloseHandle(jo);
5805 jo = NULL;
5806 }
5807
5808 ResumeThread(proc_info.hThread);
5809 CloseHandle(proc_info.hThread);
5810
5811 vim_free(cmd_wchar);
5812 vim_free(cmd_wchar_copy);
5813 vim_free(cwd_wchar);
5814 vim_free(env_wchar);
5815
5816 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
5817 goto failed;
5818
5819#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5820 if (opt->jo_set2 & JO2_ANSI_COLORS)
5821 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5822 else
5823 init_vterm_ansi_colors(term->tl_vterm);
5824#endif
5825
5826 channel_set_job(channel, job, opt);
5827 job_set_options(job, opt);
5828
5829 job->jv_channel = channel;
5830 job->jv_proc_info = proc_info;
5831 job->jv_job_object = jo;
5832 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01005833 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005834 ++job->jv_refcount;
5835 term->tl_job = job;
5836
5837 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5838 * open the file here and handle it in. opt->jo_io was changed in
5839 * setup_job_options(), use the original flags here. */
5840 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5841 {
5842 char_u *fname = opt->jo_io_name[PART_OUT];
5843
5844 ch_log(channel, "Opening output file %s", fname);
5845 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5846 if (term->tl_out_fd == NULL)
5847 semsg(_(e_notopen), fname);
5848 }
5849
5850 return OK;
5851
5852failed:
5853 ga_clear(&ga_cmd);
5854 ga_clear(&ga_env);
5855 vim_free(cmd_wchar);
5856 vim_free(cmd_wchar_copy);
5857 vim_free(cwd_wchar);
5858 if (channel != NULL)
5859 channel_clear(channel);
5860 if (job != NULL)
5861 {
5862 job->jv_channel = NULL;
5863 job_cleanup(job);
5864 }
5865 term->tl_job = NULL;
5866 if (jo != NULL)
5867 CloseHandle(jo);
5868
5869 if (term->tl_siex.lpAttributeList != NULL)
5870 {
5871 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
5872 vim_free(term->tl_siex.lpAttributeList);
5873 }
5874 term->tl_siex.lpAttributeList = NULL;
5875 if (o_theirs != NULL)
5876 CloseHandle(o_theirs);
5877 if (o_ours != NULL)
5878 CloseHandle(o_ours);
5879 if (i_ours != NULL)
5880 CloseHandle(i_ours);
5881 if (i_theirs != NULL)
5882 CloseHandle(i_theirs);
5883 if (term->tl_conpty != NULL)
5884 pClosePseudoConsole(term->tl_conpty);
5885 term->tl_conpty = NULL;
5886 return FAIL;
5887}
5888
5889 static void
5890conpty_term_report_winsize(term_T *term, int rows, int cols)
5891{
5892 COORD consize;
5893
5894 consize.X = cols;
5895 consize.Y = rows;
5896 pResizePseudoConsole(term->tl_conpty, consize);
5897}
5898
5899 void
5900term_free_conpty(term_T *term)
5901{
5902 if (term->tl_siex.lpAttributeList != NULL)
5903 {
5904 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
5905 vim_free(term->tl_siex.lpAttributeList);
5906 }
5907 term->tl_siex.lpAttributeList = NULL;
5908 if (term->tl_conpty != NULL)
5909 pClosePseudoConsole(term->tl_conpty);
5910 term->tl_conpty = NULL;
5911}
5912
5913 int
5914use_conpty(void)
5915{
5916 return has_conpty;
5917}
5918
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005919# ifndef PROTO
5920
5921#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5922#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005923#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005924
5925void* (*winpty_config_new)(UINT64, void*);
5926void* (*winpty_open)(void*, void*);
5927void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5928BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5929void (*winpty_config_set_mouse_mode)(void*, int);
5930void (*winpty_config_set_initial_size)(void*, int, int);
5931LPCWSTR (*winpty_conin_name)(void*);
5932LPCWSTR (*winpty_conout_name)(void*);
5933LPCWSTR (*winpty_conerr_name)(void*);
5934void (*winpty_free)(void*);
5935void (*winpty_config_free)(void*);
5936void (*winpty_spawn_config_free)(void*);
5937void (*winpty_error_free)(void*);
5938LPCWSTR (*winpty_error_msg)(void*);
5939BOOL (*winpty_set_size)(void*, int, int, void*);
5940HANDLE (*winpty_agent_process)(void*);
5941
5942#define WINPTY_DLL "winpty.dll"
5943
5944static HINSTANCE hWinPtyDLL = NULL;
5945# endif
5946
5947 static int
5948dyn_winpty_init(int verbose)
5949{
5950 int i;
5951 static struct
5952 {
5953 char *name;
5954 FARPROC *ptr;
5955 } winpty_entry[] =
5956 {
5957 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5958 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5959 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5960 {"winpty_config_set_mouse_mode",
5961 (FARPROC*)&winpty_config_set_mouse_mode},
5962 {"winpty_config_set_initial_size",
5963 (FARPROC*)&winpty_config_set_initial_size},
5964 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5965 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5966 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5967 {"winpty_free", (FARPROC*)&winpty_free},
5968 {"winpty_open", (FARPROC*)&winpty_open},
5969 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5970 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5971 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5972 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5973 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5974 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5975 {NULL, NULL}
5976 };
5977
5978 /* No need to initialize twice. */
5979 if (hWinPtyDLL)
5980 return OK;
5981 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5982 * winpty.dll. */
5983 if (*p_winptydll != NUL)
5984 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5985 if (!hWinPtyDLL)
5986 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5987 if (!hWinPtyDLL)
5988 {
5989 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005990 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005991 : (char_u *)WINPTY_DLL);
5992 return FAIL;
5993 }
5994 for (i = 0; winpty_entry[i].name != NULL
5995 && winpty_entry[i].ptr != NULL; ++i)
5996 {
5997 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5998 winpty_entry[i].name)) == NULL)
5999 {
6000 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006001 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006002 return FAIL;
6003 }
6004 }
6005
6006 return OK;
6007}
6008
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006009 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006010winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006011 term_T *term,
6012 typval_T *argvar,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006013 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006014 jobopt_T *opt,
6015 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006016{
6017 WCHAR *cmd_wchar = NULL;
6018 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006019 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006020 channel_T *channel = NULL;
6021 job_T *job = NULL;
6022 DWORD error;
6023 HANDLE jo = NULL;
6024 HANDLE child_process_handle;
6025 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006026 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006027 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006028 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006029 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006030
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006031 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6032 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006033
6034 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006035 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006036 cmd = argvar->vval.v_string;
6037 }
6038 else if (argvar->v_type == VAR_LIST)
6039 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006040 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006041 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006042 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006043 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006044 if (cmd == NULL || *cmd == NUL)
6045 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006046 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006047 goto failed;
6048 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006049
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006050 term->tl_arg0_cmd = vim_strsave(cmd);
6051
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006052 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006053 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006054 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006055 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006056 if (opt->jo_cwd != NULL)
6057 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006058
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006059 win32_build_env(opt->jo_env, &ga_env, TRUE);
6060 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006061
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006062 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6063 if (term->tl_winpty_config == NULL)
6064 goto failed;
6065
6066 winpty_config_set_mouse_mode(term->tl_winpty_config,
6067 WINPTY_MOUSE_MODE_FORCE);
6068 winpty_config_set_initial_size(term->tl_winpty_config,
6069 term->tl_cols, term->tl_rows);
6070 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6071 if (term->tl_winpty == NULL)
6072 goto failed;
6073
6074 spawn_config = winpty_spawn_config_new(
6075 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6076 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6077 NULL,
6078 cmd_wchar,
6079 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006080 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006081 &winpty_err);
6082 if (spawn_config == NULL)
6083 goto failed;
6084
6085 channel = add_channel();
6086 if (channel == NULL)
6087 goto failed;
6088
6089 job = job_alloc();
6090 if (job == NULL)
6091 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006092 if (argvar->v_type == VAR_STRING)
6093 {
6094 int argc;
6095
6096 build_argv_from_string(cmd, &job->jv_argv, &argc);
6097 }
6098 else
6099 {
6100 int argc;
6101
6102 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6103 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006104
6105 if (opt->jo_set & JO_IN_BUF)
6106 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6107
6108 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6109 &child_thread_handle, &error, &winpty_err))
6110 goto failed;
6111
6112 channel_set_pipes(channel,
6113 (sock_T)CreateFileW(
6114 winpty_conin_name(term->tl_winpty),
6115 GENERIC_WRITE, 0, NULL,
6116 OPEN_EXISTING, 0, NULL),
6117 (sock_T)CreateFileW(
6118 winpty_conout_name(term->tl_winpty),
6119 GENERIC_READ, 0, NULL,
6120 OPEN_EXISTING, 0, NULL),
6121 (sock_T)CreateFileW(
6122 winpty_conerr_name(term->tl_winpty),
6123 GENERIC_READ, 0, NULL,
6124 OPEN_EXISTING, 0, NULL));
6125
6126 /* Write lines with CR instead of NL. */
6127 channel->ch_write_text_mode = TRUE;
6128
6129 jo = CreateJobObject(NULL, NULL);
6130 if (jo == NULL)
6131 goto failed;
6132
6133 if (!AssignProcessToJobObject(jo, child_process_handle))
6134 {
6135 /* Failed, switch the way to terminate process with TerminateProcess. */
6136 CloseHandle(jo);
6137 jo = NULL;
6138 }
6139
6140 winpty_spawn_config_free(spawn_config);
6141 vim_free(cmd_wchar);
6142 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006143 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006144
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006145 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6146 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006147
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006148#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6149 if (opt->jo_set2 & JO2_ANSI_COLORS)
6150 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6151 else
6152 init_vterm_ansi_colors(term->tl_vterm);
6153#endif
6154
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006155 channel_set_job(channel, job, opt);
6156 job_set_options(job, opt);
6157
6158 job->jv_channel = channel;
6159 job->jv_proc_info.hProcess = child_process_handle;
6160 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6161 job->jv_job_object = jo;
6162 job->jv_status = JOB_STARTED;
6163 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006164 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006165 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006166 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006167 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006168 ++job->jv_refcount;
6169 term->tl_job = job;
6170
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006171 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6172 * open the file here and handle it in. opt->jo_io was changed in
6173 * setup_job_options(), use the original flags here. */
6174 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6175 {
6176 char_u *fname = opt->jo_io_name[PART_OUT];
6177
6178 ch_log(channel, "Opening output file %s", fname);
6179 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6180 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006181 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006182 }
6183
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006184 return OK;
6185
6186failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006187 ga_clear(&ga_cmd);
6188 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006189 vim_free(cmd_wchar);
6190 vim_free(cwd_wchar);
6191 if (spawn_config != NULL)
6192 winpty_spawn_config_free(spawn_config);
6193 if (channel != NULL)
6194 channel_clear(channel);
6195 if (job != NULL)
6196 {
6197 job->jv_channel = NULL;
6198 job_cleanup(job);
6199 }
6200 term->tl_job = NULL;
6201 if (jo != NULL)
6202 CloseHandle(jo);
6203 if (term->tl_winpty != NULL)
6204 winpty_free(term->tl_winpty);
6205 term->tl_winpty = NULL;
6206 if (term->tl_winpty_config != NULL)
6207 winpty_config_free(term->tl_winpty_config);
6208 term->tl_winpty_config = NULL;
6209 if (winpty_err != NULL)
6210 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006211 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006212 (short_u *)winpty_error_msg(winpty_err), NULL);
6213
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006214 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006215 winpty_error_free(winpty_err);
6216 }
6217 return FAIL;
6218}
6219
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006220/*
6221 * Create a new terminal of "rows" by "cols" cells.
6222 * Store a reference in "term".
6223 * Return OK or FAIL.
6224 */
6225 static int
6226term_and_job_init(
6227 term_T *term,
6228 typval_T *argvar,
6229 char **argv UNUSED,
6230 jobopt_T *opt,
6231 jobopt_T *orig_opt)
6232{
6233 int use_winpty = FALSE;
6234 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006235 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006236
6237 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6238 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6239
6240 if (!has_winpty && !has_conpty)
6241 // If neither is available give the errors for winpty, since when
6242 // conpty is not available it can't be installed either.
6243 return dyn_winpty_init(TRUE);
6244
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006245 if (opt->jo_tty_type != NUL)
6246 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006247
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006248 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006249 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006250 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006251 use_conpty = TRUE;
6252 else if (has_winpty)
6253 use_winpty = TRUE;
6254 // else: error
6255 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006256 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006257 {
6258 if (has_winpty)
6259 use_winpty = TRUE;
6260 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006261 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006262 {
6263 if (has_conpty)
6264 use_conpty = TRUE;
6265 else
6266 return dyn_conpty_init(TRUE);
6267 }
6268
6269 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006270 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006271
6272 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006273 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006274
6275 // error
6276 return dyn_winpty_init(TRUE);
6277}
6278
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006279 static int
6280create_pty_only(term_T *term, jobopt_T *options)
6281{
6282 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6283 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6284 char in_name[80], out_name[80];
6285 channel_T *channel = NULL;
6286
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006287 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6288 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006289
6290 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6291 GetCurrentProcessId(),
6292 curbuf->b_fnum);
6293 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6294 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6295 PIPE_UNLIMITED_INSTANCES,
6296 0, 0, NMPWAIT_NOWAIT, NULL);
6297 if (hPipeIn == INVALID_HANDLE_VALUE)
6298 goto failed;
6299
6300 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6301 GetCurrentProcessId(),
6302 curbuf->b_fnum);
6303 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6304 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6305 PIPE_UNLIMITED_INSTANCES,
6306 0, 0, 0, NULL);
6307 if (hPipeOut == INVALID_HANDLE_VALUE)
6308 goto failed;
6309
6310 ConnectNamedPipe(hPipeIn, NULL);
6311 ConnectNamedPipe(hPipeOut, NULL);
6312
6313 term->tl_job = job_alloc();
6314 if (term->tl_job == NULL)
6315 goto failed;
6316 ++term->tl_job->jv_refcount;
6317
6318 /* behave like the job is already finished */
6319 term->tl_job->jv_status = JOB_FINISHED;
6320
6321 channel = add_channel();
6322 if (channel == NULL)
6323 goto failed;
6324 term->tl_job->jv_channel = channel;
6325 channel->ch_keep_open = TRUE;
6326 channel->ch_named_pipe = TRUE;
6327
6328 channel_set_pipes(channel,
6329 (sock_T)hPipeIn,
6330 (sock_T)hPipeOut,
6331 (sock_T)hPipeOut);
6332 channel_set_job(channel, term->tl_job, options);
6333 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6334 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6335
6336 return OK;
6337
6338failed:
6339 if (hPipeIn != NULL)
6340 CloseHandle(hPipeIn);
6341 if (hPipeOut != NULL)
6342 CloseHandle(hPipeOut);
6343 return FAIL;
6344}
6345
6346/*
6347 * Free the terminal emulator part of "term".
6348 */
6349 static void
6350term_free_vterm(term_T *term)
6351{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006352 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006353 if (term->tl_winpty != NULL)
6354 winpty_free(term->tl_winpty);
6355 term->tl_winpty = NULL;
6356 if (term->tl_winpty_config != NULL)
6357 winpty_config_free(term->tl_winpty_config);
6358 term->tl_winpty_config = NULL;
6359 if (term->tl_vterm != NULL)
6360 vterm_free(term->tl_vterm);
6361 term->tl_vterm = NULL;
6362}
6363
6364/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006365 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006366 */
6367 static void
6368term_report_winsize(term_T *term, int rows, int cols)
6369{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006370 if (term->tl_conpty)
6371 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006372 if (term->tl_winpty)
6373 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6374}
6375
6376 int
6377terminal_enabled(void)
6378{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006379 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006380}
6381
6382# else
6383
6384/**************************************
6385 * 3. Unix-like implementation.
6386 */
6387
6388/*
6389 * Create a new terminal of "rows" by "cols" cells.
6390 * Start job for "cmd".
6391 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006392 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006393 * Return OK or FAIL.
6394 */
6395 static int
6396term_and_job_init(
6397 term_T *term,
6398 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006399 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006400 jobopt_T *opt,
6401 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006402{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006403 term->tl_arg0_cmd = NULL;
6404
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006405 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6406 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006407
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006408#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6409 if (opt->jo_set2 & JO2_ANSI_COLORS)
6410 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6411 else
6412 init_vterm_ansi_colors(term->tl_vterm);
6413#endif
6414
Bram Moolenaar13568252018-03-16 20:46:58 +01006415 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006416 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006417 if (term->tl_job != NULL)
6418 ++term->tl_job->jv_refcount;
6419
6420 return term->tl_job != NULL
6421 && term->tl_job->jv_channel != NULL
6422 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6423}
6424
6425 static int
6426create_pty_only(term_T *term, jobopt_T *opt)
6427{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006428 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6429 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006430
6431 term->tl_job = job_alloc();
6432 if (term->tl_job == NULL)
6433 return FAIL;
6434 ++term->tl_job->jv_refcount;
6435
6436 /* behave like the job is already finished */
6437 term->tl_job->jv_status = JOB_FINISHED;
6438
6439 return mch_create_pty_channel(term->tl_job, opt);
6440}
6441
6442/*
6443 * Free the terminal emulator part of "term".
6444 */
6445 static void
6446term_free_vterm(term_T *term)
6447{
6448 if (term->tl_vterm != NULL)
6449 vterm_free(term->tl_vterm);
6450 term->tl_vterm = NULL;
6451}
6452
6453/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006454 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006455 */
6456 static void
6457term_report_winsize(term_T *term, int rows, int cols)
6458{
6459 /* Use an ioctl() to report the new window size to the job. */
6460 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6461 {
6462 int fd = -1;
6463 int part;
6464
6465 for (part = PART_OUT; part < PART_COUNT; ++part)
6466 {
6467 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006468 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006469 break;
6470 }
6471 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6472 mch_signal_job(term->tl_job, (char_u *)"winch");
6473 }
6474}
6475
6476# endif
6477
6478#endif /* FEAT_TERMINAL */