blob: f1d89ab9e4bc7692122eec9a7c411c52f88a67db [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 Moolenaar4f974752019-02-17 17:44:42 +010069#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010070# 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 Moolenaar4f974752019-02-17 17:44:42 +0100115#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200116 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 Moolenaar4f974752019-02-17 17:44:42 +0100175#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100176static 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 Moolenaar4f974752019-02-17 17:44:42 +0100327#ifndef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200328 /* 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 Moolenaar4f974752019-02-17 17:44:42 +0100340#ifndef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200341 /* 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 Moolenaar5c381eb2019-06-25 06:50:31 +0200361 * Flush messages on channels.
362 */
363 static void
364term_flush_messages()
365{
366 mch_check_messages();
367 parse_queued_messages();
368}
369
370/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100371 * Close a terminal buffer (and its window). Used when creating the terminal
372 * fails.
373 */
374 static void
375term_close_buffer(buf_T *buf, buf_T *old_curbuf)
376{
377 free_terminal(buf);
378 if (old_curbuf != NULL)
379 {
380 --curbuf->b_nwindows;
381 curbuf = old_curbuf;
382 curwin->w_buffer = curbuf;
383 ++curbuf->b_nwindows;
384 }
385
386 /* Wiping out the buffer will also close the window and call
387 * free_terminal(). */
388 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
389}
390
391/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200392 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100393 * Use either "argvar" or "argv", the other must be NULL.
394 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
395 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200396 * Returns NULL when failed.
397 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100398 buf_T *
399term_start(
400 typval_T *argvar,
401 char **argv,
402 jobopt_T *opt,
403 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200404{
405 exarg_T split_ea;
406 win_T *old_curwin = curwin;
407 term_T *term;
408 buf_T *old_curbuf = NULL;
409 int res;
410 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100411 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200412 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200413
414 if (check_restricted() || check_secure())
415 return NULL;
416
417 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
418 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
419 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
420 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
421 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100422 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200423 return NULL;
424 }
425
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200426 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200427 if (term == NULL)
428 return NULL;
429 term->tl_dirty_row_end = MAX_ROW;
430 term->tl_cursor_visible = TRUE;
431 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
432 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100433#ifdef FEAT_GUI
434 term->tl_system = (flags & TERM_START_SYSTEM);
435#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200436 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100437 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200438
439 vim_memset(&split_ea, 0, sizeof(split_ea));
440 if (opt->jo_curwin)
441 {
442 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100443 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200444 {
445 no_write_message();
446 vim_free(term);
447 return NULL;
448 }
449 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100450 ECMD_HIDE
451 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
452 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200453 {
454 vim_free(term);
455 return NULL;
456 }
457 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100458 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200459 {
460 buf_T *buf;
461
462 /* Create a new buffer without a window. Make it the current buffer for
463 * a moment to be able to do the initialisations. */
464 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
465 BLN_NEW | BLN_LISTED);
466 if (buf == NULL || ml_open(buf) == FAIL)
467 {
468 vim_free(term);
469 return NULL;
470 }
471 old_curbuf = curbuf;
472 --curbuf->b_nwindows;
473 curbuf = buf;
474 curwin->w_buffer = buf;
475 ++curbuf->b_nwindows;
476 }
477 else
478 {
479 /* Open a new window or tab. */
480 split_ea.cmdidx = CMD_new;
481 split_ea.cmd = (char_u *)"new";
482 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100483 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200484 {
485 split_ea.line2 = opt->jo_term_rows;
486 split_ea.addr_count = 1;
487 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100488 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200489 {
490 split_ea.line2 = opt->jo_term_cols;
491 split_ea.addr_count = 1;
492 }
493
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100494 if (vertical)
495 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200496 ex_splitview(&split_ea);
497 if (curwin == old_curwin)
498 {
499 /* split failed */
500 vim_free(term);
501 return NULL;
502 }
503 }
504 term->tl_buffer = curbuf;
505 curbuf->b_term = term;
506
507 if (!opt->jo_hidden)
508 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100509 /* Only one size was taken care of with :new, do the other one. With
510 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100511 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200512 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100513 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200514 win_setwidth(opt->jo_term_cols);
515 }
516
517 /* Link the new terminal in the list of active terminals. */
518 term->tl_next = first_term;
519 first_term = term;
520
521 if (opt->jo_term_name != NULL)
522 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100523 else if (argv != NULL)
524 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200525 else
526 {
527 int i;
528 size_t len;
529 char_u *cmd, *p;
530
531 if (argvar->v_type == VAR_STRING)
532 {
533 cmd = argvar->vval.v_string;
534 if (cmd == NULL)
535 cmd = (char_u *)"";
536 else if (STRCMP(cmd, "NONE") == 0)
537 cmd = (char_u *)"pty";
538 }
539 else if (argvar->v_type != VAR_LIST
540 || argvar->vval.v_list == NULL
541 || argvar->vval.v_list->lv_len < 1
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100542 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200543 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
544 cmd = (char_u*)"";
545
546 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200547 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200548
549 for (i = 0; p != NULL; ++i)
550 {
551 /* Prepend a ! to the command name to avoid the buffer name equals
552 * the executable, otherwise ":w!" would overwrite it. */
553 if (i == 0)
554 vim_snprintf((char *)p, len, "!%s", cmd);
555 else
556 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
557 if (buflist_findname(p) == NULL)
558 {
559 vim_free(curbuf->b_ffname);
560 curbuf->b_ffname = p;
561 break;
562 }
563 }
564 }
565 curbuf->b_fname = curbuf->b_ffname;
566
567 if (opt->jo_term_opencmd != NULL)
568 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
569
570 if (opt->jo_eof_chars != NULL)
571 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
572
573 set_string_option_direct((char_u *)"buftype", -1,
574 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200575 // Avoid that 'buftype' is reset when this buffer is entered.
576 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200577
578 /* Mark the buffer as not modifiable. It can only be made modifiable after
579 * the job finished. */
580 curbuf->b_p_ma = FALSE;
581
582 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100583#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200584 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
585#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200586 setup_job_options(opt, term->tl_rows, term->tl_cols);
587
Bram Moolenaar13568252018-03-16 20:46:58 +0100588 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100589 return curbuf;
590
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100591#if defined(FEAT_SESSION)
592 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100593 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100594 {
595 term->tl_command = vim_strsave((char_u *)"NONE");
596 }
597 else if (argvar->v_type == VAR_STRING)
598 {
599 char_u *cmd = argvar->vval.v_string;
600
601 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
602 term->tl_command = vim_strsave(cmd);
603 }
604 else if (argvar->v_type == VAR_LIST
605 && argvar->vval.v_list != NULL
606 && argvar->vval.v_list->lv_len > 0)
607 {
608 garray_T ga;
609 listitem_T *item;
610
611 ga_init2(&ga, 1, 100);
612 for (item = argvar->vval.v_list->lv_first;
613 item != NULL; item = item->li_next)
614 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100615 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100616 char_u *p;
617
618 if (s == NULL)
619 break;
620 p = vim_strsave_fnameescape(s, FALSE);
621 if (p == NULL)
622 break;
623 ga_concat(&ga, p);
624 vim_free(p);
625 ga_append(&ga, ' ');
626 }
627 if (item == NULL)
628 {
629 ga_append(&ga, NUL);
630 term->tl_command = ga.ga_data;
631 }
632 else
633 ga_clear(&ga);
634 }
635#endif
636
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100637 if (opt->jo_term_kill != NULL)
638 {
639 char_u *p = skiptowhite(opt->jo_term_kill);
640
641 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
642 }
643
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200644 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100645 if (argv == NULL
646 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200647 && argvar->vval.v_string != NULL
648 && STRCMP(argvar->vval.v_string, "NONE") == 0)
649 res = create_pty_only(term, opt);
650 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200651 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200652
653 newbuf = curbuf;
654 if (res == OK)
655 {
656 /* Get and remember the size we ended up with. Update the pty. */
657 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
658 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100659#ifdef FEAT_GUI
660 if (term->tl_system)
661 {
662 /* display first line below typed command */
663 term->tl_toprow = msg_row + 1;
664 term->tl_dirty_row_end = 0;
665 }
666#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200667
668 /* Make sure we don't get stuck on sending keys to the job, it leads to
669 * a deadlock if the job is waiting for Vim to read. */
670 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
671
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200672 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200673 {
674 --curbuf->b_nwindows;
675 curbuf = old_curbuf;
676 curwin->w_buffer = curbuf;
677 ++curbuf->b_nwindows;
678 }
679 }
680 else
681 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100682 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200683 return NULL;
684 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100685
Bram Moolenaar13568252018-03-16 20:46:58 +0100686 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200687 return newbuf;
688}
689
690/*
691 * ":terminal": open a terminal window and execute a job in it.
692 */
693 void
694ex_terminal(exarg_T *eap)
695{
696 typval_T argvar[2];
697 jobopt_T opt;
698 char_u *cmd;
699 char_u *tofree = NULL;
700
701 init_job_options(&opt);
702
703 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100704 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200705 {
706 char_u *p, *ep;
707
708 cmd += 2;
709 p = skiptowhite(cmd);
710 ep = vim_strchr(cmd, '=');
711 if (ep != NULL && ep < p)
712 p = ep;
713
714 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
715 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100716 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
717 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200718 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
719 opt.jo_term_finish = 'o';
720 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
721 opt.jo_curwin = 1;
722 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
723 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100724 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
725 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100726 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
727 && ep != NULL)
728 {
729 opt.jo_set2 |= JO2_TERM_KILL;
730 opt.jo_term_kill = ep + 1;
731 p = skiptowhite(cmd);
732 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200733 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
734 && ep != NULL && isdigit(ep[1]))
735 {
736 opt.jo_set2 |= JO2_TERM_ROWS;
737 opt.jo_term_rows = atoi((char *)ep + 1);
738 p = skiptowhite(cmd);
739 }
740 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
741 && ep != NULL && isdigit(ep[1]))
742 {
743 opt.jo_set2 |= JO2_TERM_COLS;
744 opt.jo_term_cols = atoi((char *)ep + 1);
745 p = skiptowhite(cmd);
746 }
747 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
748 && ep != NULL)
749 {
750 char_u *buf = NULL;
751 char_u *keys;
752
753 p = skiptowhite(cmd);
754 *p = NUL;
755 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
756 opt.jo_set2 |= JO2_EOF_CHARS;
757 opt.jo_eof_chars = vim_strsave(keys);
758 vim_free(buf);
759 *p = ' ';
760 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100761#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100762 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
763 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100764 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100765 int tty_type = NUL;
766
767 p = skiptowhite(cmd);
768 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
769 tty_type = 'w';
770 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
771 tty_type = 'c';
772 else
773 {
774 semsg(e_invargval, "type");
775 goto theend;
776 }
777 opt.jo_set2 |= JO2_TTY_TYPE;
778 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100779 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100780#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200781 else
782 {
783 if (*p)
784 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100785 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100786 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200787 }
788 cmd = skipwhite(p);
789 }
790 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100791 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200792 /* Make a copy of 'shell', an autocommand may change the option. */
793 tofree = cmd = vim_strsave(p_sh);
794
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100795 /* default to close when the shell exits */
796 if (opt.jo_term_finish == NUL)
797 opt.jo_term_finish = 'c';
798 }
799
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200800 if (eap->addr_count > 0)
801 {
802 /* Write lines from current buffer to the job. */
803 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
804 opt.jo_io[PART_IN] = JIO_BUFFER;
805 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
806 opt.jo_in_top = eap->line1;
807 opt.jo_in_bot = eap->line2;
808 }
809
810 argvar[0].v_type = VAR_STRING;
811 argvar[0].vval.v_string = cmd;
812 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100813 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200814 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100815
816theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200817 vim_free(opt.jo_eof_chars);
818}
819
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100820#if defined(FEAT_SESSION) || defined(PROTO)
821/*
822 * Write a :terminal command to the session file to restore the terminal in
823 * window "wp".
824 * Return FAIL if writing fails.
825 */
826 int
827term_write_session(FILE *fd, win_T *wp)
828{
829 term_T *term = wp->w_buffer->b_term;
830
831 /* Create the terminal and run the command. This is not without
832 * risk, but let's assume the user only creates a session when this
833 * will be OK. */
834 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
835 term->tl_cols, term->tl_rows) < 0)
836 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100837#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100838 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
839 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100840#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100841 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
842 return FAIL;
843
844 return put_eol(fd);
845}
846
847/*
848 * Return TRUE if "buf" has a terminal that should be restored.
849 */
850 int
851term_should_restore(buf_T *buf)
852{
853 term_T *term = buf->b_term;
854
855 return term != NULL && (term->tl_command == NULL
856 || STRCMP(term->tl_command, "NONE") != 0);
857}
858#endif
859
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200860/*
861 * Free the scrollback buffer for "term".
862 */
863 static void
864free_scrollback(term_T *term)
865{
866 int i;
867
868 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
869 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
870 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100871 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
872 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
873 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200874}
875
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100876
877// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200878static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100879
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200880/*
881 * Free a terminal and everything it refers to.
882 * Kills the job if there is one.
883 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100884 * The actual terminal structure is freed later in free_unused_terminals(),
885 * because callbacks may wipe out a buffer while the terminal is still
886 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200887 */
888 void
889free_terminal(buf_T *buf)
890{
891 term_T *term = buf->b_term;
892 term_T *tp;
893
894 if (term == NULL)
895 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100896
897 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200898 if (first_term == term)
899 first_term = term->tl_next;
900 else
901 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
902 if (tp->tl_next == term)
903 {
904 tp->tl_next = term->tl_next;
905 break;
906 }
907
908 if (term->tl_job != NULL)
909 {
910 if (term->tl_job->jv_status != JOB_ENDED
911 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100912 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200913 job_stop(term->tl_job, NULL, "kill");
914 job_unref(term->tl_job);
915 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100916 term->tl_next = terminals_to_free;
917 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200918
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200919 buf->b_term = NULL;
920 if (in_terminal_loop == term)
921 in_terminal_loop = NULL;
922}
923
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100924 void
925free_unused_terminals()
926{
927 while (terminals_to_free != NULL)
928 {
929 term_T *term = terminals_to_free;
930
931 terminals_to_free = term->tl_next;
932
933 free_scrollback(term);
934
935 term_free_vterm(term);
936 vim_free(term->tl_title);
937#ifdef FEAT_SESSION
938 vim_free(term->tl_command);
939#endif
940 vim_free(term->tl_kill);
941 vim_free(term->tl_status_text);
942 vim_free(term->tl_opencmd);
943 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100944 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100945#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100946 if (term->tl_out_fd != NULL)
947 fclose(term->tl_out_fd);
948#endif
949 vim_free(term->tl_cursor_color);
950 vim_free(term);
951 }
952}
953
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200954/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100955 * Get the part that is connected to the tty. Normally this is PART_IN, but
956 * when writing buffer lines to the job it can be another. This makes it
957 * possible to do "1,5term vim -".
958 */
959 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200960get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100961{
962#ifdef UNIX
963 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
964 int i;
965
966 for (i = 0; i < 3; ++i)
967 {
968 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
969
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +0100970 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100971 return parts[i];
972 }
973#endif
974 return PART_IN;
975}
976
977/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200978 * Write job output "msg[len]" to the vterm.
979 */
980 static void
981term_write_job_output(term_T *term, char_u *msg, size_t len)
982{
983 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100984 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200985
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100986 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200987
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100988 /* flush vterm buffer when vterm responded to control sequence */
989 if (prevlen != vterm_output_get_buffer_current(vterm))
990 {
991 char buf[KEY_BUF_LEN];
992 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
993
994 if (curlen > 0)
995 channel_send(term->tl_job->jv_channel, get_tty_part(term),
996 (char_u *)buf, (int)curlen, NULL);
997 }
998
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200999 /* this invokes the damage callbacks */
1000 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1001}
1002
1003 static void
1004update_cursor(term_T *term, int redraw)
1005{
1006 if (term->tl_normal_mode)
1007 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001008#ifdef FEAT_GUI
1009 if (term->tl_system)
1010 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1011 term->tl_cursor_pos.col);
1012 else
1013#endif
1014 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001015 if (redraw)
1016 {
1017 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1018 cursor_on();
1019 out_flush();
1020#ifdef FEAT_GUI
1021 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001022 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001023 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001024 gui_mch_flush();
1025 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001026#endif
1027 }
1028}
1029
1030/*
1031 * Invoked when "msg" output from a job was received. Write it to the terminal
1032 * of "buffer".
1033 */
1034 void
1035write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1036{
1037 size_t len = STRLEN(msg);
1038 term_T *term = buffer->b_term;
1039
Bram Moolenaar4f974752019-02-17 17:44:42 +01001040#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001041 /* Win32: Cannot redirect output of the job, intercept it here and write to
1042 * the file. */
1043 if (term->tl_out_fd != NULL)
1044 {
1045 ch_log(channel, "Writing %d bytes to output file", (int)len);
1046 fwrite(msg, len, 1, term->tl_out_fd);
1047 return;
1048 }
1049#endif
1050
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001051 if (term->tl_vterm == NULL)
1052 {
1053 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1054 return;
1055 }
1056 ch_log(channel, "writing %d bytes to terminal", (int)len);
1057 term_write_job_output(term, msg, len);
1058
Bram Moolenaar13568252018-03-16 20:46:58 +01001059#ifdef FEAT_GUI
1060 if (term->tl_system)
1061 {
1062 /* show system output, scrolling up the screen as needed */
1063 update_system_term(term);
1064 update_cursor(term, TRUE);
1065 }
1066 else
1067#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001068 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
1069 * contents, thus no screen update is needed. */
1070 if (!term->tl_normal_mode)
1071 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001072 // Don't use update_screen() when editing the command line, it gets
1073 // cleared.
1074 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001075 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001076 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001077 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001078 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001079 /* update_screen() can be slow, check the terminal wasn't closed
1080 * already */
1081 if (buffer == curbuf && curbuf->b_term != NULL)
1082 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001083 }
1084 else
1085 redraw_after_callback(TRUE);
1086 }
1087}
1088
1089/*
1090 * Send a mouse position and click to the vterm
1091 */
1092 static int
1093term_send_mouse(VTerm *vterm, int button, int pressed)
1094{
1095 VTermModifier mod = VTERM_MOD_NONE;
1096
1097 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001098 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001099 if (button != 0)
1100 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001101 return TRUE;
1102}
1103
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001104static int enter_mouse_col = -1;
1105static int enter_mouse_row = -1;
1106
1107/*
1108 * Handle a mouse click, drag or release.
1109 * Return TRUE when a mouse event is sent to the terminal.
1110 */
1111 static int
1112term_mouse_click(VTerm *vterm, int key)
1113{
1114#if defined(FEAT_CLIPBOARD)
1115 /* For modeless selection mouse drag and release events are ignored, unless
1116 * they are preceded with a mouse down event */
1117 static int ignore_drag_release = TRUE;
1118 VTermMouseState mouse_state;
1119
1120 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1121 if (mouse_state.flags == 0)
1122 {
1123 /* Terminal is not using the mouse, use modeless selection. */
1124 switch (key)
1125 {
1126 case K_LEFTDRAG:
1127 case K_LEFTRELEASE:
1128 case K_RIGHTDRAG:
1129 case K_RIGHTRELEASE:
1130 /* Ignore drag and release events when the button-down wasn't
1131 * seen before. */
1132 if (ignore_drag_release)
1133 {
1134 int save_mouse_col, save_mouse_row;
1135
1136 if (enter_mouse_col < 0)
1137 break;
1138
1139 /* mouse click in the window gave us focus, handle that
1140 * click now */
1141 save_mouse_col = mouse_col;
1142 save_mouse_row = mouse_row;
1143 mouse_col = enter_mouse_col;
1144 mouse_row = enter_mouse_row;
1145 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1146 mouse_col = save_mouse_col;
1147 mouse_row = save_mouse_row;
1148 }
1149 /* FALLTHROUGH */
1150 case K_LEFTMOUSE:
1151 case K_RIGHTMOUSE:
1152 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1153 ignore_drag_release = TRUE;
1154 else
1155 ignore_drag_release = FALSE;
1156 /* Should we call mouse_has() here? */
1157 if (clip_star.available)
1158 {
1159 int button, is_click, is_drag;
1160
1161 button = get_mouse_button(KEY2TERMCAP1(key),
1162 &is_click, &is_drag);
1163 if (mouse_model_popup() && button == MOUSE_LEFT
1164 && (mod_mask & MOD_MASK_SHIFT))
1165 {
1166 /* Translate shift-left to right button. */
1167 button = MOUSE_RIGHT;
1168 mod_mask &= ~MOD_MASK_SHIFT;
1169 }
1170 clip_modeless(button, is_click, is_drag);
1171 }
1172 break;
1173
1174 case K_MIDDLEMOUSE:
1175 if (clip_star.available)
1176 insert_reg('*', TRUE);
1177 break;
1178 }
1179 enter_mouse_col = -1;
1180 return FALSE;
1181 }
1182#endif
1183 enter_mouse_col = -1;
1184
1185 switch (key)
1186 {
1187 case K_LEFTMOUSE:
1188 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1189 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1190 case K_LEFTRELEASE:
1191 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1192 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1193 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1194 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1195 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1196 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1197 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1198 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1199 }
1200 return TRUE;
1201}
1202
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001203/*
1204 * Convert typed key "c" into bytes to send to the job.
1205 * Return the number of bytes in "buf".
1206 */
1207 static int
1208term_convert_key(term_T *term, int c, char *buf)
1209{
1210 VTerm *vterm = term->tl_vterm;
1211 VTermKey key = VTERM_KEY_NONE;
1212 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001213 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001214
1215 switch (c)
1216 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001217 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1218
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001219 /* don't use VTERM_KEY_BACKSPACE, it always
1220 * becomes 0x7f DEL */
1221 case K_BS: c = term_backspace_char; break;
1222
1223 case ESC: key = VTERM_KEY_ESCAPE; break;
1224 case K_DEL: key = VTERM_KEY_DEL; break;
1225 case K_DOWN: key = VTERM_KEY_DOWN; break;
1226 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1227 key = VTERM_KEY_DOWN; break;
1228 case K_END: key = VTERM_KEY_END; break;
1229 case K_S_END: mod = VTERM_MOD_SHIFT;
1230 key = VTERM_KEY_END; break;
1231 case K_C_END: mod = VTERM_MOD_CTRL;
1232 key = VTERM_KEY_END; break;
1233 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1234 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1235 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1236 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1237 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1238 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1239 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1240 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1241 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1242 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1243 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1244 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1245 case K_HOME: key = VTERM_KEY_HOME; break;
1246 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1247 key = VTERM_KEY_HOME; break;
1248 case K_C_HOME: mod = VTERM_MOD_CTRL;
1249 key = VTERM_KEY_HOME; break;
1250 case K_INS: key = VTERM_KEY_INS; break;
1251 case K_K0: key = VTERM_KEY_KP_0; break;
1252 case K_K1: key = VTERM_KEY_KP_1; break;
1253 case K_K2: key = VTERM_KEY_KP_2; break;
1254 case K_K3: key = VTERM_KEY_KP_3; break;
1255 case K_K4: key = VTERM_KEY_KP_4; break;
1256 case K_K5: key = VTERM_KEY_KP_5; break;
1257 case K_K6: key = VTERM_KEY_KP_6; break;
1258 case K_K7: key = VTERM_KEY_KP_7; break;
1259 case K_K8: key = VTERM_KEY_KP_8; break;
1260 case K_K9: key = VTERM_KEY_KP_9; break;
1261 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1262 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1263 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1264 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1265 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1266 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1267 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1268 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1269 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1270 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1271 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1272 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1273 case K_LEFT: key = VTERM_KEY_LEFT; break;
1274 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1275 key = VTERM_KEY_LEFT; break;
1276 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1277 key = VTERM_KEY_LEFT; break;
1278 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1279 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1280 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1281 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1282 key = VTERM_KEY_RIGHT; break;
1283 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1284 key = VTERM_KEY_RIGHT; break;
1285 case K_UP: key = VTERM_KEY_UP; break;
1286 case K_S_UP: mod = VTERM_MOD_SHIFT;
1287 key = VTERM_KEY_UP; break;
1288 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001289 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1290 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001291
Bram Moolenaara42ad572017-11-16 13:08:04 +01001292 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1293 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001294 case K_MOUSELEFT: /* TODO */ return 0;
1295 case K_MOUSERIGHT: /* TODO */ return 0;
1296
1297 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001298 case K_LEFTMOUSE_NM:
1299 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001300 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001301 case K_LEFTRELEASE_NM:
1302 case K_MOUSEMOVE:
1303 case K_MIDDLEMOUSE:
1304 case K_MIDDLEDRAG:
1305 case K_MIDDLERELEASE:
1306 case K_RIGHTMOUSE:
1307 case K_RIGHTDRAG:
1308 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1309 return 0;
1310 other = TRUE;
1311 break;
1312
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001313 case K_X1MOUSE: /* TODO */ return 0;
1314 case K_X1DRAG: /* TODO */ return 0;
1315 case K_X1RELEASE: /* TODO */ return 0;
1316 case K_X2MOUSE: /* TODO */ return 0;
1317 case K_X2DRAG: /* TODO */ return 0;
1318 case K_X2RELEASE: /* TODO */ return 0;
1319
1320 case K_IGNORE: return 0;
1321 case K_NOP: return 0;
1322 case K_UNDO: return 0;
1323 case K_HELP: return 0;
1324 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1325 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1326 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1327 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1328 case K_SELECT: return 0;
1329#ifdef FEAT_GUI
1330 case K_VER_SCROLLBAR: return 0;
1331 case K_HOR_SCROLLBAR: return 0;
1332#endif
1333#ifdef FEAT_GUI_TABLINE
1334 case K_TABLINE: return 0;
1335 case K_TABMENU: return 0;
1336#endif
1337#ifdef FEAT_NETBEANS_INTG
1338 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1339#endif
1340#ifdef FEAT_DND
1341 case K_DROP: return 0;
1342#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001343 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001344 case K_PS: vterm_keyboard_start_paste(vterm);
1345 other = TRUE;
1346 break;
1347 case K_PE: vterm_keyboard_end_paste(vterm);
1348 other = TRUE;
1349 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001350 }
1351
1352 /*
1353 * Convert special keys to vterm keys:
1354 * - Write keys to vterm: vterm_keyboard_key()
1355 * - Write output to channel.
1356 * TODO: use mod_mask
1357 */
1358 if (key != VTERM_KEY_NONE)
1359 /* Special key, let vterm convert it. */
1360 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001361 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001362 /* Normal character, let vterm convert it. */
1363 vterm_keyboard_unichar(vterm, c, mod);
1364
1365 /* Read back the converted escape sequence. */
1366 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1367}
1368
1369/*
1370 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001371 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001372 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001373 */
1374 static int
1375term_job_running_check(term_T *term, int check_job_status)
1376{
1377 /* Also consider the job finished when the channel is closed, to avoid a
1378 * race condition when updating the title. */
1379 if (term != NULL
1380 && term->tl_job != NULL
1381 && channel_is_open(term->tl_job->jv_channel))
1382 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001383 job_T *job = term->tl_job;
1384
1385 // Careful: Checking the job status may invoked callbacks, which close
1386 // the buffer and terminate "term". However, "job" will not be freed
1387 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001388 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001389 job_status(job);
1390 return (job->jv_status == JOB_STARTED
1391 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001392 }
1393 return FALSE;
1394}
1395
1396/*
1397 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001398 */
1399 int
1400term_job_running(term_T *term)
1401{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001402 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001403}
1404
1405/*
1406 * Return TRUE if "term" has an active channel and used ":term NONE".
1407 */
1408 int
1409term_none_open(term_T *term)
1410{
1411 /* Also consider the job finished when the channel is closed, to avoid a
1412 * race condition when updating the title. */
1413 return term != NULL
1414 && term->tl_job != NULL
1415 && channel_is_open(term->tl_job->jv_channel)
1416 && term->tl_job->jv_channel->ch_keep_open;
1417}
1418
1419/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001420 * Used when exiting: kill the job in "buf" if so desired.
1421 * Return OK when the job finished.
1422 * Return FAIL when the job is still running.
1423 */
1424 int
1425term_try_stop_job(buf_T *buf)
1426{
1427 int count;
1428 char *how = (char *)buf->b_term->tl_kill;
1429
1430#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1431 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1432 {
1433 char_u buff[DIALOG_MSG_SIZE];
1434 int ret;
1435
1436 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1437 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1438 if (ret == VIM_YES)
1439 how = "kill";
1440 else if (ret == VIM_CANCEL)
1441 return FAIL;
1442 }
1443#endif
1444 if (how == NULL || *how == NUL)
1445 return FAIL;
1446
1447 job_stop(buf->b_term->tl_job, NULL, how);
1448
Bram Moolenaar9172d232019-01-29 23:06:54 +01001449 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001450 for (count = 0; count < 100; ++count)
1451 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001452 job_T *job;
1453
1454 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001455 if (!buf_valid(buf)
1456 || buf->b_term == NULL
1457 || buf->b_term->tl_job == NULL)
1458 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001459 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001460
Bram Moolenaar9172d232019-01-29 23:06:54 +01001461 // Call job_status() to update jv_status. It may cause the job to be
1462 // cleaned up but it won't be freed.
1463 job_status(job);
1464 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001465 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001466
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001467 ui_delay(10L, FALSE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001468 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001469 }
1470 return FAIL;
1471}
1472
1473/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001474 * Add the last line of the scrollback buffer to the buffer in the window.
1475 */
1476 static void
1477add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1478{
1479 buf_T *buf = term->tl_buffer;
1480 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1481 linenr_T lnum = buf->b_ml.ml_line_count;
1482
Bram Moolenaar4f974752019-02-17 17:44:42 +01001483#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001484 if (!enc_utf8 && enc_codepage > 0)
1485 {
1486 WCHAR *ret = NULL;
1487 int length = 0;
1488
1489 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1490 &ret, &length);
1491 if (ret != NULL)
1492 {
1493 WideCharToMultiByte_alloc(enc_codepage, 0,
1494 ret, length, (char **)&text, &len, 0, 0);
1495 vim_free(ret);
1496 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1497 vim_free(text);
1498 }
1499 }
1500 else
1501#endif
1502 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1503 if (empty)
1504 {
1505 /* Delete the empty line that was in the empty buffer. */
1506 curbuf = buf;
1507 ml_delete(1, FALSE);
1508 curbuf = curwin->w_buffer;
1509 }
1510}
1511
1512 static void
1513cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1514{
1515 attr->width = cell->width;
1516 attr->attrs = cell->attrs;
1517 attr->fg = cell->fg;
1518 attr->bg = cell->bg;
1519}
1520
1521 static int
1522equal_celattr(cellattr_T *a, cellattr_T *b)
1523{
1524 /* Comparing the colors should be sufficient. */
1525 return a->fg.red == b->fg.red
1526 && a->fg.green == b->fg.green
1527 && a->fg.blue == b->fg.blue
1528 && a->bg.red == b->bg.red
1529 && a->bg.green == b->bg.green
1530 && a->bg.blue == b->bg.blue;
1531}
1532
Bram Moolenaard96ff162018-02-18 22:13:29 +01001533/*
1534 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1535 * line at this position. Otherwise at the end.
1536 */
1537 static int
1538add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1539{
1540 if (ga_grow(&term->tl_scrollback, 1) == OK)
1541 {
1542 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1543 + term->tl_scrollback.ga_len;
1544
1545 if (lnum > 0)
1546 {
1547 int i;
1548
1549 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1550 {
1551 *line = *(line - 1);
1552 --line;
1553 }
1554 }
1555 line->sb_cols = 0;
1556 line->sb_cells = NULL;
1557 line->sb_fill_attr = *fill_attr;
1558 ++term->tl_scrollback.ga_len;
1559 return OK;
1560 }
1561 return FALSE;
1562}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001563
1564/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001565 * Remove the terminal contents from the scrollback and the buffer.
1566 * Used before adding a new scrollback line or updating the buffer for lines
1567 * displayed in the terminal.
1568 */
1569 static void
1570cleanup_scrollback(term_T *term)
1571{
1572 sb_line_T *line;
1573 garray_T *gap;
1574
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001575 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001576 gap = &term->tl_scrollback;
1577 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1578 && gap->ga_len > 0)
1579 {
1580 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1581 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1582 vim_free(line->sb_cells);
1583 --gap->ga_len;
1584 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001585 curbuf = curwin->w_buffer;
1586 if (curbuf == term->tl_buffer)
1587 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001588}
1589
1590/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001591 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001592 */
1593 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001594update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001595{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001596 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001597 int len;
1598 int lines_skipped = 0;
1599 VTermPos pos;
1600 VTermScreenCell cell;
1601 cellattr_T fill_attr, new_fill_attr;
1602 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001603
1604 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1605 "Adding terminal window snapshot to buffer");
1606
1607 /* First remove the lines that were appended before, they might be
1608 * outdated. */
1609 cleanup_scrollback(term);
1610
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001611 screen = vterm_obtain_screen(term->tl_vterm);
1612 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001613 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1614 {
1615 len = 0;
1616 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1617 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1618 && cell.chars[0] != NUL)
1619 {
1620 len = pos.col + 1;
1621 new_fill_attr = term->tl_default_color;
1622 }
1623 else
1624 /* Assume the last attr is the filler attr. */
1625 cell2cellattr(&cell, &new_fill_attr);
1626
1627 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1628 ++lines_skipped;
1629 else
1630 {
1631 while (lines_skipped > 0)
1632 {
1633 /* Line was skipped, add an empty line. */
1634 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001635 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001636 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001637 }
1638
1639 if (len == 0)
1640 p = NULL;
1641 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001642 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001643 if ((p != NULL || len == 0)
1644 && ga_grow(&term->tl_scrollback, 1) == OK)
1645 {
1646 garray_T ga;
1647 int width;
1648 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1649 + term->tl_scrollback.ga_len;
1650
1651 ga_init2(&ga, 1, 100);
1652 for (pos.col = 0; pos.col < len; pos.col += width)
1653 {
1654 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1655 {
1656 width = 1;
1657 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1658 if (ga_grow(&ga, 1) == OK)
1659 ga.ga_len += utf_char2bytes(' ',
1660 (char_u *)ga.ga_data + ga.ga_len);
1661 }
1662 else
1663 {
1664 width = cell.width;
1665
1666 cell2cellattr(&cell, &p[pos.col]);
1667
Bram Moolenaara79fd562018-12-20 20:47:32 +01001668 // Each character can be up to 6 bytes.
1669 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001670 {
1671 int i;
1672 int c;
1673
1674 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1675 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1676 (char_u *)ga.ga_data + ga.ga_len);
1677 }
1678 }
1679 }
1680 line->sb_cols = len;
1681 line->sb_cells = p;
1682 line->sb_fill_attr = new_fill_attr;
1683 fill_attr = new_fill_attr;
1684 ++term->tl_scrollback.ga_len;
1685
1686 if (ga_grow(&ga, 1) == FAIL)
1687 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1688 else
1689 {
1690 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1691 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1692 }
1693 ga_clear(&ga);
1694 }
1695 else
1696 vim_free(p);
1697 }
1698 }
1699
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001700 // Add trailing empty lines.
1701 for (pos.row = term->tl_scrollback.ga_len;
1702 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1703 ++pos.row)
1704 {
1705 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1706 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1707 }
1708
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001709 term->tl_dirty_snapshot = FALSE;
1710#ifdef FEAT_TIMERS
1711 term->tl_timer_set = FALSE;
1712#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001713}
1714
1715/*
1716 * If needed, add the current lines of the terminal to scrollback and to the
1717 * buffer. Called after the job has ended and when switching to
1718 * Terminal-Normal mode.
1719 * When "redraw" is TRUE redraw the windows that show the terminal.
1720 */
1721 static void
1722may_move_terminal_to_buffer(term_T *term, int redraw)
1723{
1724 win_T *wp;
1725
1726 if (term->tl_vterm == NULL)
1727 return;
1728
1729 /* Update the snapshot only if something changes or the buffer does not
1730 * have all the lines. */
1731 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1732 <= term->tl_scrollback_scrolled)
1733 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001734
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001735 /* Obtain the current background color. */
1736 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1737 &term->tl_default_color.fg, &term->tl_default_color.bg);
1738
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001739 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001740 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001741 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001742 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001743 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001744 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1745 wp->w_cursor.col = 0;
1746 wp->w_valid = 0;
1747 if (wp->w_cursor.lnum >= wp->w_height)
1748 {
1749 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001750
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001751 if (wp->w_topline < min_topline)
1752 wp->w_topline = min_topline;
1753 }
1754 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001755 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001756 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001757}
1758
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001759#if defined(FEAT_TIMERS) || defined(PROTO)
1760/*
1761 * Check if any terminal timer expired. If so, copy text from the terminal to
1762 * the buffer.
1763 * Return the time until the next timer will expire.
1764 */
1765 int
1766term_check_timers(int next_due_arg, proftime_T *now)
1767{
1768 term_T *term;
1769 int next_due = next_due_arg;
1770
1771 for (term = first_term; term != NULL; term = term->tl_next)
1772 {
1773 if (term->tl_timer_set && !term->tl_normal_mode)
1774 {
1775 long this_due = proftime_time_left(&term->tl_timer_due, now);
1776
1777 if (this_due <= 1)
1778 {
1779 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001780 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001781 }
1782 else if (next_due == -1 || next_due > this_due)
1783 next_due = this_due;
1784 }
1785 }
1786
1787 return next_due;
1788}
1789#endif
1790
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001791/*
1792 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1793 * otherwise end it.
1794 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001795 static void
1796set_terminal_mode(term_T *term, int normal_mode)
1797{
1798 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001799 if (!normal_mode)
1800 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001801 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001802 if (term->tl_buffer == curbuf)
1803 maketitle();
1804}
1805
1806/*
1807 * Called after the job if finished and Terminal mode is not active:
1808 * Move the vterm contents into the scrollback buffer and free the vterm.
1809 */
1810 static void
1811cleanup_vterm(term_T *term)
1812{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001813 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001814 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001815 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001816 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001817}
1818
1819/*
1820 * Switch from Terminal-Job mode to Terminal-Normal mode.
1821 * Suspends updating the terminal window.
1822 */
1823 static void
1824term_enter_normal_mode(void)
1825{
1826 term_T *term = curbuf->b_term;
1827
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001828 set_terminal_mode(term, TRUE);
1829
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001830 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001831 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001832
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001833 /* Move the window cursor to the position of the cursor in the
1834 * terminal. */
1835 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1836 + term->tl_cursor_pos.row + 1;
1837 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001838 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1839 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001840
1841 /* Display the same lines as in the terminal. */
1842 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1843}
1844
1845/*
1846 * Returns TRUE if the current window contains a terminal and we are in
1847 * Terminal-Normal mode.
1848 */
1849 int
1850term_in_normal_mode(void)
1851{
1852 term_T *term = curbuf->b_term;
1853
1854 return term != NULL && term->tl_normal_mode;
1855}
1856
1857/*
1858 * Switch from Terminal-Normal mode to Terminal-Job mode.
1859 * Restores updating the terminal window.
1860 */
1861 void
1862term_enter_job_mode()
1863{
1864 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001865
1866 set_terminal_mode(term, FALSE);
1867
1868 if (term->tl_channel_closed)
1869 cleanup_vterm(term);
1870 redraw_buf_and_status_later(curbuf, NOT_VALID);
1871}
1872
1873/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001874 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875 * Note: while waiting a terminal may be closed and freed if the channel is
1876 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001877 */
1878 static int
1879term_vgetc()
1880{
1881 int c;
1882 int save_State = State;
1883
1884 State = TERMINAL;
1885 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001886#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001887 ctrl_break_was_pressed = FALSE;
1888#endif
1889 c = vgetc();
1890 got_int = FALSE;
1891 State = save_State;
1892 return c;
1893}
1894
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001895static int mouse_was_outside = FALSE;
1896
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001898 * Send keys to terminal.
1899 * Return FAIL when the key needs to be handled in Normal mode.
1900 * Return OK when the key was dropped or sent to the terminal.
1901 */
1902 int
1903send_keys_to_term(term_T *term, int c, int typed)
1904{
1905 char msg[KEY_BUF_LEN];
1906 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001907 int dragging_outside = FALSE;
1908
1909 /* Catch keys that need to be handled as in Normal mode. */
1910 switch (c)
1911 {
1912 case NUL:
1913 case K_ZERO:
1914 if (typed)
1915 stuffcharReadbuff(c);
1916 return FAIL;
1917
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001918 case K_TABLINE:
1919 stuffcharReadbuff(c);
1920 return FAIL;
1921
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001922 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001923 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001924 return FAIL;
1925
1926 case K_LEFTDRAG:
1927 case K_MIDDLEDRAG:
1928 case K_RIGHTDRAG:
1929 case K_X1DRAG:
1930 case K_X2DRAG:
1931 dragging_outside = mouse_was_outside;
1932 /* FALLTHROUGH */
1933 case K_LEFTMOUSE:
1934 case K_LEFTMOUSE_NM:
1935 case K_LEFTRELEASE:
1936 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001937 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001938 case K_MIDDLEMOUSE:
1939 case K_MIDDLERELEASE:
1940 case K_RIGHTMOUSE:
1941 case K_RIGHTRELEASE:
1942 case K_X1MOUSE:
1943 case K_X1RELEASE:
1944 case K_X2MOUSE:
1945 case K_X2RELEASE:
1946
1947 case K_MOUSEUP:
1948 case K_MOUSEDOWN:
1949 case K_MOUSELEFT:
1950 case K_MOUSERIGHT:
1951 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001952 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001953 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001954 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001955 || dragging_outside)
1956 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001957 /* click or scroll outside the current window or on status line
1958 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001959 if (typed)
1960 {
1961 stuffcharReadbuff(c);
1962 mouse_was_outside = TRUE;
1963 }
1964 return FAIL;
1965 }
1966 }
1967 if (typed)
1968 mouse_was_outside = FALSE;
1969
1970 /* Convert the typed key to a sequence of bytes for the job. */
1971 len = term_convert_key(term, c, msg);
1972 if (len > 0)
1973 /* TODO: if FAIL is returned, stop? */
1974 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1975 (char_u *)msg, (int)len, NULL);
1976
1977 return OK;
1978}
1979
1980 static void
1981position_cursor(win_T *wp, VTermPos *pos)
1982{
1983 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1984 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1985 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1986}
1987
1988/*
1989 * Handle CTRL-W "": send register contents to the job.
1990 */
1991 static void
1992term_paste_register(int prev_c UNUSED)
1993{
1994 int c;
1995 list_T *l;
1996 listitem_T *item;
1997 long reglen = 0;
1998 int type;
1999
2000#ifdef FEAT_CMDL_INFO
2001 if (add_to_showcmd(prev_c))
2002 if (add_to_showcmd('"'))
2003 out_flush();
2004#endif
2005 c = term_vgetc();
2006#ifdef FEAT_CMDL_INFO
2007 clear_showcmd();
2008#endif
2009 if (!term_use_loop())
2010 /* job finished while waiting for a character */
2011 return;
2012
2013 /* CTRL-W "= prompt for expression to evaluate. */
2014 if (c == '=' && get_expr_register() != '=')
2015 return;
2016 if (!term_use_loop())
2017 /* job finished while waiting for a character */
2018 return;
2019
2020 l = (list_T *)get_reg_contents(c, GREG_LIST);
2021 if (l != NULL)
2022 {
2023 type = get_reg_type(c, &reglen);
2024 for (item = l->lv_first; item != NULL; item = item->li_next)
2025 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002026 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002027#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 char_u *tmp = s;
2029
2030 if (!enc_utf8 && enc_codepage > 0)
2031 {
2032 WCHAR *ret = NULL;
2033 int length = 0;
2034
2035 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2036 (int)STRLEN(s), &ret, &length);
2037 if (ret != NULL)
2038 {
2039 WideCharToMultiByte_alloc(CP_UTF8, 0,
2040 ret, length, (char **)&s, &length, 0, 0);
2041 vim_free(ret);
2042 }
2043 }
2044#endif
2045 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2046 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002047#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002048 if (tmp != s)
2049 vim_free(s);
2050#endif
2051
2052 if (item->li_next != NULL || type == MLINE)
2053 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2054 (char_u *)"\r", 1, NULL);
2055 }
2056 list_free(l);
2057 }
2058}
2059
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002060/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002061 * Return TRUE when waiting for a character in the terminal, the cursor of the
2062 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002063 */
2064 int
2065terminal_is_active()
2066{
2067 return in_terminal_loop != NULL;
2068}
2069
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002070#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002071 cursorentry_T *
2072term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2073{
2074 term_T *term = in_terminal_loop;
2075 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002076 int id;
2077 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002078
2079 vim_memset(&entry, 0, sizeof(entry));
2080 entry.shape = entry.mshape =
2081 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2082 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2083 SHAPE_BLOCK;
2084 entry.percentage = 20;
2085 if (term->tl_cursor_blink)
2086 {
2087 entry.blinkwait = 700;
2088 entry.blinkon = 400;
2089 entry.blinkoff = 250;
2090 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002091
2092 /* The "Terminal" highlight group overrules the defaults. */
2093 id = syn_name2id((char_u *)"Terminal");
2094 if (id != 0)
2095 {
2096 syn_id2colors(id, &term_fg, &term_bg);
2097 *fg = term_bg;
2098 }
2099 else
2100 *fg = gui.back_pixel;
2101
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002102 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002103 {
2104 if (id != 0)
2105 *bg = term_fg;
2106 else
2107 *bg = gui.norm_pixel;
2108 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002109 else
2110 *bg = color_name2handle(term->tl_cursor_color);
2111 entry.name = "n";
2112 entry.used_for = SHAPE_CURSOR;
2113
2114 return &entry;
2115}
2116#endif
2117
Bram Moolenaard317b382018-02-08 22:33:31 +01002118 static void
2119may_output_cursor_props(void)
2120{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002121 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002122 || last_set_cursor_shape != desired_cursor_shape
2123 || last_set_cursor_blink != desired_cursor_blink)
2124 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002125 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002126 last_set_cursor_shape = desired_cursor_shape;
2127 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002128 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002129 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2130 /* this will restore the initial cursor style, if possible */
2131 ui_cursor_shape_forced(TRUE);
2132 else
2133 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2134 }
2135}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002136
Bram Moolenaard317b382018-02-08 22:33:31 +01002137/*
2138 * Set the cursor color and shape, if not last set to these.
2139 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002140 static void
2141may_set_cursor_props(term_T *term)
2142{
2143#ifdef FEAT_GUI
2144 /* For the GUI the cursor properties are obtained with
2145 * term_get_cursor_shape(). */
2146 if (gui.in_use)
2147 return;
2148#endif
2149 if (in_terminal_loop == term)
2150 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002151 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002152 desired_cursor_shape = term->tl_cursor_shape;
2153 desired_cursor_blink = term->tl_cursor_blink;
2154 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002155 }
2156}
2157
Bram Moolenaard317b382018-02-08 22:33:31 +01002158/*
2159 * Reset the desired cursor properties and restore them when needed.
2160 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002161 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002162prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002163{
2164#ifdef FEAT_GUI
2165 if (gui.in_use)
2166 return;
2167#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002168 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002169 desired_cursor_shape = -1;
2170 desired_cursor_blink = -1;
2171 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002172}
2173
2174/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002175 * Returns TRUE if the current window contains a terminal and we are sending
2176 * keys to the job.
2177 * If "check_job_status" is TRUE update the job status.
2178 */
2179 static int
2180term_use_loop_check(int check_job_status)
2181{
2182 term_T *term = curbuf->b_term;
2183
2184 return term != NULL
2185 && !term->tl_normal_mode
2186 && term->tl_vterm != NULL
2187 && term_job_running_check(term, check_job_status);
2188}
2189
2190/*
2191 * Returns TRUE if the current window contains a terminal and we are sending
2192 * keys to the job.
2193 */
2194 int
2195term_use_loop(void)
2196{
2197 return term_use_loop_check(FALSE);
2198}
2199
2200/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002201 * Called when entering a window with the mouse. If this is a terminal window
2202 * we may want to change state.
2203 */
2204 void
2205term_win_entered()
2206{
2207 term_T *term = curbuf->b_term;
2208
2209 if (term != NULL)
2210 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002211 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002212 {
2213 reset_VIsual_and_resel();
2214 if (State & INSERT)
2215 stop_insert_mode = TRUE;
2216 }
2217 mouse_was_outside = FALSE;
2218 enter_mouse_col = mouse_col;
2219 enter_mouse_row = mouse_row;
2220 }
2221}
2222
2223/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002224 * Wait for input and send it to the job.
2225 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2226 * when there is no more typahead.
2227 * Return when the start of a CTRL-W command is typed or anything else that
2228 * should be handled as a Normal mode command.
2229 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2230 * the terminal was closed.
2231 */
2232 int
2233terminal_loop(int blocking)
2234{
2235 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002236 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002237 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002238#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002239 int tty_fd = curbuf->b_term->tl_job->jv_channel
2240 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002241#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002242 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002243
2244 /* Remember the terminal we are sending keys to. However, the terminal
2245 * might be closed while waiting for a character, e.g. typing "exit" in a
2246 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2247 * stored reference. */
2248 in_terminal_loop = curbuf->b_term;
2249
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002250 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002251 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002252 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002253 if (termwinkey == Ctrl_W)
2254 termwinkey = 0;
2255 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002256 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2257 may_set_cursor_props(curbuf->b_term);
2258
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002259 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002260 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002261#ifdef FEAT_GUI
2262 if (!curbuf->b_term->tl_system)
2263#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002264 // TODO: skip screen update when handling a sequence of keys.
2265 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002266 while (must_redraw != 0)
2267 if (update_screen(0) == FAIL)
2268 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002269 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002270 /* job finished while redrawing */
2271 break;
2272
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002273 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002274 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002275
2276 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002277 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002278 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002279 /* Job finished while waiting for a character. Push back the
2280 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002281 if (c != K_IGNORE)
2282 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002283 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002284 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002285 if (c == K_IGNORE)
2286 continue;
2287
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002288#ifdef UNIX
2289 /*
2290 * The shell or another program may change the tty settings. Getting
2291 * them for every typed character is a bit of overhead, but it's needed
2292 * for the first character typed, e.g. when Vim starts in a shell.
2293 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002294 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002295 {
2296 ttyinfo_T info;
2297
2298 /* Get the current backspace character of the pty. */
2299 if (get_tty_info(tty_fd, &info) == OK)
2300 term_backspace_char = info.backspace;
2301 }
2302#endif
2303
Bram Moolenaar4f974752019-02-17 17:44:42 +01002304#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002305 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2306 * Use CTRL-BREAK to kill the job. */
2307 if (ctrl_break_was_pressed)
2308 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2309#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002310 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002311 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002312 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002313#ifdef FEAT_GUI
2314 && !curbuf->b_term->tl_system
2315#endif
2316 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002317 {
2318 int prev_c = c;
2319
2320#ifdef FEAT_CMDL_INFO
2321 if (add_to_showcmd(c))
2322 out_flush();
2323#endif
2324 c = term_vgetc();
2325#ifdef FEAT_CMDL_INFO
2326 clear_showcmd();
2327#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002328 if (!term_use_loop_check(TRUE)
2329 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002330 /* job finished while waiting for a character */
2331 break;
2332
2333 if (prev_c == Ctrl_BSL)
2334 {
2335 if (c == Ctrl_N)
2336 {
2337 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2338 term_enter_normal_mode();
2339 ret = FAIL;
2340 goto theend;
2341 }
2342 /* Send both keys to the terminal. */
2343 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2344 }
2345 else if (c == Ctrl_C)
2346 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002347 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002348 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2349 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002350 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002351 {
2352 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002353 /* "'termwinkey' .": send 'termwinkey' to the job */
2354 c = termwinkey == 0 ? Ctrl_W : termwinkey;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002355 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002356 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002357 {
2358 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2359 c = Ctrl_BSL;
2360 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002361 else if (c == 'N')
2362 {
2363 /* CTRL-W N : go to Terminal-Normal mode. */
2364 term_enter_normal_mode();
2365 ret = FAIL;
2366 goto theend;
2367 }
2368 else if (c == '"')
2369 {
2370 term_paste_register(prev_c);
2371 continue;
2372 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002373 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002374 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002375 char_u buf[MB_MAXBYTES + 2];
2376
2377 // Put the command into the typeahead buffer, when using the
2378 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2379 buf[0] = Ctrl_W;
2380 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2381 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002382 ret = OK;
2383 goto theend;
2384 }
2385 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002386# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002387 if (!enc_utf8 && has_mbyte && c >= 0x80)
2388 {
2389 WCHAR wc;
2390 char_u mb[3];
2391
2392 mb[0] = (unsigned)c >> 8;
2393 mb[1] = c;
2394 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2395 c = wc;
2396 }
2397# endif
2398 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2399 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002400 if (c == K_MOUSEMOVE)
2401 /* We are sure to come back here, don't reset the cursor color
2402 * and shape to avoid flickering. */
2403 restore_cursor = FALSE;
2404
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002405 ret = OK;
2406 goto theend;
2407 }
2408 }
2409 ret = FAIL;
2410
2411theend:
2412 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002413 if (restore_cursor)
2414 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002415
2416 /* Move a snapshot of the screen contents to the buffer, so that completion
2417 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002418 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2419 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002420
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002421 return ret;
2422}
2423
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002424 static void
2425may_toggle_cursor(term_T *term)
2426{
2427 if (in_terminal_loop == term)
2428 {
2429 if (term->tl_cursor_visible)
2430 cursor_on();
2431 else
2432 cursor_off();
2433 }
2434}
2435
2436/*
2437 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002438 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002439 */
2440 static int
2441color2index(VTermColor *color, int fg, int *boldp)
2442{
2443 int red = color->red;
2444 int blue = color->blue;
2445 int green = color->green;
2446
Bram Moolenaar46359e12017-11-29 22:33:38 +01002447 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002448 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002449 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002450 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002451 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002452 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002453 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002454 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2455 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2456 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002457 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002458 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2459 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2460 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2461 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2462 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2463 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2464 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2465 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2466 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2467 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2468 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002469 }
2470 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002471
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002472 if (t_colors >= 256)
2473 {
2474 if (red == blue && red == green)
2475 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002476 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002477 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002478 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2479 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2480 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002481 int i;
2482
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002483 if (red < 5)
2484 return 17; /* 00/00/00 */
2485 if (red > 245) /* ff/ff/ff */
2486 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002487 for (i = 0; i < 23; ++i)
2488 if (red < cutoff[i])
2489 return i + 233;
2490 return 256;
2491 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002492 {
2493 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2494 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002495
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002496 /* 216-color cube */
2497 for (ri = 0; ri < 5; ++ri)
2498 if (red < cutoff[ri])
2499 break;
2500 for (gi = 0; gi < 5; ++gi)
2501 if (green < cutoff[gi])
2502 break;
2503 for (bi = 0; bi < 5; ++bi)
2504 if (blue < cutoff[bi])
2505 break;
2506 return 17 + ri * 36 + gi * 6 + bi;
2507 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002508 }
2509 return 0;
2510}
2511
2512/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002513 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002514 */
2515 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002516vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002517{
2518 int attr = 0;
2519
2520 if (cellattrs.bold)
2521 attr |= HL_BOLD;
2522 if (cellattrs.underline)
2523 attr |= HL_UNDERLINE;
2524 if (cellattrs.italic)
2525 attr |= HL_ITALIC;
2526 if (cellattrs.strike)
2527 attr |= HL_STRIKETHROUGH;
2528 if (cellattrs.reverse)
2529 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002530 return attr;
2531}
2532
2533/*
2534 * Store Vterm attributes in "cell" from highlight flags.
2535 */
2536 static void
2537hl2vtermAttr(int attr, cellattr_T *cell)
2538{
2539 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2540 if (attr & HL_BOLD)
2541 cell->attrs.bold = 1;
2542 if (attr & HL_UNDERLINE)
2543 cell->attrs.underline = 1;
2544 if (attr & HL_ITALIC)
2545 cell->attrs.italic = 1;
2546 if (attr & HL_STRIKETHROUGH)
2547 cell->attrs.strike = 1;
2548 if (attr & HL_INVERSE)
2549 cell->attrs.reverse = 1;
2550}
2551
2552/*
2553 * Convert the attributes of a vterm cell into an attribute index.
2554 */
2555 static int
2556cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2557{
2558 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002559
2560#ifdef FEAT_GUI
2561 if (gui.in_use)
2562 {
2563 guicolor_T fg, bg;
2564
2565 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2566 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2567 return get_gui_attr_idx(attr, fg, bg);
2568 }
2569 else
2570#endif
2571#ifdef FEAT_TERMGUICOLORS
2572 if (p_tgc)
2573 {
2574 guicolor_T fg, bg;
2575
2576 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2577 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2578
2579 return get_tgc_attr_idx(attr, fg, bg);
2580 }
2581 else
2582#endif
2583 {
2584 int bold = MAYBE;
2585 int fg = color2index(&cellfg, TRUE, &bold);
2586 int bg = color2index(&cellbg, FALSE, &bold);
2587
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002588 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002589 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002590 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002591 if (fg == 0 && term_default_cterm_fg >= 0)
2592 fg = term_default_cterm_fg + 1;
2593 if (bg == 0 && term_default_cterm_bg >= 0)
2594 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002595 }
2596
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002597 /* with 8 colors set the bold attribute to get a bright foreground */
2598 if (bold == TRUE)
2599 attr |= HL_BOLD;
2600 return get_cterm_attr_idx(attr, fg, bg);
2601 }
2602 return 0;
2603}
2604
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002605 static void
2606set_dirty_snapshot(term_T *term)
2607{
2608 term->tl_dirty_snapshot = TRUE;
2609#ifdef FEAT_TIMERS
2610 if (!term->tl_normal_mode)
2611 {
2612 /* Update the snapshot after 100 msec of not getting updates. */
2613 profile_setlimit(100L, &term->tl_timer_due);
2614 term->tl_timer_set = TRUE;
2615 }
2616#endif
2617}
2618
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002619 static int
2620handle_damage(VTermRect rect, void *user)
2621{
2622 term_T *term = (term_T *)user;
2623
2624 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2625 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002626 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002627 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002628 return 1;
2629}
2630
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002631 static void
2632term_scroll_up(term_T *term, int start_row, int count)
2633{
2634 win_T *wp;
2635 VTermColor fg, bg;
2636 VTermScreenCellAttrs attr;
2637 int clear_attr;
2638
2639 /* Set the color to clear lines with. */
2640 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2641 &fg, &bg);
2642 vim_memset(&attr, 0, sizeof(attr));
2643 clear_attr = cell2attr(attr, fg, bg);
2644
2645 FOR_ALL_WINDOWS(wp)
2646 {
2647 if (wp->w_buffer == term->tl_buffer)
2648 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2649 }
2650}
2651
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002652 static int
2653handle_moverect(VTermRect dest, VTermRect src, void *user)
2654{
2655 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002656 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002657
2658 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002659 * redrawing the text. But avoid doing this multiple times, postpone until
2660 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002661 if (dest.start_col == src.start_col
2662 && dest.end_col == src.end_col
2663 && dest.start_row < src.start_row)
2664 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002665 if (dest.start_row == 0)
2666 term->tl_postponed_scroll += count;
2667 else
2668 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002669 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002670
2671 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2672 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002673 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002674
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002675 /* Note sure if the scrolling will work correctly, let's do a complete
2676 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002677 redraw_buf_later(term->tl_buffer, NOT_VALID);
2678 return 1;
2679}
2680
2681 static int
2682handle_movecursor(
2683 VTermPos pos,
2684 VTermPos oldpos UNUSED,
2685 int visible,
2686 void *user)
2687{
2688 term_T *term = (term_T *)user;
2689 win_T *wp;
2690
2691 term->tl_cursor_pos = pos;
2692 term->tl_cursor_visible = visible;
2693
2694 FOR_ALL_WINDOWS(wp)
2695 {
2696 if (wp->w_buffer == term->tl_buffer)
2697 position_cursor(wp, &pos);
2698 }
2699 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2700 {
2701 may_toggle_cursor(term);
2702 update_cursor(term, term->tl_cursor_visible);
2703 }
2704
2705 return 1;
2706}
2707
2708 static int
2709handle_settermprop(
2710 VTermProp prop,
2711 VTermValue *value,
2712 void *user)
2713{
2714 term_T *term = (term_T *)user;
2715
2716 switch (prop)
2717 {
2718 case VTERM_PROP_TITLE:
2719 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002720 // a blank title isn't useful, make it empty, so that "running" is
2721 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002722 if (*skipwhite((char_u *)value->string) == NUL)
2723 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002724 // Same as blank
2725 else if (term->tl_arg0_cmd != NULL
2726 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2727 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2728 term->tl_title = NULL;
2729 // Empty corrupted data of winpty
2730 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2731 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002732#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002733 else if (!enc_utf8 && enc_codepage > 0)
2734 {
2735 WCHAR *ret = NULL;
2736 int length = 0;
2737
2738 MultiByteToWideChar_alloc(CP_UTF8, 0,
2739 (char*)value->string, (int)STRLEN(value->string),
2740 &ret, &length);
2741 if (ret != NULL)
2742 {
2743 WideCharToMultiByte_alloc(enc_codepage, 0,
2744 ret, length, (char**)&term->tl_title,
2745 &length, 0, 0);
2746 vim_free(ret);
2747 }
2748 }
2749#endif
2750 else
2751 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002752 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002753 if (term == curbuf->b_term)
2754 maketitle();
2755 break;
2756
2757 case VTERM_PROP_CURSORVISIBLE:
2758 term->tl_cursor_visible = value->boolean;
2759 may_toggle_cursor(term);
2760 out_flush();
2761 break;
2762
2763 case VTERM_PROP_CURSORBLINK:
2764 term->tl_cursor_blink = value->boolean;
2765 may_set_cursor_props(term);
2766 break;
2767
2768 case VTERM_PROP_CURSORSHAPE:
2769 term->tl_cursor_shape = value->number;
2770 may_set_cursor_props(term);
2771 break;
2772
2773 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002774 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002775 may_set_cursor_props(term);
2776 break;
2777
2778 case VTERM_PROP_ALTSCREEN:
2779 /* TODO: do anything else? */
2780 term->tl_using_altscreen = value->boolean;
2781 break;
2782
2783 default:
2784 break;
2785 }
2786 /* Always return 1, otherwise vterm doesn't store the value internally. */
2787 return 1;
2788}
2789
2790/*
2791 * The job running in the terminal resized the terminal.
2792 */
2793 static int
2794handle_resize(int rows, int cols, void *user)
2795{
2796 term_T *term = (term_T *)user;
2797 win_T *wp;
2798
2799 term->tl_rows = rows;
2800 term->tl_cols = cols;
2801 if (term->tl_vterm_size_changed)
2802 /* Size was set by vterm_set_size(), don't set the window size. */
2803 term->tl_vterm_size_changed = FALSE;
2804 else
2805 {
2806 FOR_ALL_WINDOWS(wp)
2807 {
2808 if (wp->w_buffer == term->tl_buffer)
2809 {
2810 win_setheight_win(rows, wp);
2811 win_setwidth_win(cols, wp);
2812 }
2813 }
2814 redraw_buf_later(term->tl_buffer, NOT_VALID);
2815 }
2816 return 1;
2817}
2818
2819/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002820 * If the number of lines that are stored goes over 'termscrollback' then
2821 * delete the first 10%.
2822 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2823 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002824 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002825 static void
2826limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002827{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002828 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002829 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002830 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002831 int i;
2832
2833 curbuf = term->tl_buffer;
2834 for (i = 0; i < todo; ++i)
2835 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002836 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
2837 if (update_buffer)
2838 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002839 }
2840 curbuf = curwin->w_buffer;
2841
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002842 gap->ga_len -= todo;
2843 mch_memmove(gap->ga_data,
2844 (sb_line_T *)gap->ga_data + todo,
2845 sizeof(sb_line_T) * gap->ga_len);
2846 if (update_buffer)
2847 term->tl_scrollback_scrolled -= todo;
2848 }
2849}
2850
2851/*
2852 * Handle a line that is pushed off the top of the screen.
2853 */
2854 static int
2855handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2856{
2857 term_T *term = (term_T *)user;
2858 garray_T *gap;
2859 int update_buffer;
2860
2861 if (term->tl_normal_mode)
2862 {
2863 // In Terminal-Normal mode the user interacts with the buffer, thus we
2864 // must not change it. Postpone adding the scrollback lines.
2865 gap = &term->tl_scrollback_postponed;
2866 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002867 }
2868 else
2869 {
2870 // First remove the lines that were appended before, the pushed line
2871 // goes above it.
2872 cleanup_scrollback(term);
2873 gap = &term->tl_scrollback;
2874 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002875 }
2876
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002877 limit_scrollback(term, gap, update_buffer);
2878
2879 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880 {
2881 cellattr_T *p = NULL;
2882 int len = 0;
2883 int i;
2884 int c;
2885 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002886 int text_len;
2887 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888 sb_line_T *line;
2889 garray_T ga;
2890 cellattr_T fill_attr = term->tl_default_color;
2891
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002892 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002893 for (i = 0; i < cols; ++i)
2894 if (cells[i].chars[0] != 0)
2895 len = i + 1;
2896 else
2897 cell2cellattr(&cells[i], &fill_attr);
2898
2899 ga_init2(&ga, 1, 100);
2900 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002901 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002902 if (p != NULL)
2903 {
2904 for (col = 0; col < len; col += cells[col].width)
2905 {
2906 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2907 {
2908 ga.ga_len = 0;
2909 break;
2910 }
2911 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2912 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2913 (char_u *)ga.ga_data + ga.ga_len);
2914 cell2cellattr(&cells[col], &p[col]);
2915 }
2916 }
2917 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002918 {
2919 if (update_buffer)
2920 text = (char_u *)"";
2921 else
2922 text = vim_strsave((char_u *)"");
2923 text_len = 0;
2924 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 else
2926 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002927 text = ga.ga_data;
2928 text_len = ga.ga_len;
2929 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002930 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002931 if (update_buffer)
2932 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002933
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002934 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002935 line->sb_cols = len;
2936 line->sb_cells = p;
2937 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002938 if (update_buffer)
2939 {
2940 line->sb_text = NULL;
2941 ++term->tl_scrollback_scrolled;
2942 ga_clear(&ga); // free the text
2943 }
2944 else
2945 {
2946 line->sb_text = text;
2947 ga_init(&ga); // text is kept in tl_scrollback_postponed
2948 }
2949 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002950 }
2951 return 0; /* ignored */
2952}
2953
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002954/*
2955 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
2956 * received and stored in tl_scrollback_postponed.
2957 */
2958 static void
2959handle_postponed_scrollback(term_T *term)
2960{
2961 int i;
2962
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01002963 if (term->tl_scrollback_postponed.ga_len == 0)
2964 return;
2965 ch_log(NULL, "Moving postponed scrollback to scrollback");
2966
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002967 // First remove the lines that were appended before, the pushed lines go
2968 // above it.
2969 cleanup_scrollback(term);
2970
2971 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
2972 {
2973 char_u *text;
2974 sb_line_T *pp_line;
2975 sb_line_T *line;
2976
2977 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
2978 break;
2979 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
2980
2981 text = pp_line->sb_text;
2982 if (text == NULL)
2983 text = (char_u *)"";
2984 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
2985 vim_free(pp_line->sb_text);
2986
2987 line = (sb_line_T *)term->tl_scrollback.ga_data
2988 + term->tl_scrollback.ga_len;
2989 line->sb_cols = pp_line->sb_cols;
2990 line->sb_cells = pp_line->sb_cells;
2991 line->sb_fill_attr = pp_line->sb_fill_attr;
2992 line->sb_text = NULL;
2993 ++term->tl_scrollback_scrolled;
2994 ++term->tl_scrollback.ga_len;
2995 }
2996
2997 ga_clear(&term->tl_scrollback_postponed);
2998 limit_scrollback(term, &term->tl_scrollback, TRUE);
2999}
3000
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003001static VTermScreenCallbacks screen_callbacks = {
3002 handle_damage, /* damage */
3003 handle_moverect, /* moverect */
3004 handle_movecursor, /* movecursor */
3005 handle_settermprop, /* settermprop */
3006 NULL, /* bell */
3007 handle_resize, /* resize */
3008 handle_pushline, /* sb_pushline */
3009 NULL /* sb_popline */
3010};
3011
3012/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003013 * Do the work after the channel of a terminal was closed.
3014 * Must be called only when updating_screen is FALSE.
3015 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3016 */
3017 static int
3018term_after_channel_closed(term_T *term)
3019{
3020 /* Unless in Terminal-Normal mode: clear the vterm. */
3021 if (!term->tl_normal_mode)
3022 {
3023 int fnum = term->tl_buffer->b_fnum;
3024
3025 cleanup_vterm(term);
3026
3027 if (term->tl_finish == TL_FINISH_CLOSE)
3028 {
3029 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003030 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003031
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003032 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003033 ch_log(NULL, "terminal job finished, closing window");
3034 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003035 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003036 if (curwin == aucmd_win)
3037 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003038 if (do_set_w_closing)
3039 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003040 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003041 if (do_set_w_closing)
3042 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003043 aucmd_restbuf(&aco);
3044 return TRUE;
3045 }
3046 if (term->tl_finish == TL_FINISH_OPEN
3047 && term->tl_buffer->b_nwindows == 0)
3048 {
3049 char buf[50];
3050
3051 /* TODO: use term_opencmd */
3052 ch_log(NULL, "terminal job finished, opening window");
3053 vim_snprintf(buf, sizeof(buf),
3054 term->tl_opencmd == NULL
3055 ? "botright sbuf %d"
3056 : (char *)term->tl_opencmd, fnum);
3057 do_cmdline_cmd((char_u *)buf);
3058 }
3059 else
3060 ch_log(NULL, "terminal job finished");
3061 }
3062
3063 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3064 return FALSE;
3065}
3066
3067/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003068 * Called when a channel has been closed.
3069 * If this was a channel for a terminal window then finish it up.
3070 */
3071 void
3072term_channel_closed(channel_T *ch)
3073{
3074 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003075 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003076 int did_one = FALSE;
3077
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003078 for (term = first_term; term != NULL; term = next_term)
3079 {
3080 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003081 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003082 {
3083 term->tl_channel_closed = TRUE;
3084 did_one = TRUE;
3085
Bram Moolenaard23a8232018-02-10 18:45:26 +01003086 VIM_CLEAR(term->tl_title);
3087 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003088#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003089 if (term->tl_out_fd != NULL)
3090 {
3091 fclose(term->tl_out_fd);
3092 term->tl_out_fd = NULL;
3093 }
3094#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003096 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003098 /* Cannot open or close windows now. Can happen when
3099 * 'lazyredraw' is set. */
3100 term->tl_channel_recently_closed = TRUE;
3101 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003102 }
3103
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003104 if (term_after_channel_closed(term))
3105 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003106 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003107 }
3108
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003109 if (did_one)
3110 {
3111 redraw_statuslines();
3112
3113 /* Need to break out of vgetc(). */
3114 ins_char_typebuf(K_IGNORE);
3115 typebuf_was_filled = TRUE;
3116
3117 term = curbuf->b_term;
3118 if (term != NULL)
3119 {
3120 if (term->tl_job == ch->ch_job)
3121 maketitle();
3122 update_cursor(term, term->tl_cursor_visible);
3123 }
3124 }
3125}
3126
3127/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003128 * To be called after resetting updating_screen: handle any terminal where the
3129 * channel was closed.
3130 */
3131 void
3132term_check_channel_closed_recently()
3133{
3134 term_T *term;
3135 term_T *next_term;
3136
3137 for (term = first_term; term != NULL; term = next_term)
3138 {
3139 next_term = term->tl_next;
3140 if (term->tl_channel_recently_closed)
3141 {
3142 term->tl_channel_recently_closed = FALSE;
3143 if (term_after_channel_closed(term))
3144 // start over, the list may have changed
3145 next_term = first_term;
3146 }
3147 }
3148}
3149
3150/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003151 * Fill one screen line from a line of the terminal.
3152 * Advances "pos" to past the last column.
3153 */
3154 static void
3155term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3156{
3157 int off = screen_get_current_line_off();
3158
3159 for (pos->col = 0; pos->col < max_col; )
3160 {
3161 VTermScreenCell cell;
3162 int c;
3163
3164 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3165 vim_memset(&cell, 0, sizeof(cell));
3166
3167 c = cell.chars[0];
3168 if (c == NUL)
3169 {
3170 ScreenLines[off] = ' ';
3171 if (enc_utf8)
3172 ScreenLinesUC[off] = NUL;
3173 }
3174 else
3175 {
3176 if (enc_utf8)
3177 {
3178 int i;
3179
3180 /* composing chars */
3181 for (i = 0; i < Screen_mco
3182 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3183 {
3184 ScreenLinesC[i][off] = cell.chars[i + 1];
3185 if (cell.chars[i + 1] == 0)
3186 break;
3187 }
3188 if (c >= 0x80 || (Screen_mco > 0
3189 && ScreenLinesC[0][off] != 0))
3190 {
3191 ScreenLines[off] = ' ';
3192 ScreenLinesUC[off] = c;
3193 }
3194 else
3195 {
3196 ScreenLines[off] = c;
3197 ScreenLinesUC[off] = NUL;
3198 }
3199 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003200#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003201 else if (has_mbyte && c >= 0x80)
3202 {
3203 char_u mb[MB_MAXBYTES+1];
3204 WCHAR wc = c;
3205
3206 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3207 (char*)mb, 2, 0, 0) > 1)
3208 {
3209 ScreenLines[off] = mb[0];
3210 ScreenLines[off + 1] = mb[1];
3211 cell.width = mb_ptr2cells(mb);
3212 }
3213 else
3214 ScreenLines[off] = c;
3215 }
3216#endif
3217 else
3218 ScreenLines[off] = c;
3219 }
3220 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3221
3222 ++pos->col;
3223 ++off;
3224 if (cell.width == 2)
3225 {
3226 if (enc_utf8)
3227 ScreenLinesUC[off] = NUL;
3228
3229 /* don't set the second byte to NUL for a DBCS encoding, it
3230 * has been set above */
3231 if (enc_utf8 || !has_mbyte)
3232 ScreenLines[off] = NUL;
3233
3234 ++pos->col;
3235 ++off;
3236 }
3237 }
3238}
3239
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003240#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003241 static void
3242update_system_term(term_T *term)
3243{
3244 VTermPos pos;
3245 VTermScreen *screen;
3246
3247 if (term->tl_vterm == NULL)
3248 return;
3249 screen = vterm_obtain_screen(term->tl_vterm);
3250
3251 /* Scroll up to make more room for terminal lines if needed. */
3252 while (term->tl_toprow > 0
3253 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3254 {
3255 int save_p_more = p_more;
3256
3257 p_more = FALSE;
3258 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003259 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003260 p_more = save_p_more;
3261 --term->tl_toprow;
3262 }
3263
3264 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3265 && pos.row < Rows; ++pos.row)
3266 {
3267 if (pos.row < term->tl_rows)
3268 {
3269 int max_col = MIN(Columns, term->tl_cols);
3270
3271 term_line2screenline(screen, &pos, max_col);
3272 }
3273 else
3274 pos.col = 0;
3275
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003276 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003277 }
3278
3279 term->tl_dirty_row_start = MAX_ROW;
3280 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003281}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003282#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003283
3284/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003285 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3286 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003287 * Terminal-Normal mode.
3288 */
3289 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003290term_do_update_window(win_T *wp)
3291{
3292 term_T *term = wp->w_buffer->b_term;
3293
3294 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3295}
3296
3297/*
3298 * Called to update a window that contains an active terminal.
3299 */
3300 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003301term_update_window(win_T *wp)
3302{
3303 term_T *term = wp->w_buffer->b_term;
3304 VTerm *vterm;
3305 VTermScreen *screen;
3306 VTermState *state;
3307 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003308 int rows, cols;
3309 int newrows, newcols;
3310 int minsize;
3311 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003312
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003313 vterm = term->tl_vterm;
3314 screen = vterm_obtain_screen(vterm);
3315 state = vterm_obtain_state(vterm);
3316
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003317 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3318 * SOME_VALID only redraw what was marked dirty. */
3319 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003320 {
3321 term->tl_dirty_row_start = 0;
3322 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003323
3324 if (term->tl_postponed_scroll > 0
3325 && term->tl_postponed_scroll < term->tl_rows / 3)
3326 /* Scrolling is usually faster than redrawing, when there are only
3327 * a few lines to scroll. */
3328 term_scroll_up(term, 0, term->tl_postponed_scroll);
3329 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003330 }
3331
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003332 /*
3333 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003334 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003335 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003336 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003337
Bram Moolenaar498c2562018-04-15 23:45:15 +02003338 newrows = 99999;
3339 newcols = 99999;
3340 FOR_ALL_WINDOWS(twp)
3341 {
3342 /* When more than one window shows the same terminal, use the
3343 * smallest size. */
3344 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003345 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003346 newrows = MIN(newrows, twp->w_height);
3347 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003348 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003349 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003350 if (newrows == 99999 || newcols == 99999)
3351 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003352 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3353 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3354
3355 if (term->tl_rows != newrows || term->tl_cols != newcols)
3356 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003358 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003359 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003360 newrows);
3361 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003362
3363 // Updating the terminal size will cause the snapshot to be cleared.
3364 // When not in terminal_loop() we need to restore it.
3365 if (term != in_terminal_loop)
3366 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003367 }
3368
3369 /* The cursor may have been moved when resizing. */
3370 vterm_state_get_cursorpos(state, &pos);
3371 position_cursor(wp, &pos);
3372
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003373 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3374 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003375 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003376 if (pos.row < term->tl_rows)
3377 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003378 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003379
Bram Moolenaar13568252018-03-16 20:46:58 +01003380 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003381 }
3382 else
3383 pos.col = 0;
3384
Bram Moolenaarf118d482018-03-13 13:14:00 +01003385 screen_line(wp->w_winrow + pos.row
3386#ifdef FEAT_MENU
3387 + winbar_height(wp)
3388#endif
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003389 , wp->w_wincol, pos.col, wp->w_width, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003390 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003391 term->tl_dirty_row_start = MAX_ROW;
3392 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003393}
3394
3395/*
3396 * Return TRUE if "wp" is a terminal window where the job has finished.
3397 */
3398 int
3399term_is_finished(buf_T *buf)
3400{
3401 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3402}
3403
3404/*
3405 * Return TRUE if "wp" is a terminal window where the job has finished or we
3406 * are in Terminal-Normal mode, thus we show the buffer contents.
3407 */
3408 int
3409term_show_buffer(buf_T *buf)
3410{
3411 term_T *term = buf->b_term;
3412
3413 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3414}
3415
3416/*
3417 * The current buffer is going to be changed. If there is terminal
3418 * highlighting remove it now.
3419 */
3420 void
3421term_change_in_curbuf(void)
3422{
3423 term_T *term = curbuf->b_term;
3424
3425 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3426 {
3427 free_scrollback(term);
3428 redraw_buf_later(term->tl_buffer, NOT_VALID);
3429
3430 /* The buffer is now like a normal buffer, it cannot be easily
3431 * abandoned when changed. */
3432 set_string_option_direct((char_u *)"buftype", -1,
3433 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3434 }
3435}
3436
3437/*
3438 * Get the screen attribute for a position in the buffer.
3439 * Use a negative "col" to get the filler background color.
3440 */
3441 int
3442term_get_attr(buf_T *buf, linenr_T lnum, int col)
3443{
3444 term_T *term = buf->b_term;
3445 sb_line_T *line;
3446 cellattr_T *cellattr;
3447
3448 if (lnum > term->tl_scrollback.ga_len)
3449 cellattr = &term->tl_default_color;
3450 else
3451 {
3452 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3453 if (col < 0 || col >= line->sb_cols)
3454 cellattr = &line->sb_fill_attr;
3455 else
3456 cellattr = line->sb_cells + col;
3457 }
3458 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3459}
3460
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003461/*
3462 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003463 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003464 */
3465 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003466cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003467{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003468 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003469}
3470
3471/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003472 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003473 */
3474 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003475init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003476{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003477 VTermColor *fg, *bg;
3478 int fgval, bgval;
3479 int id;
3480
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003481 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3482 term->tl_default_color.width = 1;
3483 fg = &term->tl_default_color.fg;
3484 bg = &term->tl_default_color.bg;
3485
3486 /* Vterm uses a default black background. Set it to white when
3487 * 'background' is "light". */
3488 if (*p_bg == 'l')
3489 {
3490 fgval = 0;
3491 bgval = 255;
3492 }
3493 else
3494 {
3495 fgval = 255;
3496 bgval = 0;
3497 }
3498 fg->red = fg->green = fg->blue = fgval;
3499 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003500 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003501
3502 /* The "Terminal" highlight group overrules the defaults. */
3503 id = syn_name2id((char_u *)"Terminal");
3504
Bram Moolenaar46359e12017-11-29 22:33:38 +01003505 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003506#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3507 if (0
3508# ifdef FEAT_GUI
3509 || gui.in_use
3510# endif
3511# ifdef FEAT_TERMGUICOLORS
3512 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003513# ifdef FEAT_VTP
3514 /* Finally get INVALCOLOR on this execution path */
3515 || (!p_tgc && t_colors >= 256)
3516# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003517# endif
3518 )
3519 {
3520 guicolor_T fg_rgb = INVALCOLOR;
3521 guicolor_T bg_rgb = INVALCOLOR;
3522
3523 if (id != 0)
3524 syn_id2colors(id, &fg_rgb, &bg_rgb);
3525
3526# ifdef FEAT_GUI
3527 if (gui.in_use)
3528 {
3529 if (fg_rgb == INVALCOLOR)
3530 fg_rgb = gui.norm_pixel;
3531 if (bg_rgb == INVALCOLOR)
3532 bg_rgb = gui.back_pixel;
3533 }
3534# ifdef FEAT_TERMGUICOLORS
3535 else
3536# endif
3537# endif
3538# ifdef FEAT_TERMGUICOLORS
3539 {
3540 if (fg_rgb == INVALCOLOR)
3541 fg_rgb = cterm_normal_fg_gui_color;
3542 if (bg_rgb == INVALCOLOR)
3543 bg_rgb = cterm_normal_bg_gui_color;
3544 }
3545# endif
3546 if (fg_rgb != INVALCOLOR)
3547 {
3548 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3549
3550 fg->red = (unsigned)(rgb >> 16);
3551 fg->green = (unsigned)(rgb >> 8) & 255;
3552 fg->blue = (unsigned)rgb & 255;
3553 }
3554 if (bg_rgb != INVALCOLOR)
3555 {
3556 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3557
3558 bg->red = (unsigned)(rgb >> 16);
3559 bg->green = (unsigned)(rgb >> 8) & 255;
3560 bg->blue = (unsigned)rgb & 255;
3561 }
3562 }
3563 else
3564#endif
3565 if (id != 0 && t_colors >= 16)
3566 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003567 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003568 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003569 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003570 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003571 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003572 else
3573 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003574#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003575 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003576#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003577
3578 /* In an MS-Windows console we know the normal colors. */
3579 if (cterm_normal_fg_color > 0)
3580 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003581 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003582# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3583# ifdef VIMDLL
3584 if (!gui.in_use)
3585# endif
3586 {
3587 tmp = fg->red;
3588 fg->red = fg->blue;
3589 fg->blue = tmp;
3590 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003591# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003592 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003593# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003594 else
3595 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003596# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003597
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003598 if (cterm_normal_bg_color > 0)
3599 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003600 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003601# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3602# ifdef VIMDLL
3603 if (!gui.in_use)
3604# endif
3605 {
3606 tmp = fg->red;
3607 fg->red = fg->blue;
3608 fg->blue = tmp;
3609 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003610# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003611 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003612# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003613 else
3614 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003615# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003616 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003617}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003618
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003619#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3620/*
3621 * Set the 16 ANSI colors from array of RGB values
3622 */
3623 static void
3624set_vterm_palette(VTerm *vterm, long_u *rgb)
3625{
3626 int index = 0;
3627 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003628
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003629 for (; index < 16; index++)
3630 {
3631 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003632
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003633 color.red = (unsigned)(rgb[index] >> 16);
3634 color.green = (unsigned)(rgb[index] >> 8) & 255;
3635 color.blue = (unsigned)rgb[index] & 255;
3636 vterm_state_set_palette_color(state, index, &color);
3637 }
3638}
3639
3640/*
3641 * Set the ANSI color palette from a list of colors
3642 */
3643 static int
3644set_ansi_colors_list(VTerm *vterm, list_T *list)
3645{
3646 int n = 0;
3647 long_u rgb[16];
3648 listitem_T *li = list->lv_first;
3649
3650 for (; li != NULL && n < 16; li = li->li_next, n++)
3651 {
3652 char_u *color_name;
3653 guicolor_T guicolor;
3654
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003655 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003656 if (color_name == NULL)
3657 return FAIL;
3658
3659 guicolor = GUI_GET_COLOR(color_name);
3660 if (guicolor == INVALCOLOR)
3661 return FAIL;
3662
3663 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3664 }
3665
3666 if (n != 16 || li != NULL)
3667 return FAIL;
3668
3669 set_vterm_palette(vterm, rgb);
3670
3671 return OK;
3672}
3673
3674/*
3675 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3676 */
3677 static void
3678init_vterm_ansi_colors(VTerm *vterm)
3679{
3680 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3681
3682 if (var != NULL
3683 && (var->di_tv.v_type != VAR_LIST
3684 || var->di_tv.vval.v_list == NULL
3685 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003686 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003687}
3688#endif
3689
Bram Moolenaar52acb112018-03-18 19:20:22 +01003690/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003691 * Handles a "drop" command from the job in the terminal.
3692 * "item" is the file name, "item->li_next" may have options.
3693 */
3694 static void
3695handle_drop_command(listitem_T *item)
3696{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003697 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003698 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003699 int bufnr;
3700 win_T *wp;
3701 tabpage_T *tp;
3702 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003703 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003704
3705 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3706 FOR_ALL_TAB_WINDOWS(tp, wp)
3707 {
3708 if (wp->w_buffer->b_fnum == bufnr)
3709 {
3710 /* buffer is in a window already, go there */
3711 goto_tabpage_win(tp, wp);
3712 return;
3713 }
3714 }
3715
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003716 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003717
3718 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3719 && opt_item->li_tv.vval.v_dict != NULL)
3720 {
3721 dict_T *dict = opt_item->li_tv.vval.v_dict;
3722 char_u *p;
3723
Bram Moolenaar8f667172018-12-14 15:38:31 +01003724 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003725 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003726 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003727 if (p != NULL)
3728 {
3729 if (check_ff_value(p) == FAIL)
3730 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3731 else
3732 ea.force_ff = *p;
3733 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003734 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003735 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003736 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003737 if (p != NULL)
3738 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003739 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003740 if (ea.cmd != NULL)
3741 {
3742 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3743 ea.force_enc = 11;
3744 tofree = ea.cmd;
3745 }
3746 }
3747
Bram Moolenaar8f667172018-12-14 15:38:31 +01003748 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003749 if (p != NULL)
3750 get_bad_opt(p, &ea);
3751
3752 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3753 ea.force_bin = FORCE_BIN;
3754 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3755 ea.force_bin = FORCE_BIN;
3756 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3757 ea.force_bin = FORCE_NOBIN;
3758 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3759 ea.force_bin = FORCE_NOBIN;
3760 }
3761
3762 /* open in new window, like ":split fname" */
3763 if (ea.cmd == NULL)
3764 ea.cmd = (char_u *)"split";
3765 ea.arg = fname;
3766 ea.cmdidx = CMD_split;
3767 ex_splitview(&ea);
3768
3769 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003770}
3771
3772/*
3773 * Handles a function call from the job running in a terminal.
3774 * "item" is the function name, "item->li_next" has the arguments.
3775 */
3776 static void
3777handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3778{
3779 char_u *func;
3780 typval_T argvars[2];
3781 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003782 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003783
3784 if (item->li_next == NULL)
3785 {
3786 ch_log(channel, "Missing function arguments for call");
3787 return;
3788 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003789 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003790
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003791 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003792 {
3793 ch_log(channel, "Invalid function name: %s", func);
3794 return;
3795 }
3796
3797 argvars[0].v_type = VAR_NUMBER;
3798 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3799 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003800 vim_memset(&funcexe, 0, sizeof(funcexe));
3801 funcexe.firstline = 1L;
3802 funcexe.lastline = 1L;
3803 funcexe.evaluate = TRUE;
3804 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003805 {
3806 clear_tv(&rettv);
3807 ch_log(channel, "Function %s called", func);
3808 }
3809 else
3810 ch_log(channel, "Calling function %s failed", func);
3811}
3812
3813/*
3814 * Called by libvterm when it cannot recognize an OSC sequence.
3815 * We recognize a terminal API command.
3816 */
3817 static int
3818parse_osc(const char *command, size_t cmdlen, void *user)
3819{
3820 term_T *term = (term_T *)user;
3821 js_read_T reader;
3822 typval_T tv;
3823 channel_T *channel = term->tl_job == NULL ? NULL
3824 : term->tl_job->jv_channel;
3825
3826 /* We recognize only OSC 5 1 ; {command} */
3827 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3828 return 0; /* not handled */
3829
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003830 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003831 if (reader.js_buf == NULL)
3832 return 1;
3833 reader.js_fill = NULL;
3834 reader.js_used = 0;
3835 if (json_decode(&reader, &tv, 0) == OK
3836 && tv.v_type == VAR_LIST
3837 && tv.vval.v_list != NULL)
3838 {
3839 listitem_T *item = tv.vval.v_list->lv_first;
3840
3841 if (item == NULL)
3842 ch_log(channel, "Missing command");
3843 else
3844 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003845 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003846
Bram Moolenaara997b452018-04-17 23:24:06 +02003847 /* Make sure an invoked command doesn't delete the buffer (and the
3848 * terminal) under our fingers. */
3849 ++term->tl_buffer->b_locked;
3850
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003851 item = item->li_next;
3852 if (item == NULL)
3853 ch_log(channel, "Missing argument for %s", cmd);
3854 else if (STRCMP(cmd, "drop") == 0)
3855 handle_drop_command(item);
3856 else if (STRCMP(cmd, "call") == 0)
3857 handle_call_command(term, channel, item);
3858 else
3859 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003860 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003861 }
3862 }
3863 else
3864 ch_log(channel, "Invalid JSON received");
3865
3866 vim_free(reader.js_buf);
3867 clear_tv(&tv);
3868 return 1;
3869}
3870
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003871/*
3872 * Called by libvterm when it cannot recognize a CSI sequence.
3873 * We recognize the window position report.
3874 */
3875 static int
3876parse_csi(
3877 const char *leader UNUSED,
3878 const long args[],
3879 int argcount,
3880 const char *intermed UNUSED,
3881 char command,
3882 void *user)
3883{
3884 term_T *term = (term_T *)user;
3885 char buf[100];
3886 int len;
3887 int x = 0;
3888 int y = 0;
3889 win_T *wp;
3890
3891 // We recognize only CSI 13 t
3892 if (command != 't' || argcount != 1 || args[0] != 13)
3893 return 0; // not handled
3894
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003895 // When getting the window position is not possible or it fails it results
3896 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02003897#if defined(FEAT_GUI) \
3898 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
3899 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003900 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003901#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003902
3903 FOR_ALL_WINDOWS(wp)
3904 if (wp->w_buffer == term->tl_buffer)
3905 break;
3906 if (wp != NULL)
3907 {
3908#ifdef FEAT_GUI
3909 if (gui.in_use)
3910 {
3911 x += wp->w_wincol * gui.char_width;
3912 y += W_WINROW(wp) * gui.char_height;
3913 }
3914 else
3915#endif
3916 {
3917 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003918 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003919 x += wp->w_wincol * 7;
3920 y += W_WINROW(wp) * 10;
3921 }
3922 }
3923
3924 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
3925 channel_send(term->tl_job->jv_channel, get_tty_part(term),
3926 (char_u *)buf, len, NULL);
3927 return 1;
3928}
3929
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003930static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003931 NULL, // text
3932 NULL, // control
3933 NULL, // escape
3934 parse_csi, // csi
3935 parse_osc, // osc
3936 NULL, // dcs
3937 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003938};
3939
3940/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003941 * Use Vim's allocation functions for vterm so profiling works.
3942 */
3943 static void *
3944vterm_malloc(size_t size, void *data UNUSED)
3945{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02003946 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003947}
3948
3949 static void
3950vterm_memfree(void *ptr, void *data UNUSED)
3951{
3952 vim_free(ptr);
3953}
3954
3955static VTermAllocatorFunctions vterm_allocator = {
3956 &vterm_malloc,
3957 &vterm_memfree
3958};
3959
3960/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003961 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003962 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01003963 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003964 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01003965create_vterm(term_T *term, int rows, int cols)
3966{
3967 VTerm *vterm;
3968 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003969 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003970 VTermValue value;
3971
Bram Moolenaar756ef112018-04-10 12:04:27 +02003972 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003973 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003974 if (vterm == NULL)
3975 return FAIL;
3976
3977 // Allocate screen and state here, so we can bail out if that fails.
3978 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003979 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003980 if (state == NULL || screen == NULL)
3981 {
3982 vterm_free(vterm);
3983 return FAIL;
3984 }
3985
Bram Moolenaar52acb112018-03-18 19:20:22 +01003986 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3987 /* TODO: depends on 'encoding'. */
3988 vterm_set_utf8(vterm, 1);
3989
3990 init_default_colors(term);
3991
3992 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003993 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01003994 &term->tl_default_color.fg,
3995 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003996
Bram Moolenaar9e587872019-05-13 20:27:23 +02003997 if (t_colors < 16)
3998 // Less than 16 colors: assume that bold means using a bright color for
3999 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004000 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4001
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004002 /* Required to initialize most things. */
4003 vterm_screen_reset(screen, 1 /* hard */);
4004
4005 /* Allow using alternate screen. */
4006 vterm_screen_enable_altscreen(screen, 1);
4007
4008 /* For unix do not use a blinking cursor. In an xterm this causes the
4009 * cursor to blink if it's blinking in the xterm.
4010 * For Windows we respect the system wide setting. */
Bram Moolenaar4f974752019-02-17 17:44:42 +01004011#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004012 if (GetCaretBlinkTime() == INFINITE)
4013 value.boolean = 0;
4014 else
4015 value.boolean = 1;
4016#else
4017 value.boolean = 0;
4018#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004019 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4020 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004021
4022 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004023}
4024
4025/*
4026 * Return the text to show for the buffer name and status.
4027 */
4028 char_u *
4029term_get_status_text(term_T *term)
4030{
4031 if (term->tl_status_text == NULL)
4032 {
4033 char_u *txt;
4034 size_t len;
4035
4036 if (term->tl_normal_mode)
4037 {
4038 if (term_job_running(term))
4039 txt = (char_u *)_("Terminal");
4040 else
4041 txt = (char_u *)_("Terminal-finished");
4042 }
4043 else if (term->tl_title != NULL)
4044 txt = term->tl_title;
4045 else if (term_none_open(term))
4046 txt = (char_u *)_("active");
4047 else if (term_job_running(term))
4048 txt = (char_u *)_("running");
4049 else
4050 txt = (char_u *)_("finished");
4051 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004052 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004053 if (term->tl_status_text != NULL)
4054 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4055 term->tl_buffer->b_fname, txt);
4056 }
4057 return term->tl_status_text;
4058}
4059
4060/*
4061 * Mark references in jobs of terminals.
4062 */
4063 int
4064set_ref_in_term(int copyID)
4065{
4066 int abort = FALSE;
4067 term_T *term;
4068 typval_T tv;
4069
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004070 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004071 if (term->tl_job != NULL)
4072 {
4073 tv.v_type = VAR_JOB;
4074 tv.vval.v_job = term->tl_job;
4075 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4076 }
4077 return abort;
4078}
4079
4080/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004081 * Cache "Terminal" highlight group colors.
4082 */
4083 void
4084set_terminal_default_colors(int cterm_fg, int cterm_bg)
4085{
4086 term_default_cterm_fg = cterm_fg - 1;
4087 term_default_cterm_bg = cterm_bg - 1;
4088}
4089
4090/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004091 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004092 * Returns NULL when the buffer is not for a terminal window and logs a message
4093 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004094 */
4095 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004096term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004097{
4098 buf_T *buf;
4099
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004100 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004101 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004102 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004103 --emsg_off;
4104 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004105 {
4106 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004107 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004108 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004109 return buf;
4110}
4111
Bram Moolenaard96ff162018-02-18 22:13:29 +01004112 static int
4113same_color(VTermColor *a, VTermColor *b)
4114{
4115 return a->red == b->red
4116 && a->green == b->green
4117 && a->blue == b->blue
4118 && a->ansi_index == b->ansi_index;
4119}
4120
4121 static void
4122dump_term_color(FILE *fd, VTermColor *color)
4123{
4124 fprintf(fd, "%02x%02x%02x%d",
4125 (int)color->red, (int)color->green, (int)color->blue,
4126 (int)color->ansi_index);
4127}
4128
4129/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004130 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004131 *
4132 * Each screen cell in full is:
4133 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4134 * {characters} is a space for an empty cell
4135 * For a double-width character "+" is changed to "*" and the next cell is
4136 * skipped.
4137 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4138 * when "&" use the same as the previous cell.
4139 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4140 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4141 * {color-idx} is a number from 0 to 255
4142 *
4143 * Screen cell with same width, attributes and color as the previous one:
4144 * |{characters}
4145 *
4146 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4147 *
4148 * Repeating the previous screen cell:
4149 * @{count}
4150 */
4151 void
4152f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4153{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004154 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004155 term_T *term;
4156 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004157 int max_height = 0;
4158 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004159 stat_T st;
4160 FILE *fd;
4161 VTermPos pos;
4162 VTermScreen *screen;
4163 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004164 VTermState *state;
4165 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004166
4167 if (check_restricted() || check_secure())
4168 return;
4169 if (buf == NULL)
4170 return;
4171 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004172 if (term->tl_vterm == NULL)
4173 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004174 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004175 return;
4176 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004177
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004178 if (argvars[2].v_type != VAR_UNKNOWN)
4179 {
4180 dict_T *d;
4181
4182 if (argvars[2].v_type != VAR_DICT)
4183 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004184 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004185 return;
4186 }
4187 d = argvars[2].vval.v_dict;
4188 if (d != NULL)
4189 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004190 max_height = dict_get_number(d, (char_u *)"rows");
4191 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004192 }
4193 }
4194
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004195 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004196 if (fname == NULL)
4197 return;
4198 if (mch_stat((char *)fname, &st) >= 0)
4199 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004200 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004201 return;
4202 }
4203
Bram Moolenaard96ff162018-02-18 22:13:29 +01004204 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4205 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004206 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004207 return;
4208 }
4209
4210 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4211
4212 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004213 state = vterm_obtain_state(term->tl_vterm);
4214 vterm_state_get_cursorpos(state, &cursor_pos);
4215
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004216 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4217 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004218 {
4219 int repeat = 0;
4220
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004221 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4222 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004223 {
4224 VTermScreenCell cell;
4225 int same_attr;
4226 int same_chars = TRUE;
4227 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004228 int is_cursor_pos = (pos.col == cursor_pos.col
4229 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004230
4231 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4232 vim_memset(&cell, 0, sizeof(cell));
4233
4234 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4235 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004236 int c = cell.chars[i];
4237 int pc = prev_cell.chars[i];
4238
4239 /* For the first character NUL is the same as space. */
4240 if (i == 0)
4241 {
4242 c = (c == NUL) ? ' ' : c;
4243 pc = (pc == NUL) ? ' ' : pc;
4244 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004245 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004246 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004247 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004248 break;
4249 }
4250 same_attr = vtermAttr2hl(cell.attrs)
4251 == vtermAttr2hl(prev_cell.attrs)
4252 && same_color(&cell.fg, &prev_cell.fg)
4253 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004254 if (same_chars && cell.width == prev_cell.width && same_attr
4255 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004256 {
4257 ++repeat;
4258 }
4259 else
4260 {
4261 if (repeat > 0)
4262 {
4263 fprintf(fd, "@%d", repeat);
4264 repeat = 0;
4265 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004266 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004267
4268 if (cell.chars[0] == NUL)
4269 fputs(" ", fd);
4270 else
4271 {
4272 char_u charbuf[10];
4273 int len;
4274
4275 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4276 && cell.chars[i] != NUL; ++i)
4277 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004278 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004279 fwrite(charbuf, len, 1, fd);
4280 }
4281 }
4282
4283 /* When only the characters differ we don't write anything, the
4284 * following "|", "@" or NL will indicate using the same
4285 * attributes. */
4286 if (cell.width != prev_cell.width || !same_attr)
4287 {
4288 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004289 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004290 else
4291 fputs("+", fd);
4292
4293 if (same_attr)
4294 {
4295 fputs("&", fd);
4296 }
4297 else
4298 {
4299 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4300 if (same_color(&cell.fg, &prev_cell.fg))
4301 fputs("&", fd);
4302 else
4303 {
4304 fputs("#", fd);
4305 dump_term_color(fd, &cell.fg);
4306 }
4307 if (same_color(&cell.bg, &prev_cell.bg))
4308 fputs("&", fd);
4309 else
4310 {
4311 fputs("#", fd);
4312 dump_term_color(fd, &cell.bg);
4313 }
4314 }
4315 }
4316
4317 prev_cell = cell;
4318 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004319
4320 if (cell.width == 2)
4321 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004322 }
4323 if (repeat > 0)
4324 fprintf(fd, "@%d", repeat);
4325 fputs("\n", fd);
4326 }
4327
4328 fclose(fd);
4329}
4330
4331/*
4332 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4333 */
4334 static void
4335dump_is_corrupt(garray_T *gap)
4336{
4337 ga_concat(gap, (char_u *)"CORRUPT");
4338}
4339
4340 static void
4341append_cell(garray_T *gap, cellattr_T *cell)
4342{
4343 if (ga_grow(gap, 1) == OK)
4344 {
4345 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4346 ++gap->ga_len;
4347 }
4348}
4349
4350/*
4351 * Read the dump file from "fd" and append lines to the current buffer.
4352 * Return the cell width of the longest line.
4353 */
4354 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004355read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004356{
4357 int c;
4358 garray_T ga_text;
4359 garray_T ga_cell;
4360 char_u *prev_char = NULL;
4361 int attr = 0;
4362 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004363 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004364 term_T *term = curbuf->b_term;
4365 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004366 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004367
4368 ga_init2(&ga_text, 1, 90);
4369 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4370 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004371 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004372 cursor_pos->row = -1;
4373 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004374
4375 c = fgetc(fd);
4376 for (;;)
4377 {
4378 if (c == EOF)
4379 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004380 if (c == '\r')
4381 {
4382 // DOS line endings? Ignore.
4383 c = fgetc(fd);
4384 }
4385 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004386 {
4387 /* End of a line: append it to the buffer. */
4388 if (ga_text.ga_data == NULL)
4389 dump_is_corrupt(&ga_text);
4390 if (ga_grow(&term->tl_scrollback, 1) == OK)
4391 {
4392 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4393 + term->tl_scrollback.ga_len;
4394
4395 if (max_cells < ga_cell.ga_len)
4396 max_cells = ga_cell.ga_len;
4397 line->sb_cols = ga_cell.ga_len;
4398 line->sb_cells = ga_cell.ga_data;
4399 line->sb_fill_attr = term->tl_default_color;
4400 ++term->tl_scrollback.ga_len;
4401 ga_init(&ga_cell);
4402
4403 ga_append(&ga_text, NUL);
4404 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4405 ga_text.ga_len, FALSE);
4406 }
4407 else
4408 ga_clear(&ga_cell);
4409 ga_text.ga_len = 0;
4410
4411 c = fgetc(fd);
4412 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004413 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004414 {
4415 int prev_len = ga_text.ga_len;
4416
Bram Moolenaar9271d052018-02-25 21:39:46 +01004417 if (c == '>')
4418 {
4419 if (cursor_pos->row != -1)
4420 dump_is_corrupt(&ga_text); /* duplicate cursor */
4421 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4422 cursor_pos->col = ga_cell.ga_len;
4423 }
4424
Bram Moolenaard96ff162018-02-18 22:13:29 +01004425 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4426 c = fgetc(fd);
4427 if (c != EOF)
4428 ga_append(&ga_text, c);
4429 for (;;)
4430 {
4431 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004432 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004433 || c == EOF || c == '\n')
4434 break;
4435 ga_append(&ga_text, c);
4436 }
4437
4438 /* save the character for repeating it */
4439 vim_free(prev_char);
4440 if (ga_text.ga_data != NULL)
4441 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4442 ga_text.ga_len - prev_len);
4443
Bram Moolenaar9271d052018-02-25 21:39:46 +01004444 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004445 {
4446 /* use all attributes from previous cell */
4447 }
4448 else if (c == '+' || c == '*')
4449 {
4450 int is_bg;
4451
4452 cell.width = c == '+' ? 1 : 2;
4453
4454 c = fgetc(fd);
4455 if (c == '&')
4456 {
4457 /* use same attr as previous cell */
4458 c = fgetc(fd);
4459 }
4460 else if (isdigit(c))
4461 {
4462 /* get the decimal attribute */
4463 attr = 0;
4464 while (isdigit(c))
4465 {
4466 attr = attr * 10 + (c - '0');
4467 c = fgetc(fd);
4468 }
4469 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004470
4471 /* is_bg == 0: fg, is_bg == 1: bg */
4472 for (is_bg = 0; is_bg <= 1; ++is_bg)
4473 {
4474 if (c == '&')
4475 {
4476 /* use same color as previous cell */
4477 c = fgetc(fd);
4478 }
4479 else if (c == '#')
4480 {
4481 int red, green, blue, index = 0;
4482
4483 c = fgetc(fd);
4484 red = hex2nr(c);
4485 c = fgetc(fd);
4486 red = (red << 4) + hex2nr(c);
4487 c = fgetc(fd);
4488 green = hex2nr(c);
4489 c = fgetc(fd);
4490 green = (green << 4) + hex2nr(c);
4491 c = fgetc(fd);
4492 blue = hex2nr(c);
4493 c = fgetc(fd);
4494 blue = (blue << 4) + hex2nr(c);
4495 c = fgetc(fd);
4496 if (!isdigit(c))
4497 dump_is_corrupt(&ga_text);
4498 while (isdigit(c))
4499 {
4500 index = index * 10 + (c - '0');
4501 c = fgetc(fd);
4502 }
4503
4504 if (is_bg)
4505 {
4506 cell.bg.red = red;
4507 cell.bg.green = green;
4508 cell.bg.blue = blue;
4509 cell.bg.ansi_index = index;
4510 }
4511 else
4512 {
4513 cell.fg.red = red;
4514 cell.fg.green = green;
4515 cell.fg.blue = blue;
4516 cell.fg.ansi_index = index;
4517 }
4518 }
4519 else
4520 dump_is_corrupt(&ga_text);
4521 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004522 }
4523 else
4524 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004525 }
4526 else
4527 dump_is_corrupt(&ga_text);
4528
4529 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004530 if (cell.width == 2)
4531 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004532 }
4533 else if (c == '@')
4534 {
4535 if (prev_char == NULL)
4536 dump_is_corrupt(&ga_text);
4537 else
4538 {
4539 int count = 0;
4540
4541 /* repeat previous character, get the count */
4542 for (;;)
4543 {
4544 c = fgetc(fd);
4545 if (!isdigit(c))
4546 break;
4547 count = count * 10 + (c - '0');
4548 }
4549
4550 while (count-- > 0)
4551 {
4552 ga_concat(&ga_text, prev_char);
4553 append_cell(&ga_cell, &cell);
4554 }
4555 }
4556 }
4557 else
4558 {
4559 dump_is_corrupt(&ga_text);
4560 c = fgetc(fd);
4561 }
4562 }
4563
4564 if (ga_text.ga_len > 0)
4565 {
4566 /* trailing characters after last NL */
4567 dump_is_corrupt(&ga_text);
4568 ga_append(&ga_text, NUL);
4569 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4570 ga_text.ga_len, FALSE);
4571 }
4572
4573 ga_clear(&ga_text);
4574 vim_free(prev_char);
4575
4576 return max_cells;
4577}
4578
4579/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004580 * Return an allocated string with at least "text_width" "=" characters and
4581 * "fname" inserted in the middle.
4582 */
4583 static char_u *
4584get_separator(int text_width, char_u *fname)
4585{
4586 int width = MAX(text_width, curwin->w_width);
4587 char_u *textline;
4588 int fname_size;
4589 char_u *p = fname;
4590 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004591 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004592
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004593 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004594 if (textline == NULL)
4595 return NULL;
4596
4597 fname_size = vim_strsize(fname);
4598 if (fname_size < width - 8)
4599 {
4600 /* enough room, don't use the full window width */
4601 width = MAX(text_width, fname_size + 8);
4602 }
4603 else if (fname_size > width - 8)
4604 {
4605 /* full name doesn't fit, use only the tail */
4606 p = gettail(fname);
4607 fname_size = vim_strsize(p);
4608 }
4609 /* skip characters until the name fits */
4610 while (fname_size > width - 8)
4611 {
4612 p += (*mb_ptr2len)(p);
4613 fname_size = vim_strsize(p);
4614 }
4615
4616 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4617 textline[i] = '=';
4618 textline[i++] = ' ';
4619
4620 STRCPY(textline + i, p);
4621 off = STRLEN(textline);
4622 textline[off] = ' ';
4623 for (i = 1; i < (width - fname_size) / 2; ++i)
4624 textline[off + i] = '=';
4625 textline[off + i] = NUL;
4626
4627 return textline;
4628}
4629
4630/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004631 * Common for "term_dumpdiff()" and "term_dumpload()".
4632 */
4633 static void
4634term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4635{
4636 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004637 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004638 char_u buf1[NUMBUFLEN];
4639 char_u buf2[NUMBUFLEN];
4640 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004641 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004642 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004643 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004644 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004645 char_u *textline = NULL;
4646
4647 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004648 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004649 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004650 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004651 if (fname1 == NULL || (do_diff && fname2 == NULL))
4652 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004653 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004654 return;
4655 }
4656 fd1 = mch_fopen((char *)fname1, READBIN);
4657 if (fd1 == NULL)
4658 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004659 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004660 return;
4661 }
4662 if (do_diff)
4663 {
4664 fd2 = mch_fopen((char *)fname2, READBIN);
4665 if (fd2 == NULL)
4666 {
4667 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004668 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004669 return;
4670 }
4671 }
4672
4673 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004674 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4675 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4676 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4677 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4678 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004679
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004680 if (opt.jo_term_name == NULL)
4681 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004682 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004683
Bram Moolenaar51e14382019-05-25 20:21:28 +02004684 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004685 if (fname_tofree != NULL)
4686 {
4687 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4688 opt.jo_term_name = fname_tofree;
4689 }
4690 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004691
Bram Moolenaar87abab92019-06-03 21:14:59 +02004692 if (opt.jo_bufnr_buf != NULL)
4693 {
4694 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4695
4696 // With "bufnr" argument: enter the window with this buffer and make it
4697 // empty.
4698 if (wp == NULL)
4699 semsg(_(e_invarg2), "bufnr");
4700 else
4701 {
4702 buf = curbuf;
4703 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4704 ml_delete((linenr_T)1, FALSE);
4705 ga_clear(&curbuf->b_term->tl_scrollback);
4706 redraw_later(NOT_VALID);
4707 }
4708 }
4709 else
4710 // Create a new terminal window.
4711 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4712
Bram Moolenaard96ff162018-02-18 22:13:29 +01004713 if (buf != NULL && buf->b_term != NULL)
4714 {
4715 int i;
4716 linenr_T bot_lnum;
4717 linenr_T lnum;
4718 term_T *term = buf->b_term;
4719 int width;
4720 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004721 VTermPos cursor_pos1;
4722 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004723
Bram Moolenaar52acb112018-03-18 19:20:22 +01004724 init_default_colors(term);
4725
Bram Moolenaard96ff162018-02-18 22:13:29 +01004726 rettv->vval.v_number = buf->b_fnum;
4727
4728 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004729 width = read_dump_file(fd1, &cursor_pos1);
4730
4731 /* position the cursor */
4732 if (cursor_pos1.row >= 0)
4733 {
4734 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4735 coladvance(cursor_pos1.col);
4736 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004737
4738 /* Delete the empty line that was in the empty buffer. */
4739 ml_delete(1, FALSE);
4740
4741 /* For term_dumpload() we are done here. */
4742 if (!do_diff)
4743 goto theend;
4744
4745 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4746
Bram Moolenaar4a696342018-04-05 18:45:26 +02004747 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004748 if (textline == NULL)
4749 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004750 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4751 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4752 vim_free(textline);
4753
4754 textline = get_separator(width, fname2);
4755 if (textline == NULL)
4756 goto theend;
4757 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4758 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004759 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004760
4761 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004762 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004763 if (width2 > width)
4764 {
4765 vim_free(textline);
4766 textline = alloc(width2 + 1);
4767 if (textline == NULL)
4768 goto theend;
4769 width = width2;
4770 textline[width] = NUL;
4771 }
4772 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4773
4774 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4775 {
4776 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4777 {
4778 /* bottom part has fewer rows, fill with "-" */
4779 for (i = 0; i < width; ++i)
4780 textline[i] = '-';
4781 }
4782 else
4783 {
4784 char_u *line1;
4785 char_u *line2;
4786 char_u *p1;
4787 char_u *p2;
4788 int col;
4789 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4790 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4791 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4792 ->sb_cells;
4793
4794 /* Make a copy, getting the second line will invalidate it. */
4795 line1 = vim_strsave(ml_get(lnum));
4796 if (line1 == NULL)
4797 break;
4798 p1 = line1;
4799
4800 line2 = ml_get(lnum + bot_lnum);
4801 p2 = line2;
4802 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4803 {
4804 int len1 = utfc_ptr2len(p1);
4805 int len2 = utfc_ptr2len(p2);
4806
4807 textline[col] = ' ';
4808 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004809 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004810 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004811 else if (lnum == cursor_pos1.row + 1
4812 && col == cursor_pos1.col
4813 && (cursor_pos1.row != cursor_pos2.row
4814 || cursor_pos1.col != cursor_pos2.col))
4815 /* cursor in first but not in second */
4816 textline[col] = '>';
4817 else if (lnum == cursor_pos2.row + 1
4818 && col == cursor_pos2.col
4819 && (cursor_pos1.row != cursor_pos2.row
4820 || cursor_pos1.col != cursor_pos2.col))
4821 /* cursor in second but not in first */
4822 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004823 else if (cellattr1 != NULL && cellattr2 != NULL)
4824 {
4825 if ((cellattr1 + col)->width
4826 != (cellattr2 + col)->width)
4827 textline[col] = 'w';
4828 else if (!same_color(&(cellattr1 + col)->fg,
4829 &(cellattr2 + col)->fg))
4830 textline[col] = 'f';
4831 else if (!same_color(&(cellattr1 + col)->bg,
4832 &(cellattr2 + col)->bg))
4833 textline[col] = 'b';
4834 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4835 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4836 textline[col] = 'a';
4837 }
4838 p1 += len1;
4839 p2 += len2;
4840 /* TODO: handle different width */
4841 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004842
4843 while (col < width)
4844 {
4845 if (*p1 == NUL && *p2 == NUL)
4846 textline[col] = '?';
4847 else if (*p1 == NUL)
4848 {
4849 textline[col] = '+';
4850 p2 += utfc_ptr2len(p2);
4851 }
4852 else
4853 {
4854 textline[col] = '-';
4855 p1 += utfc_ptr2len(p1);
4856 }
4857 ++col;
4858 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004859
4860 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004861 }
4862 if (add_empty_scrollback(term, &term->tl_default_color,
4863 term->tl_top_diff_rows) == OK)
4864 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4865 ++bot_lnum;
4866 }
4867
4868 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4869 {
4870 /* bottom part has more rows, fill with "+" */
4871 for (i = 0; i < width; ++i)
4872 textline[i] = '+';
4873 if (add_empty_scrollback(term, &term->tl_default_color,
4874 term->tl_top_diff_rows) == OK)
4875 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4876 ++lnum;
4877 ++bot_lnum;
4878 }
4879
4880 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004881
4882 /* looks better without wrapping */
4883 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004884 }
4885
4886theend:
4887 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004888 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004889 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004890 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004891 fclose(fd2);
4892}
4893
4894/*
4895 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4896 * bottom files.
4897 * Return FAIL when this is not possible.
4898 */
4899 int
4900term_swap_diff()
4901{
4902 term_T *term = curbuf->b_term;
4903 linenr_T line_count;
4904 linenr_T top_rows;
4905 linenr_T bot_rows;
4906 linenr_T bot_start;
4907 linenr_T lnum;
4908 char_u *p;
4909 sb_line_T *sb_line;
4910
4911 if (term == NULL
4912 || !term_is_finished(curbuf)
4913 || term->tl_top_diff_rows == 0
4914 || term->tl_scrollback.ga_len == 0)
4915 return FAIL;
4916
4917 line_count = curbuf->b_ml.ml_line_count;
4918 top_rows = term->tl_top_diff_rows;
4919 bot_rows = term->tl_bot_diff_rows;
4920 bot_start = line_count - bot_rows;
4921 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4922
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004923 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01004924 for (lnum = 1; lnum <= top_rows; ++lnum)
4925 {
4926 p = vim_strsave(ml_get(1));
4927 if (p == NULL)
4928 return OK;
4929 ml_append(bot_start, p, 0, FALSE);
4930 ml_delete(1, FALSE);
4931 vim_free(p);
4932 }
4933
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004934 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01004935 for (lnum = 1; lnum <= bot_rows; ++lnum)
4936 {
4937 p = vim_strsave(ml_get(bot_start + lnum));
4938 if (p == NULL)
4939 return OK;
4940 ml_delete(bot_start + lnum, FALSE);
4941 ml_append(lnum - 1, p, 0, FALSE);
4942 vim_free(p);
4943 }
4944
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004945 // move top title to bottom
4946 p = vim_strsave(ml_get(bot_rows + 1));
4947 if (p == NULL)
4948 return OK;
4949 ml_append(line_count - top_rows - 1, p, 0, FALSE);
4950 ml_delete(bot_rows + 1, FALSE);
4951 vim_free(p);
4952
4953 // move bottom title to top
4954 p = vim_strsave(ml_get(line_count - top_rows));
4955 if (p == NULL)
4956 return OK;
4957 ml_delete(line_count - top_rows, FALSE);
4958 ml_append(bot_rows, p, 0, FALSE);
4959 vim_free(p);
4960
Bram Moolenaard96ff162018-02-18 22:13:29 +01004961 if (top_rows == bot_rows)
4962 {
4963 /* rows counts are equal, can swap cell properties */
4964 for (lnum = 0; lnum < top_rows; ++lnum)
4965 {
4966 sb_line_T temp;
4967
4968 temp = *(sb_line + lnum);
4969 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4970 *(sb_line + bot_start + lnum) = temp;
4971 }
4972 }
4973 else
4974 {
4975 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004976 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004977
4978 /* need to copy cell properties into temp memory */
4979 if (temp != NULL)
4980 {
4981 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4982 mch_memmove(term->tl_scrollback.ga_data,
4983 temp + bot_start,
4984 sizeof(sb_line_T) * bot_rows);
4985 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4986 temp + top_rows,
4987 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4988 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4989 + line_count - top_rows,
4990 temp,
4991 sizeof(sb_line_T) * top_rows);
4992 vim_free(temp);
4993 }
4994 }
4995
4996 term->tl_top_diff_rows = bot_rows;
4997 term->tl_bot_diff_rows = top_rows;
4998
4999 update_screen(NOT_VALID);
5000 return OK;
5001}
5002
5003/*
5004 * "term_dumpdiff(filename, filename, options)" function
5005 */
5006 void
5007f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5008{
5009 term_load_dump(argvars, rettv, TRUE);
5010}
5011
5012/*
5013 * "term_dumpload(filename, options)" function
5014 */
5015 void
5016f_term_dumpload(typval_T *argvars, typval_T *rettv)
5017{
5018 term_load_dump(argvars, rettv, FALSE);
5019}
5020
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005021/*
5022 * "term_getaltscreen(buf)" function
5023 */
5024 void
5025f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5026{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005027 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005028
5029 if (buf == NULL)
5030 return;
5031 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5032}
5033
5034/*
5035 * "term_getattr(attr, name)" function
5036 */
5037 void
5038f_term_getattr(typval_T *argvars, typval_T *rettv)
5039{
5040 int attr;
5041 size_t i;
5042 char_u *name;
5043
5044 static struct {
5045 char *name;
5046 int attr;
5047 } attrs[] = {
5048 {"bold", HL_BOLD},
5049 {"italic", HL_ITALIC},
5050 {"underline", HL_UNDERLINE},
5051 {"strike", HL_STRIKETHROUGH},
5052 {"reverse", HL_INVERSE},
5053 };
5054
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005055 attr = tv_get_number(&argvars[0]);
5056 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005057 if (name == NULL)
5058 return;
5059
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005060 if (attr > HL_ALL)
5061 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005062 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5063 if (STRCMP(name, attrs[i].name) == 0)
5064 {
5065 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5066 break;
5067 }
5068}
5069
5070/*
5071 * "term_getcursor(buf)" function
5072 */
5073 void
5074f_term_getcursor(typval_T *argvars, typval_T *rettv)
5075{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005076 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005077 term_T *term;
5078 list_T *l;
5079 dict_T *d;
5080
5081 if (rettv_list_alloc(rettv) == FAIL)
5082 return;
5083 if (buf == NULL)
5084 return;
5085 term = buf->b_term;
5086
5087 l = rettv->vval.v_list;
5088 list_append_number(l, term->tl_cursor_pos.row + 1);
5089 list_append_number(l, term->tl_cursor_pos.col + 1);
5090
5091 d = dict_alloc();
5092 if (d != NULL)
5093 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005094 dict_add_number(d, "visible", term->tl_cursor_visible);
5095 dict_add_number(d, "blink", blink_state_is_inverted()
5096 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5097 dict_add_number(d, "shape", term->tl_cursor_shape);
5098 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005099 list_append_dict(l, d);
5100 }
5101}
5102
5103/*
5104 * "term_getjob(buf)" function
5105 */
5106 void
5107f_term_getjob(typval_T *argvars, typval_T *rettv)
5108{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005109 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005110
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005111 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005112 {
5113 rettv->v_type = VAR_SPECIAL;
5114 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005115 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005116 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005117
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005118 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005119 rettv->vval.v_job = buf->b_term->tl_job;
5120 if (rettv->vval.v_job != NULL)
5121 ++rettv->vval.v_job->jv_refcount;
5122}
5123
5124 static int
5125get_row_number(typval_T *tv, term_T *term)
5126{
5127 if (tv->v_type == VAR_STRING
5128 && tv->vval.v_string != NULL
5129 && STRCMP(tv->vval.v_string, ".") == 0)
5130 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005131 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005132}
5133
5134/*
5135 * "term_getline(buf, row)" function
5136 */
5137 void
5138f_term_getline(typval_T *argvars, typval_T *rettv)
5139{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005140 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005141 term_T *term;
5142 int row;
5143
5144 rettv->v_type = VAR_STRING;
5145 if (buf == NULL)
5146 return;
5147 term = buf->b_term;
5148 row = get_row_number(&argvars[1], term);
5149
5150 if (term->tl_vterm == NULL)
5151 {
5152 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5153
5154 /* vterm is finished, get the text from the buffer */
5155 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5156 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5157 }
5158 else
5159 {
5160 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5161 VTermRect rect;
5162 int len;
5163 char_u *p;
5164
5165 if (row < 0 || row >= term->tl_rows)
5166 return;
5167 len = term->tl_cols * MB_MAXBYTES + 1;
5168 p = alloc(len);
5169 if (p == NULL)
5170 return;
5171 rettv->vval.v_string = p;
5172
5173 rect.start_col = 0;
5174 rect.end_col = term->tl_cols;
5175 rect.start_row = row;
5176 rect.end_row = row + 1;
5177 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5178 }
5179}
5180
5181/*
5182 * "term_getscrolled(buf)" function
5183 */
5184 void
5185f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5186{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005187 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005188
5189 if (buf == NULL)
5190 return;
5191 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5192}
5193
5194/*
5195 * "term_getsize(buf)" function
5196 */
5197 void
5198f_term_getsize(typval_T *argvars, typval_T *rettv)
5199{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005200 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005201 list_T *l;
5202
5203 if (rettv_list_alloc(rettv) == FAIL)
5204 return;
5205 if (buf == NULL)
5206 return;
5207
5208 l = rettv->vval.v_list;
5209 list_append_number(l, buf->b_term->tl_rows);
5210 list_append_number(l, buf->b_term->tl_cols);
5211}
5212
5213/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005214 * "term_setsize(buf, rows, cols)" function
5215 */
5216 void
5217f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5218{
5219 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5220 term_T *term;
5221 varnumber_T rows, cols;
5222
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005223 if (buf == NULL)
5224 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005225 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005226 return;
5227 }
5228 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005229 return;
5230 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005231 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005232 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005233 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005234 cols = cols <= 0 ? term->tl_cols : cols;
5235 vterm_set_size(term->tl_vterm, rows, cols);
5236 /* handle_resize() will resize the windows */
5237
5238 /* Get and remember the size we ended up with. Update the pty. */
5239 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5240 term_report_winsize(term, term->tl_rows, term->tl_cols);
5241}
5242
5243/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005244 * "term_getstatus(buf)" function
5245 */
5246 void
5247f_term_getstatus(typval_T *argvars, typval_T *rettv)
5248{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005249 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005250 term_T *term;
5251 char_u val[100];
5252
5253 rettv->v_type = VAR_STRING;
5254 if (buf == NULL)
5255 return;
5256 term = buf->b_term;
5257
5258 if (term_job_running(term))
5259 STRCPY(val, "running");
5260 else
5261 STRCPY(val, "finished");
5262 if (term->tl_normal_mode)
5263 STRCAT(val, ",normal");
5264 rettv->vval.v_string = vim_strsave(val);
5265}
5266
5267/*
5268 * "term_gettitle(buf)" function
5269 */
5270 void
5271f_term_gettitle(typval_T *argvars, typval_T *rettv)
5272{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005273 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005274
5275 rettv->v_type = VAR_STRING;
5276 if (buf == NULL)
5277 return;
5278
5279 if (buf->b_term->tl_title != NULL)
5280 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5281}
5282
5283/*
5284 * "term_gettty(buf)" function
5285 */
5286 void
5287f_term_gettty(typval_T *argvars, typval_T *rettv)
5288{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005289 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005290 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005291 int num = 0;
5292
5293 rettv->v_type = VAR_STRING;
5294 if (buf == NULL)
5295 return;
5296 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005297 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005298
5299 switch (num)
5300 {
5301 case 0:
5302 if (buf->b_term->tl_job != NULL)
5303 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005304 break;
5305 case 1:
5306 if (buf->b_term->tl_job != NULL)
5307 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005308 break;
5309 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005310 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005311 return;
5312 }
5313 if (p != NULL)
5314 rettv->vval.v_string = vim_strsave(p);
5315}
5316
5317/*
5318 * "term_list()" function
5319 */
5320 void
5321f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5322{
5323 term_T *tp;
5324 list_T *l;
5325
5326 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5327 return;
5328
5329 l = rettv->vval.v_list;
5330 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5331 if (tp != NULL && tp->tl_buffer != NULL)
5332 if (list_append_number(l,
5333 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5334 return;
5335}
5336
5337/*
5338 * "term_scrape(buf, row)" function
5339 */
5340 void
5341f_term_scrape(typval_T *argvars, typval_T *rettv)
5342{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005343 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005344 VTermScreen *screen = NULL;
5345 VTermPos pos;
5346 list_T *l;
5347 term_T *term;
5348 char_u *p;
5349 sb_line_T *line;
5350
5351 if (rettv_list_alloc(rettv) == FAIL)
5352 return;
5353 if (buf == NULL)
5354 return;
5355 term = buf->b_term;
5356
5357 l = rettv->vval.v_list;
5358 pos.row = get_row_number(&argvars[1], term);
5359
5360 if (term->tl_vterm != NULL)
5361 {
5362 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005363 if (screen == NULL) // can't really happen
5364 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005365 p = NULL;
5366 line = NULL;
5367 }
5368 else
5369 {
5370 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5371
5372 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5373 return;
5374 p = ml_get_buf(buf, lnum + 1, FALSE);
5375 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5376 }
5377
5378 for (pos.col = 0; pos.col < term->tl_cols; )
5379 {
5380 dict_T *dcell;
5381 int width;
5382 VTermScreenCellAttrs attrs;
5383 VTermColor fg, bg;
5384 char_u rgb[8];
5385 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5386 int off = 0;
5387 int i;
5388
5389 if (screen == NULL)
5390 {
5391 cellattr_T *cellattr;
5392 int len;
5393
5394 /* vterm has finished, get the cell from scrollback */
5395 if (pos.col >= line->sb_cols)
5396 break;
5397 cellattr = line->sb_cells + pos.col;
5398 width = cellattr->width;
5399 attrs = cellattr->attrs;
5400 fg = cellattr->fg;
5401 bg = cellattr->bg;
5402 len = MB_PTR2LEN(p);
5403 mch_memmove(mbs, p, len);
5404 mbs[len] = NUL;
5405 p += len;
5406 }
5407 else
5408 {
5409 VTermScreenCell cell;
5410 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5411 break;
5412 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5413 {
5414 if (cell.chars[i] == 0)
5415 break;
5416 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5417 }
5418 mbs[off] = NUL;
5419 width = cell.width;
5420 attrs = cell.attrs;
5421 fg = cell.fg;
5422 bg = cell.bg;
5423 }
5424 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005425 if (dcell == NULL)
5426 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005427 list_append_dict(l, dcell);
5428
Bram Moolenaare0be1672018-07-08 16:50:37 +02005429 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005430
5431 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5432 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005433 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005434 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5435 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005436 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005437
Bram Moolenaare0be1672018-07-08 16:50:37 +02005438 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5439 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005440
5441 ++pos.col;
5442 if (width == 2)
5443 ++pos.col;
5444 }
5445}
5446
5447/*
5448 * "term_sendkeys(buf, keys)" function
5449 */
5450 void
5451f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5452{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005453 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005454 char_u *msg;
5455 term_T *term;
5456
5457 rettv->v_type = VAR_UNKNOWN;
5458 if (buf == NULL)
5459 return;
5460
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005461 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005462 if (msg == NULL)
5463 return;
5464 term = buf->b_term;
5465 if (term->tl_vterm == NULL)
5466 return;
5467
5468 while (*msg != NUL)
5469 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005470 int c;
5471
5472 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5473 {
5474 c = TO_SPECIAL(msg[1], msg[2]);
5475 msg += 3;
5476 }
5477 else
5478 {
5479 c = PTR2CHAR(msg);
5480 msg += MB_CPTR2LEN(msg);
5481 }
5482 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005483 }
5484}
5485
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005486#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5487/*
5488 * "term_getansicolors(buf)" function
5489 */
5490 void
5491f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5492{
5493 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5494 term_T *term;
5495 VTermState *state;
5496 VTermColor color;
5497 char_u hexbuf[10];
5498 int index;
5499 list_T *list;
5500
5501 if (rettv_list_alloc(rettv) == FAIL)
5502 return;
5503
5504 if (buf == NULL)
5505 return;
5506 term = buf->b_term;
5507 if (term->tl_vterm == NULL)
5508 return;
5509
5510 list = rettv->vval.v_list;
5511 state = vterm_obtain_state(term->tl_vterm);
5512 for (index = 0; index < 16; index++)
5513 {
5514 vterm_state_get_palette_color(state, index, &color);
5515 sprintf((char *)hexbuf, "#%02x%02x%02x",
5516 color.red, color.green, color.blue);
5517 if (list_append_string(list, hexbuf, 7) == FAIL)
5518 return;
5519 }
5520}
5521
5522/*
5523 * "term_setansicolors(buf, list)" function
5524 */
5525 void
5526f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5527{
5528 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5529 term_T *term;
5530
5531 if (buf == NULL)
5532 return;
5533 term = buf->b_term;
5534 if (term->tl_vterm == NULL)
5535 return;
5536
5537 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5538 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005539 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005540 return;
5541 }
5542
5543 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005544 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005545}
5546#endif
5547
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005548/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005549 * "term_setrestore(buf, command)" function
5550 */
5551 void
5552f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5553{
5554#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005555 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005556 term_T *term;
5557 char_u *cmd;
5558
5559 if (buf == NULL)
5560 return;
5561 term = buf->b_term;
5562 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005563 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005564 if (cmd != NULL)
5565 term->tl_command = vim_strsave(cmd);
5566 else
5567 term->tl_command = NULL;
5568#endif
5569}
5570
5571/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005572 * "term_setkill(buf, how)" function
5573 */
5574 void
5575f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5576{
5577 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5578 term_T *term;
5579 char_u *how;
5580
5581 if (buf == NULL)
5582 return;
5583 term = buf->b_term;
5584 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005585 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005586 if (how != NULL)
5587 term->tl_kill = vim_strsave(how);
5588 else
5589 term->tl_kill = NULL;
5590}
5591
5592/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005593 * "term_start(command, options)" function
5594 */
5595 void
5596f_term_start(typval_T *argvars, typval_T *rettv)
5597{
5598 jobopt_T opt;
5599 buf_T *buf;
5600
5601 init_job_options(&opt);
5602 if (argvars[1].v_type != VAR_UNKNOWN
5603 && get_job_options(&argvars[1], &opt,
5604 JO_TIMEOUT_ALL + JO_STOPONEXIT
5605 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5606 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5607 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5608 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005609 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005610 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01005611 + JO2_ANSI_COLORS + JO2_TTY_TYPE) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005612 return;
5613
Bram Moolenaar13568252018-03-16 20:46:58 +01005614 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005615
5616 if (buf != NULL && buf->b_term != NULL)
5617 rettv->vval.v_number = buf->b_fnum;
5618}
5619
5620/*
5621 * "term_wait" function
5622 */
5623 void
5624f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5625{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005626 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005627
5628 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005629 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005630 if (buf->b_term->tl_job == NULL)
5631 {
5632 ch_log(NULL, "term_wait(): no job to wait for");
5633 return;
5634 }
5635 if (buf->b_term->tl_job->jv_channel == NULL)
5636 /* channel is closed, nothing to do */
5637 return;
5638
5639 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005640 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005641 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5642 {
5643 /* The job is dead, keep reading channel I/O until the channel is
5644 * closed. buf->b_term may become NULL if the terminal was closed while
5645 * waiting. */
5646 ch_log(NULL, "term_wait(): waiting for channel to close");
5647 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5648 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005649 term_flush_messages();
5650
Bram Moolenaard45aa552018-05-21 22:50:29 +02005651 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005652 if (!buf_valid(buf))
5653 /* If the terminal is closed when the channel is closed the
5654 * buffer disappears. */
5655 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005656 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005657
5658 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005659 }
5660 else
5661 {
5662 long wait = 10L;
5663
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005664 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005665
5666 /* Wait for some time for any channel I/O. */
5667 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005668 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005669 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005670
5671 /* Flushing messages on channels is hopefully sufficient.
5672 * TODO: is there a better way? */
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005673 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005674 }
5675}
5676
5677/*
5678 * Called when a channel has sent all the lines to a terminal.
5679 * Send a CTRL-D to mark the end of the text.
5680 */
5681 void
5682term_send_eof(channel_T *ch)
5683{
5684 term_T *term;
5685
5686 for (term = first_term; term != NULL; term = term->tl_next)
5687 if (term->tl_job == ch->ch_job)
5688 {
5689 if (term->tl_eof_chars != NULL)
5690 {
5691 channel_send(ch, PART_IN, term->tl_eof_chars,
5692 (int)STRLEN(term->tl_eof_chars), NULL);
5693 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5694 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005695# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005696 else
5697 /* Default: CTRL-D */
5698 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5699# endif
5700 }
5701}
5702
Bram Moolenaar113e1072019-01-20 15:30:40 +01005703#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005704 job_T *
5705term_getjob(term_T *term)
5706{
5707 return term != NULL ? term->tl_job : NULL;
5708}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005709#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005710
Bram Moolenaar4f974752019-02-17 17:44:42 +01005711# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005712
5713/**************************************
5714 * 2. MS-Windows implementation.
5715 */
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005716#ifdef PROTO
5717typedef int COORD;
5718typedef int DWORD;
5719typedef int HANDLE;
5720typedef int *DWORD_PTR;
5721typedef int HPCON;
5722typedef int HRESULT;
5723typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005724typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005725typedef int PSIZE_T;
5726typedef int PVOID;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005727typedef int WINAPI;
5728#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005729
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005730HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5731HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5732HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005733BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5734BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5735void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005736
5737 static int
5738dyn_conpty_init(int verbose)
5739{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005740 static HMODULE hKerneldll = NULL;
5741 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005742 static struct
5743 {
5744 char *name;
5745 FARPROC *ptr;
5746 } conpty_entry[] =
5747 {
5748 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5749 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5750 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5751 {"InitializeProcThreadAttributeList",
5752 (FARPROC*)&pInitializeProcThreadAttributeList},
5753 {"UpdateProcThreadAttribute",
5754 (FARPROC*)&pUpdateProcThreadAttribute},
5755 {"DeleteProcThreadAttributeList",
5756 (FARPROC*)&pDeleteProcThreadAttributeList},
5757 {NULL, NULL}
5758 };
5759
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005760 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005761 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005762 if (verbose)
5763 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005764 return FAIL;
5765 }
5766
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005767 // No need to initialize twice.
5768 if (hKerneldll)
5769 return OK;
5770
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005771 hKerneldll = vimLoadLib("kernel32.dll");
5772 for (i = 0; conpty_entry[i].name != NULL
5773 && conpty_entry[i].ptr != NULL; ++i)
5774 {
5775 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5776 conpty_entry[i].name)) == NULL)
5777 {
5778 if (verbose)
5779 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005780 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005781 return FAIL;
5782 }
5783 }
5784
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005785 return OK;
5786}
5787
5788 static int
5789conpty_term_and_job_init(
5790 term_T *term,
5791 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005792 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005793 jobopt_T *opt,
5794 jobopt_T *orig_opt)
5795{
5796 WCHAR *cmd_wchar = NULL;
5797 WCHAR *cmd_wchar_copy = NULL;
5798 WCHAR *cwd_wchar = NULL;
5799 WCHAR *env_wchar = NULL;
5800 channel_T *channel = NULL;
5801 job_T *job = NULL;
5802 HANDLE jo = NULL;
5803 garray_T ga_cmd, ga_env;
5804 char_u *cmd = NULL;
5805 HRESULT hr;
5806 COORD consize;
5807 SIZE_T breq;
5808 PROCESS_INFORMATION proc_info;
5809 HANDLE i_theirs = NULL;
5810 HANDLE o_theirs = NULL;
5811 HANDLE i_ours = NULL;
5812 HANDLE o_ours = NULL;
5813
5814 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5815 ga_init2(&ga_env, (int)sizeof(char*), 20);
5816
5817 if (argvar->v_type == VAR_STRING)
5818 {
5819 cmd = argvar->vval.v_string;
5820 }
5821 else if (argvar->v_type == VAR_LIST)
5822 {
5823 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5824 goto failed;
5825 cmd = ga_cmd.ga_data;
5826 }
5827 if (cmd == NULL || *cmd == NUL)
5828 {
5829 emsg(_(e_invarg));
5830 goto failed;
5831 }
5832
5833 term->tl_arg0_cmd = vim_strsave(cmd);
5834
5835 cmd_wchar = enc_to_utf16(cmd, NULL);
5836
5837 if (cmd_wchar != NULL)
5838 {
5839 /* Request by CreateProcessW */
5840 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005841 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005842 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5843 }
5844
5845 ga_clear(&ga_cmd);
5846 if (cmd_wchar == NULL)
5847 goto failed;
5848 if (opt->jo_cwd != NULL)
5849 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5850
5851 win32_build_env(opt->jo_env, &ga_env, TRUE);
5852 env_wchar = ga_env.ga_data;
5853
5854 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5855 goto failed;
5856 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5857 goto failed;
5858
5859 consize.X = term->tl_cols;
5860 consize.Y = term->tl_rows;
5861 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
5862 &term->tl_conpty);
5863 if (FAILED(hr))
5864 goto failed;
5865
5866 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
5867
5868 /* Set up pipe inheritance safely: Vista or later. */
5869 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005870 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005871 if (!term->tl_siex.lpAttributeList)
5872 goto failed;
5873 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
5874 0, &breq))
5875 goto failed;
5876 if (!pUpdateProcThreadAttribute(
5877 term->tl_siex.lpAttributeList, 0,
5878 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
5879 sizeof(HPCON), NULL, NULL))
5880 goto failed;
5881
5882 channel = add_channel();
5883 if (channel == NULL)
5884 goto failed;
5885
5886 job = job_alloc();
5887 if (job == NULL)
5888 goto failed;
5889 if (argvar->v_type == VAR_STRING)
5890 {
5891 int argc;
5892
5893 build_argv_from_string(cmd, &job->jv_argv, &argc);
5894 }
5895 else
5896 {
5897 int argc;
5898
5899 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5900 }
5901
5902 if (opt->jo_set & JO_IN_BUF)
5903 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5904
5905 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
5906 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
5907 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
5908 | CREATE_DEFAULT_ERROR_MODE,
5909 env_wchar, cwd_wchar,
5910 &term->tl_siex.StartupInfo, &proc_info))
5911 goto failed;
5912
5913 CloseHandle(i_theirs);
5914 CloseHandle(o_theirs);
5915
5916 channel_set_pipes(channel,
5917 (sock_T)i_ours,
5918 (sock_T)o_ours,
5919 (sock_T)o_ours);
5920
5921 /* Write lines with CR instead of NL. */
5922 channel->ch_write_text_mode = TRUE;
5923
5924 /* Use to explicitly delete anonymous pipe handle. */
5925 channel->ch_anonymous_pipe = TRUE;
5926
5927 jo = CreateJobObject(NULL, NULL);
5928 if (jo == NULL)
5929 goto failed;
5930
5931 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
5932 {
5933 /* Failed, switch the way to terminate process with TerminateProcess. */
5934 CloseHandle(jo);
5935 jo = NULL;
5936 }
5937
5938 ResumeThread(proc_info.hThread);
5939 CloseHandle(proc_info.hThread);
5940
5941 vim_free(cmd_wchar);
5942 vim_free(cmd_wchar_copy);
5943 vim_free(cwd_wchar);
5944 vim_free(env_wchar);
5945
5946 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
5947 goto failed;
5948
5949#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5950 if (opt->jo_set2 & JO2_ANSI_COLORS)
5951 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5952 else
5953 init_vterm_ansi_colors(term->tl_vterm);
5954#endif
5955
5956 channel_set_job(channel, job, opt);
5957 job_set_options(job, opt);
5958
5959 job->jv_channel = channel;
5960 job->jv_proc_info = proc_info;
5961 job->jv_job_object = jo;
5962 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01005963 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005964 ++job->jv_refcount;
5965 term->tl_job = job;
5966
5967 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5968 * open the file here and handle it in. opt->jo_io was changed in
5969 * setup_job_options(), use the original flags here. */
5970 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5971 {
5972 char_u *fname = opt->jo_io_name[PART_OUT];
5973
5974 ch_log(channel, "Opening output file %s", fname);
5975 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5976 if (term->tl_out_fd == NULL)
5977 semsg(_(e_notopen), fname);
5978 }
5979
5980 return OK;
5981
5982failed:
5983 ga_clear(&ga_cmd);
5984 ga_clear(&ga_env);
5985 vim_free(cmd_wchar);
5986 vim_free(cmd_wchar_copy);
5987 vim_free(cwd_wchar);
5988 if (channel != NULL)
5989 channel_clear(channel);
5990 if (job != NULL)
5991 {
5992 job->jv_channel = NULL;
5993 job_cleanup(job);
5994 }
5995 term->tl_job = NULL;
5996 if (jo != NULL)
5997 CloseHandle(jo);
5998
5999 if (term->tl_siex.lpAttributeList != NULL)
6000 {
6001 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6002 vim_free(term->tl_siex.lpAttributeList);
6003 }
6004 term->tl_siex.lpAttributeList = NULL;
6005 if (o_theirs != NULL)
6006 CloseHandle(o_theirs);
6007 if (o_ours != NULL)
6008 CloseHandle(o_ours);
6009 if (i_ours != NULL)
6010 CloseHandle(i_ours);
6011 if (i_theirs != NULL)
6012 CloseHandle(i_theirs);
6013 if (term->tl_conpty != NULL)
6014 pClosePseudoConsole(term->tl_conpty);
6015 term->tl_conpty = NULL;
6016 return FAIL;
6017}
6018
6019 static void
6020conpty_term_report_winsize(term_T *term, int rows, int cols)
6021{
6022 COORD consize;
6023
6024 consize.X = cols;
6025 consize.Y = rows;
6026 pResizePseudoConsole(term->tl_conpty, consize);
6027}
6028
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006029 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006030term_free_conpty(term_T *term)
6031{
6032 if (term->tl_siex.lpAttributeList != NULL)
6033 {
6034 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6035 vim_free(term->tl_siex.lpAttributeList);
6036 }
6037 term->tl_siex.lpAttributeList = NULL;
6038 if (term->tl_conpty != NULL)
6039 pClosePseudoConsole(term->tl_conpty);
6040 term->tl_conpty = NULL;
6041}
6042
6043 int
6044use_conpty(void)
6045{
6046 return has_conpty;
6047}
6048
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006049# ifndef PROTO
6050
6051#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6052#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006053#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006054
6055void* (*winpty_config_new)(UINT64, void*);
6056void* (*winpty_open)(void*, void*);
6057void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6058BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6059void (*winpty_config_set_mouse_mode)(void*, int);
6060void (*winpty_config_set_initial_size)(void*, int, int);
6061LPCWSTR (*winpty_conin_name)(void*);
6062LPCWSTR (*winpty_conout_name)(void*);
6063LPCWSTR (*winpty_conerr_name)(void*);
6064void (*winpty_free)(void*);
6065void (*winpty_config_free)(void*);
6066void (*winpty_spawn_config_free)(void*);
6067void (*winpty_error_free)(void*);
6068LPCWSTR (*winpty_error_msg)(void*);
6069BOOL (*winpty_set_size)(void*, int, int, void*);
6070HANDLE (*winpty_agent_process)(void*);
6071
6072#define WINPTY_DLL "winpty.dll"
6073
6074static HINSTANCE hWinPtyDLL = NULL;
6075# endif
6076
6077 static int
6078dyn_winpty_init(int verbose)
6079{
6080 int i;
6081 static struct
6082 {
6083 char *name;
6084 FARPROC *ptr;
6085 } winpty_entry[] =
6086 {
6087 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6088 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6089 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6090 {"winpty_config_set_mouse_mode",
6091 (FARPROC*)&winpty_config_set_mouse_mode},
6092 {"winpty_config_set_initial_size",
6093 (FARPROC*)&winpty_config_set_initial_size},
6094 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6095 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6096 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6097 {"winpty_free", (FARPROC*)&winpty_free},
6098 {"winpty_open", (FARPROC*)&winpty_open},
6099 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6100 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6101 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6102 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6103 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6104 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6105 {NULL, NULL}
6106 };
6107
6108 /* No need to initialize twice. */
6109 if (hWinPtyDLL)
6110 return OK;
6111 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6112 * winpty.dll. */
6113 if (*p_winptydll != NUL)
6114 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6115 if (!hWinPtyDLL)
6116 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6117 if (!hWinPtyDLL)
6118 {
6119 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006120 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006121 : (char_u *)WINPTY_DLL);
6122 return FAIL;
6123 }
6124 for (i = 0; winpty_entry[i].name != NULL
6125 && winpty_entry[i].ptr != NULL; ++i)
6126 {
6127 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6128 winpty_entry[i].name)) == NULL)
6129 {
6130 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006131 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006132 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006133 return FAIL;
6134 }
6135 }
6136
6137 return OK;
6138}
6139
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006140 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006141winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006142 term_T *term,
6143 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006144 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006145 jobopt_T *opt,
6146 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006147{
6148 WCHAR *cmd_wchar = NULL;
6149 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006150 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006151 channel_T *channel = NULL;
6152 job_T *job = NULL;
6153 DWORD error;
6154 HANDLE jo = NULL;
6155 HANDLE child_process_handle;
6156 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006157 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006158 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006159 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006160 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006161
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006162 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6163 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006164
6165 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006166 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006167 cmd = argvar->vval.v_string;
6168 }
6169 else if (argvar->v_type == VAR_LIST)
6170 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006171 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006172 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006173 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006174 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006175 if (cmd == NULL || *cmd == NUL)
6176 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006177 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006178 goto failed;
6179 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006180
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006181 term->tl_arg0_cmd = vim_strsave(cmd);
6182
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006183 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006184 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006185 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006186 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006187 if (opt->jo_cwd != NULL)
6188 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006189
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006190 win32_build_env(opt->jo_env, &ga_env, TRUE);
6191 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006192
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006193 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6194 if (term->tl_winpty_config == NULL)
6195 goto failed;
6196
6197 winpty_config_set_mouse_mode(term->tl_winpty_config,
6198 WINPTY_MOUSE_MODE_FORCE);
6199 winpty_config_set_initial_size(term->tl_winpty_config,
6200 term->tl_cols, term->tl_rows);
6201 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6202 if (term->tl_winpty == NULL)
6203 goto failed;
6204
6205 spawn_config = winpty_spawn_config_new(
6206 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6207 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6208 NULL,
6209 cmd_wchar,
6210 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006211 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006212 &winpty_err);
6213 if (spawn_config == NULL)
6214 goto failed;
6215
6216 channel = add_channel();
6217 if (channel == NULL)
6218 goto failed;
6219
6220 job = job_alloc();
6221 if (job == NULL)
6222 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006223 if (argvar->v_type == VAR_STRING)
6224 {
6225 int argc;
6226
6227 build_argv_from_string(cmd, &job->jv_argv, &argc);
6228 }
6229 else
6230 {
6231 int argc;
6232
6233 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6234 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006235
6236 if (opt->jo_set & JO_IN_BUF)
6237 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6238
6239 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6240 &child_thread_handle, &error, &winpty_err))
6241 goto failed;
6242
6243 channel_set_pipes(channel,
6244 (sock_T)CreateFileW(
6245 winpty_conin_name(term->tl_winpty),
6246 GENERIC_WRITE, 0, NULL,
6247 OPEN_EXISTING, 0, NULL),
6248 (sock_T)CreateFileW(
6249 winpty_conout_name(term->tl_winpty),
6250 GENERIC_READ, 0, NULL,
6251 OPEN_EXISTING, 0, NULL),
6252 (sock_T)CreateFileW(
6253 winpty_conerr_name(term->tl_winpty),
6254 GENERIC_READ, 0, NULL,
6255 OPEN_EXISTING, 0, NULL));
6256
6257 /* Write lines with CR instead of NL. */
6258 channel->ch_write_text_mode = TRUE;
6259
6260 jo = CreateJobObject(NULL, NULL);
6261 if (jo == NULL)
6262 goto failed;
6263
6264 if (!AssignProcessToJobObject(jo, child_process_handle))
6265 {
6266 /* Failed, switch the way to terminate process with TerminateProcess. */
6267 CloseHandle(jo);
6268 jo = NULL;
6269 }
6270
6271 winpty_spawn_config_free(spawn_config);
6272 vim_free(cmd_wchar);
6273 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006274 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006275
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006276 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6277 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006278
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006279#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6280 if (opt->jo_set2 & JO2_ANSI_COLORS)
6281 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6282 else
6283 init_vterm_ansi_colors(term->tl_vterm);
6284#endif
6285
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006286 channel_set_job(channel, job, opt);
6287 job_set_options(job, opt);
6288
6289 job->jv_channel = channel;
6290 job->jv_proc_info.hProcess = child_process_handle;
6291 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6292 job->jv_job_object = jo;
6293 job->jv_status = JOB_STARTED;
6294 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006295 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006296 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006297 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006298 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006299 ++job->jv_refcount;
6300 term->tl_job = job;
6301
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006302 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6303 * open the file here and handle it in. opt->jo_io was changed in
6304 * setup_job_options(), use the original flags here. */
6305 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6306 {
6307 char_u *fname = opt->jo_io_name[PART_OUT];
6308
6309 ch_log(channel, "Opening output file %s", fname);
6310 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6311 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006312 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006313 }
6314
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006315 return OK;
6316
6317failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006318 ga_clear(&ga_cmd);
6319 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006320 vim_free(cmd_wchar);
6321 vim_free(cwd_wchar);
6322 if (spawn_config != NULL)
6323 winpty_spawn_config_free(spawn_config);
6324 if (channel != NULL)
6325 channel_clear(channel);
6326 if (job != NULL)
6327 {
6328 job->jv_channel = NULL;
6329 job_cleanup(job);
6330 }
6331 term->tl_job = NULL;
6332 if (jo != NULL)
6333 CloseHandle(jo);
6334 if (term->tl_winpty != NULL)
6335 winpty_free(term->tl_winpty);
6336 term->tl_winpty = NULL;
6337 if (term->tl_winpty_config != NULL)
6338 winpty_config_free(term->tl_winpty_config);
6339 term->tl_winpty_config = NULL;
6340 if (winpty_err != NULL)
6341 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006342 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006343 (short_u *)winpty_error_msg(winpty_err), NULL);
6344
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006345 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006346 winpty_error_free(winpty_err);
6347 }
6348 return FAIL;
6349}
6350
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006351/*
6352 * Create a new terminal of "rows" by "cols" cells.
6353 * Store a reference in "term".
6354 * Return OK or FAIL.
6355 */
6356 static int
6357term_and_job_init(
6358 term_T *term,
6359 typval_T *argvar,
6360 char **argv UNUSED,
6361 jobopt_T *opt,
6362 jobopt_T *orig_opt)
6363{
6364 int use_winpty = FALSE;
6365 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006366 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006367
6368 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6369 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6370
6371 if (!has_winpty && !has_conpty)
6372 // If neither is available give the errors for winpty, since when
6373 // conpty is not available it can't be installed either.
6374 return dyn_winpty_init(TRUE);
6375
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006376 if (opt->jo_tty_type != NUL)
6377 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006378
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006379 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006380 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006381 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006382 use_conpty = TRUE;
6383 else if (has_winpty)
6384 use_winpty = TRUE;
6385 // else: error
6386 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006387 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006388 {
6389 if (has_winpty)
6390 use_winpty = TRUE;
6391 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006392 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006393 {
6394 if (has_conpty)
6395 use_conpty = TRUE;
6396 else
6397 return dyn_conpty_init(TRUE);
6398 }
6399
6400 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006401 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006402
6403 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006404 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006405
6406 // error
6407 return dyn_winpty_init(TRUE);
6408}
6409
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006410 static int
6411create_pty_only(term_T *term, jobopt_T *options)
6412{
6413 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6414 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6415 char in_name[80], out_name[80];
6416 channel_T *channel = NULL;
6417
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006418 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6419 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006420
6421 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6422 GetCurrentProcessId(),
6423 curbuf->b_fnum);
6424 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6425 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6426 PIPE_UNLIMITED_INSTANCES,
6427 0, 0, NMPWAIT_NOWAIT, NULL);
6428 if (hPipeIn == INVALID_HANDLE_VALUE)
6429 goto failed;
6430
6431 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6432 GetCurrentProcessId(),
6433 curbuf->b_fnum);
6434 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6435 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6436 PIPE_UNLIMITED_INSTANCES,
6437 0, 0, 0, NULL);
6438 if (hPipeOut == INVALID_HANDLE_VALUE)
6439 goto failed;
6440
6441 ConnectNamedPipe(hPipeIn, NULL);
6442 ConnectNamedPipe(hPipeOut, NULL);
6443
6444 term->tl_job = job_alloc();
6445 if (term->tl_job == NULL)
6446 goto failed;
6447 ++term->tl_job->jv_refcount;
6448
6449 /* behave like the job is already finished */
6450 term->tl_job->jv_status = JOB_FINISHED;
6451
6452 channel = add_channel();
6453 if (channel == NULL)
6454 goto failed;
6455 term->tl_job->jv_channel = channel;
6456 channel->ch_keep_open = TRUE;
6457 channel->ch_named_pipe = TRUE;
6458
6459 channel_set_pipes(channel,
6460 (sock_T)hPipeIn,
6461 (sock_T)hPipeOut,
6462 (sock_T)hPipeOut);
6463 channel_set_job(channel, term->tl_job, options);
6464 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6465 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6466
6467 return OK;
6468
6469failed:
6470 if (hPipeIn != NULL)
6471 CloseHandle(hPipeIn);
6472 if (hPipeOut != NULL)
6473 CloseHandle(hPipeOut);
6474 return FAIL;
6475}
6476
6477/*
6478 * Free the terminal emulator part of "term".
6479 */
6480 static void
6481term_free_vterm(term_T *term)
6482{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006483 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006484 if (term->tl_winpty != NULL)
6485 winpty_free(term->tl_winpty);
6486 term->tl_winpty = NULL;
6487 if (term->tl_winpty_config != NULL)
6488 winpty_config_free(term->tl_winpty_config);
6489 term->tl_winpty_config = NULL;
6490 if (term->tl_vterm != NULL)
6491 vterm_free(term->tl_vterm);
6492 term->tl_vterm = NULL;
6493}
6494
6495/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006496 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006497 */
6498 static void
6499term_report_winsize(term_T *term, int rows, int cols)
6500{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006501 if (term->tl_conpty)
6502 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006503 if (term->tl_winpty)
6504 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6505}
6506
6507 int
6508terminal_enabled(void)
6509{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006510 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006511}
6512
6513# else
6514
6515/**************************************
6516 * 3. Unix-like implementation.
6517 */
6518
6519/*
6520 * Create a new terminal of "rows" by "cols" cells.
6521 * Start job for "cmd".
6522 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006523 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006524 * Return OK or FAIL.
6525 */
6526 static int
6527term_and_job_init(
6528 term_T *term,
6529 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006530 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006531 jobopt_T *opt,
6532 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006533{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006534 term->tl_arg0_cmd = NULL;
6535
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006536 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6537 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006538
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006539#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6540 if (opt->jo_set2 & JO2_ANSI_COLORS)
6541 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6542 else
6543 init_vterm_ansi_colors(term->tl_vterm);
6544#endif
6545
Bram Moolenaar13568252018-03-16 20:46:58 +01006546 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006547 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006548 if (term->tl_job != NULL)
6549 ++term->tl_job->jv_refcount;
6550
6551 return term->tl_job != NULL
6552 && term->tl_job->jv_channel != NULL
6553 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6554}
6555
6556 static int
6557create_pty_only(term_T *term, jobopt_T *opt)
6558{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006559 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6560 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006561
6562 term->tl_job = job_alloc();
6563 if (term->tl_job == NULL)
6564 return FAIL;
6565 ++term->tl_job->jv_refcount;
6566
6567 /* behave like the job is already finished */
6568 term->tl_job->jv_status = JOB_FINISHED;
6569
6570 return mch_create_pty_channel(term->tl_job, opt);
6571}
6572
6573/*
6574 * Free the terminal emulator part of "term".
6575 */
6576 static void
6577term_free_vterm(term_T *term)
6578{
6579 if (term->tl_vterm != NULL)
6580 vterm_free(term->tl_vterm);
6581 term->tl_vterm = NULL;
6582}
6583
6584/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006585 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006586 */
6587 static void
6588term_report_winsize(term_T *term, int rows, int cols)
6589{
6590 /* Use an ioctl() to report the new window size to the job. */
6591 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6592 {
6593 int fd = -1;
6594 int part;
6595
6596 for (part = PART_OUT; part < PART_COUNT; ++part)
6597 {
6598 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006599 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006600 break;
6601 }
6602 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6603 mch_signal_job(term->tl_job, (char_u *)"winch");
6604 }
6605}
6606
6607# endif
6608
6609#endif /* FEAT_TERMINAL */