blob: 93b08170760a31c74167026a444388a8ddbad59a [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.
878term_T *terminals_to_free = NULL;
879
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
960get_tty_part(term_T *term)
961{
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 {
2375 stuffcharReadbuff(Ctrl_W);
2376 stuffcharReadbuff(c);
2377 ret = OK;
2378 goto theend;
2379 }
2380 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002381# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002382 if (!enc_utf8 && has_mbyte && c >= 0x80)
2383 {
2384 WCHAR wc;
2385 char_u mb[3];
2386
2387 mb[0] = (unsigned)c >> 8;
2388 mb[1] = c;
2389 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2390 c = wc;
2391 }
2392# endif
2393 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2394 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002395 if (c == K_MOUSEMOVE)
2396 /* We are sure to come back here, don't reset the cursor color
2397 * and shape to avoid flickering. */
2398 restore_cursor = FALSE;
2399
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002400 ret = OK;
2401 goto theend;
2402 }
2403 }
2404 ret = FAIL;
2405
2406theend:
2407 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002408 if (restore_cursor)
2409 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002410
2411 /* Move a snapshot of the screen contents to the buffer, so that completion
2412 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002413 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2414 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002415
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002416 return ret;
2417}
2418
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002419 static void
2420may_toggle_cursor(term_T *term)
2421{
2422 if (in_terminal_loop == term)
2423 {
2424 if (term->tl_cursor_visible)
2425 cursor_on();
2426 else
2427 cursor_off();
2428 }
2429}
2430
2431/*
2432 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002433 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002434 */
2435 static int
2436color2index(VTermColor *color, int fg, int *boldp)
2437{
2438 int red = color->red;
2439 int blue = color->blue;
2440 int green = color->green;
2441
Bram Moolenaar46359e12017-11-29 22:33:38 +01002442 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002443 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002444 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002445 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002446 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002447 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002448 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002449 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2450 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2451 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002452 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002453 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2454 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2455 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2456 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2457 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2458 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2459 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2460 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2461 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2462 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2463 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002464 }
2465 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002466
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002467 if (t_colors >= 256)
2468 {
2469 if (red == blue && red == green)
2470 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002471 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002472 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002473 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2474 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2475 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002476 int i;
2477
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002478 if (red < 5)
2479 return 17; /* 00/00/00 */
2480 if (red > 245) /* ff/ff/ff */
2481 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002482 for (i = 0; i < 23; ++i)
2483 if (red < cutoff[i])
2484 return i + 233;
2485 return 256;
2486 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002487 {
2488 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2489 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002490
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002491 /* 216-color cube */
2492 for (ri = 0; ri < 5; ++ri)
2493 if (red < cutoff[ri])
2494 break;
2495 for (gi = 0; gi < 5; ++gi)
2496 if (green < cutoff[gi])
2497 break;
2498 for (bi = 0; bi < 5; ++bi)
2499 if (blue < cutoff[bi])
2500 break;
2501 return 17 + ri * 36 + gi * 6 + bi;
2502 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 }
2504 return 0;
2505}
2506
2507/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002508 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002509 */
2510 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002511vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002512{
2513 int attr = 0;
2514
2515 if (cellattrs.bold)
2516 attr |= HL_BOLD;
2517 if (cellattrs.underline)
2518 attr |= HL_UNDERLINE;
2519 if (cellattrs.italic)
2520 attr |= HL_ITALIC;
2521 if (cellattrs.strike)
2522 attr |= HL_STRIKETHROUGH;
2523 if (cellattrs.reverse)
2524 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002525 return attr;
2526}
2527
2528/*
2529 * Store Vterm attributes in "cell" from highlight flags.
2530 */
2531 static void
2532hl2vtermAttr(int attr, cellattr_T *cell)
2533{
2534 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2535 if (attr & HL_BOLD)
2536 cell->attrs.bold = 1;
2537 if (attr & HL_UNDERLINE)
2538 cell->attrs.underline = 1;
2539 if (attr & HL_ITALIC)
2540 cell->attrs.italic = 1;
2541 if (attr & HL_STRIKETHROUGH)
2542 cell->attrs.strike = 1;
2543 if (attr & HL_INVERSE)
2544 cell->attrs.reverse = 1;
2545}
2546
2547/*
2548 * Convert the attributes of a vterm cell into an attribute index.
2549 */
2550 static int
2551cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2552{
2553 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002554
2555#ifdef FEAT_GUI
2556 if (gui.in_use)
2557 {
2558 guicolor_T fg, bg;
2559
2560 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2561 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2562 return get_gui_attr_idx(attr, fg, bg);
2563 }
2564 else
2565#endif
2566#ifdef FEAT_TERMGUICOLORS
2567 if (p_tgc)
2568 {
2569 guicolor_T fg, bg;
2570
2571 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2572 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2573
2574 return get_tgc_attr_idx(attr, fg, bg);
2575 }
2576 else
2577#endif
2578 {
2579 int bold = MAYBE;
2580 int fg = color2index(&cellfg, TRUE, &bold);
2581 int bg = color2index(&cellbg, FALSE, &bold);
2582
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002583 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002584 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002585 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002586 if (fg == 0 && term_default_cterm_fg >= 0)
2587 fg = term_default_cterm_fg + 1;
2588 if (bg == 0 && term_default_cterm_bg >= 0)
2589 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002590 }
2591
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002592 /* with 8 colors set the bold attribute to get a bright foreground */
2593 if (bold == TRUE)
2594 attr |= HL_BOLD;
2595 return get_cterm_attr_idx(attr, fg, bg);
2596 }
2597 return 0;
2598}
2599
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002600 static void
2601set_dirty_snapshot(term_T *term)
2602{
2603 term->tl_dirty_snapshot = TRUE;
2604#ifdef FEAT_TIMERS
2605 if (!term->tl_normal_mode)
2606 {
2607 /* Update the snapshot after 100 msec of not getting updates. */
2608 profile_setlimit(100L, &term->tl_timer_due);
2609 term->tl_timer_set = TRUE;
2610 }
2611#endif
2612}
2613
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002614 static int
2615handle_damage(VTermRect rect, void *user)
2616{
2617 term_T *term = (term_T *)user;
2618
2619 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2620 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002621 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002622 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002623 return 1;
2624}
2625
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002626 static void
2627term_scroll_up(term_T *term, int start_row, int count)
2628{
2629 win_T *wp;
2630 VTermColor fg, bg;
2631 VTermScreenCellAttrs attr;
2632 int clear_attr;
2633
2634 /* Set the color to clear lines with. */
2635 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2636 &fg, &bg);
2637 vim_memset(&attr, 0, sizeof(attr));
2638 clear_attr = cell2attr(attr, fg, bg);
2639
2640 FOR_ALL_WINDOWS(wp)
2641 {
2642 if (wp->w_buffer == term->tl_buffer)
2643 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2644 }
2645}
2646
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002647 static int
2648handle_moverect(VTermRect dest, VTermRect src, void *user)
2649{
2650 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002651 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002652
2653 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002654 * redrawing the text. But avoid doing this multiple times, postpone until
2655 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002656 if (dest.start_col == src.start_col
2657 && dest.end_col == src.end_col
2658 && dest.start_row < src.start_row)
2659 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002660 if (dest.start_row == 0)
2661 term->tl_postponed_scroll += count;
2662 else
2663 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002664 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002665
2666 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2667 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002668 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002669
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002670 /* Note sure if the scrolling will work correctly, let's do a complete
2671 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002672 redraw_buf_later(term->tl_buffer, NOT_VALID);
2673 return 1;
2674}
2675
2676 static int
2677handle_movecursor(
2678 VTermPos pos,
2679 VTermPos oldpos UNUSED,
2680 int visible,
2681 void *user)
2682{
2683 term_T *term = (term_T *)user;
2684 win_T *wp;
2685
2686 term->tl_cursor_pos = pos;
2687 term->tl_cursor_visible = visible;
2688
2689 FOR_ALL_WINDOWS(wp)
2690 {
2691 if (wp->w_buffer == term->tl_buffer)
2692 position_cursor(wp, &pos);
2693 }
2694 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2695 {
2696 may_toggle_cursor(term);
2697 update_cursor(term, term->tl_cursor_visible);
2698 }
2699
2700 return 1;
2701}
2702
2703 static int
2704handle_settermprop(
2705 VTermProp prop,
2706 VTermValue *value,
2707 void *user)
2708{
2709 term_T *term = (term_T *)user;
2710
2711 switch (prop)
2712 {
2713 case VTERM_PROP_TITLE:
2714 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002715 // a blank title isn't useful, make it empty, so that "running" is
2716 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002717 if (*skipwhite((char_u *)value->string) == NUL)
2718 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002719 // Same as blank
2720 else if (term->tl_arg0_cmd != NULL
2721 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2722 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2723 term->tl_title = NULL;
2724 // Empty corrupted data of winpty
2725 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2726 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002727#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002728 else if (!enc_utf8 && enc_codepage > 0)
2729 {
2730 WCHAR *ret = NULL;
2731 int length = 0;
2732
2733 MultiByteToWideChar_alloc(CP_UTF8, 0,
2734 (char*)value->string, (int)STRLEN(value->string),
2735 &ret, &length);
2736 if (ret != NULL)
2737 {
2738 WideCharToMultiByte_alloc(enc_codepage, 0,
2739 ret, length, (char**)&term->tl_title,
2740 &length, 0, 0);
2741 vim_free(ret);
2742 }
2743 }
2744#endif
2745 else
2746 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002747 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002748 if (term == curbuf->b_term)
2749 maketitle();
2750 break;
2751
2752 case VTERM_PROP_CURSORVISIBLE:
2753 term->tl_cursor_visible = value->boolean;
2754 may_toggle_cursor(term);
2755 out_flush();
2756 break;
2757
2758 case VTERM_PROP_CURSORBLINK:
2759 term->tl_cursor_blink = value->boolean;
2760 may_set_cursor_props(term);
2761 break;
2762
2763 case VTERM_PROP_CURSORSHAPE:
2764 term->tl_cursor_shape = value->number;
2765 may_set_cursor_props(term);
2766 break;
2767
2768 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002769 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002770 may_set_cursor_props(term);
2771 break;
2772
2773 case VTERM_PROP_ALTSCREEN:
2774 /* TODO: do anything else? */
2775 term->tl_using_altscreen = value->boolean;
2776 break;
2777
2778 default:
2779 break;
2780 }
2781 /* Always return 1, otherwise vterm doesn't store the value internally. */
2782 return 1;
2783}
2784
2785/*
2786 * The job running in the terminal resized the terminal.
2787 */
2788 static int
2789handle_resize(int rows, int cols, void *user)
2790{
2791 term_T *term = (term_T *)user;
2792 win_T *wp;
2793
2794 term->tl_rows = rows;
2795 term->tl_cols = cols;
2796 if (term->tl_vterm_size_changed)
2797 /* Size was set by vterm_set_size(), don't set the window size. */
2798 term->tl_vterm_size_changed = FALSE;
2799 else
2800 {
2801 FOR_ALL_WINDOWS(wp)
2802 {
2803 if (wp->w_buffer == term->tl_buffer)
2804 {
2805 win_setheight_win(rows, wp);
2806 win_setwidth_win(cols, wp);
2807 }
2808 }
2809 redraw_buf_later(term->tl_buffer, NOT_VALID);
2810 }
2811 return 1;
2812}
2813
2814/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002815 * If the number of lines that are stored goes over 'termscrollback' then
2816 * delete the first 10%.
2817 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2818 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002819 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002820 static void
2821limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002822{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002823 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002824 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002825 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002826 int i;
2827
2828 curbuf = term->tl_buffer;
2829 for (i = 0; i < todo; ++i)
2830 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002831 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
2832 if (update_buffer)
2833 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002834 }
2835 curbuf = curwin->w_buffer;
2836
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002837 gap->ga_len -= todo;
2838 mch_memmove(gap->ga_data,
2839 (sb_line_T *)gap->ga_data + todo,
2840 sizeof(sb_line_T) * gap->ga_len);
2841 if (update_buffer)
2842 term->tl_scrollback_scrolled -= todo;
2843 }
2844}
2845
2846/*
2847 * Handle a line that is pushed off the top of the screen.
2848 */
2849 static int
2850handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2851{
2852 term_T *term = (term_T *)user;
2853 garray_T *gap;
2854 int update_buffer;
2855
2856 if (term->tl_normal_mode)
2857 {
2858 // In Terminal-Normal mode the user interacts with the buffer, thus we
2859 // must not change it. Postpone adding the scrollback lines.
2860 gap = &term->tl_scrollback_postponed;
2861 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002862 }
2863 else
2864 {
2865 // First remove the lines that were appended before, the pushed line
2866 // goes above it.
2867 cleanup_scrollback(term);
2868 gap = &term->tl_scrollback;
2869 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002870 }
2871
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002872 limit_scrollback(term, gap, update_buffer);
2873
2874 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002875 {
2876 cellattr_T *p = NULL;
2877 int len = 0;
2878 int i;
2879 int c;
2880 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002881 int text_len;
2882 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002883 sb_line_T *line;
2884 garray_T ga;
2885 cellattr_T fill_attr = term->tl_default_color;
2886
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002887 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888 for (i = 0; i < cols; ++i)
2889 if (cells[i].chars[0] != 0)
2890 len = i + 1;
2891 else
2892 cell2cellattr(&cells[i], &fill_attr);
2893
2894 ga_init2(&ga, 1, 100);
2895 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002896 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002897 if (p != NULL)
2898 {
2899 for (col = 0; col < len; col += cells[col].width)
2900 {
2901 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2902 {
2903 ga.ga_len = 0;
2904 break;
2905 }
2906 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2907 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2908 (char_u *)ga.ga_data + ga.ga_len);
2909 cell2cellattr(&cells[col], &p[col]);
2910 }
2911 }
2912 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002913 {
2914 if (update_buffer)
2915 text = (char_u *)"";
2916 else
2917 text = vim_strsave((char_u *)"");
2918 text_len = 0;
2919 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002920 else
2921 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002922 text = ga.ga_data;
2923 text_len = ga.ga_len;
2924 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002926 if (update_buffer)
2927 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002928
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002929 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002930 line->sb_cols = len;
2931 line->sb_cells = p;
2932 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002933 if (update_buffer)
2934 {
2935 line->sb_text = NULL;
2936 ++term->tl_scrollback_scrolled;
2937 ga_clear(&ga); // free the text
2938 }
2939 else
2940 {
2941 line->sb_text = text;
2942 ga_init(&ga); // text is kept in tl_scrollback_postponed
2943 }
2944 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002945 }
2946 return 0; /* ignored */
2947}
2948
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002949/*
2950 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
2951 * received and stored in tl_scrollback_postponed.
2952 */
2953 static void
2954handle_postponed_scrollback(term_T *term)
2955{
2956 int i;
2957
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01002958 if (term->tl_scrollback_postponed.ga_len == 0)
2959 return;
2960 ch_log(NULL, "Moving postponed scrollback to scrollback");
2961
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002962 // First remove the lines that were appended before, the pushed lines go
2963 // above it.
2964 cleanup_scrollback(term);
2965
2966 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
2967 {
2968 char_u *text;
2969 sb_line_T *pp_line;
2970 sb_line_T *line;
2971
2972 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
2973 break;
2974 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
2975
2976 text = pp_line->sb_text;
2977 if (text == NULL)
2978 text = (char_u *)"";
2979 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
2980 vim_free(pp_line->sb_text);
2981
2982 line = (sb_line_T *)term->tl_scrollback.ga_data
2983 + term->tl_scrollback.ga_len;
2984 line->sb_cols = pp_line->sb_cols;
2985 line->sb_cells = pp_line->sb_cells;
2986 line->sb_fill_attr = pp_line->sb_fill_attr;
2987 line->sb_text = NULL;
2988 ++term->tl_scrollback_scrolled;
2989 ++term->tl_scrollback.ga_len;
2990 }
2991
2992 ga_clear(&term->tl_scrollback_postponed);
2993 limit_scrollback(term, &term->tl_scrollback, TRUE);
2994}
2995
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002996static VTermScreenCallbacks screen_callbacks = {
2997 handle_damage, /* damage */
2998 handle_moverect, /* moverect */
2999 handle_movecursor, /* movecursor */
3000 handle_settermprop, /* settermprop */
3001 NULL, /* bell */
3002 handle_resize, /* resize */
3003 handle_pushline, /* sb_pushline */
3004 NULL /* sb_popline */
3005};
3006
3007/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003008 * Do the work after the channel of a terminal was closed.
3009 * Must be called only when updating_screen is FALSE.
3010 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3011 */
3012 static int
3013term_after_channel_closed(term_T *term)
3014{
3015 /* Unless in Terminal-Normal mode: clear the vterm. */
3016 if (!term->tl_normal_mode)
3017 {
3018 int fnum = term->tl_buffer->b_fnum;
3019
3020 cleanup_vterm(term);
3021
3022 if (term->tl_finish == TL_FINISH_CLOSE)
3023 {
3024 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003025 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003026
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003027 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003028 ch_log(NULL, "terminal job finished, closing window");
3029 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003030 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003031 if (curwin == aucmd_win)
3032 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003033 if (do_set_w_closing)
3034 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003035 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003036 if (do_set_w_closing)
3037 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003038 aucmd_restbuf(&aco);
3039 return TRUE;
3040 }
3041 if (term->tl_finish == TL_FINISH_OPEN
3042 && term->tl_buffer->b_nwindows == 0)
3043 {
3044 char buf[50];
3045
3046 /* TODO: use term_opencmd */
3047 ch_log(NULL, "terminal job finished, opening window");
3048 vim_snprintf(buf, sizeof(buf),
3049 term->tl_opencmd == NULL
3050 ? "botright sbuf %d"
3051 : (char *)term->tl_opencmd, fnum);
3052 do_cmdline_cmd((char_u *)buf);
3053 }
3054 else
3055 ch_log(NULL, "terminal job finished");
3056 }
3057
3058 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3059 return FALSE;
3060}
3061
3062/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003063 * Called when a channel has been closed.
3064 * If this was a channel for a terminal window then finish it up.
3065 */
3066 void
3067term_channel_closed(channel_T *ch)
3068{
3069 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003070 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003071 int did_one = FALSE;
3072
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003073 for (term = first_term; term != NULL; term = next_term)
3074 {
3075 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003076 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003077 {
3078 term->tl_channel_closed = TRUE;
3079 did_one = TRUE;
3080
Bram Moolenaard23a8232018-02-10 18:45:26 +01003081 VIM_CLEAR(term->tl_title);
3082 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003083#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003084 if (term->tl_out_fd != NULL)
3085 {
3086 fclose(term->tl_out_fd);
3087 term->tl_out_fd = NULL;
3088 }
3089#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003090
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003091 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003092 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003093 /* Cannot open or close windows now. Can happen when
3094 * 'lazyredraw' is set. */
3095 term->tl_channel_recently_closed = TRUE;
3096 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097 }
3098
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003099 if (term_after_channel_closed(term))
3100 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003101 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003102 }
3103
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003104 if (did_one)
3105 {
3106 redraw_statuslines();
3107
3108 /* Need to break out of vgetc(). */
3109 ins_char_typebuf(K_IGNORE);
3110 typebuf_was_filled = TRUE;
3111
3112 term = curbuf->b_term;
3113 if (term != NULL)
3114 {
3115 if (term->tl_job == ch->ch_job)
3116 maketitle();
3117 update_cursor(term, term->tl_cursor_visible);
3118 }
3119 }
3120}
3121
3122/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003123 * To be called after resetting updating_screen: handle any terminal where the
3124 * channel was closed.
3125 */
3126 void
3127term_check_channel_closed_recently()
3128{
3129 term_T *term;
3130 term_T *next_term;
3131
3132 for (term = first_term; term != NULL; term = next_term)
3133 {
3134 next_term = term->tl_next;
3135 if (term->tl_channel_recently_closed)
3136 {
3137 term->tl_channel_recently_closed = FALSE;
3138 if (term_after_channel_closed(term))
3139 // start over, the list may have changed
3140 next_term = first_term;
3141 }
3142 }
3143}
3144
3145/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003146 * Fill one screen line from a line of the terminal.
3147 * Advances "pos" to past the last column.
3148 */
3149 static void
3150term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3151{
3152 int off = screen_get_current_line_off();
3153
3154 for (pos->col = 0; pos->col < max_col; )
3155 {
3156 VTermScreenCell cell;
3157 int c;
3158
3159 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3160 vim_memset(&cell, 0, sizeof(cell));
3161
3162 c = cell.chars[0];
3163 if (c == NUL)
3164 {
3165 ScreenLines[off] = ' ';
3166 if (enc_utf8)
3167 ScreenLinesUC[off] = NUL;
3168 }
3169 else
3170 {
3171 if (enc_utf8)
3172 {
3173 int i;
3174
3175 /* composing chars */
3176 for (i = 0; i < Screen_mco
3177 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3178 {
3179 ScreenLinesC[i][off] = cell.chars[i + 1];
3180 if (cell.chars[i + 1] == 0)
3181 break;
3182 }
3183 if (c >= 0x80 || (Screen_mco > 0
3184 && ScreenLinesC[0][off] != 0))
3185 {
3186 ScreenLines[off] = ' ';
3187 ScreenLinesUC[off] = c;
3188 }
3189 else
3190 {
3191 ScreenLines[off] = c;
3192 ScreenLinesUC[off] = NUL;
3193 }
3194 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003195#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003196 else if (has_mbyte && c >= 0x80)
3197 {
3198 char_u mb[MB_MAXBYTES+1];
3199 WCHAR wc = c;
3200
3201 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3202 (char*)mb, 2, 0, 0) > 1)
3203 {
3204 ScreenLines[off] = mb[0];
3205 ScreenLines[off + 1] = mb[1];
3206 cell.width = mb_ptr2cells(mb);
3207 }
3208 else
3209 ScreenLines[off] = c;
3210 }
3211#endif
3212 else
3213 ScreenLines[off] = c;
3214 }
3215 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3216
3217 ++pos->col;
3218 ++off;
3219 if (cell.width == 2)
3220 {
3221 if (enc_utf8)
3222 ScreenLinesUC[off] = NUL;
3223
3224 /* don't set the second byte to NUL for a DBCS encoding, it
3225 * has been set above */
3226 if (enc_utf8 || !has_mbyte)
3227 ScreenLines[off] = NUL;
3228
3229 ++pos->col;
3230 ++off;
3231 }
3232 }
3233}
3234
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003235#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003236 static void
3237update_system_term(term_T *term)
3238{
3239 VTermPos pos;
3240 VTermScreen *screen;
3241
3242 if (term->tl_vterm == NULL)
3243 return;
3244 screen = vterm_obtain_screen(term->tl_vterm);
3245
3246 /* Scroll up to make more room for terminal lines if needed. */
3247 while (term->tl_toprow > 0
3248 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3249 {
3250 int save_p_more = p_more;
3251
3252 p_more = FALSE;
3253 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003254 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003255 p_more = save_p_more;
3256 --term->tl_toprow;
3257 }
3258
3259 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3260 && pos.row < Rows; ++pos.row)
3261 {
3262 if (pos.row < term->tl_rows)
3263 {
3264 int max_col = MIN(Columns, term->tl_cols);
3265
3266 term_line2screenline(screen, &pos, max_col);
3267 }
3268 else
3269 pos.col = 0;
3270
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003271 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003272 }
3273
3274 term->tl_dirty_row_start = MAX_ROW;
3275 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003276}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003277#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003278
3279/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003280 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3281 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003282 * Terminal-Normal mode.
3283 */
3284 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003285term_do_update_window(win_T *wp)
3286{
3287 term_T *term = wp->w_buffer->b_term;
3288
3289 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3290}
3291
3292/*
3293 * Called to update a window that contains an active terminal.
3294 */
3295 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003296term_update_window(win_T *wp)
3297{
3298 term_T *term = wp->w_buffer->b_term;
3299 VTerm *vterm;
3300 VTermScreen *screen;
3301 VTermState *state;
3302 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003303 int rows, cols;
3304 int newrows, newcols;
3305 int minsize;
3306 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003307
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003308 vterm = term->tl_vterm;
3309 screen = vterm_obtain_screen(vterm);
3310 state = vterm_obtain_state(vterm);
3311
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003312 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3313 * SOME_VALID only redraw what was marked dirty. */
3314 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003315 {
3316 term->tl_dirty_row_start = 0;
3317 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003318
3319 if (term->tl_postponed_scroll > 0
3320 && term->tl_postponed_scroll < term->tl_rows / 3)
3321 /* Scrolling is usually faster than redrawing, when there are only
3322 * a few lines to scroll. */
3323 term_scroll_up(term, 0, term->tl_postponed_scroll);
3324 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003325 }
3326
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003327 /*
3328 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003329 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003330 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003331 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003332
Bram Moolenaar498c2562018-04-15 23:45:15 +02003333 newrows = 99999;
3334 newcols = 99999;
3335 FOR_ALL_WINDOWS(twp)
3336 {
3337 /* When more than one window shows the same terminal, use the
3338 * smallest size. */
3339 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003340 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003341 newrows = MIN(newrows, twp->w_height);
3342 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003343 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003344 }
3345 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3346 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3347
3348 if (term->tl_rows != newrows || term->tl_cols != newcols)
3349 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003350 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003351 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003352 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003353 newrows);
3354 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003355
3356 // Updating the terminal size will cause the snapshot to be cleared.
3357 // When not in terminal_loop() we need to restore it.
3358 if (term != in_terminal_loop)
3359 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003360 }
3361
3362 /* The cursor may have been moved when resizing. */
3363 vterm_state_get_cursorpos(state, &pos);
3364 position_cursor(wp, &pos);
3365
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003366 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3367 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003368 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003369 if (pos.row < term->tl_rows)
3370 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003371 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003372
Bram Moolenaar13568252018-03-16 20:46:58 +01003373 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003374 }
3375 else
3376 pos.col = 0;
3377
Bram Moolenaarf118d482018-03-13 13:14:00 +01003378 screen_line(wp->w_winrow + pos.row
3379#ifdef FEAT_MENU
3380 + winbar_height(wp)
3381#endif
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003382 , wp->w_wincol, pos.col, wp->w_width, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003383 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003384 term->tl_dirty_row_start = MAX_ROW;
3385 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003386}
3387
3388/*
3389 * Return TRUE if "wp" is a terminal window where the job has finished.
3390 */
3391 int
3392term_is_finished(buf_T *buf)
3393{
3394 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3395}
3396
3397/*
3398 * Return TRUE if "wp" is a terminal window where the job has finished or we
3399 * are in Terminal-Normal mode, thus we show the buffer contents.
3400 */
3401 int
3402term_show_buffer(buf_T *buf)
3403{
3404 term_T *term = buf->b_term;
3405
3406 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3407}
3408
3409/*
3410 * The current buffer is going to be changed. If there is terminal
3411 * highlighting remove it now.
3412 */
3413 void
3414term_change_in_curbuf(void)
3415{
3416 term_T *term = curbuf->b_term;
3417
3418 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3419 {
3420 free_scrollback(term);
3421 redraw_buf_later(term->tl_buffer, NOT_VALID);
3422
3423 /* The buffer is now like a normal buffer, it cannot be easily
3424 * abandoned when changed. */
3425 set_string_option_direct((char_u *)"buftype", -1,
3426 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3427 }
3428}
3429
3430/*
3431 * Get the screen attribute for a position in the buffer.
3432 * Use a negative "col" to get the filler background color.
3433 */
3434 int
3435term_get_attr(buf_T *buf, linenr_T lnum, int col)
3436{
3437 term_T *term = buf->b_term;
3438 sb_line_T *line;
3439 cellattr_T *cellattr;
3440
3441 if (lnum > term->tl_scrollback.ga_len)
3442 cellattr = &term->tl_default_color;
3443 else
3444 {
3445 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3446 if (col < 0 || col >= line->sb_cols)
3447 cellattr = &line->sb_fill_attr;
3448 else
3449 cellattr = line->sb_cells + col;
3450 }
3451 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3452}
3453
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003454/*
3455 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003456 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003457 */
3458 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003459cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003460{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003461 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003462}
3463
3464/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003465 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003466 */
3467 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003468init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003469{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003470 VTermColor *fg, *bg;
3471 int fgval, bgval;
3472 int id;
3473
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003474 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3475 term->tl_default_color.width = 1;
3476 fg = &term->tl_default_color.fg;
3477 bg = &term->tl_default_color.bg;
3478
3479 /* Vterm uses a default black background. Set it to white when
3480 * 'background' is "light". */
3481 if (*p_bg == 'l')
3482 {
3483 fgval = 0;
3484 bgval = 255;
3485 }
3486 else
3487 {
3488 fgval = 255;
3489 bgval = 0;
3490 }
3491 fg->red = fg->green = fg->blue = fgval;
3492 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003493 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003494
3495 /* The "Terminal" highlight group overrules the defaults. */
3496 id = syn_name2id((char_u *)"Terminal");
3497
Bram Moolenaar46359e12017-11-29 22:33:38 +01003498 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003499#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3500 if (0
3501# ifdef FEAT_GUI
3502 || gui.in_use
3503# endif
3504# ifdef FEAT_TERMGUICOLORS
3505 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003506# ifdef FEAT_VTP
3507 /* Finally get INVALCOLOR on this execution path */
3508 || (!p_tgc && t_colors >= 256)
3509# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003510# endif
3511 )
3512 {
3513 guicolor_T fg_rgb = INVALCOLOR;
3514 guicolor_T bg_rgb = INVALCOLOR;
3515
3516 if (id != 0)
3517 syn_id2colors(id, &fg_rgb, &bg_rgb);
3518
3519# ifdef FEAT_GUI
3520 if (gui.in_use)
3521 {
3522 if (fg_rgb == INVALCOLOR)
3523 fg_rgb = gui.norm_pixel;
3524 if (bg_rgb == INVALCOLOR)
3525 bg_rgb = gui.back_pixel;
3526 }
3527# ifdef FEAT_TERMGUICOLORS
3528 else
3529# endif
3530# endif
3531# ifdef FEAT_TERMGUICOLORS
3532 {
3533 if (fg_rgb == INVALCOLOR)
3534 fg_rgb = cterm_normal_fg_gui_color;
3535 if (bg_rgb == INVALCOLOR)
3536 bg_rgb = cterm_normal_bg_gui_color;
3537 }
3538# endif
3539 if (fg_rgb != INVALCOLOR)
3540 {
3541 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3542
3543 fg->red = (unsigned)(rgb >> 16);
3544 fg->green = (unsigned)(rgb >> 8) & 255;
3545 fg->blue = (unsigned)rgb & 255;
3546 }
3547 if (bg_rgb != INVALCOLOR)
3548 {
3549 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3550
3551 bg->red = (unsigned)(rgb >> 16);
3552 bg->green = (unsigned)(rgb >> 8) & 255;
3553 bg->blue = (unsigned)rgb & 255;
3554 }
3555 }
3556 else
3557#endif
3558 if (id != 0 && t_colors >= 16)
3559 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003560 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003561 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003562 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003563 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003564 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003565 else
3566 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003567#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003568 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003569#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003570
3571 /* In an MS-Windows console we know the normal colors. */
3572 if (cterm_normal_fg_color > 0)
3573 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003574 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003575# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3576# ifdef VIMDLL
3577 if (!gui.in_use)
3578# endif
3579 {
3580 tmp = fg->red;
3581 fg->red = fg->blue;
3582 fg->blue = tmp;
3583 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003584# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003585 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003586# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003587 else
3588 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003589# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003590
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003591 if (cterm_normal_bg_color > 0)
3592 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003593 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003594# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3595# ifdef VIMDLL
3596 if (!gui.in_use)
3597# endif
3598 {
3599 tmp = fg->red;
3600 fg->red = fg->blue;
3601 fg->blue = tmp;
3602 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003603# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003604 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003605# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003606 else
3607 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003608# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003609 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003610}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003611
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003612#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3613/*
3614 * Set the 16 ANSI colors from array of RGB values
3615 */
3616 static void
3617set_vterm_palette(VTerm *vterm, long_u *rgb)
3618{
3619 int index = 0;
3620 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003621
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003622 for (; index < 16; index++)
3623 {
3624 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003625
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003626 color.red = (unsigned)(rgb[index] >> 16);
3627 color.green = (unsigned)(rgb[index] >> 8) & 255;
3628 color.blue = (unsigned)rgb[index] & 255;
3629 vterm_state_set_palette_color(state, index, &color);
3630 }
3631}
3632
3633/*
3634 * Set the ANSI color palette from a list of colors
3635 */
3636 static int
3637set_ansi_colors_list(VTerm *vterm, list_T *list)
3638{
3639 int n = 0;
3640 long_u rgb[16];
3641 listitem_T *li = list->lv_first;
3642
3643 for (; li != NULL && n < 16; li = li->li_next, n++)
3644 {
3645 char_u *color_name;
3646 guicolor_T guicolor;
3647
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003648 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003649 if (color_name == NULL)
3650 return FAIL;
3651
3652 guicolor = GUI_GET_COLOR(color_name);
3653 if (guicolor == INVALCOLOR)
3654 return FAIL;
3655
3656 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3657 }
3658
3659 if (n != 16 || li != NULL)
3660 return FAIL;
3661
3662 set_vterm_palette(vterm, rgb);
3663
3664 return OK;
3665}
3666
3667/*
3668 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3669 */
3670 static void
3671init_vterm_ansi_colors(VTerm *vterm)
3672{
3673 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3674
3675 if (var != NULL
3676 && (var->di_tv.v_type != VAR_LIST
3677 || var->di_tv.vval.v_list == NULL
3678 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003679 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003680}
3681#endif
3682
Bram Moolenaar52acb112018-03-18 19:20:22 +01003683/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003684 * Handles a "drop" command from the job in the terminal.
3685 * "item" is the file name, "item->li_next" may have options.
3686 */
3687 static void
3688handle_drop_command(listitem_T *item)
3689{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003690 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003691 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003692 int bufnr;
3693 win_T *wp;
3694 tabpage_T *tp;
3695 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003696 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003697
3698 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3699 FOR_ALL_TAB_WINDOWS(tp, wp)
3700 {
3701 if (wp->w_buffer->b_fnum == bufnr)
3702 {
3703 /* buffer is in a window already, go there */
3704 goto_tabpage_win(tp, wp);
3705 return;
3706 }
3707 }
3708
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003709 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003710
3711 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3712 && opt_item->li_tv.vval.v_dict != NULL)
3713 {
3714 dict_T *dict = opt_item->li_tv.vval.v_dict;
3715 char_u *p;
3716
Bram Moolenaar8f667172018-12-14 15:38:31 +01003717 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003718 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003719 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003720 if (p != NULL)
3721 {
3722 if (check_ff_value(p) == FAIL)
3723 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3724 else
3725 ea.force_ff = *p;
3726 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003727 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003728 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003729 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003730 if (p != NULL)
3731 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003732 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003733 if (ea.cmd != NULL)
3734 {
3735 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3736 ea.force_enc = 11;
3737 tofree = ea.cmd;
3738 }
3739 }
3740
Bram Moolenaar8f667172018-12-14 15:38:31 +01003741 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003742 if (p != NULL)
3743 get_bad_opt(p, &ea);
3744
3745 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3746 ea.force_bin = FORCE_BIN;
3747 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3748 ea.force_bin = FORCE_BIN;
3749 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3750 ea.force_bin = FORCE_NOBIN;
3751 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3752 ea.force_bin = FORCE_NOBIN;
3753 }
3754
3755 /* open in new window, like ":split fname" */
3756 if (ea.cmd == NULL)
3757 ea.cmd = (char_u *)"split";
3758 ea.arg = fname;
3759 ea.cmdidx = CMD_split;
3760 ex_splitview(&ea);
3761
3762 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003763}
3764
3765/*
3766 * Handles a function call from the job running in a terminal.
3767 * "item" is the function name, "item->li_next" has the arguments.
3768 */
3769 static void
3770handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3771{
3772 char_u *func;
3773 typval_T argvars[2];
3774 typval_T rettv;
3775 int doesrange;
3776
3777 if (item->li_next == NULL)
3778 {
3779 ch_log(channel, "Missing function arguments for call");
3780 return;
3781 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003782 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003783
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003784 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003785 {
3786 ch_log(channel, "Invalid function name: %s", func);
3787 return;
3788 }
3789
3790 argvars[0].v_type = VAR_NUMBER;
3791 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3792 argvars[1] = item->li_next->li_tv;
Bram Moolenaar6ed88192019-05-11 18:37:44 +02003793 if (call_func(func, -1, &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003794 2, argvars, /* argv_func */ NULL,
3795 /* firstline */ 1, /* lastline */ 1,
3796 &doesrange, /* evaluate */ TRUE,
3797 /* partial */ NULL, /* selfdict */ NULL) == OK)
3798 {
3799 clear_tv(&rettv);
3800 ch_log(channel, "Function %s called", func);
3801 }
3802 else
3803 ch_log(channel, "Calling function %s failed", func);
3804}
3805
3806/*
3807 * Called by libvterm when it cannot recognize an OSC sequence.
3808 * We recognize a terminal API command.
3809 */
3810 static int
3811parse_osc(const char *command, size_t cmdlen, void *user)
3812{
3813 term_T *term = (term_T *)user;
3814 js_read_T reader;
3815 typval_T tv;
3816 channel_T *channel = term->tl_job == NULL ? NULL
3817 : term->tl_job->jv_channel;
3818
3819 /* We recognize only OSC 5 1 ; {command} */
3820 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3821 return 0; /* not handled */
3822
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003823 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003824 if (reader.js_buf == NULL)
3825 return 1;
3826 reader.js_fill = NULL;
3827 reader.js_used = 0;
3828 if (json_decode(&reader, &tv, 0) == OK
3829 && tv.v_type == VAR_LIST
3830 && tv.vval.v_list != NULL)
3831 {
3832 listitem_T *item = tv.vval.v_list->lv_first;
3833
3834 if (item == NULL)
3835 ch_log(channel, "Missing command");
3836 else
3837 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003838 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003839
Bram Moolenaara997b452018-04-17 23:24:06 +02003840 /* Make sure an invoked command doesn't delete the buffer (and the
3841 * terminal) under our fingers. */
3842 ++term->tl_buffer->b_locked;
3843
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003844 item = item->li_next;
3845 if (item == NULL)
3846 ch_log(channel, "Missing argument for %s", cmd);
3847 else if (STRCMP(cmd, "drop") == 0)
3848 handle_drop_command(item);
3849 else if (STRCMP(cmd, "call") == 0)
3850 handle_call_command(term, channel, item);
3851 else
3852 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003853 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003854 }
3855 }
3856 else
3857 ch_log(channel, "Invalid JSON received");
3858
3859 vim_free(reader.js_buf);
3860 clear_tv(&tv);
3861 return 1;
3862}
3863
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003864/*
3865 * Called by libvterm when it cannot recognize a CSI sequence.
3866 * We recognize the window position report.
3867 */
3868 static int
3869parse_csi(
3870 const char *leader UNUSED,
3871 const long args[],
3872 int argcount,
3873 const char *intermed UNUSED,
3874 char command,
3875 void *user)
3876{
3877 term_T *term = (term_T *)user;
3878 char buf[100];
3879 int len;
3880 int x = 0;
3881 int y = 0;
3882 win_T *wp;
3883
3884 // We recognize only CSI 13 t
3885 if (command != 't' || argcount != 1 || args[0] != 13)
3886 return 0; // not handled
3887
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003888 // When getting the window position is not possible or it fails it results
3889 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02003890#if defined(FEAT_GUI) \
3891 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
3892 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003893 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003894#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003895
3896 FOR_ALL_WINDOWS(wp)
3897 if (wp->w_buffer == term->tl_buffer)
3898 break;
3899 if (wp != NULL)
3900 {
3901#ifdef FEAT_GUI
3902 if (gui.in_use)
3903 {
3904 x += wp->w_wincol * gui.char_width;
3905 y += W_WINROW(wp) * gui.char_height;
3906 }
3907 else
3908#endif
3909 {
3910 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003911 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003912 x += wp->w_wincol * 7;
3913 y += W_WINROW(wp) * 10;
3914 }
3915 }
3916
3917 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
3918 channel_send(term->tl_job->jv_channel, get_tty_part(term),
3919 (char_u *)buf, len, NULL);
3920 return 1;
3921}
3922
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003923static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003924 NULL, // text
3925 NULL, // control
3926 NULL, // escape
3927 parse_csi, // csi
3928 parse_osc, // osc
3929 NULL, // dcs
3930 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003931};
3932
3933/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003934 * Use Vim's allocation functions for vterm so profiling works.
3935 */
3936 static void *
3937vterm_malloc(size_t size, void *data UNUSED)
3938{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02003939 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003940}
3941
3942 static void
3943vterm_memfree(void *ptr, void *data UNUSED)
3944{
3945 vim_free(ptr);
3946}
3947
3948static VTermAllocatorFunctions vterm_allocator = {
3949 &vterm_malloc,
3950 &vterm_memfree
3951};
3952
3953/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003954 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003955 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01003956 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003957 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01003958create_vterm(term_T *term, int rows, int cols)
3959{
3960 VTerm *vterm;
3961 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003962 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003963 VTermValue value;
3964
Bram Moolenaar756ef112018-04-10 12:04:27 +02003965 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003966 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003967 if (vterm == NULL)
3968 return FAIL;
3969
3970 // Allocate screen and state here, so we can bail out if that fails.
3971 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003972 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003973 if (state == NULL || screen == NULL)
3974 {
3975 vterm_free(vterm);
3976 return FAIL;
3977 }
3978
Bram Moolenaar52acb112018-03-18 19:20:22 +01003979 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3980 /* TODO: depends on 'encoding'. */
3981 vterm_set_utf8(vterm, 1);
3982
3983 init_default_colors(term);
3984
3985 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003986 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01003987 &term->tl_default_color.fg,
3988 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003989
Bram Moolenaar9e587872019-05-13 20:27:23 +02003990 if (t_colors < 16)
3991 // Less than 16 colors: assume that bold means using a bright color for
3992 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003993 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3994
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003995 /* Required to initialize most things. */
3996 vterm_screen_reset(screen, 1 /* hard */);
3997
3998 /* Allow using alternate screen. */
3999 vterm_screen_enable_altscreen(screen, 1);
4000
4001 /* For unix do not use a blinking cursor. In an xterm this causes the
4002 * cursor to blink if it's blinking in the xterm.
4003 * For Windows we respect the system wide setting. */
Bram Moolenaar4f974752019-02-17 17:44:42 +01004004#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004005 if (GetCaretBlinkTime() == INFINITE)
4006 value.boolean = 0;
4007 else
4008 value.boolean = 1;
4009#else
4010 value.boolean = 0;
4011#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004012 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4013 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004014
4015 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004016}
4017
4018/*
4019 * Return the text to show for the buffer name and status.
4020 */
4021 char_u *
4022term_get_status_text(term_T *term)
4023{
4024 if (term->tl_status_text == NULL)
4025 {
4026 char_u *txt;
4027 size_t len;
4028
4029 if (term->tl_normal_mode)
4030 {
4031 if (term_job_running(term))
4032 txt = (char_u *)_("Terminal");
4033 else
4034 txt = (char_u *)_("Terminal-finished");
4035 }
4036 else if (term->tl_title != NULL)
4037 txt = term->tl_title;
4038 else if (term_none_open(term))
4039 txt = (char_u *)_("active");
4040 else if (term_job_running(term))
4041 txt = (char_u *)_("running");
4042 else
4043 txt = (char_u *)_("finished");
4044 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004045 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004046 if (term->tl_status_text != NULL)
4047 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4048 term->tl_buffer->b_fname, txt);
4049 }
4050 return term->tl_status_text;
4051}
4052
4053/*
4054 * Mark references in jobs of terminals.
4055 */
4056 int
4057set_ref_in_term(int copyID)
4058{
4059 int abort = FALSE;
4060 term_T *term;
4061 typval_T tv;
4062
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004063 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004064 if (term->tl_job != NULL)
4065 {
4066 tv.v_type = VAR_JOB;
4067 tv.vval.v_job = term->tl_job;
4068 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4069 }
4070 return abort;
4071}
4072
4073/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004074 * Cache "Terminal" highlight group colors.
4075 */
4076 void
4077set_terminal_default_colors(int cterm_fg, int cterm_bg)
4078{
4079 term_default_cterm_fg = cterm_fg - 1;
4080 term_default_cterm_bg = cterm_bg - 1;
4081}
4082
4083/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004084 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004085 * Returns NULL when the buffer is not for a terminal window and logs a message
4086 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004087 */
4088 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004089term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004090{
4091 buf_T *buf;
4092
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004093 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004094 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004095 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004096 --emsg_off;
4097 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004098 {
4099 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004100 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004101 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004102 return buf;
4103}
4104
Bram Moolenaard96ff162018-02-18 22:13:29 +01004105 static int
4106same_color(VTermColor *a, VTermColor *b)
4107{
4108 return a->red == b->red
4109 && a->green == b->green
4110 && a->blue == b->blue
4111 && a->ansi_index == b->ansi_index;
4112}
4113
4114 static void
4115dump_term_color(FILE *fd, VTermColor *color)
4116{
4117 fprintf(fd, "%02x%02x%02x%d",
4118 (int)color->red, (int)color->green, (int)color->blue,
4119 (int)color->ansi_index);
4120}
4121
4122/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004123 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004124 *
4125 * Each screen cell in full is:
4126 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4127 * {characters} is a space for an empty cell
4128 * For a double-width character "+" is changed to "*" and the next cell is
4129 * skipped.
4130 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4131 * when "&" use the same as the previous cell.
4132 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4133 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4134 * {color-idx} is a number from 0 to 255
4135 *
4136 * Screen cell with same width, attributes and color as the previous one:
4137 * |{characters}
4138 *
4139 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4140 *
4141 * Repeating the previous screen cell:
4142 * @{count}
4143 */
4144 void
4145f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4146{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004147 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004148 term_T *term;
4149 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004150 int max_height = 0;
4151 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004152 stat_T st;
4153 FILE *fd;
4154 VTermPos pos;
4155 VTermScreen *screen;
4156 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004157 VTermState *state;
4158 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004159
4160 if (check_restricted() || check_secure())
4161 return;
4162 if (buf == NULL)
4163 return;
4164 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004165 if (term->tl_vterm == NULL)
4166 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004167 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004168 return;
4169 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004170
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004171 if (argvars[2].v_type != VAR_UNKNOWN)
4172 {
4173 dict_T *d;
4174
4175 if (argvars[2].v_type != VAR_DICT)
4176 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004177 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004178 return;
4179 }
4180 d = argvars[2].vval.v_dict;
4181 if (d != NULL)
4182 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004183 max_height = dict_get_number(d, (char_u *)"rows");
4184 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004185 }
4186 }
4187
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004188 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004189 if (fname == NULL)
4190 return;
4191 if (mch_stat((char *)fname, &st) >= 0)
4192 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004193 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004194 return;
4195 }
4196
Bram Moolenaard96ff162018-02-18 22:13:29 +01004197 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4198 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004199 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004200 return;
4201 }
4202
4203 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4204
4205 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004206 state = vterm_obtain_state(term->tl_vterm);
4207 vterm_state_get_cursorpos(state, &cursor_pos);
4208
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004209 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4210 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004211 {
4212 int repeat = 0;
4213
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004214 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4215 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004216 {
4217 VTermScreenCell cell;
4218 int same_attr;
4219 int same_chars = TRUE;
4220 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004221 int is_cursor_pos = (pos.col == cursor_pos.col
4222 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004223
4224 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4225 vim_memset(&cell, 0, sizeof(cell));
4226
4227 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4228 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004229 int c = cell.chars[i];
4230 int pc = prev_cell.chars[i];
4231
4232 /* For the first character NUL is the same as space. */
4233 if (i == 0)
4234 {
4235 c = (c == NUL) ? ' ' : c;
4236 pc = (pc == NUL) ? ' ' : pc;
4237 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004238 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004239 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004240 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004241 break;
4242 }
4243 same_attr = vtermAttr2hl(cell.attrs)
4244 == vtermAttr2hl(prev_cell.attrs)
4245 && same_color(&cell.fg, &prev_cell.fg)
4246 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004247 if (same_chars && cell.width == prev_cell.width && same_attr
4248 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004249 {
4250 ++repeat;
4251 }
4252 else
4253 {
4254 if (repeat > 0)
4255 {
4256 fprintf(fd, "@%d", repeat);
4257 repeat = 0;
4258 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004259 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004260
4261 if (cell.chars[0] == NUL)
4262 fputs(" ", fd);
4263 else
4264 {
4265 char_u charbuf[10];
4266 int len;
4267
4268 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4269 && cell.chars[i] != NUL; ++i)
4270 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004271 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004272 fwrite(charbuf, len, 1, fd);
4273 }
4274 }
4275
4276 /* When only the characters differ we don't write anything, the
4277 * following "|", "@" or NL will indicate using the same
4278 * attributes. */
4279 if (cell.width != prev_cell.width || !same_attr)
4280 {
4281 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004282 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004283 else
4284 fputs("+", fd);
4285
4286 if (same_attr)
4287 {
4288 fputs("&", fd);
4289 }
4290 else
4291 {
4292 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4293 if (same_color(&cell.fg, &prev_cell.fg))
4294 fputs("&", fd);
4295 else
4296 {
4297 fputs("#", fd);
4298 dump_term_color(fd, &cell.fg);
4299 }
4300 if (same_color(&cell.bg, &prev_cell.bg))
4301 fputs("&", fd);
4302 else
4303 {
4304 fputs("#", fd);
4305 dump_term_color(fd, &cell.bg);
4306 }
4307 }
4308 }
4309
4310 prev_cell = cell;
4311 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004312
4313 if (cell.width == 2)
4314 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004315 }
4316 if (repeat > 0)
4317 fprintf(fd, "@%d", repeat);
4318 fputs("\n", fd);
4319 }
4320
4321 fclose(fd);
4322}
4323
4324/*
4325 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4326 */
4327 static void
4328dump_is_corrupt(garray_T *gap)
4329{
4330 ga_concat(gap, (char_u *)"CORRUPT");
4331}
4332
4333 static void
4334append_cell(garray_T *gap, cellattr_T *cell)
4335{
4336 if (ga_grow(gap, 1) == OK)
4337 {
4338 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4339 ++gap->ga_len;
4340 }
4341}
4342
4343/*
4344 * Read the dump file from "fd" and append lines to the current buffer.
4345 * Return the cell width of the longest line.
4346 */
4347 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004348read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004349{
4350 int c;
4351 garray_T ga_text;
4352 garray_T ga_cell;
4353 char_u *prev_char = NULL;
4354 int attr = 0;
4355 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004356 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004357 term_T *term = curbuf->b_term;
4358 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004359 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004360
4361 ga_init2(&ga_text, 1, 90);
4362 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4363 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004364 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004365 cursor_pos->row = -1;
4366 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004367
4368 c = fgetc(fd);
4369 for (;;)
4370 {
4371 if (c == EOF)
4372 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004373 if (c == '\r')
4374 {
4375 // DOS line endings? Ignore.
4376 c = fgetc(fd);
4377 }
4378 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004379 {
4380 /* End of a line: append it to the buffer. */
4381 if (ga_text.ga_data == NULL)
4382 dump_is_corrupt(&ga_text);
4383 if (ga_grow(&term->tl_scrollback, 1) == OK)
4384 {
4385 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4386 + term->tl_scrollback.ga_len;
4387
4388 if (max_cells < ga_cell.ga_len)
4389 max_cells = ga_cell.ga_len;
4390 line->sb_cols = ga_cell.ga_len;
4391 line->sb_cells = ga_cell.ga_data;
4392 line->sb_fill_attr = term->tl_default_color;
4393 ++term->tl_scrollback.ga_len;
4394 ga_init(&ga_cell);
4395
4396 ga_append(&ga_text, NUL);
4397 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4398 ga_text.ga_len, FALSE);
4399 }
4400 else
4401 ga_clear(&ga_cell);
4402 ga_text.ga_len = 0;
4403
4404 c = fgetc(fd);
4405 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004406 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004407 {
4408 int prev_len = ga_text.ga_len;
4409
Bram Moolenaar9271d052018-02-25 21:39:46 +01004410 if (c == '>')
4411 {
4412 if (cursor_pos->row != -1)
4413 dump_is_corrupt(&ga_text); /* duplicate cursor */
4414 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4415 cursor_pos->col = ga_cell.ga_len;
4416 }
4417
Bram Moolenaard96ff162018-02-18 22:13:29 +01004418 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4419 c = fgetc(fd);
4420 if (c != EOF)
4421 ga_append(&ga_text, c);
4422 for (;;)
4423 {
4424 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004425 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004426 || c == EOF || c == '\n')
4427 break;
4428 ga_append(&ga_text, c);
4429 }
4430
4431 /* save the character for repeating it */
4432 vim_free(prev_char);
4433 if (ga_text.ga_data != NULL)
4434 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4435 ga_text.ga_len - prev_len);
4436
Bram Moolenaar9271d052018-02-25 21:39:46 +01004437 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004438 {
4439 /* use all attributes from previous cell */
4440 }
4441 else if (c == '+' || c == '*')
4442 {
4443 int is_bg;
4444
4445 cell.width = c == '+' ? 1 : 2;
4446
4447 c = fgetc(fd);
4448 if (c == '&')
4449 {
4450 /* use same attr as previous cell */
4451 c = fgetc(fd);
4452 }
4453 else if (isdigit(c))
4454 {
4455 /* get the decimal attribute */
4456 attr = 0;
4457 while (isdigit(c))
4458 {
4459 attr = attr * 10 + (c - '0');
4460 c = fgetc(fd);
4461 }
4462 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004463
4464 /* is_bg == 0: fg, is_bg == 1: bg */
4465 for (is_bg = 0; is_bg <= 1; ++is_bg)
4466 {
4467 if (c == '&')
4468 {
4469 /* use same color as previous cell */
4470 c = fgetc(fd);
4471 }
4472 else if (c == '#')
4473 {
4474 int red, green, blue, index = 0;
4475
4476 c = fgetc(fd);
4477 red = hex2nr(c);
4478 c = fgetc(fd);
4479 red = (red << 4) + hex2nr(c);
4480 c = fgetc(fd);
4481 green = hex2nr(c);
4482 c = fgetc(fd);
4483 green = (green << 4) + hex2nr(c);
4484 c = fgetc(fd);
4485 blue = hex2nr(c);
4486 c = fgetc(fd);
4487 blue = (blue << 4) + hex2nr(c);
4488 c = fgetc(fd);
4489 if (!isdigit(c))
4490 dump_is_corrupt(&ga_text);
4491 while (isdigit(c))
4492 {
4493 index = index * 10 + (c - '0');
4494 c = fgetc(fd);
4495 }
4496
4497 if (is_bg)
4498 {
4499 cell.bg.red = red;
4500 cell.bg.green = green;
4501 cell.bg.blue = blue;
4502 cell.bg.ansi_index = index;
4503 }
4504 else
4505 {
4506 cell.fg.red = red;
4507 cell.fg.green = green;
4508 cell.fg.blue = blue;
4509 cell.fg.ansi_index = index;
4510 }
4511 }
4512 else
4513 dump_is_corrupt(&ga_text);
4514 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004515 }
4516 else
4517 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004518 }
4519 else
4520 dump_is_corrupt(&ga_text);
4521
4522 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004523 if (cell.width == 2)
4524 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004525 }
4526 else if (c == '@')
4527 {
4528 if (prev_char == NULL)
4529 dump_is_corrupt(&ga_text);
4530 else
4531 {
4532 int count = 0;
4533
4534 /* repeat previous character, get the count */
4535 for (;;)
4536 {
4537 c = fgetc(fd);
4538 if (!isdigit(c))
4539 break;
4540 count = count * 10 + (c - '0');
4541 }
4542
4543 while (count-- > 0)
4544 {
4545 ga_concat(&ga_text, prev_char);
4546 append_cell(&ga_cell, &cell);
4547 }
4548 }
4549 }
4550 else
4551 {
4552 dump_is_corrupt(&ga_text);
4553 c = fgetc(fd);
4554 }
4555 }
4556
4557 if (ga_text.ga_len > 0)
4558 {
4559 /* trailing characters after last NL */
4560 dump_is_corrupt(&ga_text);
4561 ga_append(&ga_text, NUL);
4562 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4563 ga_text.ga_len, FALSE);
4564 }
4565
4566 ga_clear(&ga_text);
4567 vim_free(prev_char);
4568
4569 return max_cells;
4570}
4571
4572/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004573 * Return an allocated string with at least "text_width" "=" characters and
4574 * "fname" inserted in the middle.
4575 */
4576 static char_u *
4577get_separator(int text_width, char_u *fname)
4578{
4579 int width = MAX(text_width, curwin->w_width);
4580 char_u *textline;
4581 int fname_size;
4582 char_u *p = fname;
4583 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004584 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004585
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004586 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004587 if (textline == NULL)
4588 return NULL;
4589
4590 fname_size = vim_strsize(fname);
4591 if (fname_size < width - 8)
4592 {
4593 /* enough room, don't use the full window width */
4594 width = MAX(text_width, fname_size + 8);
4595 }
4596 else if (fname_size > width - 8)
4597 {
4598 /* full name doesn't fit, use only the tail */
4599 p = gettail(fname);
4600 fname_size = vim_strsize(p);
4601 }
4602 /* skip characters until the name fits */
4603 while (fname_size > width - 8)
4604 {
4605 p += (*mb_ptr2len)(p);
4606 fname_size = vim_strsize(p);
4607 }
4608
4609 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4610 textline[i] = '=';
4611 textline[i++] = ' ';
4612
4613 STRCPY(textline + i, p);
4614 off = STRLEN(textline);
4615 textline[off] = ' ';
4616 for (i = 1; i < (width - fname_size) / 2; ++i)
4617 textline[off + i] = '=';
4618 textline[off + i] = NUL;
4619
4620 return textline;
4621}
4622
4623/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004624 * Common for "term_dumpdiff()" and "term_dumpload()".
4625 */
4626 static void
4627term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4628{
4629 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004630 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004631 char_u buf1[NUMBUFLEN];
4632 char_u buf2[NUMBUFLEN];
4633 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004634 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004635 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004636 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004637 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004638 char_u *textline = NULL;
4639
4640 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004641 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004642 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004643 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004644 if (fname1 == NULL || (do_diff && fname2 == NULL))
4645 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004646 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004647 return;
4648 }
4649 fd1 = mch_fopen((char *)fname1, READBIN);
4650 if (fd1 == NULL)
4651 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004652 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004653 return;
4654 }
4655 if (do_diff)
4656 {
4657 fd2 = mch_fopen((char *)fname2, READBIN);
4658 if (fd2 == NULL)
4659 {
4660 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004661 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004662 return;
4663 }
4664 }
4665
4666 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004667 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4668 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4669 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4670 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4671 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004672
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004673 if (opt.jo_term_name == NULL)
4674 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004675 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004676
Bram Moolenaar51e14382019-05-25 20:21:28 +02004677 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004678 if (fname_tofree != NULL)
4679 {
4680 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4681 opt.jo_term_name = fname_tofree;
4682 }
4683 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004684
Bram Moolenaar87abab92019-06-03 21:14:59 +02004685 if (opt.jo_bufnr_buf != NULL)
4686 {
4687 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4688
4689 // With "bufnr" argument: enter the window with this buffer and make it
4690 // empty.
4691 if (wp == NULL)
4692 semsg(_(e_invarg2), "bufnr");
4693 else
4694 {
4695 buf = curbuf;
4696 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4697 ml_delete((linenr_T)1, FALSE);
4698 ga_clear(&curbuf->b_term->tl_scrollback);
4699 redraw_later(NOT_VALID);
4700 }
4701 }
4702 else
4703 // Create a new terminal window.
4704 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4705
Bram Moolenaard96ff162018-02-18 22:13:29 +01004706 if (buf != NULL && buf->b_term != NULL)
4707 {
4708 int i;
4709 linenr_T bot_lnum;
4710 linenr_T lnum;
4711 term_T *term = buf->b_term;
4712 int width;
4713 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004714 VTermPos cursor_pos1;
4715 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004716
Bram Moolenaar52acb112018-03-18 19:20:22 +01004717 init_default_colors(term);
4718
Bram Moolenaard96ff162018-02-18 22:13:29 +01004719 rettv->vval.v_number = buf->b_fnum;
4720
4721 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004722 width = read_dump_file(fd1, &cursor_pos1);
4723
4724 /* position the cursor */
4725 if (cursor_pos1.row >= 0)
4726 {
4727 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4728 coladvance(cursor_pos1.col);
4729 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004730
4731 /* Delete the empty line that was in the empty buffer. */
4732 ml_delete(1, FALSE);
4733
4734 /* For term_dumpload() we are done here. */
4735 if (!do_diff)
4736 goto theend;
4737
4738 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4739
Bram Moolenaar4a696342018-04-05 18:45:26 +02004740 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004741 if (textline == NULL)
4742 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004743 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4744 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4745 vim_free(textline);
4746
4747 textline = get_separator(width, fname2);
4748 if (textline == NULL)
4749 goto theend;
4750 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4751 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004752 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004753
4754 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004755 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004756 if (width2 > width)
4757 {
4758 vim_free(textline);
4759 textline = alloc(width2 + 1);
4760 if (textline == NULL)
4761 goto theend;
4762 width = width2;
4763 textline[width] = NUL;
4764 }
4765 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4766
4767 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4768 {
4769 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4770 {
4771 /* bottom part has fewer rows, fill with "-" */
4772 for (i = 0; i < width; ++i)
4773 textline[i] = '-';
4774 }
4775 else
4776 {
4777 char_u *line1;
4778 char_u *line2;
4779 char_u *p1;
4780 char_u *p2;
4781 int col;
4782 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4783 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4784 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4785 ->sb_cells;
4786
4787 /* Make a copy, getting the second line will invalidate it. */
4788 line1 = vim_strsave(ml_get(lnum));
4789 if (line1 == NULL)
4790 break;
4791 p1 = line1;
4792
4793 line2 = ml_get(lnum + bot_lnum);
4794 p2 = line2;
4795 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4796 {
4797 int len1 = utfc_ptr2len(p1);
4798 int len2 = utfc_ptr2len(p2);
4799
4800 textline[col] = ' ';
4801 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004802 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004803 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004804 else if (lnum == cursor_pos1.row + 1
4805 && col == cursor_pos1.col
4806 && (cursor_pos1.row != cursor_pos2.row
4807 || cursor_pos1.col != cursor_pos2.col))
4808 /* cursor in first but not in second */
4809 textline[col] = '>';
4810 else if (lnum == cursor_pos2.row + 1
4811 && col == cursor_pos2.col
4812 && (cursor_pos1.row != cursor_pos2.row
4813 || cursor_pos1.col != cursor_pos2.col))
4814 /* cursor in second but not in first */
4815 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004816 else if (cellattr1 != NULL && cellattr2 != NULL)
4817 {
4818 if ((cellattr1 + col)->width
4819 != (cellattr2 + col)->width)
4820 textline[col] = 'w';
4821 else if (!same_color(&(cellattr1 + col)->fg,
4822 &(cellattr2 + col)->fg))
4823 textline[col] = 'f';
4824 else if (!same_color(&(cellattr1 + col)->bg,
4825 &(cellattr2 + col)->bg))
4826 textline[col] = 'b';
4827 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4828 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4829 textline[col] = 'a';
4830 }
4831 p1 += len1;
4832 p2 += len2;
4833 /* TODO: handle different width */
4834 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004835
4836 while (col < width)
4837 {
4838 if (*p1 == NUL && *p2 == NUL)
4839 textline[col] = '?';
4840 else if (*p1 == NUL)
4841 {
4842 textline[col] = '+';
4843 p2 += utfc_ptr2len(p2);
4844 }
4845 else
4846 {
4847 textline[col] = '-';
4848 p1 += utfc_ptr2len(p1);
4849 }
4850 ++col;
4851 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004852
4853 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004854 }
4855 if (add_empty_scrollback(term, &term->tl_default_color,
4856 term->tl_top_diff_rows) == OK)
4857 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4858 ++bot_lnum;
4859 }
4860
4861 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4862 {
4863 /* bottom part has more rows, fill with "+" */
4864 for (i = 0; i < width; ++i)
4865 textline[i] = '+';
4866 if (add_empty_scrollback(term, &term->tl_default_color,
4867 term->tl_top_diff_rows) == OK)
4868 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4869 ++lnum;
4870 ++bot_lnum;
4871 }
4872
4873 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004874
4875 /* looks better without wrapping */
4876 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004877 }
4878
4879theend:
4880 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004881 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004882 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004883 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004884 fclose(fd2);
4885}
4886
4887/*
4888 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4889 * bottom files.
4890 * Return FAIL when this is not possible.
4891 */
4892 int
4893term_swap_diff()
4894{
4895 term_T *term = curbuf->b_term;
4896 linenr_T line_count;
4897 linenr_T top_rows;
4898 linenr_T bot_rows;
4899 linenr_T bot_start;
4900 linenr_T lnum;
4901 char_u *p;
4902 sb_line_T *sb_line;
4903
4904 if (term == NULL
4905 || !term_is_finished(curbuf)
4906 || term->tl_top_diff_rows == 0
4907 || term->tl_scrollback.ga_len == 0)
4908 return FAIL;
4909
4910 line_count = curbuf->b_ml.ml_line_count;
4911 top_rows = term->tl_top_diff_rows;
4912 bot_rows = term->tl_bot_diff_rows;
4913 bot_start = line_count - bot_rows;
4914 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4915
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004916 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01004917 for (lnum = 1; lnum <= top_rows; ++lnum)
4918 {
4919 p = vim_strsave(ml_get(1));
4920 if (p == NULL)
4921 return OK;
4922 ml_append(bot_start, p, 0, FALSE);
4923 ml_delete(1, FALSE);
4924 vim_free(p);
4925 }
4926
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004927 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01004928 for (lnum = 1; lnum <= bot_rows; ++lnum)
4929 {
4930 p = vim_strsave(ml_get(bot_start + lnum));
4931 if (p == NULL)
4932 return OK;
4933 ml_delete(bot_start + lnum, FALSE);
4934 ml_append(lnum - 1, p, 0, FALSE);
4935 vim_free(p);
4936 }
4937
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004938 // move top title to bottom
4939 p = vim_strsave(ml_get(bot_rows + 1));
4940 if (p == NULL)
4941 return OK;
4942 ml_append(line_count - top_rows - 1, p, 0, FALSE);
4943 ml_delete(bot_rows + 1, FALSE);
4944 vim_free(p);
4945
4946 // move bottom title to top
4947 p = vim_strsave(ml_get(line_count - top_rows));
4948 if (p == NULL)
4949 return OK;
4950 ml_delete(line_count - top_rows, FALSE);
4951 ml_append(bot_rows, p, 0, FALSE);
4952 vim_free(p);
4953
Bram Moolenaard96ff162018-02-18 22:13:29 +01004954 if (top_rows == bot_rows)
4955 {
4956 /* rows counts are equal, can swap cell properties */
4957 for (lnum = 0; lnum < top_rows; ++lnum)
4958 {
4959 sb_line_T temp;
4960
4961 temp = *(sb_line + lnum);
4962 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4963 *(sb_line + bot_start + lnum) = temp;
4964 }
4965 }
4966 else
4967 {
4968 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004969 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004970
4971 /* need to copy cell properties into temp memory */
4972 if (temp != NULL)
4973 {
4974 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4975 mch_memmove(term->tl_scrollback.ga_data,
4976 temp + bot_start,
4977 sizeof(sb_line_T) * bot_rows);
4978 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4979 temp + top_rows,
4980 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4981 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4982 + line_count - top_rows,
4983 temp,
4984 sizeof(sb_line_T) * top_rows);
4985 vim_free(temp);
4986 }
4987 }
4988
4989 term->tl_top_diff_rows = bot_rows;
4990 term->tl_bot_diff_rows = top_rows;
4991
4992 update_screen(NOT_VALID);
4993 return OK;
4994}
4995
4996/*
4997 * "term_dumpdiff(filename, filename, options)" function
4998 */
4999 void
5000f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5001{
5002 term_load_dump(argvars, rettv, TRUE);
5003}
5004
5005/*
5006 * "term_dumpload(filename, options)" function
5007 */
5008 void
5009f_term_dumpload(typval_T *argvars, typval_T *rettv)
5010{
5011 term_load_dump(argvars, rettv, FALSE);
5012}
5013
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005014/*
5015 * "term_getaltscreen(buf)" function
5016 */
5017 void
5018f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5019{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005020 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005021
5022 if (buf == NULL)
5023 return;
5024 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5025}
5026
5027/*
5028 * "term_getattr(attr, name)" function
5029 */
5030 void
5031f_term_getattr(typval_T *argvars, typval_T *rettv)
5032{
5033 int attr;
5034 size_t i;
5035 char_u *name;
5036
5037 static struct {
5038 char *name;
5039 int attr;
5040 } attrs[] = {
5041 {"bold", HL_BOLD},
5042 {"italic", HL_ITALIC},
5043 {"underline", HL_UNDERLINE},
5044 {"strike", HL_STRIKETHROUGH},
5045 {"reverse", HL_INVERSE},
5046 };
5047
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005048 attr = tv_get_number(&argvars[0]);
5049 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005050 if (name == NULL)
5051 return;
5052
5053 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5054 if (STRCMP(name, attrs[i].name) == 0)
5055 {
5056 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5057 break;
5058 }
5059}
5060
5061/*
5062 * "term_getcursor(buf)" function
5063 */
5064 void
5065f_term_getcursor(typval_T *argvars, typval_T *rettv)
5066{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005067 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005068 term_T *term;
5069 list_T *l;
5070 dict_T *d;
5071
5072 if (rettv_list_alloc(rettv) == FAIL)
5073 return;
5074 if (buf == NULL)
5075 return;
5076 term = buf->b_term;
5077
5078 l = rettv->vval.v_list;
5079 list_append_number(l, term->tl_cursor_pos.row + 1);
5080 list_append_number(l, term->tl_cursor_pos.col + 1);
5081
5082 d = dict_alloc();
5083 if (d != NULL)
5084 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005085 dict_add_number(d, "visible", term->tl_cursor_visible);
5086 dict_add_number(d, "blink", blink_state_is_inverted()
5087 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5088 dict_add_number(d, "shape", term->tl_cursor_shape);
5089 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005090 list_append_dict(l, d);
5091 }
5092}
5093
5094/*
5095 * "term_getjob(buf)" function
5096 */
5097 void
5098f_term_getjob(typval_T *argvars, typval_T *rettv)
5099{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005100 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005101
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005102 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005103 {
5104 rettv->v_type = VAR_SPECIAL;
5105 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005106 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005107 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005108
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005109 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005110 rettv->vval.v_job = buf->b_term->tl_job;
5111 if (rettv->vval.v_job != NULL)
5112 ++rettv->vval.v_job->jv_refcount;
5113}
5114
5115 static int
5116get_row_number(typval_T *tv, term_T *term)
5117{
5118 if (tv->v_type == VAR_STRING
5119 && tv->vval.v_string != NULL
5120 && STRCMP(tv->vval.v_string, ".") == 0)
5121 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005122 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005123}
5124
5125/*
5126 * "term_getline(buf, row)" function
5127 */
5128 void
5129f_term_getline(typval_T *argvars, typval_T *rettv)
5130{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005131 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005132 term_T *term;
5133 int row;
5134
5135 rettv->v_type = VAR_STRING;
5136 if (buf == NULL)
5137 return;
5138 term = buf->b_term;
5139 row = get_row_number(&argvars[1], term);
5140
5141 if (term->tl_vterm == NULL)
5142 {
5143 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5144
5145 /* vterm is finished, get the text from the buffer */
5146 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5147 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5148 }
5149 else
5150 {
5151 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5152 VTermRect rect;
5153 int len;
5154 char_u *p;
5155
5156 if (row < 0 || row >= term->tl_rows)
5157 return;
5158 len = term->tl_cols * MB_MAXBYTES + 1;
5159 p = alloc(len);
5160 if (p == NULL)
5161 return;
5162 rettv->vval.v_string = p;
5163
5164 rect.start_col = 0;
5165 rect.end_col = term->tl_cols;
5166 rect.start_row = row;
5167 rect.end_row = row + 1;
5168 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5169 }
5170}
5171
5172/*
5173 * "term_getscrolled(buf)" function
5174 */
5175 void
5176f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5177{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005178 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005179
5180 if (buf == NULL)
5181 return;
5182 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5183}
5184
5185/*
5186 * "term_getsize(buf)" function
5187 */
5188 void
5189f_term_getsize(typval_T *argvars, typval_T *rettv)
5190{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005191 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005192 list_T *l;
5193
5194 if (rettv_list_alloc(rettv) == FAIL)
5195 return;
5196 if (buf == NULL)
5197 return;
5198
5199 l = rettv->vval.v_list;
5200 list_append_number(l, buf->b_term->tl_rows);
5201 list_append_number(l, buf->b_term->tl_cols);
5202}
5203
5204/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005205 * "term_setsize(buf, rows, cols)" function
5206 */
5207 void
5208f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5209{
5210 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5211 term_T *term;
5212 varnumber_T rows, cols;
5213
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005214 if (buf == NULL)
5215 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005216 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005217 return;
5218 }
5219 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005220 return;
5221 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005222 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005223 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005224 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005225 cols = cols <= 0 ? term->tl_cols : cols;
5226 vterm_set_size(term->tl_vterm, rows, cols);
5227 /* handle_resize() will resize the windows */
5228
5229 /* Get and remember the size we ended up with. Update the pty. */
5230 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5231 term_report_winsize(term, term->tl_rows, term->tl_cols);
5232}
5233
5234/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005235 * "term_getstatus(buf)" function
5236 */
5237 void
5238f_term_getstatus(typval_T *argvars, typval_T *rettv)
5239{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005240 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005241 term_T *term;
5242 char_u val[100];
5243
5244 rettv->v_type = VAR_STRING;
5245 if (buf == NULL)
5246 return;
5247 term = buf->b_term;
5248
5249 if (term_job_running(term))
5250 STRCPY(val, "running");
5251 else
5252 STRCPY(val, "finished");
5253 if (term->tl_normal_mode)
5254 STRCAT(val, ",normal");
5255 rettv->vval.v_string = vim_strsave(val);
5256}
5257
5258/*
5259 * "term_gettitle(buf)" function
5260 */
5261 void
5262f_term_gettitle(typval_T *argvars, typval_T *rettv)
5263{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005264 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005265
5266 rettv->v_type = VAR_STRING;
5267 if (buf == NULL)
5268 return;
5269
5270 if (buf->b_term->tl_title != NULL)
5271 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5272}
5273
5274/*
5275 * "term_gettty(buf)" function
5276 */
5277 void
5278f_term_gettty(typval_T *argvars, typval_T *rettv)
5279{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005280 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005281 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005282 int num = 0;
5283
5284 rettv->v_type = VAR_STRING;
5285 if (buf == NULL)
5286 return;
5287 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005288 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005289
5290 switch (num)
5291 {
5292 case 0:
5293 if (buf->b_term->tl_job != NULL)
5294 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005295 break;
5296 case 1:
5297 if (buf->b_term->tl_job != NULL)
5298 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005299 break;
5300 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005301 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005302 return;
5303 }
5304 if (p != NULL)
5305 rettv->vval.v_string = vim_strsave(p);
5306}
5307
5308/*
5309 * "term_list()" function
5310 */
5311 void
5312f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5313{
5314 term_T *tp;
5315 list_T *l;
5316
5317 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5318 return;
5319
5320 l = rettv->vval.v_list;
5321 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5322 if (tp != NULL && tp->tl_buffer != NULL)
5323 if (list_append_number(l,
5324 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5325 return;
5326}
5327
5328/*
5329 * "term_scrape(buf, row)" function
5330 */
5331 void
5332f_term_scrape(typval_T *argvars, typval_T *rettv)
5333{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005334 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005335 VTermScreen *screen = NULL;
5336 VTermPos pos;
5337 list_T *l;
5338 term_T *term;
5339 char_u *p;
5340 sb_line_T *line;
5341
5342 if (rettv_list_alloc(rettv) == FAIL)
5343 return;
5344 if (buf == NULL)
5345 return;
5346 term = buf->b_term;
5347
5348 l = rettv->vval.v_list;
5349 pos.row = get_row_number(&argvars[1], term);
5350
5351 if (term->tl_vterm != NULL)
5352 {
5353 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005354 if (screen == NULL) // can't really happen
5355 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005356 p = NULL;
5357 line = NULL;
5358 }
5359 else
5360 {
5361 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5362
5363 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5364 return;
5365 p = ml_get_buf(buf, lnum + 1, FALSE);
5366 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5367 }
5368
5369 for (pos.col = 0; pos.col < term->tl_cols; )
5370 {
5371 dict_T *dcell;
5372 int width;
5373 VTermScreenCellAttrs attrs;
5374 VTermColor fg, bg;
5375 char_u rgb[8];
5376 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5377 int off = 0;
5378 int i;
5379
5380 if (screen == NULL)
5381 {
5382 cellattr_T *cellattr;
5383 int len;
5384
5385 /* vterm has finished, get the cell from scrollback */
5386 if (pos.col >= line->sb_cols)
5387 break;
5388 cellattr = line->sb_cells + pos.col;
5389 width = cellattr->width;
5390 attrs = cellattr->attrs;
5391 fg = cellattr->fg;
5392 bg = cellattr->bg;
5393 len = MB_PTR2LEN(p);
5394 mch_memmove(mbs, p, len);
5395 mbs[len] = NUL;
5396 p += len;
5397 }
5398 else
5399 {
5400 VTermScreenCell cell;
5401 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5402 break;
5403 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5404 {
5405 if (cell.chars[i] == 0)
5406 break;
5407 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5408 }
5409 mbs[off] = NUL;
5410 width = cell.width;
5411 attrs = cell.attrs;
5412 fg = cell.fg;
5413 bg = cell.bg;
5414 }
5415 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005416 if (dcell == NULL)
5417 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005418 list_append_dict(l, dcell);
5419
Bram Moolenaare0be1672018-07-08 16:50:37 +02005420 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005421
5422 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5423 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005424 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005425 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5426 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005427 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005428
Bram Moolenaare0be1672018-07-08 16:50:37 +02005429 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5430 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005431
5432 ++pos.col;
5433 if (width == 2)
5434 ++pos.col;
5435 }
5436}
5437
5438/*
5439 * "term_sendkeys(buf, keys)" function
5440 */
5441 void
5442f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5443{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005444 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005445 char_u *msg;
5446 term_T *term;
5447
5448 rettv->v_type = VAR_UNKNOWN;
5449 if (buf == NULL)
5450 return;
5451
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005452 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005453 if (msg == NULL)
5454 return;
5455 term = buf->b_term;
5456 if (term->tl_vterm == NULL)
5457 return;
5458
5459 while (*msg != NUL)
5460 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005461 int c;
5462
5463 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5464 {
5465 c = TO_SPECIAL(msg[1], msg[2]);
5466 msg += 3;
5467 }
5468 else
5469 {
5470 c = PTR2CHAR(msg);
5471 msg += MB_CPTR2LEN(msg);
5472 }
5473 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005474 }
5475}
5476
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005477#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5478/*
5479 * "term_getansicolors(buf)" function
5480 */
5481 void
5482f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5483{
5484 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5485 term_T *term;
5486 VTermState *state;
5487 VTermColor color;
5488 char_u hexbuf[10];
5489 int index;
5490 list_T *list;
5491
5492 if (rettv_list_alloc(rettv) == FAIL)
5493 return;
5494
5495 if (buf == NULL)
5496 return;
5497 term = buf->b_term;
5498 if (term->tl_vterm == NULL)
5499 return;
5500
5501 list = rettv->vval.v_list;
5502 state = vterm_obtain_state(term->tl_vterm);
5503 for (index = 0; index < 16; index++)
5504 {
5505 vterm_state_get_palette_color(state, index, &color);
5506 sprintf((char *)hexbuf, "#%02x%02x%02x",
5507 color.red, color.green, color.blue);
5508 if (list_append_string(list, hexbuf, 7) == FAIL)
5509 return;
5510 }
5511}
5512
5513/*
5514 * "term_setansicolors(buf, list)" function
5515 */
5516 void
5517f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5518{
5519 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5520 term_T *term;
5521
5522 if (buf == NULL)
5523 return;
5524 term = buf->b_term;
5525 if (term->tl_vterm == NULL)
5526 return;
5527
5528 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5529 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005530 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005531 return;
5532 }
5533
5534 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005535 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005536}
5537#endif
5538
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005539/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005540 * "term_setrestore(buf, command)" function
5541 */
5542 void
5543f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5544{
5545#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005546 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005547 term_T *term;
5548 char_u *cmd;
5549
5550 if (buf == NULL)
5551 return;
5552 term = buf->b_term;
5553 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005554 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005555 if (cmd != NULL)
5556 term->tl_command = vim_strsave(cmd);
5557 else
5558 term->tl_command = NULL;
5559#endif
5560}
5561
5562/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005563 * "term_setkill(buf, how)" function
5564 */
5565 void
5566f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5567{
5568 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5569 term_T *term;
5570 char_u *how;
5571
5572 if (buf == NULL)
5573 return;
5574 term = buf->b_term;
5575 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005576 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005577 if (how != NULL)
5578 term->tl_kill = vim_strsave(how);
5579 else
5580 term->tl_kill = NULL;
5581}
5582
5583/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005584 * "term_start(command, options)" function
5585 */
5586 void
5587f_term_start(typval_T *argvars, typval_T *rettv)
5588{
5589 jobopt_T opt;
5590 buf_T *buf;
5591
5592 init_job_options(&opt);
5593 if (argvars[1].v_type != VAR_UNKNOWN
5594 && get_job_options(&argvars[1], &opt,
5595 JO_TIMEOUT_ALL + JO_STOPONEXIT
5596 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5597 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5598 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5599 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005600 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005601 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01005602 + JO2_ANSI_COLORS + JO2_TTY_TYPE) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005603 return;
5604
Bram Moolenaar13568252018-03-16 20:46:58 +01005605 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005606
5607 if (buf != NULL && buf->b_term != NULL)
5608 rettv->vval.v_number = buf->b_fnum;
5609}
5610
5611/*
5612 * "term_wait" function
5613 */
5614 void
5615f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5616{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005617 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005618
5619 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005620 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005621 if (buf->b_term->tl_job == NULL)
5622 {
5623 ch_log(NULL, "term_wait(): no job to wait for");
5624 return;
5625 }
5626 if (buf->b_term->tl_job->jv_channel == NULL)
5627 /* channel is closed, nothing to do */
5628 return;
5629
5630 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005631 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005632 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5633 {
5634 /* The job is dead, keep reading channel I/O until the channel is
5635 * closed. buf->b_term may become NULL if the terminal was closed while
5636 * waiting. */
5637 ch_log(NULL, "term_wait(): waiting for channel to close");
5638 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5639 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005640 term_flush_messages();
5641
Bram Moolenaard45aa552018-05-21 22:50:29 +02005642 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005643 if (!buf_valid(buf))
5644 /* If the terminal is closed when the channel is closed the
5645 * buffer disappears. */
5646 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005647 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005648
5649 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005650 }
5651 else
5652 {
5653 long wait = 10L;
5654
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005655 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005656
5657 /* Wait for some time for any channel I/O. */
5658 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005659 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005660 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005661
5662 /* Flushing messages on channels is hopefully sufficient.
5663 * TODO: is there a better way? */
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005664 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005665 }
5666}
5667
5668/*
5669 * Called when a channel has sent all the lines to a terminal.
5670 * Send a CTRL-D to mark the end of the text.
5671 */
5672 void
5673term_send_eof(channel_T *ch)
5674{
5675 term_T *term;
5676
5677 for (term = first_term; term != NULL; term = term->tl_next)
5678 if (term->tl_job == ch->ch_job)
5679 {
5680 if (term->tl_eof_chars != NULL)
5681 {
5682 channel_send(ch, PART_IN, term->tl_eof_chars,
5683 (int)STRLEN(term->tl_eof_chars), NULL);
5684 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5685 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005686# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005687 else
5688 /* Default: CTRL-D */
5689 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5690# endif
5691 }
5692}
5693
Bram Moolenaar113e1072019-01-20 15:30:40 +01005694#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005695 job_T *
5696term_getjob(term_T *term)
5697{
5698 return term != NULL ? term->tl_job : NULL;
5699}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005700#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005701
Bram Moolenaar4f974752019-02-17 17:44:42 +01005702# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005703
5704/**************************************
5705 * 2. MS-Windows implementation.
5706 */
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005707#ifdef PROTO
5708typedef int COORD;
5709typedef int DWORD;
5710typedef int HANDLE;
5711typedef int *DWORD_PTR;
5712typedef int HPCON;
5713typedef int HRESULT;
5714typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005715typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005716typedef int PSIZE_T;
5717typedef int PVOID;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005718typedef int WINAPI;
5719#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005720
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005721HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5722HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5723HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005724BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5725BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5726void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005727
5728 static int
5729dyn_conpty_init(int verbose)
5730{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005731 static HMODULE hKerneldll = NULL;
5732 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005733 static struct
5734 {
5735 char *name;
5736 FARPROC *ptr;
5737 } conpty_entry[] =
5738 {
5739 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5740 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5741 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5742 {"InitializeProcThreadAttributeList",
5743 (FARPROC*)&pInitializeProcThreadAttributeList},
5744 {"UpdateProcThreadAttribute",
5745 (FARPROC*)&pUpdateProcThreadAttribute},
5746 {"DeleteProcThreadAttributeList",
5747 (FARPROC*)&pDeleteProcThreadAttributeList},
5748 {NULL, NULL}
5749 };
5750
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005751 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005752 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005753 if (verbose)
5754 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005755 return FAIL;
5756 }
5757
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005758 // No need to initialize twice.
5759 if (hKerneldll)
5760 return OK;
5761
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005762 hKerneldll = vimLoadLib("kernel32.dll");
5763 for (i = 0; conpty_entry[i].name != NULL
5764 && conpty_entry[i].ptr != NULL; ++i)
5765 {
5766 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5767 conpty_entry[i].name)) == NULL)
5768 {
5769 if (verbose)
5770 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005771 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005772 return FAIL;
5773 }
5774 }
5775
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005776 return OK;
5777}
5778
5779 static int
5780conpty_term_and_job_init(
5781 term_T *term,
5782 typval_T *argvar,
5783 char **argv,
5784 jobopt_T *opt,
5785 jobopt_T *orig_opt)
5786{
5787 WCHAR *cmd_wchar = NULL;
5788 WCHAR *cmd_wchar_copy = NULL;
5789 WCHAR *cwd_wchar = NULL;
5790 WCHAR *env_wchar = NULL;
5791 channel_T *channel = NULL;
5792 job_T *job = NULL;
5793 HANDLE jo = NULL;
5794 garray_T ga_cmd, ga_env;
5795 char_u *cmd = NULL;
5796 HRESULT hr;
5797 COORD consize;
5798 SIZE_T breq;
5799 PROCESS_INFORMATION proc_info;
5800 HANDLE i_theirs = NULL;
5801 HANDLE o_theirs = NULL;
5802 HANDLE i_ours = NULL;
5803 HANDLE o_ours = NULL;
5804
5805 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5806 ga_init2(&ga_env, (int)sizeof(char*), 20);
5807
5808 if (argvar->v_type == VAR_STRING)
5809 {
5810 cmd = argvar->vval.v_string;
5811 }
5812 else if (argvar->v_type == VAR_LIST)
5813 {
5814 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5815 goto failed;
5816 cmd = ga_cmd.ga_data;
5817 }
5818 if (cmd == NULL || *cmd == NUL)
5819 {
5820 emsg(_(e_invarg));
5821 goto failed;
5822 }
5823
5824 term->tl_arg0_cmd = vim_strsave(cmd);
5825
5826 cmd_wchar = enc_to_utf16(cmd, NULL);
5827
5828 if (cmd_wchar != NULL)
5829 {
5830 /* Request by CreateProcessW */
5831 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005832 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005833 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5834 }
5835
5836 ga_clear(&ga_cmd);
5837 if (cmd_wchar == NULL)
5838 goto failed;
5839 if (opt->jo_cwd != NULL)
5840 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5841
5842 win32_build_env(opt->jo_env, &ga_env, TRUE);
5843 env_wchar = ga_env.ga_data;
5844
5845 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5846 goto failed;
5847 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5848 goto failed;
5849
5850 consize.X = term->tl_cols;
5851 consize.Y = term->tl_rows;
5852 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
5853 &term->tl_conpty);
5854 if (FAILED(hr))
5855 goto failed;
5856
5857 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
5858
5859 /* Set up pipe inheritance safely: Vista or later. */
5860 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005861 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005862 if (!term->tl_siex.lpAttributeList)
5863 goto failed;
5864 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
5865 0, &breq))
5866 goto failed;
5867 if (!pUpdateProcThreadAttribute(
5868 term->tl_siex.lpAttributeList, 0,
5869 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
5870 sizeof(HPCON), NULL, NULL))
5871 goto failed;
5872
5873 channel = add_channel();
5874 if (channel == NULL)
5875 goto failed;
5876
5877 job = job_alloc();
5878 if (job == NULL)
5879 goto failed;
5880 if (argvar->v_type == VAR_STRING)
5881 {
5882 int argc;
5883
5884 build_argv_from_string(cmd, &job->jv_argv, &argc);
5885 }
5886 else
5887 {
5888 int argc;
5889
5890 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5891 }
5892
5893 if (opt->jo_set & JO_IN_BUF)
5894 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5895
5896 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
5897 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
5898 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
5899 | CREATE_DEFAULT_ERROR_MODE,
5900 env_wchar, cwd_wchar,
5901 &term->tl_siex.StartupInfo, &proc_info))
5902 goto failed;
5903
5904 CloseHandle(i_theirs);
5905 CloseHandle(o_theirs);
5906
5907 channel_set_pipes(channel,
5908 (sock_T)i_ours,
5909 (sock_T)o_ours,
5910 (sock_T)o_ours);
5911
5912 /* Write lines with CR instead of NL. */
5913 channel->ch_write_text_mode = TRUE;
5914
5915 /* Use to explicitly delete anonymous pipe handle. */
5916 channel->ch_anonymous_pipe = TRUE;
5917
5918 jo = CreateJobObject(NULL, NULL);
5919 if (jo == NULL)
5920 goto failed;
5921
5922 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
5923 {
5924 /* Failed, switch the way to terminate process with TerminateProcess. */
5925 CloseHandle(jo);
5926 jo = NULL;
5927 }
5928
5929 ResumeThread(proc_info.hThread);
5930 CloseHandle(proc_info.hThread);
5931
5932 vim_free(cmd_wchar);
5933 vim_free(cmd_wchar_copy);
5934 vim_free(cwd_wchar);
5935 vim_free(env_wchar);
5936
5937 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
5938 goto failed;
5939
5940#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5941 if (opt->jo_set2 & JO2_ANSI_COLORS)
5942 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5943 else
5944 init_vterm_ansi_colors(term->tl_vterm);
5945#endif
5946
5947 channel_set_job(channel, job, opt);
5948 job_set_options(job, opt);
5949
5950 job->jv_channel = channel;
5951 job->jv_proc_info = proc_info;
5952 job->jv_job_object = jo;
5953 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01005954 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005955 ++job->jv_refcount;
5956 term->tl_job = job;
5957
5958 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5959 * open the file here and handle it in. opt->jo_io was changed in
5960 * setup_job_options(), use the original flags here. */
5961 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5962 {
5963 char_u *fname = opt->jo_io_name[PART_OUT];
5964
5965 ch_log(channel, "Opening output file %s", fname);
5966 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5967 if (term->tl_out_fd == NULL)
5968 semsg(_(e_notopen), fname);
5969 }
5970
5971 return OK;
5972
5973failed:
5974 ga_clear(&ga_cmd);
5975 ga_clear(&ga_env);
5976 vim_free(cmd_wchar);
5977 vim_free(cmd_wchar_copy);
5978 vim_free(cwd_wchar);
5979 if (channel != NULL)
5980 channel_clear(channel);
5981 if (job != NULL)
5982 {
5983 job->jv_channel = NULL;
5984 job_cleanup(job);
5985 }
5986 term->tl_job = NULL;
5987 if (jo != NULL)
5988 CloseHandle(jo);
5989
5990 if (term->tl_siex.lpAttributeList != NULL)
5991 {
5992 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
5993 vim_free(term->tl_siex.lpAttributeList);
5994 }
5995 term->tl_siex.lpAttributeList = NULL;
5996 if (o_theirs != NULL)
5997 CloseHandle(o_theirs);
5998 if (o_ours != NULL)
5999 CloseHandle(o_ours);
6000 if (i_ours != NULL)
6001 CloseHandle(i_ours);
6002 if (i_theirs != NULL)
6003 CloseHandle(i_theirs);
6004 if (term->tl_conpty != NULL)
6005 pClosePseudoConsole(term->tl_conpty);
6006 term->tl_conpty = NULL;
6007 return FAIL;
6008}
6009
6010 static void
6011conpty_term_report_winsize(term_T *term, int rows, int cols)
6012{
6013 COORD consize;
6014
6015 consize.X = cols;
6016 consize.Y = rows;
6017 pResizePseudoConsole(term->tl_conpty, consize);
6018}
6019
6020 void
6021term_free_conpty(term_T *term)
6022{
6023 if (term->tl_siex.lpAttributeList != NULL)
6024 {
6025 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6026 vim_free(term->tl_siex.lpAttributeList);
6027 }
6028 term->tl_siex.lpAttributeList = NULL;
6029 if (term->tl_conpty != NULL)
6030 pClosePseudoConsole(term->tl_conpty);
6031 term->tl_conpty = NULL;
6032}
6033
6034 int
6035use_conpty(void)
6036{
6037 return has_conpty;
6038}
6039
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006040# ifndef PROTO
6041
6042#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6043#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006044#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006045
6046void* (*winpty_config_new)(UINT64, void*);
6047void* (*winpty_open)(void*, void*);
6048void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6049BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6050void (*winpty_config_set_mouse_mode)(void*, int);
6051void (*winpty_config_set_initial_size)(void*, int, int);
6052LPCWSTR (*winpty_conin_name)(void*);
6053LPCWSTR (*winpty_conout_name)(void*);
6054LPCWSTR (*winpty_conerr_name)(void*);
6055void (*winpty_free)(void*);
6056void (*winpty_config_free)(void*);
6057void (*winpty_spawn_config_free)(void*);
6058void (*winpty_error_free)(void*);
6059LPCWSTR (*winpty_error_msg)(void*);
6060BOOL (*winpty_set_size)(void*, int, int, void*);
6061HANDLE (*winpty_agent_process)(void*);
6062
6063#define WINPTY_DLL "winpty.dll"
6064
6065static HINSTANCE hWinPtyDLL = NULL;
6066# endif
6067
6068 static int
6069dyn_winpty_init(int verbose)
6070{
6071 int i;
6072 static struct
6073 {
6074 char *name;
6075 FARPROC *ptr;
6076 } winpty_entry[] =
6077 {
6078 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6079 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6080 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6081 {"winpty_config_set_mouse_mode",
6082 (FARPROC*)&winpty_config_set_mouse_mode},
6083 {"winpty_config_set_initial_size",
6084 (FARPROC*)&winpty_config_set_initial_size},
6085 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6086 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6087 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6088 {"winpty_free", (FARPROC*)&winpty_free},
6089 {"winpty_open", (FARPROC*)&winpty_open},
6090 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6091 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6092 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6093 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6094 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6095 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6096 {NULL, NULL}
6097 };
6098
6099 /* No need to initialize twice. */
6100 if (hWinPtyDLL)
6101 return OK;
6102 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6103 * winpty.dll. */
6104 if (*p_winptydll != NUL)
6105 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6106 if (!hWinPtyDLL)
6107 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6108 if (!hWinPtyDLL)
6109 {
6110 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006111 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006112 : (char_u *)WINPTY_DLL);
6113 return FAIL;
6114 }
6115 for (i = 0; winpty_entry[i].name != NULL
6116 && winpty_entry[i].ptr != NULL; ++i)
6117 {
6118 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6119 winpty_entry[i].name)) == NULL)
6120 {
6121 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006122 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006123 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006124 return FAIL;
6125 }
6126 }
6127
6128 return OK;
6129}
6130
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006131 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006132winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006133 term_T *term,
6134 typval_T *argvar,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006135 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006136 jobopt_T *opt,
6137 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006138{
6139 WCHAR *cmd_wchar = NULL;
6140 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006141 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006142 channel_T *channel = NULL;
6143 job_T *job = NULL;
6144 DWORD error;
6145 HANDLE jo = NULL;
6146 HANDLE child_process_handle;
6147 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006148 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006149 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006150 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006151 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006152
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006153 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6154 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006155
6156 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006157 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006158 cmd = argvar->vval.v_string;
6159 }
6160 else if (argvar->v_type == VAR_LIST)
6161 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006162 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006163 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006164 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006165 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006166 if (cmd == NULL || *cmd == NUL)
6167 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006168 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006169 goto failed;
6170 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006171
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006172 term->tl_arg0_cmd = vim_strsave(cmd);
6173
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006174 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006175 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006176 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006177 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006178 if (opt->jo_cwd != NULL)
6179 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006180
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006181 win32_build_env(opt->jo_env, &ga_env, TRUE);
6182 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006183
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006184 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6185 if (term->tl_winpty_config == NULL)
6186 goto failed;
6187
6188 winpty_config_set_mouse_mode(term->tl_winpty_config,
6189 WINPTY_MOUSE_MODE_FORCE);
6190 winpty_config_set_initial_size(term->tl_winpty_config,
6191 term->tl_cols, term->tl_rows);
6192 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6193 if (term->tl_winpty == NULL)
6194 goto failed;
6195
6196 spawn_config = winpty_spawn_config_new(
6197 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6198 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6199 NULL,
6200 cmd_wchar,
6201 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006202 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006203 &winpty_err);
6204 if (spawn_config == NULL)
6205 goto failed;
6206
6207 channel = add_channel();
6208 if (channel == NULL)
6209 goto failed;
6210
6211 job = job_alloc();
6212 if (job == NULL)
6213 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006214 if (argvar->v_type == VAR_STRING)
6215 {
6216 int argc;
6217
6218 build_argv_from_string(cmd, &job->jv_argv, &argc);
6219 }
6220 else
6221 {
6222 int argc;
6223
6224 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6225 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006226
6227 if (opt->jo_set & JO_IN_BUF)
6228 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6229
6230 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6231 &child_thread_handle, &error, &winpty_err))
6232 goto failed;
6233
6234 channel_set_pipes(channel,
6235 (sock_T)CreateFileW(
6236 winpty_conin_name(term->tl_winpty),
6237 GENERIC_WRITE, 0, NULL,
6238 OPEN_EXISTING, 0, NULL),
6239 (sock_T)CreateFileW(
6240 winpty_conout_name(term->tl_winpty),
6241 GENERIC_READ, 0, NULL,
6242 OPEN_EXISTING, 0, NULL),
6243 (sock_T)CreateFileW(
6244 winpty_conerr_name(term->tl_winpty),
6245 GENERIC_READ, 0, NULL,
6246 OPEN_EXISTING, 0, NULL));
6247
6248 /* Write lines with CR instead of NL. */
6249 channel->ch_write_text_mode = TRUE;
6250
6251 jo = CreateJobObject(NULL, NULL);
6252 if (jo == NULL)
6253 goto failed;
6254
6255 if (!AssignProcessToJobObject(jo, child_process_handle))
6256 {
6257 /* Failed, switch the way to terminate process with TerminateProcess. */
6258 CloseHandle(jo);
6259 jo = NULL;
6260 }
6261
6262 winpty_spawn_config_free(spawn_config);
6263 vim_free(cmd_wchar);
6264 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006265 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006266
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006267 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6268 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006269
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006270#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6271 if (opt->jo_set2 & JO2_ANSI_COLORS)
6272 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6273 else
6274 init_vterm_ansi_colors(term->tl_vterm);
6275#endif
6276
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006277 channel_set_job(channel, job, opt);
6278 job_set_options(job, opt);
6279
6280 job->jv_channel = channel;
6281 job->jv_proc_info.hProcess = child_process_handle;
6282 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6283 job->jv_job_object = jo;
6284 job->jv_status = JOB_STARTED;
6285 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006286 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006287 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006288 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006289 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006290 ++job->jv_refcount;
6291 term->tl_job = job;
6292
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006293 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6294 * open the file here and handle it in. opt->jo_io was changed in
6295 * setup_job_options(), use the original flags here. */
6296 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6297 {
6298 char_u *fname = opt->jo_io_name[PART_OUT];
6299
6300 ch_log(channel, "Opening output file %s", fname);
6301 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6302 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006303 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006304 }
6305
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006306 return OK;
6307
6308failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006309 ga_clear(&ga_cmd);
6310 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006311 vim_free(cmd_wchar);
6312 vim_free(cwd_wchar);
6313 if (spawn_config != NULL)
6314 winpty_spawn_config_free(spawn_config);
6315 if (channel != NULL)
6316 channel_clear(channel);
6317 if (job != NULL)
6318 {
6319 job->jv_channel = NULL;
6320 job_cleanup(job);
6321 }
6322 term->tl_job = NULL;
6323 if (jo != NULL)
6324 CloseHandle(jo);
6325 if (term->tl_winpty != NULL)
6326 winpty_free(term->tl_winpty);
6327 term->tl_winpty = NULL;
6328 if (term->tl_winpty_config != NULL)
6329 winpty_config_free(term->tl_winpty_config);
6330 term->tl_winpty_config = NULL;
6331 if (winpty_err != NULL)
6332 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006333 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006334 (short_u *)winpty_error_msg(winpty_err), NULL);
6335
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006336 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006337 winpty_error_free(winpty_err);
6338 }
6339 return FAIL;
6340}
6341
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006342/*
6343 * Create a new terminal of "rows" by "cols" cells.
6344 * Store a reference in "term".
6345 * Return OK or FAIL.
6346 */
6347 static int
6348term_and_job_init(
6349 term_T *term,
6350 typval_T *argvar,
6351 char **argv UNUSED,
6352 jobopt_T *opt,
6353 jobopt_T *orig_opt)
6354{
6355 int use_winpty = FALSE;
6356 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006357 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006358
6359 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6360 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6361
6362 if (!has_winpty && !has_conpty)
6363 // If neither is available give the errors for winpty, since when
6364 // conpty is not available it can't be installed either.
6365 return dyn_winpty_init(TRUE);
6366
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006367 if (opt->jo_tty_type != NUL)
6368 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006369
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006370 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006371 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006372 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006373 use_conpty = TRUE;
6374 else if (has_winpty)
6375 use_winpty = TRUE;
6376 // else: error
6377 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006378 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006379 {
6380 if (has_winpty)
6381 use_winpty = TRUE;
6382 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006383 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006384 {
6385 if (has_conpty)
6386 use_conpty = TRUE;
6387 else
6388 return dyn_conpty_init(TRUE);
6389 }
6390
6391 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006392 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006393
6394 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006395 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006396
6397 // error
6398 return dyn_winpty_init(TRUE);
6399}
6400
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006401 static int
6402create_pty_only(term_T *term, jobopt_T *options)
6403{
6404 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6405 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6406 char in_name[80], out_name[80];
6407 channel_T *channel = NULL;
6408
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006409 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6410 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006411
6412 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6413 GetCurrentProcessId(),
6414 curbuf->b_fnum);
6415 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6416 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6417 PIPE_UNLIMITED_INSTANCES,
6418 0, 0, NMPWAIT_NOWAIT, NULL);
6419 if (hPipeIn == INVALID_HANDLE_VALUE)
6420 goto failed;
6421
6422 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6423 GetCurrentProcessId(),
6424 curbuf->b_fnum);
6425 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6426 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6427 PIPE_UNLIMITED_INSTANCES,
6428 0, 0, 0, NULL);
6429 if (hPipeOut == INVALID_HANDLE_VALUE)
6430 goto failed;
6431
6432 ConnectNamedPipe(hPipeIn, NULL);
6433 ConnectNamedPipe(hPipeOut, NULL);
6434
6435 term->tl_job = job_alloc();
6436 if (term->tl_job == NULL)
6437 goto failed;
6438 ++term->tl_job->jv_refcount;
6439
6440 /* behave like the job is already finished */
6441 term->tl_job->jv_status = JOB_FINISHED;
6442
6443 channel = add_channel();
6444 if (channel == NULL)
6445 goto failed;
6446 term->tl_job->jv_channel = channel;
6447 channel->ch_keep_open = TRUE;
6448 channel->ch_named_pipe = TRUE;
6449
6450 channel_set_pipes(channel,
6451 (sock_T)hPipeIn,
6452 (sock_T)hPipeOut,
6453 (sock_T)hPipeOut);
6454 channel_set_job(channel, term->tl_job, options);
6455 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6456 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6457
6458 return OK;
6459
6460failed:
6461 if (hPipeIn != NULL)
6462 CloseHandle(hPipeIn);
6463 if (hPipeOut != NULL)
6464 CloseHandle(hPipeOut);
6465 return FAIL;
6466}
6467
6468/*
6469 * Free the terminal emulator part of "term".
6470 */
6471 static void
6472term_free_vterm(term_T *term)
6473{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006474 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006475 if (term->tl_winpty != NULL)
6476 winpty_free(term->tl_winpty);
6477 term->tl_winpty = NULL;
6478 if (term->tl_winpty_config != NULL)
6479 winpty_config_free(term->tl_winpty_config);
6480 term->tl_winpty_config = NULL;
6481 if (term->tl_vterm != NULL)
6482 vterm_free(term->tl_vterm);
6483 term->tl_vterm = NULL;
6484}
6485
6486/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006487 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006488 */
6489 static void
6490term_report_winsize(term_T *term, int rows, int cols)
6491{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006492 if (term->tl_conpty)
6493 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006494 if (term->tl_winpty)
6495 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6496}
6497
6498 int
6499terminal_enabled(void)
6500{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006501 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006502}
6503
6504# else
6505
6506/**************************************
6507 * 3. Unix-like implementation.
6508 */
6509
6510/*
6511 * Create a new terminal of "rows" by "cols" cells.
6512 * Start job for "cmd".
6513 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006514 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006515 * Return OK or FAIL.
6516 */
6517 static int
6518term_and_job_init(
6519 term_T *term,
6520 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006521 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006522 jobopt_T *opt,
6523 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006524{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006525 term->tl_arg0_cmd = NULL;
6526
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006527 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6528 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006529
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006530#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6531 if (opt->jo_set2 & JO2_ANSI_COLORS)
6532 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6533 else
6534 init_vterm_ansi_colors(term->tl_vterm);
6535#endif
6536
Bram Moolenaar13568252018-03-16 20:46:58 +01006537 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006538 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006539 if (term->tl_job != NULL)
6540 ++term->tl_job->jv_refcount;
6541
6542 return term->tl_job != NULL
6543 && term->tl_job->jv_channel != NULL
6544 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6545}
6546
6547 static int
6548create_pty_only(term_T *term, jobopt_T *opt)
6549{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006550 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6551 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006552
6553 term->tl_job = job_alloc();
6554 if (term->tl_job == NULL)
6555 return FAIL;
6556 ++term->tl_job->jv_refcount;
6557
6558 /* behave like the job is already finished */
6559 term->tl_job->jv_status = JOB_FINISHED;
6560
6561 return mch_create_pty_channel(term->tl_job, opt);
6562}
6563
6564/*
6565 * Free the terminal emulator part of "term".
6566 */
6567 static void
6568term_free_vterm(term_T *term)
6569{
6570 if (term->tl_vterm != NULL)
6571 vterm_free(term->tl_vterm);
6572 term->tl_vterm = NULL;
6573}
6574
6575/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006576 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006577 */
6578 static void
6579term_report_winsize(term_T *term, int rows, int cols)
6580{
6581 /* Use an ioctl() to report the new window size to the job. */
6582 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6583 {
6584 int fd = -1;
6585 int part;
6586
6587 for (part = PART_OUT; part < PART_COUNT; ++part)
6588 {
6589 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006590 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006591 break;
6592 }
6593 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6594 mch_signal_job(term->tl_job, (char_u *)"winch");
6595 }
6596}
6597
6598# endif
6599
6600#endif /* FEAT_TERMINAL */