blob: 1764b052d89beb255003968f2cdaffab88d18957 [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 Moolenaard96ff162018-02-18 22:13:29 +0100361 * Close a terminal buffer (and its window). Used when creating the terminal
362 * fails.
363 */
364 static void
365term_close_buffer(buf_T *buf, buf_T *old_curbuf)
366{
367 free_terminal(buf);
368 if (old_curbuf != NULL)
369 {
370 --curbuf->b_nwindows;
371 curbuf = old_curbuf;
372 curwin->w_buffer = curbuf;
373 ++curbuf->b_nwindows;
374 }
375
376 /* Wiping out the buffer will also close the window and call
377 * free_terminal(). */
378 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
379}
380
381/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200382 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100383 * Use either "argvar" or "argv", the other must be NULL.
384 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
385 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200386 * Returns NULL when failed.
387 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100388 buf_T *
389term_start(
390 typval_T *argvar,
391 char **argv,
392 jobopt_T *opt,
393 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200394{
395 exarg_T split_ea;
396 win_T *old_curwin = curwin;
397 term_T *term;
398 buf_T *old_curbuf = NULL;
399 int res;
400 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100401 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200402 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200403
404 if (check_restricted() || check_secure())
405 return NULL;
406
407 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
408 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
409 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
410 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
411 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100412 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200413 return NULL;
414 }
415
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200416 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200417 if (term == NULL)
418 return NULL;
419 term->tl_dirty_row_end = MAX_ROW;
420 term->tl_cursor_visible = TRUE;
421 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
422 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100423#ifdef FEAT_GUI
424 term->tl_system = (flags & TERM_START_SYSTEM);
425#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200426 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100427 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428
429 vim_memset(&split_ea, 0, sizeof(split_ea));
430 if (opt->jo_curwin)
431 {
432 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100433 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200434 {
435 no_write_message();
436 vim_free(term);
437 return NULL;
438 }
439 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100440 ECMD_HIDE
441 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
442 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200443 {
444 vim_free(term);
445 return NULL;
446 }
447 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100448 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200449 {
450 buf_T *buf;
451
452 /* Create a new buffer without a window. Make it the current buffer for
453 * a moment to be able to do the initialisations. */
454 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
455 BLN_NEW | BLN_LISTED);
456 if (buf == NULL || ml_open(buf) == FAIL)
457 {
458 vim_free(term);
459 return NULL;
460 }
461 old_curbuf = curbuf;
462 --curbuf->b_nwindows;
463 curbuf = buf;
464 curwin->w_buffer = buf;
465 ++curbuf->b_nwindows;
466 }
467 else
468 {
469 /* Open a new window or tab. */
470 split_ea.cmdidx = CMD_new;
471 split_ea.cmd = (char_u *)"new";
472 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100473 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200474 {
475 split_ea.line2 = opt->jo_term_rows;
476 split_ea.addr_count = 1;
477 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100478 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200479 {
480 split_ea.line2 = opt->jo_term_cols;
481 split_ea.addr_count = 1;
482 }
483
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100484 if (vertical)
485 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200486 ex_splitview(&split_ea);
487 if (curwin == old_curwin)
488 {
489 /* split failed */
490 vim_free(term);
491 return NULL;
492 }
493 }
494 term->tl_buffer = curbuf;
495 curbuf->b_term = term;
496
497 if (!opt->jo_hidden)
498 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100499 /* Only one size was taken care of with :new, do the other one. With
500 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100501 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200502 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100503 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200504 win_setwidth(opt->jo_term_cols);
505 }
506
507 /* Link the new terminal in the list of active terminals. */
508 term->tl_next = first_term;
509 first_term = term;
510
511 if (opt->jo_term_name != NULL)
512 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100513 else if (argv != NULL)
514 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200515 else
516 {
517 int i;
518 size_t len;
519 char_u *cmd, *p;
520
521 if (argvar->v_type == VAR_STRING)
522 {
523 cmd = argvar->vval.v_string;
524 if (cmd == NULL)
525 cmd = (char_u *)"";
526 else if (STRCMP(cmd, "NONE") == 0)
527 cmd = (char_u *)"pty";
528 }
529 else if (argvar->v_type != VAR_LIST
530 || argvar->vval.v_list == NULL
531 || argvar->vval.v_list->lv_len < 1
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100532 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200533 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
534 cmd = (char_u*)"";
535
536 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200537 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200538
539 for (i = 0; p != NULL; ++i)
540 {
541 /* Prepend a ! to the command name to avoid the buffer name equals
542 * the executable, otherwise ":w!" would overwrite it. */
543 if (i == 0)
544 vim_snprintf((char *)p, len, "!%s", cmd);
545 else
546 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
547 if (buflist_findname(p) == NULL)
548 {
549 vim_free(curbuf->b_ffname);
550 curbuf->b_ffname = p;
551 break;
552 }
553 }
554 }
555 curbuf->b_fname = curbuf->b_ffname;
556
557 if (opt->jo_term_opencmd != NULL)
558 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
559
560 if (opt->jo_eof_chars != NULL)
561 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
562
563 set_string_option_direct((char_u *)"buftype", -1,
564 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200565 // Avoid that 'buftype' is reset when this buffer is entered.
566 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200567
568 /* Mark the buffer as not modifiable. It can only be made modifiable after
569 * the job finished. */
570 curbuf->b_p_ma = FALSE;
571
572 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100573#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200574 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
575#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200576 setup_job_options(opt, term->tl_rows, term->tl_cols);
577
Bram Moolenaar13568252018-03-16 20:46:58 +0100578 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100579 return curbuf;
580
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100581#if defined(FEAT_SESSION)
582 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100583 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100584 {
585 term->tl_command = vim_strsave((char_u *)"NONE");
586 }
587 else if (argvar->v_type == VAR_STRING)
588 {
589 char_u *cmd = argvar->vval.v_string;
590
591 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
592 term->tl_command = vim_strsave(cmd);
593 }
594 else if (argvar->v_type == VAR_LIST
595 && argvar->vval.v_list != NULL
596 && argvar->vval.v_list->lv_len > 0)
597 {
598 garray_T ga;
599 listitem_T *item;
600
601 ga_init2(&ga, 1, 100);
602 for (item = argvar->vval.v_list->lv_first;
603 item != NULL; item = item->li_next)
604 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100605 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100606 char_u *p;
607
608 if (s == NULL)
609 break;
610 p = vim_strsave_fnameescape(s, FALSE);
611 if (p == NULL)
612 break;
613 ga_concat(&ga, p);
614 vim_free(p);
615 ga_append(&ga, ' ');
616 }
617 if (item == NULL)
618 {
619 ga_append(&ga, NUL);
620 term->tl_command = ga.ga_data;
621 }
622 else
623 ga_clear(&ga);
624 }
625#endif
626
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100627 if (opt->jo_term_kill != NULL)
628 {
629 char_u *p = skiptowhite(opt->jo_term_kill);
630
631 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
632 }
633
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200634 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100635 if (argv == NULL
636 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200637 && argvar->vval.v_string != NULL
638 && STRCMP(argvar->vval.v_string, "NONE") == 0)
639 res = create_pty_only(term, opt);
640 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200641 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200642
643 newbuf = curbuf;
644 if (res == OK)
645 {
646 /* Get and remember the size we ended up with. Update the pty. */
647 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
648 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100649#ifdef FEAT_GUI
650 if (term->tl_system)
651 {
652 /* display first line below typed command */
653 term->tl_toprow = msg_row + 1;
654 term->tl_dirty_row_end = 0;
655 }
656#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200657
658 /* Make sure we don't get stuck on sending keys to the job, it leads to
659 * a deadlock if the job is waiting for Vim to read. */
660 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
661
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200662 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200663 {
664 --curbuf->b_nwindows;
665 curbuf = old_curbuf;
666 curwin->w_buffer = curbuf;
667 ++curbuf->b_nwindows;
668 }
669 }
670 else
671 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100672 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200673 return NULL;
674 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100675
Bram Moolenaar13568252018-03-16 20:46:58 +0100676 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200677 return newbuf;
678}
679
680/*
681 * ":terminal": open a terminal window and execute a job in it.
682 */
683 void
684ex_terminal(exarg_T *eap)
685{
686 typval_T argvar[2];
687 jobopt_T opt;
688 char_u *cmd;
689 char_u *tofree = NULL;
690
691 init_job_options(&opt);
692
693 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100694 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200695 {
696 char_u *p, *ep;
697
698 cmd += 2;
699 p = skiptowhite(cmd);
700 ep = vim_strchr(cmd, '=');
701 if (ep != NULL && ep < p)
702 p = ep;
703
704 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
705 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100706 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
707 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200708 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
709 opt.jo_term_finish = 'o';
710 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
711 opt.jo_curwin = 1;
712 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
713 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100714 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
715 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100716 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
717 && ep != NULL)
718 {
719 opt.jo_set2 |= JO2_TERM_KILL;
720 opt.jo_term_kill = ep + 1;
721 p = skiptowhite(cmd);
722 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200723 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
724 && ep != NULL && isdigit(ep[1]))
725 {
726 opt.jo_set2 |= JO2_TERM_ROWS;
727 opt.jo_term_rows = atoi((char *)ep + 1);
728 p = skiptowhite(cmd);
729 }
730 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
731 && ep != NULL && isdigit(ep[1]))
732 {
733 opt.jo_set2 |= JO2_TERM_COLS;
734 opt.jo_term_cols = atoi((char *)ep + 1);
735 p = skiptowhite(cmd);
736 }
737 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
738 && ep != NULL)
739 {
740 char_u *buf = NULL;
741 char_u *keys;
742
743 p = skiptowhite(cmd);
744 *p = NUL;
745 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
746 opt.jo_set2 |= JO2_EOF_CHARS;
747 opt.jo_eof_chars = vim_strsave(keys);
748 vim_free(buf);
749 *p = ' ';
750 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100751#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100752 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
753 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100754 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100755 int tty_type = NUL;
756
757 p = skiptowhite(cmd);
758 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
759 tty_type = 'w';
760 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
761 tty_type = 'c';
762 else
763 {
764 semsg(e_invargval, "type");
765 goto theend;
766 }
767 opt.jo_set2 |= JO2_TTY_TYPE;
768 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100769 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100770#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200771 else
772 {
773 if (*p)
774 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100775 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100776 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200777 }
778 cmd = skipwhite(p);
779 }
780 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100781 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200782 /* Make a copy of 'shell', an autocommand may change the option. */
783 tofree = cmd = vim_strsave(p_sh);
784
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100785 /* default to close when the shell exits */
786 if (opt.jo_term_finish == NUL)
787 opt.jo_term_finish = 'c';
788 }
789
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200790 if (eap->addr_count > 0)
791 {
792 /* Write lines from current buffer to the job. */
793 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
794 opt.jo_io[PART_IN] = JIO_BUFFER;
795 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
796 opt.jo_in_top = eap->line1;
797 opt.jo_in_bot = eap->line2;
798 }
799
800 argvar[0].v_type = VAR_STRING;
801 argvar[0].vval.v_string = cmd;
802 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100803 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200804 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100805
806theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200807 vim_free(opt.jo_eof_chars);
808}
809
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100810#if defined(FEAT_SESSION) || defined(PROTO)
811/*
812 * Write a :terminal command to the session file to restore the terminal in
813 * window "wp".
814 * Return FAIL if writing fails.
815 */
816 int
817term_write_session(FILE *fd, win_T *wp)
818{
819 term_T *term = wp->w_buffer->b_term;
820
821 /* Create the terminal and run the command. This is not without
822 * risk, but let's assume the user only creates a session when this
823 * will be OK. */
824 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
825 term->tl_cols, term->tl_rows) < 0)
826 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100827#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100828 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
829 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100830#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100831 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
832 return FAIL;
833
834 return put_eol(fd);
835}
836
837/*
838 * Return TRUE if "buf" has a terminal that should be restored.
839 */
840 int
841term_should_restore(buf_T *buf)
842{
843 term_T *term = buf->b_term;
844
845 return term != NULL && (term->tl_command == NULL
846 || STRCMP(term->tl_command, "NONE") != 0);
847}
848#endif
849
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200850/*
851 * Free the scrollback buffer for "term".
852 */
853 static void
854free_scrollback(term_T *term)
855{
856 int i;
857
858 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
859 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
860 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100861 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
862 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
863 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200864}
865
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100866
867// Terminals that need to be freed soon.
868term_T *terminals_to_free = NULL;
869
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200870/*
871 * Free a terminal and everything it refers to.
872 * Kills the job if there is one.
873 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100874 * The actual terminal structure is freed later in free_unused_terminals(),
875 * because callbacks may wipe out a buffer while the terminal is still
876 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200877 */
878 void
879free_terminal(buf_T *buf)
880{
881 term_T *term = buf->b_term;
882 term_T *tp;
883
884 if (term == NULL)
885 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100886
887 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200888 if (first_term == term)
889 first_term = term->tl_next;
890 else
891 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
892 if (tp->tl_next == term)
893 {
894 tp->tl_next = term->tl_next;
895 break;
896 }
897
898 if (term->tl_job != NULL)
899 {
900 if (term->tl_job->jv_status != JOB_ENDED
901 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100902 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200903 job_stop(term->tl_job, NULL, "kill");
904 job_unref(term->tl_job);
905 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100906 term->tl_next = terminals_to_free;
907 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200908
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200909 buf->b_term = NULL;
910 if (in_terminal_loop == term)
911 in_terminal_loop = NULL;
912}
913
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100914 void
915free_unused_terminals()
916{
917 while (terminals_to_free != NULL)
918 {
919 term_T *term = terminals_to_free;
920
921 terminals_to_free = term->tl_next;
922
923 free_scrollback(term);
924
925 term_free_vterm(term);
926 vim_free(term->tl_title);
927#ifdef FEAT_SESSION
928 vim_free(term->tl_command);
929#endif
930 vim_free(term->tl_kill);
931 vim_free(term->tl_status_text);
932 vim_free(term->tl_opencmd);
933 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100934 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100935#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100936 if (term->tl_out_fd != NULL)
937 fclose(term->tl_out_fd);
938#endif
939 vim_free(term->tl_cursor_color);
940 vim_free(term);
941 }
942}
943
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200944/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100945 * Get the part that is connected to the tty. Normally this is PART_IN, but
946 * when writing buffer lines to the job it can be another. This makes it
947 * possible to do "1,5term vim -".
948 */
949 static ch_part_T
950get_tty_part(term_T *term)
951{
952#ifdef UNIX
953 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
954 int i;
955
956 for (i = 0; i < 3; ++i)
957 {
958 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
959
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +0100960 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100961 return parts[i];
962 }
963#endif
964 return PART_IN;
965}
966
967/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200968 * Write job output "msg[len]" to the vterm.
969 */
970 static void
971term_write_job_output(term_T *term, char_u *msg, size_t len)
972{
973 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100974 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200975
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100976 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200977
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100978 /* flush vterm buffer when vterm responded to control sequence */
979 if (prevlen != vterm_output_get_buffer_current(vterm))
980 {
981 char buf[KEY_BUF_LEN];
982 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
983
984 if (curlen > 0)
985 channel_send(term->tl_job->jv_channel, get_tty_part(term),
986 (char_u *)buf, (int)curlen, NULL);
987 }
988
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200989 /* this invokes the damage callbacks */
990 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
991}
992
993 static void
994update_cursor(term_T *term, int redraw)
995{
996 if (term->tl_normal_mode)
997 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100998#ifdef FEAT_GUI
999 if (term->tl_system)
1000 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1001 term->tl_cursor_pos.col);
1002 else
1003#endif
1004 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001005 if (redraw)
1006 {
1007 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1008 cursor_on();
1009 out_flush();
1010#ifdef FEAT_GUI
1011 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001012 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001013 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001014 gui_mch_flush();
1015 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001016#endif
1017 }
1018}
1019
1020/*
1021 * Invoked when "msg" output from a job was received. Write it to the terminal
1022 * of "buffer".
1023 */
1024 void
1025write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1026{
1027 size_t len = STRLEN(msg);
1028 term_T *term = buffer->b_term;
1029
Bram Moolenaar4f974752019-02-17 17:44:42 +01001030#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001031 /* Win32: Cannot redirect output of the job, intercept it here and write to
1032 * the file. */
1033 if (term->tl_out_fd != NULL)
1034 {
1035 ch_log(channel, "Writing %d bytes to output file", (int)len);
1036 fwrite(msg, len, 1, term->tl_out_fd);
1037 return;
1038 }
1039#endif
1040
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001041 if (term->tl_vterm == NULL)
1042 {
1043 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1044 return;
1045 }
1046 ch_log(channel, "writing %d bytes to terminal", (int)len);
1047 term_write_job_output(term, msg, len);
1048
Bram Moolenaar13568252018-03-16 20:46:58 +01001049#ifdef FEAT_GUI
1050 if (term->tl_system)
1051 {
1052 /* show system output, scrolling up the screen as needed */
1053 update_system_term(term);
1054 update_cursor(term, TRUE);
1055 }
1056 else
1057#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001058 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
1059 * contents, thus no screen update is needed. */
1060 if (!term->tl_normal_mode)
1061 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001062 // Don't use update_screen() when editing the command line, it gets
1063 // cleared.
1064 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001065 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001066 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001067 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001068 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001069 /* update_screen() can be slow, check the terminal wasn't closed
1070 * already */
1071 if (buffer == curbuf && curbuf->b_term != NULL)
1072 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001073 }
1074 else
1075 redraw_after_callback(TRUE);
1076 }
1077}
1078
1079/*
1080 * Send a mouse position and click to the vterm
1081 */
1082 static int
1083term_send_mouse(VTerm *vterm, int button, int pressed)
1084{
1085 VTermModifier mod = VTERM_MOD_NONE;
1086
1087 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001088 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001089 if (button != 0)
1090 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001091 return TRUE;
1092}
1093
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001094static int enter_mouse_col = -1;
1095static int enter_mouse_row = -1;
1096
1097/*
1098 * Handle a mouse click, drag or release.
1099 * Return TRUE when a mouse event is sent to the terminal.
1100 */
1101 static int
1102term_mouse_click(VTerm *vterm, int key)
1103{
1104#if defined(FEAT_CLIPBOARD)
1105 /* For modeless selection mouse drag and release events are ignored, unless
1106 * they are preceded with a mouse down event */
1107 static int ignore_drag_release = TRUE;
1108 VTermMouseState mouse_state;
1109
1110 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1111 if (mouse_state.flags == 0)
1112 {
1113 /* Terminal is not using the mouse, use modeless selection. */
1114 switch (key)
1115 {
1116 case K_LEFTDRAG:
1117 case K_LEFTRELEASE:
1118 case K_RIGHTDRAG:
1119 case K_RIGHTRELEASE:
1120 /* Ignore drag and release events when the button-down wasn't
1121 * seen before. */
1122 if (ignore_drag_release)
1123 {
1124 int save_mouse_col, save_mouse_row;
1125
1126 if (enter_mouse_col < 0)
1127 break;
1128
1129 /* mouse click in the window gave us focus, handle that
1130 * click now */
1131 save_mouse_col = mouse_col;
1132 save_mouse_row = mouse_row;
1133 mouse_col = enter_mouse_col;
1134 mouse_row = enter_mouse_row;
1135 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1136 mouse_col = save_mouse_col;
1137 mouse_row = save_mouse_row;
1138 }
1139 /* FALLTHROUGH */
1140 case K_LEFTMOUSE:
1141 case K_RIGHTMOUSE:
1142 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1143 ignore_drag_release = TRUE;
1144 else
1145 ignore_drag_release = FALSE;
1146 /* Should we call mouse_has() here? */
1147 if (clip_star.available)
1148 {
1149 int button, is_click, is_drag;
1150
1151 button = get_mouse_button(KEY2TERMCAP1(key),
1152 &is_click, &is_drag);
1153 if (mouse_model_popup() && button == MOUSE_LEFT
1154 && (mod_mask & MOD_MASK_SHIFT))
1155 {
1156 /* Translate shift-left to right button. */
1157 button = MOUSE_RIGHT;
1158 mod_mask &= ~MOD_MASK_SHIFT;
1159 }
1160 clip_modeless(button, is_click, is_drag);
1161 }
1162 break;
1163
1164 case K_MIDDLEMOUSE:
1165 if (clip_star.available)
1166 insert_reg('*', TRUE);
1167 break;
1168 }
1169 enter_mouse_col = -1;
1170 return FALSE;
1171 }
1172#endif
1173 enter_mouse_col = -1;
1174
1175 switch (key)
1176 {
1177 case K_LEFTMOUSE:
1178 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1179 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1180 case K_LEFTRELEASE:
1181 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1182 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1183 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1184 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1185 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1186 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1187 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1188 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1189 }
1190 return TRUE;
1191}
1192
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001193/*
1194 * Convert typed key "c" into bytes to send to the job.
1195 * Return the number of bytes in "buf".
1196 */
1197 static int
1198term_convert_key(term_T *term, int c, char *buf)
1199{
1200 VTerm *vterm = term->tl_vterm;
1201 VTermKey key = VTERM_KEY_NONE;
1202 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001203 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001204
1205 switch (c)
1206 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001207 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1208
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001209 /* don't use VTERM_KEY_BACKSPACE, it always
1210 * becomes 0x7f DEL */
1211 case K_BS: c = term_backspace_char; break;
1212
1213 case ESC: key = VTERM_KEY_ESCAPE; break;
1214 case K_DEL: key = VTERM_KEY_DEL; break;
1215 case K_DOWN: key = VTERM_KEY_DOWN; break;
1216 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1217 key = VTERM_KEY_DOWN; break;
1218 case K_END: key = VTERM_KEY_END; break;
1219 case K_S_END: mod = VTERM_MOD_SHIFT;
1220 key = VTERM_KEY_END; break;
1221 case K_C_END: mod = VTERM_MOD_CTRL;
1222 key = VTERM_KEY_END; break;
1223 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1224 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1225 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1226 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1227 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1228 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1229 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1230 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1231 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1232 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1233 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1234 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1235 case K_HOME: key = VTERM_KEY_HOME; break;
1236 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1237 key = VTERM_KEY_HOME; break;
1238 case K_C_HOME: mod = VTERM_MOD_CTRL;
1239 key = VTERM_KEY_HOME; break;
1240 case K_INS: key = VTERM_KEY_INS; break;
1241 case K_K0: key = VTERM_KEY_KP_0; break;
1242 case K_K1: key = VTERM_KEY_KP_1; break;
1243 case K_K2: key = VTERM_KEY_KP_2; break;
1244 case K_K3: key = VTERM_KEY_KP_3; break;
1245 case K_K4: key = VTERM_KEY_KP_4; break;
1246 case K_K5: key = VTERM_KEY_KP_5; break;
1247 case K_K6: key = VTERM_KEY_KP_6; break;
1248 case K_K7: key = VTERM_KEY_KP_7; break;
1249 case K_K8: key = VTERM_KEY_KP_8; break;
1250 case K_K9: key = VTERM_KEY_KP_9; break;
1251 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1252 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1253 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1254 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1255 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1256 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1257 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1258 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1259 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1260 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1261 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1262 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1263 case K_LEFT: key = VTERM_KEY_LEFT; break;
1264 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1265 key = VTERM_KEY_LEFT; break;
1266 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1267 key = VTERM_KEY_LEFT; break;
1268 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1269 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1270 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1271 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1272 key = VTERM_KEY_RIGHT; break;
1273 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1274 key = VTERM_KEY_RIGHT; break;
1275 case K_UP: key = VTERM_KEY_UP; break;
1276 case K_S_UP: mod = VTERM_MOD_SHIFT;
1277 key = VTERM_KEY_UP; break;
1278 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001279 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1280 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001281
Bram Moolenaara42ad572017-11-16 13:08:04 +01001282 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1283 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001284 case K_MOUSELEFT: /* TODO */ return 0;
1285 case K_MOUSERIGHT: /* TODO */ return 0;
1286
1287 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001288 case K_LEFTMOUSE_NM:
1289 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001290 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001291 case K_LEFTRELEASE_NM:
1292 case K_MOUSEMOVE:
1293 case K_MIDDLEMOUSE:
1294 case K_MIDDLEDRAG:
1295 case K_MIDDLERELEASE:
1296 case K_RIGHTMOUSE:
1297 case K_RIGHTDRAG:
1298 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1299 return 0;
1300 other = TRUE;
1301 break;
1302
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001303 case K_X1MOUSE: /* TODO */ return 0;
1304 case K_X1DRAG: /* TODO */ return 0;
1305 case K_X1RELEASE: /* TODO */ return 0;
1306 case K_X2MOUSE: /* TODO */ return 0;
1307 case K_X2DRAG: /* TODO */ return 0;
1308 case K_X2RELEASE: /* TODO */ return 0;
1309
1310 case K_IGNORE: return 0;
1311 case K_NOP: return 0;
1312 case K_UNDO: return 0;
1313 case K_HELP: return 0;
1314 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1315 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1316 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1317 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1318 case K_SELECT: return 0;
1319#ifdef FEAT_GUI
1320 case K_VER_SCROLLBAR: return 0;
1321 case K_HOR_SCROLLBAR: return 0;
1322#endif
1323#ifdef FEAT_GUI_TABLINE
1324 case K_TABLINE: return 0;
1325 case K_TABMENU: return 0;
1326#endif
1327#ifdef FEAT_NETBEANS_INTG
1328 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1329#endif
1330#ifdef FEAT_DND
1331 case K_DROP: return 0;
1332#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001333 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001334 case K_PS: vterm_keyboard_start_paste(vterm);
1335 other = TRUE;
1336 break;
1337 case K_PE: vterm_keyboard_end_paste(vterm);
1338 other = TRUE;
1339 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001340 }
1341
1342 /*
1343 * Convert special keys to vterm keys:
1344 * - Write keys to vterm: vterm_keyboard_key()
1345 * - Write output to channel.
1346 * TODO: use mod_mask
1347 */
1348 if (key != VTERM_KEY_NONE)
1349 /* Special key, let vterm convert it. */
1350 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001351 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001352 /* Normal character, let vterm convert it. */
1353 vterm_keyboard_unichar(vterm, c, mod);
1354
1355 /* Read back the converted escape sequence. */
1356 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1357}
1358
1359/*
1360 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001361 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001362 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001363 */
1364 static int
1365term_job_running_check(term_T *term, int check_job_status)
1366{
1367 /* Also consider the job finished when the channel is closed, to avoid a
1368 * race condition when updating the title. */
1369 if (term != NULL
1370 && term->tl_job != NULL
1371 && channel_is_open(term->tl_job->jv_channel))
1372 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001373 job_T *job = term->tl_job;
1374
1375 // Careful: Checking the job status may invoked callbacks, which close
1376 // the buffer and terminate "term". However, "job" will not be freed
1377 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001378 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001379 job_status(job);
1380 return (job->jv_status == JOB_STARTED
1381 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001382 }
1383 return FALSE;
1384}
1385
1386/*
1387 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001388 */
1389 int
1390term_job_running(term_T *term)
1391{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001392 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001393}
1394
1395/*
1396 * Return TRUE if "term" has an active channel and used ":term NONE".
1397 */
1398 int
1399term_none_open(term_T *term)
1400{
1401 /* Also consider the job finished when the channel is closed, to avoid a
1402 * race condition when updating the title. */
1403 return term != NULL
1404 && term->tl_job != NULL
1405 && channel_is_open(term->tl_job->jv_channel)
1406 && term->tl_job->jv_channel->ch_keep_open;
1407}
1408
1409/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001410 * Used when exiting: kill the job in "buf" if so desired.
1411 * Return OK when the job finished.
1412 * Return FAIL when the job is still running.
1413 */
1414 int
1415term_try_stop_job(buf_T *buf)
1416{
1417 int count;
1418 char *how = (char *)buf->b_term->tl_kill;
1419
1420#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1421 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1422 {
1423 char_u buff[DIALOG_MSG_SIZE];
1424 int ret;
1425
1426 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1427 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1428 if (ret == VIM_YES)
1429 how = "kill";
1430 else if (ret == VIM_CANCEL)
1431 return FAIL;
1432 }
1433#endif
1434 if (how == NULL || *how == NUL)
1435 return FAIL;
1436
1437 job_stop(buf->b_term->tl_job, NULL, how);
1438
Bram Moolenaar9172d232019-01-29 23:06:54 +01001439 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001440 for (count = 0; count < 100; ++count)
1441 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001442 job_T *job;
1443
1444 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001445 if (!buf_valid(buf)
1446 || buf->b_term == NULL
1447 || buf->b_term->tl_job == NULL)
1448 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001449 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001450
Bram Moolenaar9172d232019-01-29 23:06:54 +01001451 // Call job_status() to update jv_status. It may cause the job to be
1452 // cleaned up but it won't be freed.
1453 job_status(job);
1454 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001455 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001456
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001457 ui_delay(10L, FALSE);
1458 mch_check_messages();
1459 parse_queued_messages();
1460 }
1461 return FAIL;
1462}
1463
1464/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001465 * Add the last line of the scrollback buffer to the buffer in the window.
1466 */
1467 static void
1468add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1469{
1470 buf_T *buf = term->tl_buffer;
1471 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1472 linenr_T lnum = buf->b_ml.ml_line_count;
1473
Bram Moolenaar4f974752019-02-17 17:44:42 +01001474#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001475 if (!enc_utf8 && enc_codepage > 0)
1476 {
1477 WCHAR *ret = NULL;
1478 int length = 0;
1479
1480 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1481 &ret, &length);
1482 if (ret != NULL)
1483 {
1484 WideCharToMultiByte_alloc(enc_codepage, 0,
1485 ret, length, (char **)&text, &len, 0, 0);
1486 vim_free(ret);
1487 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1488 vim_free(text);
1489 }
1490 }
1491 else
1492#endif
1493 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1494 if (empty)
1495 {
1496 /* Delete the empty line that was in the empty buffer. */
1497 curbuf = buf;
1498 ml_delete(1, FALSE);
1499 curbuf = curwin->w_buffer;
1500 }
1501}
1502
1503 static void
1504cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1505{
1506 attr->width = cell->width;
1507 attr->attrs = cell->attrs;
1508 attr->fg = cell->fg;
1509 attr->bg = cell->bg;
1510}
1511
1512 static int
1513equal_celattr(cellattr_T *a, cellattr_T *b)
1514{
1515 /* Comparing the colors should be sufficient. */
1516 return a->fg.red == b->fg.red
1517 && a->fg.green == b->fg.green
1518 && a->fg.blue == b->fg.blue
1519 && a->bg.red == b->bg.red
1520 && a->bg.green == b->bg.green
1521 && a->bg.blue == b->bg.blue;
1522}
1523
Bram Moolenaard96ff162018-02-18 22:13:29 +01001524/*
1525 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1526 * line at this position. Otherwise at the end.
1527 */
1528 static int
1529add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1530{
1531 if (ga_grow(&term->tl_scrollback, 1) == OK)
1532 {
1533 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1534 + term->tl_scrollback.ga_len;
1535
1536 if (lnum > 0)
1537 {
1538 int i;
1539
1540 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1541 {
1542 *line = *(line - 1);
1543 --line;
1544 }
1545 }
1546 line->sb_cols = 0;
1547 line->sb_cells = NULL;
1548 line->sb_fill_attr = *fill_attr;
1549 ++term->tl_scrollback.ga_len;
1550 return OK;
1551 }
1552 return FALSE;
1553}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001554
1555/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001556 * Remove the terminal contents from the scrollback and the buffer.
1557 * Used before adding a new scrollback line or updating the buffer for lines
1558 * displayed in the terminal.
1559 */
1560 static void
1561cleanup_scrollback(term_T *term)
1562{
1563 sb_line_T *line;
1564 garray_T *gap;
1565
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001566 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001567 gap = &term->tl_scrollback;
1568 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1569 && gap->ga_len > 0)
1570 {
1571 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1572 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1573 vim_free(line->sb_cells);
1574 --gap->ga_len;
1575 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001576 curbuf = curwin->w_buffer;
1577 if (curbuf == term->tl_buffer)
1578 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001579}
1580
1581/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001582 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001583 */
1584 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001585update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001586{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001587 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001588 int len;
1589 int lines_skipped = 0;
1590 VTermPos pos;
1591 VTermScreenCell cell;
1592 cellattr_T fill_attr, new_fill_attr;
1593 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001594
1595 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1596 "Adding terminal window snapshot to buffer");
1597
1598 /* First remove the lines that were appended before, they might be
1599 * outdated. */
1600 cleanup_scrollback(term);
1601
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001602 screen = vterm_obtain_screen(term->tl_vterm);
1603 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001604 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1605 {
1606 len = 0;
1607 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1608 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1609 && cell.chars[0] != NUL)
1610 {
1611 len = pos.col + 1;
1612 new_fill_attr = term->tl_default_color;
1613 }
1614 else
1615 /* Assume the last attr is the filler attr. */
1616 cell2cellattr(&cell, &new_fill_attr);
1617
1618 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1619 ++lines_skipped;
1620 else
1621 {
1622 while (lines_skipped > 0)
1623 {
1624 /* Line was skipped, add an empty line. */
1625 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001626 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001628 }
1629
1630 if (len == 0)
1631 p = NULL;
1632 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001633 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001634 if ((p != NULL || len == 0)
1635 && ga_grow(&term->tl_scrollback, 1) == OK)
1636 {
1637 garray_T ga;
1638 int width;
1639 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1640 + term->tl_scrollback.ga_len;
1641
1642 ga_init2(&ga, 1, 100);
1643 for (pos.col = 0; pos.col < len; pos.col += width)
1644 {
1645 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1646 {
1647 width = 1;
1648 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1649 if (ga_grow(&ga, 1) == OK)
1650 ga.ga_len += utf_char2bytes(' ',
1651 (char_u *)ga.ga_data + ga.ga_len);
1652 }
1653 else
1654 {
1655 width = cell.width;
1656
1657 cell2cellattr(&cell, &p[pos.col]);
1658
Bram Moolenaara79fd562018-12-20 20:47:32 +01001659 // Each character can be up to 6 bytes.
1660 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001661 {
1662 int i;
1663 int c;
1664
1665 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1666 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1667 (char_u *)ga.ga_data + ga.ga_len);
1668 }
1669 }
1670 }
1671 line->sb_cols = len;
1672 line->sb_cells = p;
1673 line->sb_fill_attr = new_fill_attr;
1674 fill_attr = new_fill_attr;
1675 ++term->tl_scrollback.ga_len;
1676
1677 if (ga_grow(&ga, 1) == FAIL)
1678 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1679 else
1680 {
1681 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1682 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1683 }
1684 ga_clear(&ga);
1685 }
1686 else
1687 vim_free(p);
1688 }
1689 }
1690
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001691 // Add trailing empty lines.
1692 for (pos.row = term->tl_scrollback.ga_len;
1693 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1694 ++pos.row)
1695 {
1696 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1697 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1698 }
1699
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001700 term->tl_dirty_snapshot = FALSE;
1701#ifdef FEAT_TIMERS
1702 term->tl_timer_set = FALSE;
1703#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001704}
1705
1706/*
1707 * If needed, add the current lines of the terminal to scrollback and to the
1708 * buffer. Called after the job has ended and when switching to
1709 * Terminal-Normal mode.
1710 * When "redraw" is TRUE redraw the windows that show the terminal.
1711 */
1712 static void
1713may_move_terminal_to_buffer(term_T *term, int redraw)
1714{
1715 win_T *wp;
1716
1717 if (term->tl_vterm == NULL)
1718 return;
1719
1720 /* Update the snapshot only if something changes or the buffer does not
1721 * have all the lines. */
1722 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1723 <= term->tl_scrollback_scrolled)
1724 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001725
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001726 /* Obtain the current background color. */
1727 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1728 &term->tl_default_color.fg, &term->tl_default_color.bg);
1729
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001730 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001731 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001732 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001733 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001735 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1736 wp->w_cursor.col = 0;
1737 wp->w_valid = 0;
1738 if (wp->w_cursor.lnum >= wp->w_height)
1739 {
1740 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001741
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001742 if (wp->w_topline < min_topline)
1743 wp->w_topline = min_topline;
1744 }
1745 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001746 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001747 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001748}
1749
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001750#if defined(FEAT_TIMERS) || defined(PROTO)
1751/*
1752 * Check if any terminal timer expired. If so, copy text from the terminal to
1753 * the buffer.
1754 * Return the time until the next timer will expire.
1755 */
1756 int
1757term_check_timers(int next_due_arg, proftime_T *now)
1758{
1759 term_T *term;
1760 int next_due = next_due_arg;
1761
1762 for (term = first_term; term != NULL; term = term->tl_next)
1763 {
1764 if (term->tl_timer_set && !term->tl_normal_mode)
1765 {
1766 long this_due = proftime_time_left(&term->tl_timer_due, now);
1767
1768 if (this_due <= 1)
1769 {
1770 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001771 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001772 }
1773 else if (next_due == -1 || next_due > this_due)
1774 next_due = this_due;
1775 }
1776 }
1777
1778 return next_due;
1779}
1780#endif
1781
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001782/*
1783 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1784 * otherwise end it.
1785 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001786 static void
1787set_terminal_mode(term_T *term, int normal_mode)
1788{
1789 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001790 if (!normal_mode)
1791 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001792 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001793 if (term->tl_buffer == curbuf)
1794 maketitle();
1795}
1796
1797/*
1798 * Called after the job if finished and Terminal mode is not active:
1799 * Move the vterm contents into the scrollback buffer and free the vterm.
1800 */
1801 static void
1802cleanup_vterm(term_T *term)
1803{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001804 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001805 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001806 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001807 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001808}
1809
1810/*
1811 * Switch from Terminal-Job mode to Terminal-Normal mode.
1812 * Suspends updating the terminal window.
1813 */
1814 static void
1815term_enter_normal_mode(void)
1816{
1817 term_T *term = curbuf->b_term;
1818
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001819 set_terminal_mode(term, TRUE);
1820
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001821 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001822 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001823
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824 /* Move the window cursor to the position of the cursor in the
1825 * terminal. */
1826 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1827 + term->tl_cursor_pos.row + 1;
1828 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001829 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1830 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001831
1832 /* Display the same lines as in the terminal. */
1833 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1834}
1835
1836/*
1837 * Returns TRUE if the current window contains a terminal and we are in
1838 * Terminal-Normal mode.
1839 */
1840 int
1841term_in_normal_mode(void)
1842{
1843 term_T *term = curbuf->b_term;
1844
1845 return term != NULL && term->tl_normal_mode;
1846}
1847
1848/*
1849 * Switch from Terminal-Normal mode to Terminal-Job mode.
1850 * Restores updating the terminal window.
1851 */
1852 void
1853term_enter_job_mode()
1854{
1855 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001856
1857 set_terminal_mode(term, FALSE);
1858
1859 if (term->tl_channel_closed)
1860 cleanup_vterm(term);
1861 redraw_buf_and_status_later(curbuf, NOT_VALID);
1862}
1863
1864/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001865 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001866 * Note: while waiting a terminal may be closed and freed if the channel is
1867 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001868 */
1869 static int
1870term_vgetc()
1871{
1872 int c;
1873 int save_State = State;
1874
1875 State = TERMINAL;
1876 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001877#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001878 ctrl_break_was_pressed = FALSE;
1879#endif
1880 c = vgetc();
1881 got_int = FALSE;
1882 State = save_State;
1883 return c;
1884}
1885
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001886static int mouse_was_outside = FALSE;
1887
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001888/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001889 * Send keys to terminal.
1890 * Return FAIL when the key needs to be handled in Normal mode.
1891 * Return OK when the key was dropped or sent to the terminal.
1892 */
1893 int
1894send_keys_to_term(term_T *term, int c, int typed)
1895{
1896 char msg[KEY_BUF_LEN];
1897 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001898 int dragging_outside = FALSE;
1899
1900 /* Catch keys that need to be handled as in Normal mode. */
1901 switch (c)
1902 {
1903 case NUL:
1904 case K_ZERO:
1905 if (typed)
1906 stuffcharReadbuff(c);
1907 return FAIL;
1908
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001909 case K_TABLINE:
1910 stuffcharReadbuff(c);
1911 return FAIL;
1912
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001914 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001915 return FAIL;
1916
1917 case K_LEFTDRAG:
1918 case K_MIDDLEDRAG:
1919 case K_RIGHTDRAG:
1920 case K_X1DRAG:
1921 case K_X2DRAG:
1922 dragging_outside = mouse_was_outside;
1923 /* FALLTHROUGH */
1924 case K_LEFTMOUSE:
1925 case K_LEFTMOUSE_NM:
1926 case K_LEFTRELEASE:
1927 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001928 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001929 case K_MIDDLEMOUSE:
1930 case K_MIDDLERELEASE:
1931 case K_RIGHTMOUSE:
1932 case K_RIGHTRELEASE:
1933 case K_X1MOUSE:
1934 case K_X1RELEASE:
1935 case K_X2MOUSE:
1936 case K_X2RELEASE:
1937
1938 case K_MOUSEUP:
1939 case K_MOUSEDOWN:
1940 case K_MOUSELEFT:
1941 case K_MOUSERIGHT:
1942 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001943 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001944 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001945 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001946 || dragging_outside)
1947 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001948 /* click or scroll outside the current window or on status line
1949 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001950 if (typed)
1951 {
1952 stuffcharReadbuff(c);
1953 mouse_was_outside = TRUE;
1954 }
1955 return FAIL;
1956 }
1957 }
1958 if (typed)
1959 mouse_was_outside = FALSE;
1960
1961 /* Convert the typed key to a sequence of bytes for the job. */
1962 len = term_convert_key(term, c, msg);
1963 if (len > 0)
1964 /* TODO: if FAIL is returned, stop? */
1965 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1966 (char_u *)msg, (int)len, NULL);
1967
1968 return OK;
1969}
1970
1971 static void
1972position_cursor(win_T *wp, VTermPos *pos)
1973{
1974 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1975 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1976 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1977}
1978
1979/*
1980 * Handle CTRL-W "": send register contents to the job.
1981 */
1982 static void
1983term_paste_register(int prev_c UNUSED)
1984{
1985 int c;
1986 list_T *l;
1987 listitem_T *item;
1988 long reglen = 0;
1989 int type;
1990
1991#ifdef FEAT_CMDL_INFO
1992 if (add_to_showcmd(prev_c))
1993 if (add_to_showcmd('"'))
1994 out_flush();
1995#endif
1996 c = term_vgetc();
1997#ifdef FEAT_CMDL_INFO
1998 clear_showcmd();
1999#endif
2000 if (!term_use_loop())
2001 /* job finished while waiting for a character */
2002 return;
2003
2004 /* CTRL-W "= prompt for expression to evaluate. */
2005 if (c == '=' && get_expr_register() != '=')
2006 return;
2007 if (!term_use_loop())
2008 /* job finished while waiting for a character */
2009 return;
2010
2011 l = (list_T *)get_reg_contents(c, GREG_LIST);
2012 if (l != NULL)
2013 {
2014 type = get_reg_type(c, &reglen);
2015 for (item = l->lv_first; item != NULL; item = item->li_next)
2016 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002017 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002018#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002019 char_u *tmp = s;
2020
2021 if (!enc_utf8 && enc_codepage > 0)
2022 {
2023 WCHAR *ret = NULL;
2024 int length = 0;
2025
2026 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2027 (int)STRLEN(s), &ret, &length);
2028 if (ret != NULL)
2029 {
2030 WideCharToMultiByte_alloc(CP_UTF8, 0,
2031 ret, length, (char **)&s, &length, 0, 0);
2032 vim_free(ret);
2033 }
2034 }
2035#endif
2036 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2037 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002038#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002039 if (tmp != s)
2040 vim_free(s);
2041#endif
2042
2043 if (item->li_next != NULL || type == MLINE)
2044 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2045 (char_u *)"\r", 1, NULL);
2046 }
2047 list_free(l);
2048 }
2049}
2050
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002051/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002052 * Return TRUE when waiting for a character in the terminal, the cursor of the
2053 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002054 */
2055 int
2056terminal_is_active()
2057{
2058 return in_terminal_loop != NULL;
2059}
2060
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002061#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002062 cursorentry_T *
2063term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2064{
2065 term_T *term = in_terminal_loop;
2066 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002067 int id;
2068 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002069
2070 vim_memset(&entry, 0, sizeof(entry));
2071 entry.shape = entry.mshape =
2072 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2073 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2074 SHAPE_BLOCK;
2075 entry.percentage = 20;
2076 if (term->tl_cursor_blink)
2077 {
2078 entry.blinkwait = 700;
2079 entry.blinkon = 400;
2080 entry.blinkoff = 250;
2081 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002082
2083 /* The "Terminal" highlight group overrules the defaults. */
2084 id = syn_name2id((char_u *)"Terminal");
2085 if (id != 0)
2086 {
2087 syn_id2colors(id, &term_fg, &term_bg);
2088 *fg = term_bg;
2089 }
2090 else
2091 *fg = gui.back_pixel;
2092
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002093 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002094 {
2095 if (id != 0)
2096 *bg = term_fg;
2097 else
2098 *bg = gui.norm_pixel;
2099 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002100 else
2101 *bg = color_name2handle(term->tl_cursor_color);
2102 entry.name = "n";
2103 entry.used_for = SHAPE_CURSOR;
2104
2105 return &entry;
2106}
2107#endif
2108
Bram Moolenaard317b382018-02-08 22:33:31 +01002109 static void
2110may_output_cursor_props(void)
2111{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002112 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002113 || last_set_cursor_shape != desired_cursor_shape
2114 || last_set_cursor_blink != desired_cursor_blink)
2115 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002116 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002117 last_set_cursor_shape = desired_cursor_shape;
2118 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002119 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002120 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2121 /* this will restore the initial cursor style, if possible */
2122 ui_cursor_shape_forced(TRUE);
2123 else
2124 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2125 }
2126}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002127
Bram Moolenaard317b382018-02-08 22:33:31 +01002128/*
2129 * Set the cursor color and shape, if not last set to these.
2130 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002131 static void
2132may_set_cursor_props(term_T *term)
2133{
2134#ifdef FEAT_GUI
2135 /* For the GUI the cursor properties are obtained with
2136 * term_get_cursor_shape(). */
2137 if (gui.in_use)
2138 return;
2139#endif
2140 if (in_terminal_loop == term)
2141 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002142 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002143 desired_cursor_shape = term->tl_cursor_shape;
2144 desired_cursor_blink = term->tl_cursor_blink;
2145 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002146 }
2147}
2148
Bram Moolenaard317b382018-02-08 22:33:31 +01002149/*
2150 * Reset the desired cursor properties and restore them when needed.
2151 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002152 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002153prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002154{
2155#ifdef FEAT_GUI
2156 if (gui.in_use)
2157 return;
2158#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002159 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002160 desired_cursor_shape = -1;
2161 desired_cursor_blink = -1;
2162 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002163}
2164
2165/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002166 * Returns TRUE if the current window contains a terminal and we are sending
2167 * keys to the job.
2168 * If "check_job_status" is TRUE update the job status.
2169 */
2170 static int
2171term_use_loop_check(int check_job_status)
2172{
2173 term_T *term = curbuf->b_term;
2174
2175 return term != NULL
2176 && !term->tl_normal_mode
2177 && term->tl_vterm != NULL
2178 && term_job_running_check(term, check_job_status);
2179}
2180
2181/*
2182 * Returns TRUE if the current window contains a terminal and we are sending
2183 * keys to the job.
2184 */
2185 int
2186term_use_loop(void)
2187{
2188 return term_use_loop_check(FALSE);
2189}
2190
2191/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002192 * Called when entering a window with the mouse. If this is a terminal window
2193 * we may want to change state.
2194 */
2195 void
2196term_win_entered()
2197{
2198 term_T *term = curbuf->b_term;
2199
2200 if (term != NULL)
2201 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002202 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002203 {
2204 reset_VIsual_and_resel();
2205 if (State & INSERT)
2206 stop_insert_mode = TRUE;
2207 }
2208 mouse_was_outside = FALSE;
2209 enter_mouse_col = mouse_col;
2210 enter_mouse_row = mouse_row;
2211 }
2212}
2213
2214/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002215 * Wait for input and send it to the job.
2216 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2217 * when there is no more typahead.
2218 * Return when the start of a CTRL-W command is typed or anything else that
2219 * should be handled as a Normal mode command.
2220 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2221 * the terminal was closed.
2222 */
2223 int
2224terminal_loop(int blocking)
2225{
2226 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002227 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002228 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002229#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002230 int tty_fd = curbuf->b_term->tl_job->jv_channel
2231 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002232#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002233 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002234
2235 /* Remember the terminal we are sending keys to. However, the terminal
2236 * might be closed while waiting for a character, e.g. typing "exit" in a
2237 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2238 * stored reference. */
2239 in_terminal_loop = curbuf->b_term;
2240
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002241 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002242 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002243 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002244 if (termwinkey == Ctrl_W)
2245 termwinkey = 0;
2246 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002247 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2248 may_set_cursor_props(curbuf->b_term);
2249
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002250 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002251 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002252#ifdef FEAT_GUI
2253 if (!curbuf->b_term->tl_system)
2254#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002255 // TODO: skip screen update when handling a sequence of keys.
2256 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002257 while (must_redraw != 0)
2258 if (update_screen(0) == FAIL)
2259 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002260 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002261 /* job finished while redrawing */
2262 break;
2263
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002264 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002265 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002266
2267 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002268 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002269 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002270 /* Job finished while waiting for a character. Push back the
2271 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002272 if (c != K_IGNORE)
2273 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002274 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002275 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002276 if (c == K_IGNORE)
2277 continue;
2278
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002279#ifdef UNIX
2280 /*
2281 * The shell or another program may change the tty settings. Getting
2282 * them for every typed character is a bit of overhead, but it's needed
2283 * for the first character typed, e.g. when Vim starts in a shell.
2284 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002285 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002286 {
2287 ttyinfo_T info;
2288
2289 /* Get the current backspace character of the pty. */
2290 if (get_tty_info(tty_fd, &info) == OK)
2291 term_backspace_char = info.backspace;
2292 }
2293#endif
2294
Bram Moolenaar4f974752019-02-17 17:44:42 +01002295#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002296 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2297 * Use CTRL-BREAK to kill the job. */
2298 if (ctrl_break_was_pressed)
2299 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2300#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002301 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002302 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002303 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002304#ifdef FEAT_GUI
2305 && !curbuf->b_term->tl_system
2306#endif
2307 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002308 {
2309 int prev_c = c;
2310
2311#ifdef FEAT_CMDL_INFO
2312 if (add_to_showcmd(c))
2313 out_flush();
2314#endif
2315 c = term_vgetc();
2316#ifdef FEAT_CMDL_INFO
2317 clear_showcmd();
2318#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002319 if (!term_use_loop_check(TRUE)
2320 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002321 /* job finished while waiting for a character */
2322 break;
2323
2324 if (prev_c == Ctrl_BSL)
2325 {
2326 if (c == Ctrl_N)
2327 {
2328 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2329 term_enter_normal_mode();
2330 ret = FAIL;
2331 goto theend;
2332 }
2333 /* Send both keys to the terminal. */
2334 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2335 }
2336 else if (c == Ctrl_C)
2337 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002338 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002339 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2340 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002341 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002342 {
2343 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002344 /* "'termwinkey' .": send 'termwinkey' to the job */
2345 c = termwinkey == 0 ? Ctrl_W : termwinkey;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002346 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002347 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002348 {
2349 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2350 c = Ctrl_BSL;
2351 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002352 else if (c == 'N')
2353 {
2354 /* CTRL-W N : go to Terminal-Normal mode. */
2355 term_enter_normal_mode();
2356 ret = FAIL;
2357 goto theend;
2358 }
2359 else if (c == '"')
2360 {
2361 term_paste_register(prev_c);
2362 continue;
2363 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002364 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002365 {
2366 stuffcharReadbuff(Ctrl_W);
2367 stuffcharReadbuff(c);
2368 ret = OK;
2369 goto theend;
2370 }
2371 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002372# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002373 if (!enc_utf8 && has_mbyte && c >= 0x80)
2374 {
2375 WCHAR wc;
2376 char_u mb[3];
2377
2378 mb[0] = (unsigned)c >> 8;
2379 mb[1] = c;
2380 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2381 c = wc;
2382 }
2383# endif
2384 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2385 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002386 if (c == K_MOUSEMOVE)
2387 /* We are sure to come back here, don't reset the cursor color
2388 * and shape to avoid flickering. */
2389 restore_cursor = FALSE;
2390
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002391 ret = OK;
2392 goto theend;
2393 }
2394 }
2395 ret = FAIL;
2396
2397theend:
2398 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002399 if (restore_cursor)
2400 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002401
2402 /* Move a snapshot of the screen contents to the buffer, so that completion
2403 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002404 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2405 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002406
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002407 return ret;
2408}
2409
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002410 static void
2411may_toggle_cursor(term_T *term)
2412{
2413 if (in_terminal_loop == term)
2414 {
2415 if (term->tl_cursor_visible)
2416 cursor_on();
2417 else
2418 cursor_off();
2419 }
2420}
2421
2422/*
2423 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002424 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002425 */
2426 static int
2427color2index(VTermColor *color, int fg, int *boldp)
2428{
2429 int red = color->red;
2430 int blue = color->blue;
2431 int green = color->green;
2432
Bram Moolenaar46359e12017-11-29 22:33:38 +01002433 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002434 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002435 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002436 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002437 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002438 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002439 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002440 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2441 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2442 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002443 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002444 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2445 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2446 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2447 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2448 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2449 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2450 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2451 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2452 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2453 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2454 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002455 }
2456 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002457
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002458 if (t_colors >= 256)
2459 {
2460 if (red == blue && red == green)
2461 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002462 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002463 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002464 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2465 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2466 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002467 int i;
2468
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002469 if (red < 5)
2470 return 17; /* 00/00/00 */
2471 if (red > 245) /* ff/ff/ff */
2472 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002473 for (i = 0; i < 23; ++i)
2474 if (red < cutoff[i])
2475 return i + 233;
2476 return 256;
2477 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002478 {
2479 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2480 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002481
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002482 /* 216-color cube */
2483 for (ri = 0; ri < 5; ++ri)
2484 if (red < cutoff[ri])
2485 break;
2486 for (gi = 0; gi < 5; ++gi)
2487 if (green < cutoff[gi])
2488 break;
2489 for (bi = 0; bi < 5; ++bi)
2490 if (blue < cutoff[bi])
2491 break;
2492 return 17 + ri * 36 + gi * 6 + bi;
2493 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002494 }
2495 return 0;
2496}
2497
2498/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002499 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002500 */
2501 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002502vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503{
2504 int attr = 0;
2505
2506 if (cellattrs.bold)
2507 attr |= HL_BOLD;
2508 if (cellattrs.underline)
2509 attr |= HL_UNDERLINE;
2510 if (cellattrs.italic)
2511 attr |= HL_ITALIC;
2512 if (cellattrs.strike)
2513 attr |= HL_STRIKETHROUGH;
2514 if (cellattrs.reverse)
2515 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002516 return attr;
2517}
2518
2519/*
2520 * Store Vterm attributes in "cell" from highlight flags.
2521 */
2522 static void
2523hl2vtermAttr(int attr, cellattr_T *cell)
2524{
2525 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2526 if (attr & HL_BOLD)
2527 cell->attrs.bold = 1;
2528 if (attr & HL_UNDERLINE)
2529 cell->attrs.underline = 1;
2530 if (attr & HL_ITALIC)
2531 cell->attrs.italic = 1;
2532 if (attr & HL_STRIKETHROUGH)
2533 cell->attrs.strike = 1;
2534 if (attr & HL_INVERSE)
2535 cell->attrs.reverse = 1;
2536}
2537
2538/*
2539 * Convert the attributes of a vterm cell into an attribute index.
2540 */
2541 static int
2542cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2543{
2544 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002545
2546#ifdef FEAT_GUI
2547 if (gui.in_use)
2548 {
2549 guicolor_T fg, bg;
2550
2551 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2552 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2553 return get_gui_attr_idx(attr, fg, bg);
2554 }
2555 else
2556#endif
2557#ifdef FEAT_TERMGUICOLORS
2558 if (p_tgc)
2559 {
2560 guicolor_T fg, bg;
2561
2562 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2563 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2564
2565 return get_tgc_attr_idx(attr, fg, bg);
2566 }
2567 else
2568#endif
2569 {
2570 int bold = MAYBE;
2571 int fg = color2index(&cellfg, TRUE, &bold);
2572 int bg = color2index(&cellbg, FALSE, &bold);
2573
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002574 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002575 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002576 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002577 if (fg == 0 && term_default_cterm_fg >= 0)
2578 fg = term_default_cterm_fg + 1;
2579 if (bg == 0 && term_default_cterm_bg >= 0)
2580 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002581 }
2582
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002583 /* with 8 colors set the bold attribute to get a bright foreground */
2584 if (bold == TRUE)
2585 attr |= HL_BOLD;
2586 return get_cterm_attr_idx(attr, fg, bg);
2587 }
2588 return 0;
2589}
2590
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002591 static void
2592set_dirty_snapshot(term_T *term)
2593{
2594 term->tl_dirty_snapshot = TRUE;
2595#ifdef FEAT_TIMERS
2596 if (!term->tl_normal_mode)
2597 {
2598 /* Update the snapshot after 100 msec of not getting updates. */
2599 profile_setlimit(100L, &term->tl_timer_due);
2600 term->tl_timer_set = TRUE;
2601 }
2602#endif
2603}
2604
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002605 static int
2606handle_damage(VTermRect rect, void *user)
2607{
2608 term_T *term = (term_T *)user;
2609
2610 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2611 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002612 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002613 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002614 return 1;
2615}
2616
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002617 static void
2618term_scroll_up(term_T *term, int start_row, int count)
2619{
2620 win_T *wp;
2621 VTermColor fg, bg;
2622 VTermScreenCellAttrs attr;
2623 int clear_attr;
2624
2625 /* Set the color to clear lines with. */
2626 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2627 &fg, &bg);
2628 vim_memset(&attr, 0, sizeof(attr));
2629 clear_attr = cell2attr(attr, fg, bg);
2630
2631 FOR_ALL_WINDOWS(wp)
2632 {
2633 if (wp->w_buffer == term->tl_buffer)
2634 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2635 }
2636}
2637
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002638 static int
2639handle_moverect(VTermRect dest, VTermRect src, void *user)
2640{
2641 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002642 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002643
2644 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002645 * redrawing the text. But avoid doing this multiple times, postpone until
2646 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002647 if (dest.start_col == src.start_col
2648 && dest.end_col == src.end_col
2649 && dest.start_row < src.start_row)
2650 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002651 if (dest.start_row == 0)
2652 term->tl_postponed_scroll += count;
2653 else
2654 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002655 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002656
2657 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2658 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002659 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002660
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002661 /* Note sure if the scrolling will work correctly, let's do a complete
2662 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002663 redraw_buf_later(term->tl_buffer, NOT_VALID);
2664 return 1;
2665}
2666
2667 static int
2668handle_movecursor(
2669 VTermPos pos,
2670 VTermPos oldpos UNUSED,
2671 int visible,
2672 void *user)
2673{
2674 term_T *term = (term_T *)user;
2675 win_T *wp;
2676
2677 term->tl_cursor_pos = pos;
2678 term->tl_cursor_visible = visible;
2679
2680 FOR_ALL_WINDOWS(wp)
2681 {
2682 if (wp->w_buffer == term->tl_buffer)
2683 position_cursor(wp, &pos);
2684 }
2685 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2686 {
2687 may_toggle_cursor(term);
2688 update_cursor(term, term->tl_cursor_visible);
2689 }
2690
2691 return 1;
2692}
2693
2694 static int
2695handle_settermprop(
2696 VTermProp prop,
2697 VTermValue *value,
2698 void *user)
2699{
2700 term_T *term = (term_T *)user;
2701
2702 switch (prop)
2703 {
2704 case VTERM_PROP_TITLE:
2705 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002706 // a blank title isn't useful, make it empty, so that "running" is
2707 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002708 if (*skipwhite((char_u *)value->string) == NUL)
2709 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002710 // Same as blank
2711 else if (term->tl_arg0_cmd != NULL
2712 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2713 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2714 term->tl_title = NULL;
2715 // Empty corrupted data of winpty
2716 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2717 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002718#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002719 else if (!enc_utf8 && enc_codepage > 0)
2720 {
2721 WCHAR *ret = NULL;
2722 int length = 0;
2723
2724 MultiByteToWideChar_alloc(CP_UTF8, 0,
2725 (char*)value->string, (int)STRLEN(value->string),
2726 &ret, &length);
2727 if (ret != NULL)
2728 {
2729 WideCharToMultiByte_alloc(enc_codepage, 0,
2730 ret, length, (char**)&term->tl_title,
2731 &length, 0, 0);
2732 vim_free(ret);
2733 }
2734 }
2735#endif
2736 else
2737 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002738 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002739 if (term == curbuf->b_term)
2740 maketitle();
2741 break;
2742
2743 case VTERM_PROP_CURSORVISIBLE:
2744 term->tl_cursor_visible = value->boolean;
2745 may_toggle_cursor(term);
2746 out_flush();
2747 break;
2748
2749 case VTERM_PROP_CURSORBLINK:
2750 term->tl_cursor_blink = value->boolean;
2751 may_set_cursor_props(term);
2752 break;
2753
2754 case VTERM_PROP_CURSORSHAPE:
2755 term->tl_cursor_shape = value->number;
2756 may_set_cursor_props(term);
2757 break;
2758
2759 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002760 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002761 may_set_cursor_props(term);
2762 break;
2763
2764 case VTERM_PROP_ALTSCREEN:
2765 /* TODO: do anything else? */
2766 term->tl_using_altscreen = value->boolean;
2767 break;
2768
2769 default:
2770 break;
2771 }
2772 /* Always return 1, otherwise vterm doesn't store the value internally. */
2773 return 1;
2774}
2775
2776/*
2777 * The job running in the terminal resized the terminal.
2778 */
2779 static int
2780handle_resize(int rows, int cols, void *user)
2781{
2782 term_T *term = (term_T *)user;
2783 win_T *wp;
2784
2785 term->tl_rows = rows;
2786 term->tl_cols = cols;
2787 if (term->tl_vterm_size_changed)
2788 /* Size was set by vterm_set_size(), don't set the window size. */
2789 term->tl_vterm_size_changed = FALSE;
2790 else
2791 {
2792 FOR_ALL_WINDOWS(wp)
2793 {
2794 if (wp->w_buffer == term->tl_buffer)
2795 {
2796 win_setheight_win(rows, wp);
2797 win_setwidth_win(cols, wp);
2798 }
2799 }
2800 redraw_buf_later(term->tl_buffer, NOT_VALID);
2801 }
2802 return 1;
2803}
2804
2805/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002806 * If the number of lines that are stored goes over 'termscrollback' then
2807 * delete the first 10%.
2808 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2809 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002810 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002811 static void
2812limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002813{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002814 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002815 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002816 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002817 int i;
2818
2819 curbuf = term->tl_buffer;
2820 for (i = 0; i < todo; ++i)
2821 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002822 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
2823 if (update_buffer)
2824 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002825 }
2826 curbuf = curwin->w_buffer;
2827
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002828 gap->ga_len -= todo;
2829 mch_memmove(gap->ga_data,
2830 (sb_line_T *)gap->ga_data + todo,
2831 sizeof(sb_line_T) * gap->ga_len);
2832 if (update_buffer)
2833 term->tl_scrollback_scrolled -= todo;
2834 }
2835}
2836
2837/*
2838 * Handle a line that is pushed off the top of the screen.
2839 */
2840 static int
2841handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2842{
2843 term_T *term = (term_T *)user;
2844 garray_T *gap;
2845 int update_buffer;
2846
2847 if (term->tl_normal_mode)
2848 {
2849 // In Terminal-Normal mode the user interacts with the buffer, thus we
2850 // must not change it. Postpone adding the scrollback lines.
2851 gap = &term->tl_scrollback_postponed;
2852 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002853 }
2854 else
2855 {
2856 // First remove the lines that were appended before, the pushed line
2857 // goes above it.
2858 cleanup_scrollback(term);
2859 gap = &term->tl_scrollback;
2860 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002861 }
2862
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002863 limit_scrollback(term, gap, update_buffer);
2864
2865 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002866 {
2867 cellattr_T *p = NULL;
2868 int len = 0;
2869 int i;
2870 int c;
2871 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002872 int text_len;
2873 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002874 sb_line_T *line;
2875 garray_T ga;
2876 cellattr_T fill_attr = term->tl_default_color;
2877
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002878 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002879 for (i = 0; i < cols; ++i)
2880 if (cells[i].chars[0] != 0)
2881 len = i + 1;
2882 else
2883 cell2cellattr(&cells[i], &fill_attr);
2884
2885 ga_init2(&ga, 1, 100);
2886 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002887 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888 if (p != NULL)
2889 {
2890 for (col = 0; col < len; col += cells[col].width)
2891 {
2892 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2893 {
2894 ga.ga_len = 0;
2895 break;
2896 }
2897 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2898 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2899 (char_u *)ga.ga_data + ga.ga_len);
2900 cell2cellattr(&cells[col], &p[col]);
2901 }
2902 }
2903 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002904 {
2905 if (update_buffer)
2906 text = (char_u *)"";
2907 else
2908 text = vim_strsave((char_u *)"");
2909 text_len = 0;
2910 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002911 else
2912 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002913 text = ga.ga_data;
2914 text_len = ga.ga_len;
2915 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002916 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002917 if (update_buffer)
2918 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002919
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002920 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002921 line->sb_cols = len;
2922 line->sb_cells = p;
2923 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002924 if (update_buffer)
2925 {
2926 line->sb_text = NULL;
2927 ++term->tl_scrollback_scrolled;
2928 ga_clear(&ga); // free the text
2929 }
2930 else
2931 {
2932 line->sb_text = text;
2933 ga_init(&ga); // text is kept in tl_scrollback_postponed
2934 }
2935 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002936 }
2937 return 0; /* ignored */
2938}
2939
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002940/*
2941 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
2942 * received and stored in tl_scrollback_postponed.
2943 */
2944 static void
2945handle_postponed_scrollback(term_T *term)
2946{
2947 int i;
2948
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01002949 if (term->tl_scrollback_postponed.ga_len == 0)
2950 return;
2951 ch_log(NULL, "Moving postponed scrollback to scrollback");
2952
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002953 // First remove the lines that were appended before, the pushed lines go
2954 // above it.
2955 cleanup_scrollback(term);
2956
2957 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
2958 {
2959 char_u *text;
2960 sb_line_T *pp_line;
2961 sb_line_T *line;
2962
2963 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
2964 break;
2965 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
2966
2967 text = pp_line->sb_text;
2968 if (text == NULL)
2969 text = (char_u *)"";
2970 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
2971 vim_free(pp_line->sb_text);
2972
2973 line = (sb_line_T *)term->tl_scrollback.ga_data
2974 + term->tl_scrollback.ga_len;
2975 line->sb_cols = pp_line->sb_cols;
2976 line->sb_cells = pp_line->sb_cells;
2977 line->sb_fill_attr = pp_line->sb_fill_attr;
2978 line->sb_text = NULL;
2979 ++term->tl_scrollback_scrolled;
2980 ++term->tl_scrollback.ga_len;
2981 }
2982
2983 ga_clear(&term->tl_scrollback_postponed);
2984 limit_scrollback(term, &term->tl_scrollback, TRUE);
2985}
2986
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002987static VTermScreenCallbacks screen_callbacks = {
2988 handle_damage, /* damage */
2989 handle_moverect, /* moverect */
2990 handle_movecursor, /* movecursor */
2991 handle_settermprop, /* settermprop */
2992 NULL, /* bell */
2993 handle_resize, /* resize */
2994 handle_pushline, /* sb_pushline */
2995 NULL /* sb_popline */
2996};
2997
2998/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002999 * Do the work after the channel of a terminal was closed.
3000 * Must be called only when updating_screen is FALSE.
3001 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3002 */
3003 static int
3004term_after_channel_closed(term_T *term)
3005{
3006 /* Unless in Terminal-Normal mode: clear the vterm. */
3007 if (!term->tl_normal_mode)
3008 {
3009 int fnum = term->tl_buffer->b_fnum;
3010
3011 cleanup_vterm(term);
3012
3013 if (term->tl_finish == TL_FINISH_CLOSE)
3014 {
3015 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003016 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003017
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003018 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003019 ch_log(NULL, "terminal job finished, closing window");
3020 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003021 // Avoid closing the window if we temporarily use it.
3022 if (do_set_w_closing)
3023 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003024 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003025 if (do_set_w_closing)
3026 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003027 aucmd_restbuf(&aco);
3028 return TRUE;
3029 }
3030 if (term->tl_finish == TL_FINISH_OPEN
3031 && term->tl_buffer->b_nwindows == 0)
3032 {
3033 char buf[50];
3034
3035 /* TODO: use term_opencmd */
3036 ch_log(NULL, "terminal job finished, opening window");
3037 vim_snprintf(buf, sizeof(buf),
3038 term->tl_opencmd == NULL
3039 ? "botright sbuf %d"
3040 : (char *)term->tl_opencmd, fnum);
3041 do_cmdline_cmd((char_u *)buf);
3042 }
3043 else
3044 ch_log(NULL, "terminal job finished");
3045 }
3046
3047 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3048 return FALSE;
3049}
3050
3051/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003052 * Called when a channel has been closed.
3053 * If this was a channel for a terminal window then finish it up.
3054 */
3055 void
3056term_channel_closed(channel_T *ch)
3057{
3058 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003059 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003060 int did_one = FALSE;
3061
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003062 for (term = first_term; term != NULL; term = next_term)
3063 {
3064 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003065 if (term->tl_job == ch->ch_job)
3066 {
3067 term->tl_channel_closed = TRUE;
3068 did_one = TRUE;
3069
Bram Moolenaard23a8232018-02-10 18:45:26 +01003070 VIM_CLEAR(term->tl_title);
3071 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003072#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003073 if (term->tl_out_fd != NULL)
3074 {
3075 fclose(term->tl_out_fd);
3076 term->tl_out_fd = NULL;
3077 }
3078#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003079
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003080 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003081 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003082 /* Cannot open or close windows now. Can happen when
3083 * 'lazyredraw' is set. */
3084 term->tl_channel_recently_closed = TRUE;
3085 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003086 }
3087
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003088 if (term_after_channel_closed(term))
3089 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003090 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003091 }
3092
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003093 if (did_one)
3094 {
3095 redraw_statuslines();
3096
3097 /* Need to break out of vgetc(). */
3098 ins_char_typebuf(K_IGNORE);
3099 typebuf_was_filled = TRUE;
3100
3101 term = curbuf->b_term;
3102 if (term != NULL)
3103 {
3104 if (term->tl_job == ch->ch_job)
3105 maketitle();
3106 update_cursor(term, term->tl_cursor_visible);
3107 }
3108 }
3109}
3110
3111/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003112 * To be called after resetting updating_screen: handle any terminal where the
3113 * channel was closed.
3114 */
3115 void
3116term_check_channel_closed_recently()
3117{
3118 term_T *term;
3119 term_T *next_term;
3120
3121 for (term = first_term; term != NULL; term = next_term)
3122 {
3123 next_term = term->tl_next;
3124 if (term->tl_channel_recently_closed)
3125 {
3126 term->tl_channel_recently_closed = FALSE;
3127 if (term_after_channel_closed(term))
3128 // start over, the list may have changed
3129 next_term = first_term;
3130 }
3131 }
3132}
3133
3134/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003135 * Fill one screen line from a line of the terminal.
3136 * Advances "pos" to past the last column.
3137 */
3138 static void
3139term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3140{
3141 int off = screen_get_current_line_off();
3142
3143 for (pos->col = 0; pos->col < max_col; )
3144 {
3145 VTermScreenCell cell;
3146 int c;
3147
3148 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3149 vim_memset(&cell, 0, sizeof(cell));
3150
3151 c = cell.chars[0];
3152 if (c == NUL)
3153 {
3154 ScreenLines[off] = ' ';
3155 if (enc_utf8)
3156 ScreenLinesUC[off] = NUL;
3157 }
3158 else
3159 {
3160 if (enc_utf8)
3161 {
3162 int i;
3163
3164 /* composing chars */
3165 for (i = 0; i < Screen_mco
3166 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3167 {
3168 ScreenLinesC[i][off] = cell.chars[i + 1];
3169 if (cell.chars[i + 1] == 0)
3170 break;
3171 }
3172 if (c >= 0x80 || (Screen_mco > 0
3173 && ScreenLinesC[0][off] != 0))
3174 {
3175 ScreenLines[off] = ' ';
3176 ScreenLinesUC[off] = c;
3177 }
3178 else
3179 {
3180 ScreenLines[off] = c;
3181 ScreenLinesUC[off] = NUL;
3182 }
3183 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003184#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003185 else if (has_mbyte && c >= 0x80)
3186 {
3187 char_u mb[MB_MAXBYTES+1];
3188 WCHAR wc = c;
3189
3190 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3191 (char*)mb, 2, 0, 0) > 1)
3192 {
3193 ScreenLines[off] = mb[0];
3194 ScreenLines[off + 1] = mb[1];
3195 cell.width = mb_ptr2cells(mb);
3196 }
3197 else
3198 ScreenLines[off] = c;
3199 }
3200#endif
3201 else
3202 ScreenLines[off] = c;
3203 }
3204 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3205
3206 ++pos->col;
3207 ++off;
3208 if (cell.width == 2)
3209 {
3210 if (enc_utf8)
3211 ScreenLinesUC[off] = NUL;
3212
3213 /* don't set the second byte to NUL for a DBCS encoding, it
3214 * has been set above */
3215 if (enc_utf8 || !has_mbyte)
3216 ScreenLines[off] = NUL;
3217
3218 ++pos->col;
3219 ++off;
3220 }
3221 }
3222}
3223
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003224#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003225 static void
3226update_system_term(term_T *term)
3227{
3228 VTermPos pos;
3229 VTermScreen *screen;
3230
3231 if (term->tl_vterm == NULL)
3232 return;
3233 screen = vterm_obtain_screen(term->tl_vterm);
3234
3235 /* Scroll up to make more room for terminal lines if needed. */
3236 while (term->tl_toprow > 0
3237 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3238 {
3239 int save_p_more = p_more;
3240
3241 p_more = FALSE;
3242 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003243 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003244 p_more = save_p_more;
3245 --term->tl_toprow;
3246 }
3247
3248 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3249 && pos.row < Rows; ++pos.row)
3250 {
3251 if (pos.row < term->tl_rows)
3252 {
3253 int max_col = MIN(Columns, term->tl_cols);
3254
3255 term_line2screenline(screen, &pos, max_col);
3256 }
3257 else
3258 pos.col = 0;
3259
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003260 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003261 }
3262
3263 term->tl_dirty_row_start = MAX_ROW;
3264 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003265}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003266#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003267
3268/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003269 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3270 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003271 * Terminal-Normal mode.
3272 */
3273 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003274term_do_update_window(win_T *wp)
3275{
3276 term_T *term = wp->w_buffer->b_term;
3277
3278 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3279}
3280
3281/*
3282 * Called to update a window that contains an active terminal.
3283 */
3284 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003285term_update_window(win_T *wp)
3286{
3287 term_T *term = wp->w_buffer->b_term;
3288 VTerm *vterm;
3289 VTermScreen *screen;
3290 VTermState *state;
3291 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003292 int rows, cols;
3293 int newrows, newcols;
3294 int minsize;
3295 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003296
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003297 vterm = term->tl_vterm;
3298 screen = vterm_obtain_screen(vterm);
3299 state = vterm_obtain_state(vterm);
3300
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003301 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3302 * SOME_VALID only redraw what was marked dirty. */
3303 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003304 {
3305 term->tl_dirty_row_start = 0;
3306 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003307
3308 if (term->tl_postponed_scroll > 0
3309 && term->tl_postponed_scroll < term->tl_rows / 3)
3310 /* Scrolling is usually faster than redrawing, when there are only
3311 * a few lines to scroll. */
3312 term_scroll_up(term, 0, term->tl_postponed_scroll);
3313 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003314 }
3315
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003316 /*
3317 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003318 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003319 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003320 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003321
Bram Moolenaar498c2562018-04-15 23:45:15 +02003322 newrows = 99999;
3323 newcols = 99999;
3324 FOR_ALL_WINDOWS(twp)
3325 {
3326 /* When more than one window shows the same terminal, use the
3327 * smallest size. */
3328 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003329 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003330 newrows = MIN(newrows, twp->w_height);
3331 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003332 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003333 }
3334 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3335 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3336
3337 if (term->tl_rows != newrows || term->tl_cols != newcols)
3338 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003339 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003340 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003341 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003342 newrows);
3343 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003344
3345 // Updating the terminal size will cause the snapshot to be cleared.
3346 // When not in terminal_loop() we need to restore it.
3347 if (term != in_terminal_loop)
3348 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003349 }
3350
3351 /* The cursor may have been moved when resizing. */
3352 vterm_state_get_cursorpos(state, &pos);
3353 position_cursor(wp, &pos);
3354
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003355 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3356 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003358 if (pos.row < term->tl_rows)
3359 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003360 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003361
Bram Moolenaar13568252018-03-16 20:46:58 +01003362 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003363 }
3364 else
3365 pos.col = 0;
3366
Bram Moolenaarf118d482018-03-13 13:14:00 +01003367 screen_line(wp->w_winrow + pos.row
3368#ifdef FEAT_MENU
3369 + winbar_height(wp)
3370#endif
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003371 , wp->w_wincol, pos.col, wp->w_width, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003372 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003373 term->tl_dirty_row_start = MAX_ROW;
3374 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003375}
3376
3377/*
3378 * Return TRUE if "wp" is a terminal window where the job has finished.
3379 */
3380 int
3381term_is_finished(buf_T *buf)
3382{
3383 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3384}
3385
3386/*
3387 * Return TRUE if "wp" is a terminal window where the job has finished or we
3388 * are in Terminal-Normal mode, thus we show the buffer contents.
3389 */
3390 int
3391term_show_buffer(buf_T *buf)
3392{
3393 term_T *term = buf->b_term;
3394
3395 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3396}
3397
3398/*
3399 * The current buffer is going to be changed. If there is terminal
3400 * highlighting remove it now.
3401 */
3402 void
3403term_change_in_curbuf(void)
3404{
3405 term_T *term = curbuf->b_term;
3406
3407 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3408 {
3409 free_scrollback(term);
3410 redraw_buf_later(term->tl_buffer, NOT_VALID);
3411
3412 /* The buffer is now like a normal buffer, it cannot be easily
3413 * abandoned when changed. */
3414 set_string_option_direct((char_u *)"buftype", -1,
3415 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3416 }
3417}
3418
3419/*
3420 * Get the screen attribute for a position in the buffer.
3421 * Use a negative "col" to get the filler background color.
3422 */
3423 int
3424term_get_attr(buf_T *buf, linenr_T lnum, int col)
3425{
3426 term_T *term = buf->b_term;
3427 sb_line_T *line;
3428 cellattr_T *cellattr;
3429
3430 if (lnum > term->tl_scrollback.ga_len)
3431 cellattr = &term->tl_default_color;
3432 else
3433 {
3434 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3435 if (col < 0 || col >= line->sb_cols)
3436 cellattr = &line->sb_fill_attr;
3437 else
3438 cellattr = line->sb_cells + col;
3439 }
3440 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3441}
3442
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003443/*
3444 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003445 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003446 */
3447 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003448cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003449{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003450 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003451}
3452
3453/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003454 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003455 */
3456 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003457init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003458{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003459 VTermColor *fg, *bg;
3460 int fgval, bgval;
3461 int id;
3462
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003463 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3464 term->tl_default_color.width = 1;
3465 fg = &term->tl_default_color.fg;
3466 bg = &term->tl_default_color.bg;
3467
3468 /* Vterm uses a default black background. Set it to white when
3469 * 'background' is "light". */
3470 if (*p_bg == 'l')
3471 {
3472 fgval = 0;
3473 bgval = 255;
3474 }
3475 else
3476 {
3477 fgval = 255;
3478 bgval = 0;
3479 }
3480 fg->red = fg->green = fg->blue = fgval;
3481 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003482 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003483
3484 /* The "Terminal" highlight group overrules the defaults. */
3485 id = syn_name2id((char_u *)"Terminal");
3486
Bram Moolenaar46359e12017-11-29 22:33:38 +01003487 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003488#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3489 if (0
3490# ifdef FEAT_GUI
3491 || gui.in_use
3492# endif
3493# ifdef FEAT_TERMGUICOLORS
3494 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003495# ifdef FEAT_VTP
3496 /* Finally get INVALCOLOR on this execution path */
3497 || (!p_tgc && t_colors >= 256)
3498# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003499# endif
3500 )
3501 {
3502 guicolor_T fg_rgb = INVALCOLOR;
3503 guicolor_T bg_rgb = INVALCOLOR;
3504
3505 if (id != 0)
3506 syn_id2colors(id, &fg_rgb, &bg_rgb);
3507
3508# ifdef FEAT_GUI
3509 if (gui.in_use)
3510 {
3511 if (fg_rgb == INVALCOLOR)
3512 fg_rgb = gui.norm_pixel;
3513 if (bg_rgb == INVALCOLOR)
3514 bg_rgb = gui.back_pixel;
3515 }
3516# ifdef FEAT_TERMGUICOLORS
3517 else
3518# endif
3519# endif
3520# ifdef FEAT_TERMGUICOLORS
3521 {
3522 if (fg_rgb == INVALCOLOR)
3523 fg_rgb = cterm_normal_fg_gui_color;
3524 if (bg_rgb == INVALCOLOR)
3525 bg_rgb = cterm_normal_bg_gui_color;
3526 }
3527# endif
3528 if (fg_rgb != INVALCOLOR)
3529 {
3530 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3531
3532 fg->red = (unsigned)(rgb >> 16);
3533 fg->green = (unsigned)(rgb >> 8) & 255;
3534 fg->blue = (unsigned)rgb & 255;
3535 }
3536 if (bg_rgb != INVALCOLOR)
3537 {
3538 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3539
3540 bg->red = (unsigned)(rgb >> 16);
3541 bg->green = (unsigned)(rgb >> 8) & 255;
3542 bg->blue = (unsigned)rgb & 255;
3543 }
3544 }
3545 else
3546#endif
3547 if (id != 0 && t_colors >= 16)
3548 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003549 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003550 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003551 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003552 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003553 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003554 else
3555 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003556#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003557 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003558#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003559
3560 /* In an MS-Windows console we know the normal colors. */
3561 if (cterm_normal_fg_color > 0)
3562 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003563 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003564# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3565# ifdef VIMDLL
3566 if (!gui.in_use)
3567# endif
3568 {
3569 tmp = fg->red;
3570 fg->red = fg->blue;
3571 fg->blue = tmp;
3572 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003573# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003574 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003575# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003576 else
3577 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003578# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003579
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003580 if (cterm_normal_bg_color > 0)
3581 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003582 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003583# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3584# ifdef VIMDLL
3585 if (!gui.in_use)
3586# endif
3587 {
3588 tmp = fg->red;
3589 fg->red = fg->blue;
3590 fg->blue = tmp;
3591 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003592# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003593 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003594# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003595 else
3596 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003597# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003598 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003599}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003600
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003601#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3602/*
3603 * Set the 16 ANSI colors from array of RGB values
3604 */
3605 static void
3606set_vterm_palette(VTerm *vterm, long_u *rgb)
3607{
3608 int index = 0;
3609 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003610
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003611 for (; index < 16; index++)
3612 {
3613 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003614
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003615 color.red = (unsigned)(rgb[index] >> 16);
3616 color.green = (unsigned)(rgb[index] >> 8) & 255;
3617 color.blue = (unsigned)rgb[index] & 255;
3618 vterm_state_set_palette_color(state, index, &color);
3619 }
3620}
3621
3622/*
3623 * Set the ANSI color palette from a list of colors
3624 */
3625 static int
3626set_ansi_colors_list(VTerm *vterm, list_T *list)
3627{
3628 int n = 0;
3629 long_u rgb[16];
3630 listitem_T *li = list->lv_first;
3631
3632 for (; li != NULL && n < 16; li = li->li_next, n++)
3633 {
3634 char_u *color_name;
3635 guicolor_T guicolor;
3636
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003637 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003638 if (color_name == NULL)
3639 return FAIL;
3640
3641 guicolor = GUI_GET_COLOR(color_name);
3642 if (guicolor == INVALCOLOR)
3643 return FAIL;
3644
3645 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3646 }
3647
3648 if (n != 16 || li != NULL)
3649 return FAIL;
3650
3651 set_vterm_palette(vterm, rgb);
3652
3653 return OK;
3654}
3655
3656/*
3657 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3658 */
3659 static void
3660init_vterm_ansi_colors(VTerm *vterm)
3661{
3662 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3663
3664 if (var != NULL
3665 && (var->di_tv.v_type != VAR_LIST
3666 || var->di_tv.vval.v_list == NULL
3667 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003668 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003669}
3670#endif
3671
Bram Moolenaar52acb112018-03-18 19:20:22 +01003672/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003673 * Handles a "drop" command from the job in the terminal.
3674 * "item" is the file name, "item->li_next" may have options.
3675 */
3676 static void
3677handle_drop_command(listitem_T *item)
3678{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003679 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003680 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003681 int bufnr;
3682 win_T *wp;
3683 tabpage_T *tp;
3684 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003685 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003686
3687 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3688 FOR_ALL_TAB_WINDOWS(tp, wp)
3689 {
3690 if (wp->w_buffer->b_fnum == bufnr)
3691 {
3692 /* buffer is in a window already, go there */
3693 goto_tabpage_win(tp, wp);
3694 return;
3695 }
3696 }
3697
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003698 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003699
3700 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3701 && opt_item->li_tv.vval.v_dict != NULL)
3702 {
3703 dict_T *dict = opt_item->li_tv.vval.v_dict;
3704 char_u *p;
3705
Bram Moolenaar8f667172018-12-14 15:38:31 +01003706 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003707 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003708 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003709 if (p != NULL)
3710 {
3711 if (check_ff_value(p) == FAIL)
3712 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3713 else
3714 ea.force_ff = *p;
3715 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003716 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003717 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003718 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003719 if (p != NULL)
3720 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003721 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003722 if (ea.cmd != NULL)
3723 {
3724 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3725 ea.force_enc = 11;
3726 tofree = ea.cmd;
3727 }
3728 }
3729
Bram Moolenaar8f667172018-12-14 15:38:31 +01003730 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003731 if (p != NULL)
3732 get_bad_opt(p, &ea);
3733
3734 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3735 ea.force_bin = FORCE_BIN;
3736 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3737 ea.force_bin = FORCE_BIN;
3738 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3739 ea.force_bin = FORCE_NOBIN;
3740 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3741 ea.force_bin = FORCE_NOBIN;
3742 }
3743
3744 /* open in new window, like ":split fname" */
3745 if (ea.cmd == NULL)
3746 ea.cmd = (char_u *)"split";
3747 ea.arg = fname;
3748 ea.cmdidx = CMD_split;
3749 ex_splitview(&ea);
3750
3751 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003752}
3753
3754/*
3755 * Handles a function call from the job running in a terminal.
3756 * "item" is the function name, "item->li_next" has the arguments.
3757 */
3758 static void
3759handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3760{
3761 char_u *func;
3762 typval_T argvars[2];
3763 typval_T rettv;
3764 int doesrange;
3765
3766 if (item->li_next == NULL)
3767 {
3768 ch_log(channel, "Missing function arguments for call");
3769 return;
3770 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003771 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003772
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003773 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003774 {
3775 ch_log(channel, "Invalid function name: %s", func);
3776 return;
3777 }
3778
3779 argvars[0].v_type = VAR_NUMBER;
3780 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3781 argvars[1] = item->li_next->li_tv;
Bram Moolenaar6ed88192019-05-11 18:37:44 +02003782 if (call_func(func, -1, &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003783 2, argvars, /* argv_func */ NULL,
3784 /* firstline */ 1, /* lastline */ 1,
3785 &doesrange, /* evaluate */ TRUE,
3786 /* partial */ NULL, /* selfdict */ NULL) == OK)
3787 {
3788 clear_tv(&rettv);
3789 ch_log(channel, "Function %s called", func);
3790 }
3791 else
3792 ch_log(channel, "Calling function %s failed", func);
3793}
3794
3795/*
3796 * Called by libvterm when it cannot recognize an OSC sequence.
3797 * We recognize a terminal API command.
3798 */
3799 static int
3800parse_osc(const char *command, size_t cmdlen, void *user)
3801{
3802 term_T *term = (term_T *)user;
3803 js_read_T reader;
3804 typval_T tv;
3805 channel_T *channel = term->tl_job == NULL ? NULL
3806 : term->tl_job->jv_channel;
3807
3808 /* We recognize only OSC 5 1 ; {command} */
3809 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3810 return 0; /* not handled */
3811
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003812 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003813 if (reader.js_buf == NULL)
3814 return 1;
3815 reader.js_fill = NULL;
3816 reader.js_used = 0;
3817 if (json_decode(&reader, &tv, 0) == OK
3818 && tv.v_type == VAR_LIST
3819 && tv.vval.v_list != NULL)
3820 {
3821 listitem_T *item = tv.vval.v_list->lv_first;
3822
3823 if (item == NULL)
3824 ch_log(channel, "Missing command");
3825 else
3826 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003827 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003828
Bram Moolenaara997b452018-04-17 23:24:06 +02003829 /* Make sure an invoked command doesn't delete the buffer (and the
3830 * terminal) under our fingers. */
3831 ++term->tl_buffer->b_locked;
3832
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003833 item = item->li_next;
3834 if (item == NULL)
3835 ch_log(channel, "Missing argument for %s", cmd);
3836 else if (STRCMP(cmd, "drop") == 0)
3837 handle_drop_command(item);
3838 else if (STRCMP(cmd, "call") == 0)
3839 handle_call_command(term, channel, item);
3840 else
3841 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003842 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003843 }
3844 }
3845 else
3846 ch_log(channel, "Invalid JSON received");
3847
3848 vim_free(reader.js_buf);
3849 clear_tv(&tv);
3850 return 1;
3851}
3852
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003853/*
3854 * Called by libvterm when it cannot recognize a CSI sequence.
3855 * We recognize the window position report.
3856 */
3857 static int
3858parse_csi(
3859 const char *leader UNUSED,
3860 const long args[],
3861 int argcount,
3862 const char *intermed UNUSED,
3863 char command,
3864 void *user)
3865{
3866 term_T *term = (term_T *)user;
3867 char buf[100];
3868 int len;
3869 int x = 0;
3870 int y = 0;
3871 win_T *wp;
3872
3873 // We recognize only CSI 13 t
3874 if (command != 't' || argcount != 1 || args[0] != 13)
3875 return 0; // not handled
3876
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003877 // When getting the window position is not possible or it fails it results
3878 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02003879#if defined(FEAT_GUI) \
3880 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
3881 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003882 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003883#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003884
3885 FOR_ALL_WINDOWS(wp)
3886 if (wp->w_buffer == term->tl_buffer)
3887 break;
3888 if (wp != NULL)
3889 {
3890#ifdef FEAT_GUI
3891 if (gui.in_use)
3892 {
3893 x += wp->w_wincol * gui.char_width;
3894 y += W_WINROW(wp) * gui.char_height;
3895 }
3896 else
3897#endif
3898 {
3899 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003900 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003901 x += wp->w_wincol * 7;
3902 y += W_WINROW(wp) * 10;
3903 }
3904 }
3905
3906 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
3907 channel_send(term->tl_job->jv_channel, get_tty_part(term),
3908 (char_u *)buf, len, NULL);
3909 return 1;
3910}
3911
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003912static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003913 NULL, // text
3914 NULL, // control
3915 NULL, // escape
3916 parse_csi, // csi
3917 parse_osc, // osc
3918 NULL, // dcs
3919 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003920};
3921
3922/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003923 * Use Vim's allocation functions for vterm so profiling works.
3924 */
3925 static void *
3926vterm_malloc(size_t size, void *data UNUSED)
3927{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02003928 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003929}
3930
3931 static void
3932vterm_memfree(void *ptr, void *data UNUSED)
3933{
3934 vim_free(ptr);
3935}
3936
3937static VTermAllocatorFunctions vterm_allocator = {
3938 &vterm_malloc,
3939 &vterm_memfree
3940};
3941
3942/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003943 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003944 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01003945 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003946 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01003947create_vterm(term_T *term, int rows, int cols)
3948{
3949 VTerm *vterm;
3950 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003951 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003952 VTermValue value;
3953
Bram Moolenaar756ef112018-04-10 12:04:27 +02003954 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003955 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003956 if (vterm == NULL)
3957 return FAIL;
3958
3959 // Allocate screen and state here, so we can bail out if that fails.
3960 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003961 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003962 if (state == NULL || screen == NULL)
3963 {
3964 vterm_free(vterm);
3965 return FAIL;
3966 }
3967
Bram Moolenaar52acb112018-03-18 19:20:22 +01003968 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3969 /* TODO: depends on 'encoding'. */
3970 vterm_set_utf8(vterm, 1);
3971
3972 init_default_colors(term);
3973
3974 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003975 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01003976 &term->tl_default_color.fg,
3977 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003978
Bram Moolenaar9e587872019-05-13 20:27:23 +02003979 if (t_colors < 16)
3980 // Less than 16 colors: assume that bold means using a bright color for
3981 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003982 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3983
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003984 /* Required to initialize most things. */
3985 vterm_screen_reset(screen, 1 /* hard */);
3986
3987 /* Allow using alternate screen. */
3988 vterm_screen_enable_altscreen(screen, 1);
3989
3990 /* For unix do not use a blinking cursor. In an xterm this causes the
3991 * cursor to blink if it's blinking in the xterm.
3992 * For Windows we respect the system wide setting. */
Bram Moolenaar4f974752019-02-17 17:44:42 +01003993#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003994 if (GetCaretBlinkTime() == INFINITE)
3995 value.boolean = 0;
3996 else
3997 value.boolean = 1;
3998#else
3999 value.boolean = 0;
4000#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004001 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4002 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004003
4004 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004005}
4006
4007/*
4008 * Return the text to show for the buffer name and status.
4009 */
4010 char_u *
4011term_get_status_text(term_T *term)
4012{
4013 if (term->tl_status_text == NULL)
4014 {
4015 char_u *txt;
4016 size_t len;
4017
4018 if (term->tl_normal_mode)
4019 {
4020 if (term_job_running(term))
4021 txt = (char_u *)_("Terminal");
4022 else
4023 txt = (char_u *)_("Terminal-finished");
4024 }
4025 else if (term->tl_title != NULL)
4026 txt = term->tl_title;
4027 else if (term_none_open(term))
4028 txt = (char_u *)_("active");
4029 else if (term_job_running(term))
4030 txt = (char_u *)_("running");
4031 else
4032 txt = (char_u *)_("finished");
4033 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004034 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004035 if (term->tl_status_text != NULL)
4036 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4037 term->tl_buffer->b_fname, txt);
4038 }
4039 return term->tl_status_text;
4040}
4041
4042/*
4043 * Mark references in jobs of terminals.
4044 */
4045 int
4046set_ref_in_term(int copyID)
4047{
4048 int abort = FALSE;
4049 term_T *term;
4050 typval_T tv;
4051
4052 for (term = first_term; term != NULL; term = term->tl_next)
4053 if (term->tl_job != NULL)
4054 {
4055 tv.v_type = VAR_JOB;
4056 tv.vval.v_job = term->tl_job;
4057 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4058 }
4059 return abort;
4060}
4061
4062/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004063 * Cache "Terminal" highlight group colors.
4064 */
4065 void
4066set_terminal_default_colors(int cterm_fg, int cterm_bg)
4067{
4068 term_default_cterm_fg = cterm_fg - 1;
4069 term_default_cterm_bg = cterm_bg - 1;
4070}
4071
4072/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004073 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004074 * Returns NULL when the buffer is not for a terminal window and logs a message
4075 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004076 */
4077 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004078term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004079{
4080 buf_T *buf;
4081
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004082 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004083 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004084 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004085 --emsg_off;
4086 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004087 {
4088 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004089 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004090 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004091 return buf;
4092}
4093
Bram Moolenaard96ff162018-02-18 22:13:29 +01004094 static int
4095same_color(VTermColor *a, VTermColor *b)
4096{
4097 return a->red == b->red
4098 && a->green == b->green
4099 && a->blue == b->blue
4100 && a->ansi_index == b->ansi_index;
4101}
4102
4103 static void
4104dump_term_color(FILE *fd, VTermColor *color)
4105{
4106 fprintf(fd, "%02x%02x%02x%d",
4107 (int)color->red, (int)color->green, (int)color->blue,
4108 (int)color->ansi_index);
4109}
4110
4111/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004112 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004113 *
4114 * Each screen cell in full is:
4115 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4116 * {characters} is a space for an empty cell
4117 * For a double-width character "+" is changed to "*" and the next cell is
4118 * skipped.
4119 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4120 * when "&" use the same as the previous cell.
4121 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4122 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4123 * {color-idx} is a number from 0 to 255
4124 *
4125 * Screen cell with same width, attributes and color as the previous one:
4126 * |{characters}
4127 *
4128 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4129 *
4130 * Repeating the previous screen cell:
4131 * @{count}
4132 */
4133 void
4134f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4135{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004136 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004137 term_T *term;
4138 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004139 int max_height = 0;
4140 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004141 stat_T st;
4142 FILE *fd;
4143 VTermPos pos;
4144 VTermScreen *screen;
4145 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004146 VTermState *state;
4147 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004148
4149 if (check_restricted() || check_secure())
4150 return;
4151 if (buf == NULL)
4152 return;
4153 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004154 if (term->tl_vterm == NULL)
4155 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004156 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004157 return;
4158 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004159
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004160 if (argvars[2].v_type != VAR_UNKNOWN)
4161 {
4162 dict_T *d;
4163
4164 if (argvars[2].v_type != VAR_DICT)
4165 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004166 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004167 return;
4168 }
4169 d = argvars[2].vval.v_dict;
4170 if (d != NULL)
4171 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004172 max_height = dict_get_number(d, (char_u *)"rows");
4173 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004174 }
4175 }
4176
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004177 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004178 if (fname == NULL)
4179 return;
4180 if (mch_stat((char *)fname, &st) >= 0)
4181 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004182 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004183 return;
4184 }
4185
Bram Moolenaard96ff162018-02-18 22:13:29 +01004186 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4187 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004188 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004189 return;
4190 }
4191
4192 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4193
4194 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004195 state = vterm_obtain_state(term->tl_vterm);
4196 vterm_state_get_cursorpos(state, &cursor_pos);
4197
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004198 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4199 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004200 {
4201 int repeat = 0;
4202
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004203 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4204 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004205 {
4206 VTermScreenCell cell;
4207 int same_attr;
4208 int same_chars = TRUE;
4209 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004210 int is_cursor_pos = (pos.col == cursor_pos.col
4211 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004212
4213 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4214 vim_memset(&cell, 0, sizeof(cell));
4215
4216 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4217 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004218 int c = cell.chars[i];
4219 int pc = prev_cell.chars[i];
4220
4221 /* For the first character NUL is the same as space. */
4222 if (i == 0)
4223 {
4224 c = (c == NUL) ? ' ' : c;
4225 pc = (pc == NUL) ? ' ' : pc;
4226 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004227 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004228 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004229 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004230 break;
4231 }
4232 same_attr = vtermAttr2hl(cell.attrs)
4233 == vtermAttr2hl(prev_cell.attrs)
4234 && same_color(&cell.fg, &prev_cell.fg)
4235 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004236 if (same_chars && cell.width == prev_cell.width && same_attr
4237 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004238 {
4239 ++repeat;
4240 }
4241 else
4242 {
4243 if (repeat > 0)
4244 {
4245 fprintf(fd, "@%d", repeat);
4246 repeat = 0;
4247 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004248 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004249
4250 if (cell.chars[0] == NUL)
4251 fputs(" ", fd);
4252 else
4253 {
4254 char_u charbuf[10];
4255 int len;
4256
4257 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4258 && cell.chars[i] != NUL; ++i)
4259 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004260 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004261 fwrite(charbuf, len, 1, fd);
4262 }
4263 }
4264
4265 /* When only the characters differ we don't write anything, the
4266 * following "|", "@" or NL will indicate using the same
4267 * attributes. */
4268 if (cell.width != prev_cell.width || !same_attr)
4269 {
4270 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004271 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004272 else
4273 fputs("+", fd);
4274
4275 if (same_attr)
4276 {
4277 fputs("&", fd);
4278 }
4279 else
4280 {
4281 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4282 if (same_color(&cell.fg, &prev_cell.fg))
4283 fputs("&", fd);
4284 else
4285 {
4286 fputs("#", fd);
4287 dump_term_color(fd, &cell.fg);
4288 }
4289 if (same_color(&cell.bg, &prev_cell.bg))
4290 fputs("&", fd);
4291 else
4292 {
4293 fputs("#", fd);
4294 dump_term_color(fd, &cell.bg);
4295 }
4296 }
4297 }
4298
4299 prev_cell = cell;
4300 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004301
4302 if (cell.width == 2)
4303 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004304 }
4305 if (repeat > 0)
4306 fprintf(fd, "@%d", repeat);
4307 fputs("\n", fd);
4308 }
4309
4310 fclose(fd);
4311}
4312
4313/*
4314 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4315 */
4316 static void
4317dump_is_corrupt(garray_T *gap)
4318{
4319 ga_concat(gap, (char_u *)"CORRUPT");
4320}
4321
4322 static void
4323append_cell(garray_T *gap, cellattr_T *cell)
4324{
4325 if (ga_grow(gap, 1) == OK)
4326 {
4327 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4328 ++gap->ga_len;
4329 }
4330}
4331
4332/*
4333 * Read the dump file from "fd" and append lines to the current buffer.
4334 * Return the cell width of the longest line.
4335 */
4336 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004337read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004338{
4339 int c;
4340 garray_T ga_text;
4341 garray_T ga_cell;
4342 char_u *prev_char = NULL;
4343 int attr = 0;
4344 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004345 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004346 term_T *term = curbuf->b_term;
4347 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004348 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004349
4350 ga_init2(&ga_text, 1, 90);
4351 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4352 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004353 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004354 cursor_pos->row = -1;
4355 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004356
4357 c = fgetc(fd);
4358 for (;;)
4359 {
4360 if (c == EOF)
4361 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004362 if (c == '\r')
4363 {
4364 // DOS line endings? Ignore.
4365 c = fgetc(fd);
4366 }
4367 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004368 {
4369 /* End of a line: append it to the buffer. */
4370 if (ga_text.ga_data == NULL)
4371 dump_is_corrupt(&ga_text);
4372 if (ga_grow(&term->tl_scrollback, 1) == OK)
4373 {
4374 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4375 + term->tl_scrollback.ga_len;
4376
4377 if (max_cells < ga_cell.ga_len)
4378 max_cells = ga_cell.ga_len;
4379 line->sb_cols = ga_cell.ga_len;
4380 line->sb_cells = ga_cell.ga_data;
4381 line->sb_fill_attr = term->tl_default_color;
4382 ++term->tl_scrollback.ga_len;
4383 ga_init(&ga_cell);
4384
4385 ga_append(&ga_text, NUL);
4386 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4387 ga_text.ga_len, FALSE);
4388 }
4389 else
4390 ga_clear(&ga_cell);
4391 ga_text.ga_len = 0;
4392
4393 c = fgetc(fd);
4394 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004395 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004396 {
4397 int prev_len = ga_text.ga_len;
4398
Bram Moolenaar9271d052018-02-25 21:39:46 +01004399 if (c == '>')
4400 {
4401 if (cursor_pos->row != -1)
4402 dump_is_corrupt(&ga_text); /* duplicate cursor */
4403 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4404 cursor_pos->col = ga_cell.ga_len;
4405 }
4406
Bram Moolenaard96ff162018-02-18 22:13:29 +01004407 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4408 c = fgetc(fd);
4409 if (c != EOF)
4410 ga_append(&ga_text, c);
4411 for (;;)
4412 {
4413 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004414 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004415 || c == EOF || c == '\n')
4416 break;
4417 ga_append(&ga_text, c);
4418 }
4419
4420 /* save the character for repeating it */
4421 vim_free(prev_char);
4422 if (ga_text.ga_data != NULL)
4423 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4424 ga_text.ga_len - prev_len);
4425
Bram Moolenaar9271d052018-02-25 21:39:46 +01004426 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004427 {
4428 /* use all attributes from previous cell */
4429 }
4430 else if (c == '+' || c == '*')
4431 {
4432 int is_bg;
4433
4434 cell.width = c == '+' ? 1 : 2;
4435
4436 c = fgetc(fd);
4437 if (c == '&')
4438 {
4439 /* use same attr as previous cell */
4440 c = fgetc(fd);
4441 }
4442 else if (isdigit(c))
4443 {
4444 /* get the decimal attribute */
4445 attr = 0;
4446 while (isdigit(c))
4447 {
4448 attr = attr * 10 + (c - '0');
4449 c = fgetc(fd);
4450 }
4451 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004452
4453 /* is_bg == 0: fg, is_bg == 1: bg */
4454 for (is_bg = 0; is_bg <= 1; ++is_bg)
4455 {
4456 if (c == '&')
4457 {
4458 /* use same color as previous cell */
4459 c = fgetc(fd);
4460 }
4461 else if (c == '#')
4462 {
4463 int red, green, blue, index = 0;
4464
4465 c = fgetc(fd);
4466 red = hex2nr(c);
4467 c = fgetc(fd);
4468 red = (red << 4) + hex2nr(c);
4469 c = fgetc(fd);
4470 green = hex2nr(c);
4471 c = fgetc(fd);
4472 green = (green << 4) + hex2nr(c);
4473 c = fgetc(fd);
4474 blue = hex2nr(c);
4475 c = fgetc(fd);
4476 blue = (blue << 4) + hex2nr(c);
4477 c = fgetc(fd);
4478 if (!isdigit(c))
4479 dump_is_corrupt(&ga_text);
4480 while (isdigit(c))
4481 {
4482 index = index * 10 + (c - '0');
4483 c = fgetc(fd);
4484 }
4485
4486 if (is_bg)
4487 {
4488 cell.bg.red = red;
4489 cell.bg.green = green;
4490 cell.bg.blue = blue;
4491 cell.bg.ansi_index = index;
4492 }
4493 else
4494 {
4495 cell.fg.red = red;
4496 cell.fg.green = green;
4497 cell.fg.blue = blue;
4498 cell.fg.ansi_index = index;
4499 }
4500 }
4501 else
4502 dump_is_corrupt(&ga_text);
4503 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004504 }
4505 else
4506 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004507 }
4508 else
4509 dump_is_corrupt(&ga_text);
4510
4511 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004512 if (cell.width == 2)
4513 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004514 }
4515 else if (c == '@')
4516 {
4517 if (prev_char == NULL)
4518 dump_is_corrupt(&ga_text);
4519 else
4520 {
4521 int count = 0;
4522
4523 /* repeat previous character, get the count */
4524 for (;;)
4525 {
4526 c = fgetc(fd);
4527 if (!isdigit(c))
4528 break;
4529 count = count * 10 + (c - '0');
4530 }
4531
4532 while (count-- > 0)
4533 {
4534 ga_concat(&ga_text, prev_char);
4535 append_cell(&ga_cell, &cell);
4536 }
4537 }
4538 }
4539 else
4540 {
4541 dump_is_corrupt(&ga_text);
4542 c = fgetc(fd);
4543 }
4544 }
4545
4546 if (ga_text.ga_len > 0)
4547 {
4548 /* trailing characters after last NL */
4549 dump_is_corrupt(&ga_text);
4550 ga_append(&ga_text, NUL);
4551 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4552 ga_text.ga_len, FALSE);
4553 }
4554
4555 ga_clear(&ga_text);
4556 vim_free(prev_char);
4557
4558 return max_cells;
4559}
4560
4561/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004562 * Return an allocated string with at least "text_width" "=" characters and
4563 * "fname" inserted in the middle.
4564 */
4565 static char_u *
4566get_separator(int text_width, char_u *fname)
4567{
4568 int width = MAX(text_width, curwin->w_width);
4569 char_u *textline;
4570 int fname_size;
4571 char_u *p = fname;
4572 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004573 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004574
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004575 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004576 if (textline == NULL)
4577 return NULL;
4578
4579 fname_size = vim_strsize(fname);
4580 if (fname_size < width - 8)
4581 {
4582 /* enough room, don't use the full window width */
4583 width = MAX(text_width, fname_size + 8);
4584 }
4585 else if (fname_size > width - 8)
4586 {
4587 /* full name doesn't fit, use only the tail */
4588 p = gettail(fname);
4589 fname_size = vim_strsize(p);
4590 }
4591 /* skip characters until the name fits */
4592 while (fname_size > width - 8)
4593 {
4594 p += (*mb_ptr2len)(p);
4595 fname_size = vim_strsize(p);
4596 }
4597
4598 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4599 textline[i] = '=';
4600 textline[i++] = ' ';
4601
4602 STRCPY(textline + i, p);
4603 off = STRLEN(textline);
4604 textline[off] = ' ';
4605 for (i = 1; i < (width - fname_size) / 2; ++i)
4606 textline[off + i] = '=';
4607 textline[off + i] = NUL;
4608
4609 return textline;
4610}
4611
4612/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004613 * Common for "term_dumpdiff()" and "term_dumpload()".
4614 */
4615 static void
4616term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4617{
4618 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004619 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004620 char_u buf1[NUMBUFLEN];
4621 char_u buf2[NUMBUFLEN];
4622 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004623 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004624 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004625 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004626 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004627 char_u *textline = NULL;
4628
4629 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004630 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004631 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004632 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004633 if (fname1 == NULL || (do_diff && fname2 == NULL))
4634 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004635 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004636 return;
4637 }
4638 fd1 = mch_fopen((char *)fname1, READBIN);
4639 if (fd1 == NULL)
4640 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004641 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004642 return;
4643 }
4644 if (do_diff)
4645 {
4646 fd2 = mch_fopen((char *)fname2, READBIN);
4647 if (fd2 == NULL)
4648 {
4649 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004650 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004651 return;
4652 }
4653 }
4654
4655 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004656 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4657 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4658 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4659 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4660 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004661
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004662 if (opt.jo_term_name == NULL)
4663 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004664 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004665
Bram Moolenaar51e14382019-05-25 20:21:28 +02004666 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004667 if (fname_tofree != NULL)
4668 {
4669 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4670 opt.jo_term_name = fname_tofree;
4671 }
4672 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004673
Bram Moolenaar87abab92019-06-03 21:14:59 +02004674 if (opt.jo_bufnr_buf != NULL)
4675 {
4676 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4677
4678 // With "bufnr" argument: enter the window with this buffer and make it
4679 // empty.
4680 if (wp == NULL)
4681 semsg(_(e_invarg2), "bufnr");
4682 else
4683 {
4684 buf = curbuf;
4685 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4686 ml_delete((linenr_T)1, FALSE);
4687 ga_clear(&curbuf->b_term->tl_scrollback);
4688 redraw_later(NOT_VALID);
4689 }
4690 }
4691 else
4692 // Create a new terminal window.
4693 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4694
Bram Moolenaard96ff162018-02-18 22:13:29 +01004695 if (buf != NULL && buf->b_term != NULL)
4696 {
4697 int i;
4698 linenr_T bot_lnum;
4699 linenr_T lnum;
4700 term_T *term = buf->b_term;
4701 int width;
4702 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004703 VTermPos cursor_pos1;
4704 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004705
Bram Moolenaar52acb112018-03-18 19:20:22 +01004706 init_default_colors(term);
4707
Bram Moolenaard96ff162018-02-18 22:13:29 +01004708 rettv->vval.v_number = buf->b_fnum;
4709
4710 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004711 width = read_dump_file(fd1, &cursor_pos1);
4712
4713 /* position the cursor */
4714 if (cursor_pos1.row >= 0)
4715 {
4716 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4717 coladvance(cursor_pos1.col);
4718 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004719
4720 /* Delete the empty line that was in the empty buffer. */
4721 ml_delete(1, FALSE);
4722
4723 /* For term_dumpload() we are done here. */
4724 if (!do_diff)
4725 goto theend;
4726
4727 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4728
Bram Moolenaar4a696342018-04-05 18:45:26 +02004729 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004730 if (textline == NULL)
4731 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004732 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4733 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4734 vim_free(textline);
4735
4736 textline = get_separator(width, fname2);
4737 if (textline == NULL)
4738 goto theend;
4739 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4740 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004741 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004742
4743 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004744 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004745 if (width2 > width)
4746 {
4747 vim_free(textline);
4748 textline = alloc(width2 + 1);
4749 if (textline == NULL)
4750 goto theend;
4751 width = width2;
4752 textline[width] = NUL;
4753 }
4754 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4755
4756 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4757 {
4758 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4759 {
4760 /* bottom part has fewer rows, fill with "-" */
4761 for (i = 0; i < width; ++i)
4762 textline[i] = '-';
4763 }
4764 else
4765 {
4766 char_u *line1;
4767 char_u *line2;
4768 char_u *p1;
4769 char_u *p2;
4770 int col;
4771 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4772 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4773 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4774 ->sb_cells;
4775
4776 /* Make a copy, getting the second line will invalidate it. */
4777 line1 = vim_strsave(ml_get(lnum));
4778 if (line1 == NULL)
4779 break;
4780 p1 = line1;
4781
4782 line2 = ml_get(lnum + bot_lnum);
4783 p2 = line2;
4784 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4785 {
4786 int len1 = utfc_ptr2len(p1);
4787 int len2 = utfc_ptr2len(p2);
4788
4789 textline[col] = ' ';
4790 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004791 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004792 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004793 else if (lnum == cursor_pos1.row + 1
4794 && col == cursor_pos1.col
4795 && (cursor_pos1.row != cursor_pos2.row
4796 || cursor_pos1.col != cursor_pos2.col))
4797 /* cursor in first but not in second */
4798 textline[col] = '>';
4799 else if (lnum == cursor_pos2.row + 1
4800 && col == cursor_pos2.col
4801 && (cursor_pos1.row != cursor_pos2.row
4802 || cursor_pos1.col != cursor_pos2.col))
4803 /* cursor in second but not in first */
4804 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004805 else if (cellattr1 != NULL && cellattr2 != NULL)
4806 {
4807 if ((cellattr1 + col)->width
4808 != (cellattr2 + col)->width)
4809 textline[col] = 'w';
4810 else if (!same_color(&(cellattr1 + col)->fg,
4811 &(cellattr2 + col)->fg))
4812 textline[col] = 'f';
4813 else if (!same_color(&(cellattr1 + col)->bg,
4814 &(cellattr2 + col)->bg))
4815 textline[col] = 'b';
4816 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4817 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4818 textline[col] = 'a';
4819 }
4820 p1 += len1;
4821 p2 += len2;
4822 /* TODO: handle different width */
4823 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004824
4825 while (col < width)
4826 {
4827 if (*p1 == NUL && *p2 == NUL)
4828 textline[col] = '?';
4829 else if (*p1 == NUL)
4830 {
4831 textline[col] = '+';
4832 p2 += utfc_ptr2len(p2);
4833 }
4834 else
4835 {
4836 textline[col] = '-';
4837 p1 += utfc_ptr2len(p1);
4838 }
4839 ++col;
4840 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004841
4842 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004843 }
4844 if (add_empty_scrollback(term, &term->tl_default_color,
4845 term->tl_top_diff_rows) == OK)
4846 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4847 ++bot_lnum;
4848 }
4849
4850 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4851 {
4852 /* bottom part has more rows, fill with "+" */
4853 for (i = 0; i < width; ++i)
4854 textline[i] = '+';
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 ++lnum;
4859 ++bot_lnum;
4860 }
4861
4862 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004863
4864 /* looks better without wrapping */
4865 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004866 }
4867
4868theend:
4869 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004870 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004871 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004872 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004873 fclose(fd2);
4874}
4875
4876/*
4877 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4878 * bottom files.
4879 * Return FAIL when this is not possible.
4880 */
4881 int
4882term_swap_diff()
4883{
4884 term_T *term = curbuf->b_term;
4885 linenr_T line_count;
4886 linenr_T top_rows;
4887 linenr_T bot_rows;
4888 linenr_T bot_start;
4889 linenr_T lnum;
4890 char_u *p;
4891 sb_line_T *sb_line;
4892
4893 if (term == NULL
4894 || !term_is_finished(curbuf)
4895 || term->tl_top_diff_rows == 0
4896 || term->tl_scrollback.ga_len == 0)
4897 return FAIL;
4898
4899 line_count = curbuf->b_ml.ml_line_count;
4900 top_rows = term->tl_top_diff_rows;
4901 bot_rows = term->tl_bot_diff_rows;
4902 bot_start = line_count - bot_rows;
4903 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4904
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004905 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01004906 for (lnum = 1; lnum <= top_rows; ++lnum)
4907 {
4908 p = vim_strsave(ml_get(1));
4909 if (p == NULL)
4910 return OK;
4911 ml_append(bot_start, p, 0, FALSE);
4912 ml_delete(1, FALSE);
4913 vim_free(p);
4914 }
4915
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004916 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01004917 for (lnum = 1; lnum <= bot_rows; ++lnum)
4918 {
4919 p = vim_strsave(ml_get(bot_start + lnum));
4920 if (p == NULL)
4921 return OK;
4922 ml_delete(bot_start + lnum, FALSE);
4923 ml_append(lnum - 1, p, 0, FALSE);
4924 vim_free(p);
4925 }
4926
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004927 // move top title to bottom
4928 p = vim_strsave(ml_get(bot_rows + 1));
4929 if (p == NULL)
4930 return OK;
4931 ml_append(line_count - top_rows - 1, p, 0, FALSE);
4932 ml_delete(bot_rows + 1, FALSE);
4933 vim_free(p);
4934
4935 // move bottom title to top
4936 p = vim_strsave(ml_get(line_count - top_rows));
4937 if (p == NULL)
4938 return OK;
4939 ml_delete(line_count - top_rows, FALSE);
4940 ml_append(bot_rows, p, 0, FALSE);
4941 vim_free(p);
4942
Bram Moolenaard96ff162018-02-18 22:13:29 +01004943 if (top_rows == bot_rows)
4944 {
4945 /* rows counts are equal, can swap cell properties */
4946 for (lnum = 0; lnum < top_rows; ++lnum)
4947 {
4948 sb_line_T temp;
4949
4950 temp = *(sb_line + lnum);
4951 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4952 *(sb_line + bot_start + lnum) = temp;
4953 }
4954 }
4955 else
4956 {
4957 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004958 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004959
4960 /* need to copy cell properties into temp memory */
4961 if (temp != NULL)
4962 {
4963 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4964 mch_memmove(term->tl_scrollback.ga_data,
4965 temp + bot_start,
4966 sizeof(sb_line_T) * bot_rows);
4967 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4968 temp + top_rows,
4969 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4970 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4971 + line_count - top_rows,
4972 temp,
4973 sizeof(sb_line_T) * top_rows);
4974 vim_free(temp);
4975 }
4976 }
4977
4978 term->tl_top_diff_rows = bot_rows;
4979 term->tl_bot_diff_rows = top_rows;
4980
4981 update_screen(NOT_VALID);
4982 return OK;
4983}
4984
4985/*
4986 * "term_dumpdiff(filename, filename, options)" function
4987 */
4988 void
4989f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4990{
4991 term_load_dump(argvars, rettv, TRUE);
4992}
4993
4994/*
4995 * "term_dumpload(filename, options)" function
4996 */
4997 void
4998f_term_dumpload(typval_T *argvars, typval_T *rettv)
4999{
5000 term_load_dump(argvars, rettv, FALSE);
5001}
5002
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005003/*
5004 * "term_getaltscreen(buf)" function
5005 */
5006 void
5007f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5008{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005009 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005010
5011 if (buf == NULL)
5012 return;
5013 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5014}
5015
5016/*
5017 * "term_getattr(attr, name)" function
5018 */
5019 void
5020f_term_getattr(typval_T *argvars, typval_T *rettv)
5021{
5022 int attr;
5023 size_t i;
5024 char_u *name;
5025
5026 static struct {
5027 char *name;
5028 int attr;
5029 } attrs[] = {
5030 {"bold", HL_BOLD},
5031 {"italic", HL_ITALIC},
5032 {"underline", HL_UNDERLINE},
5033 {"strike", HL_STRIKETHROUGH},
5034 {"reverse", HL_INVERSE},
5035 };
5036
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005037 attr = tv_get_number(&argvars[0]);
5038 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005039 if (name == NULL)
5040 return;
5041
5042 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5043 if (STRCMP(name, attrs[i].name) == 0)
5044 {
5045 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5046 break;
5047 }
5048}
5049
5050/*
5051 * "term_getcursor(buf)" function
5052 */
5053 void
5054f_term_getcursor(typval_T *argvars, typval_T *rettv)
5055{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005056 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005057 term_T *term;
5058 list_T *l;
5059 dict_T *d;
5060
5061 if (rettv_list_alloc(rettv) == FAIL)
5062 return;
5063 if (buf == NULL)
5064 return;
5065 term = buf->b_term;
5066
5067 l = rettv->vval.v_list;
5068 list_append_number(l, term->tl_cursor_pos.row + 1);
5069 list_append_number(l, term->tl_cursor_pos.col + 1);
5070
5071 d = dict_alloc();
5072 if (d != NULL)
5073 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005074 dict_add_number(d, "visible", term->tl_cursor_visible);
5075 dict_add_number(d, "blink", blink_state_is_inverted()
5076 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5077 dict_add_number(d, "shape", term->tl_cursor_shape);
5078 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005079 list_append_dict(l, d);
5080 }
5081}
5082
5083/*
5084 * "term_getjob(buf)" function
5085 */
5086 void
5087f_term_getjob(typval_T *argvars, typval_T *rettv)
5088{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005089 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005090
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005091 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005092 {
5093 rettv->v_type = VAR_SPECIAL;
5094 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005095 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005096 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005097
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005098 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005099 rettv->vval.v_job = buf->b_term->tl_job;
5100 if (rettv->vval.v_job != NULL)
5101 ++rettv->vval.v_job->jv_refcount;
5102}
5103
5104 static int
5105get_row_number(typval_T *tv, term_T *term)
5106{
5107 if (tv->v_type == VAR_STRING
5108 && tv->vval.v_string != NULL
5109 && STRCMP(tv->vval.v_string, ".") == 0)
5110 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005111 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005112}
5113
5114/*
5115 * "term_getline(buf, row)" function
5116 */
5117 void
5118f_term_getline(typval_T *argvars, typval_T *rettv)
5119{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005120 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005121 term_T *term;
5122 int row;
5123
5124 rettv->v_type = VAR_STRING;
5125 if (buf == NULL)
5126 return;
5127 term = buf->b_term;
5128 row = get_row_number(&argvars[1], term);
5129
5130 if (term->tl_vterm == NULL)
5131 {
5132 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5133
5134 /* vterm is finished, get the text from the buffer */
5135 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5136 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5137 }
5138 else
5139 {
5140 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5141 VTermRect rect;
5142 int len;
5143 char_u *p;
5144
5145 if (row < 0 || row >= term->tl_rows)
5146 return;
5147 len = term->tl_cols * MB_MAXBYTES + 1;
5148 p = alloc(len);
5149 if (p == NULL)
5150 return;
5151 rettv->vval.v_string = p;
5152
5153 rect.start_col = 0;
5154 rect.end_col = term->tl_cols;
5155 rect.start_row = row;
5156 rect.end_row = row + 1;
5157 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5158 }
5159}
5160
5161/*
5162 * "term_getscrolled(buf)" function
5163 */
5164 void
5165f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5166{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005167 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005168
5169 if (buf == NULL)
5170 return;
5171 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5172}
5173
5174/*
5175 * "term_getsize(buf)" function
5176 */
5177 void
5178f_term_getsize(typval_T *argvars, typval_T *rettv)
5179{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005180 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005181 list_T *l;
5182
5183 if (rettv_list_alloc(rettv) == FAIL)
5184 return;
5185 if (buf == NULL)
5186 return;
5187
5188 l = rettv->vval.v_list;
5189 list_append_number(l, buf->b_term->tl_rows);
5190 list_append_number(l, buf->b_term->tl_cols);
5191}
5192
5193/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005194 * "term_setsize(buf, rows, cols)" function
5195 */
5196 void
5197f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5198{
5199 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5200 term_T *term;
5201 varnumber_T rows, cols;
5202
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005203 if (buf == NULL)
5204 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005205 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005206 return;
5207 }
5208 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005209 return;
5210 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005211 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005212 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005213 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005214 cols = cols <= 0 ? term->tl_cols : cols;
5215 vterm_set_size(term->tl_vterm, rows, cols);
5216 /* handle_resize() will resize the windows */
5217
5218 /* Get and remember the size we ended up with. Update the pty. */
5219 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5220 term_report_winsize(term, term->tl_rows, term->tl_cols);
5221}
5222
5223/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005224 * "term_getstatus(buf)" function
5225 */
5226 void
5227f_term_getstatus(typval_T *argvars, typval_T *rettv)
5228{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005229 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005230 term_T *term;
5231 char_u val[100];
5232
5233 rettv->v_type = VAR_STRING;
5234 if (buf == NULL)
5235 return;
5236 term = buf->b_term;
5237
5238 if (term_job_running(term))
5239 STRCPY(val, "running");
5240 else
5241 STRCPY(val, "finished");
5242 if (term->tl_normal_mode)
5243 STRCAT(val, ",normal");
5244 rettv->vval.v_string = vim_strsave(val);
5245}
5246
5247/*
5248 * "term_gettitle(buf)" function
5249 */
5250 void
5251f_term_gettitle(typval_T *argvars, typval_T *rettv)
5252{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005253 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005254
5255 rettv->v_type = VAR_STRING;
5256 if (buf == NULL)
5257 return;
5258
5259 if (buf->b_term->tl_title != NULL)
5260 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5261}
5262
5263/*
5264 * "term_gettty(buf)" function
5265 */
5266 void
5267f_term_gettty(typval_T *argvars, typval_T *rettv)
5268{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005269 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005270 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005271 int num = 0;
5272
5273 rettv->v_type = VAR_STRING;
5274 if (buf == NULL)
5275 return;
5276 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005277 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005278
5279 switch (num)
5280 {
5281 case 0:
5282 if (buf->b_term->tl_job != NULL)
5283 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005284 break;
5285 case 1:
5286 if (buf->b_term->tl_job != NULL)
5287 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005288 break;
5289 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005290 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005291 return;
5292 }
5293 if (p != NULL)
5294 rettv->vval.v_string = vim_strsave(p);
5295}
5296
5297/*
5298 * "term_list()" function
5299 */
5300 void
5301f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5302{
5303 term_T *tp;
5304 list_T *l;
5305
5306 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5307 return;
5308
5309 l = rettv->vval.v_list;
5310 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5311 if (tp != NULL && tp->tl_buffer != NULL)
5312 if (list_append_number(l,
5313 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5314 return;
5315}
5316
5317/*
5318 * "term_scrape(buf, row)" function
5319 */
5320 void
5321f_term_scrape(typval_T *argvars, typval_T *rettv)
5322{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005323 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005324 VTermScreen *screen = NULL;
5325 VTermPos pos;
5326 list_T *l;
5327 term_T *term;
5328 char_u *p;
5329 sb_line_T *line;
5330
5331 if (rettv_list_alloc(rettv) == FAIL)
5332 return;
5333 if (buf == NULL)
5334 return;
5335 term = buf->b_term;
5336
5337 l = rettv->vval.v_list;
5338 pos.row = get_row_number(&argvars[1], term);
5339
5340 if (term->tl_vterm != NULL)
5341 {
5342 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005343 if (screen == NULL) // can't really happen
5344 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005345 p = NULL;
5346 line = NULL;
5347 }
5348 else
5349 {
5350 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5351
5352 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5353 return;
5354 p = ml_get_buf(buf, lnum + 1, FALSE);
5355 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5356 }
5357
5358 for (pos.col = 0; pos.col < term->tl_cols; )
5359 {
5360 dict_T *dcell;
5361 int width;
5362 VTermScreenCellAttrs attrs;
5363 VTermColor fg, bg;
5364 char_u rgb[8];
5365 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5366 int off = 0;
5367 int i;
5368
5369 if (screen == NULL)
5370 {
5371 cellattr_T *cellattr;
5372 int len;
5373
5374 /* vterm has finished, get the cell from scrollback */
5375 if (pos.col >= line->sb_cols)
5376 break;
5377 cellattr = line->sb_cells + pos.col;
5378 width = cellattr->width;
5379 attrs = cellattr->attrs;
5380 fg = cellattr->fg;
5381 bg = cellattr->bg;
5382 len = MB_PTR2LEN(p);
5383 mch_memmove(mbs, p, len);
5384 mbs[len] = NUL;
5385 p += len;
5386 }
5387 else
5388 {
5389 VTermScreenCell cell;
5390 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5391 break;
5392 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5393 {
5394 if (cell.chars[i] == 0)
5395 break;
5396 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5397 }
5398 mbs[off] = NUL;
5399 width = cell.width;
5400 attrs = cell.attrs;
5401 fg = cell.fg;
5402 bg = cell.bg;
5403 }
5404 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005405 if (dcell == NULL)
5406 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005407 list_append_dict(l, dcell);
5408
Bram Moolenaare0be1672018-07-08 16:50:37 +02005409 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005410
5411 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5412 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005413 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005414 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5415 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005416 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005417
Bram Moolenaare0be1672018-07-08 16:50:37 +02005418 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5419 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005420
5421 ++pos.col;
5422 if (width == 2)
5423 ++pos.col;
5424 }
5425}
5426
5427/*
5428 * "term_sendkeys(buf, keys)" function
5429 */
5430 void
5431f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5432{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005433 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005434 char_u *msg;
5435 term_T *term;
5436
5437 rettv->v_type = VAR_UNKNOWN;
5438 if (buf == NULL)
5439 return;
5440
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005441 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005442 if (msg == NULL)
5443 return;
5444 term = buf->b_term;
5445 if (term->tl_vterm == NULL)
5446 return;
5447
5448 while (*msg != NUL)
5449 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005450 int c;
5451
5452 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5453 {
5454 c = TO_SPECIAL(msg[1], msg[2]);
5455 msg += 3;
5456 }
5457 else
5458 {
5459 c = PTR2CHAR(msg);
5460 msg += MB_CPTR2LEN(msg);
5461 }
5462 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005463 }
5464}
5465
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005466#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5467/*
5468 * "term_getansicolors(buf)" function
5469 */
5470 void
5471f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5472{
5473 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5474 term_T *term;
5475 VTermState *state;
5476 VTermColor color;
5477 char_u hexbuf[10];
5478 int index;
5479 list_T *list;
5480
5481 if (rettv_list_alloc(rettv) == FAIL)
5482 return;
5483
5484 if (buf == NULL)
5485 return;
5486 term = buf->b_term;
5487 if (term->tl_vterm == NULL)
5488 return;
5489
5490 list = rettv->vval.v_list;
5491 state = vterm_obtain_state(term->tl_vterm);
5492 for (index = 0; index < 16; index++)
5493 {
5494 vterm_state_get_palette_color(state, index, &color);
5495 sprintf((char *)hexbuf, "#%02x%02x%02x",
5496 color.red, color.green, color.blue);
5497 if (list_append_string(list, hexbuf, 7) == FAIL)
5498 return;
5499 }
5500}
5501
5502/*
5503 * "term_setansicolors(buf, list)" function
5504 */
5505 void
5506f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5507{
5508 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5509 term_T *term;
5510
5511 if (buf == NULL)
5512 return;
5513 term = buf->b_term;
5514 if (term->tl_vterm == NULL)
5515 return;
5516
5517 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5518 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005519 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005520 return;
5521 }
5522
5523 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005524 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005525}
5526#endif
5527
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005528/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005529 * "term_setrestore(buf, command)" function
5530 */
5531 void
5532f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5533{
5534#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005535 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005536 term_T *term;
5537 char_u *cmd;
5538
5539 if (buf == NULL)
5540 return;
5541 term = buf->b_term;
5542 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005543 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005544 if (cmd != NULL)
5545 term->tl_command = vim_strsave(cmd);
5546 else
5547 term->tl_command = NULL;
5548#endif
5549}
5550
5551/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005552 * "term_setkill(buf, how)" function
5553 */
5554 void
5555f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5556{
5557 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5558 term_T *term;
5559 char_u *how;
5560
5561 if (buf == NULL)
5562 return;
5563 term = buf->b_term;
5564 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005565 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005566 if (how != NULL)
5567 term->tl_kill = vim_strsave(how);
5568 else
5569 term->tl_kill = NULL;
5570}
5571
5572/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005573 * "term_start(command, options)" function
5574 */
5575 void
5576f_term_start(typval_T *argvars, typval_T *rettv)
5577{
5578 jobopt_T opt;
5579 buf_T *buf;
5580
5581 init_job_options(&opt);
5582 if (argvars[1].v_type != VAR_UNKNOWN
5583 && get_job_options(&argvars[1], &opt,
5584 JO_TIMEOUT_ALL + JO_STOPONEXIT
5585 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5586 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5587 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5588 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005589 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005590 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01005591 + JO2_ANSI_COLORS + JO2_TTY_TYPE) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005592 return;
5593
Bram Moolenaar13568252018-03-16 20:46:58 +01005594 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005595
5596 if (buf != NULL && buf->b_term != NULL)
5597 rettv->vval.v_number = buf->b_fnum;
5598}
5599
5600/*
5601 * "term_wait" function
5602 */
5603 void
5604f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5605{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005606 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005607
5608 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005609 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005610 if (buf->b_term->tl_job == NULL)
5611 {
5612 ch_log(NULL, "term_wait(): no job to wait for");
5613 return;
5614 }
5615 if (buf->b_term->tl_job->jv_channel == NULL)
5616 /* channel is closed, nothing to do */
5617 return;
5618
5619 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005620 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005621 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5622 {
5623 /* The job is dead, keep reading channel I/O until the channel is
5624 * closed. buf->b_term may become NULL if the terminal was closed while
5625 * waiting. */
5626 ch_log(NULL, "term_wait(): waiting for channel to close");
5627 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5628 {
5629 mch_check_messages();
5630 parse_queued_messages();
Bram Moolenaard45aa552018-05-21 22:50:29 +02005631 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005632 if (!buf_valid(buf))
5633 /* If the terminal is closed when the channel is closed the
5634 * buffer disappears. */
5635 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005636 }
5637 mch_check_messages();
5638 parse_queued_messages();
5639 }
5640 else
5641 {
5642 long wait = 10L;
5643
5644 mch_check_messages();
5645 parse_queued_messages();
5646
5647 /* Wait for some time for any channel I/O. */
5648 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005649 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005650 ui_delay(wait, TRUE);
5651 mch_check_messages();
5652
5653 /* Flushing messages on channels is hopefully sufficient.
5654 * TODO: is there a better way? */
5655 parse_queued_messages();
5656 }
5657}
5658
5659/*
5660 * Called when a channel has sent all the lines to a terminal.
5661 * Send a CTRL-D to mark the end of the text.
5662 */
5663 void
5664term_send_eof(channel_T *ch)
5665{
5666 term_T *term;
5667
5668 for (term = first_term; term != NULL; term = term->tl_next)
5669 if (term->tl_job == ch->ch_job)
5670 {
5671 if (term->tl_eof_chars != NULL)
5672 {
5673 channel_send(ch, PART_IN, term->tl_eof_chars,
5674 (int)STRLEN(term->tl_eof_chars), NULL);
5675 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5676 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005677# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005678 else
5679 /* Default: CTRL-D */
5680 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5681# endif
5682 }
5683}
5684
Bram Moolenaar113e1072019-01-20 15:30:40 +01005685#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005686 job_T *
5687term_getjob(term_T *term)
5688{
5689 return term != NULL ? term->tl_job : NULL;
5690}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005691#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005692
Bram Moolenaar4f974752019-02-17 17:44:42 +01005693# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005694
5695/**************************************
5696 * 2. MS-Windows implementation.
5697 */
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005698#ifdef PROTO
5699typedef int COORD;
5700typedef int DWORD;
5701typedef int HANDLE;
5702typedef int *DWORD_PTR;
5703typedef int HPCON;
5704typedef int HRESULT;
5705typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005706typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005707typedef int PSIZE_T;
5708typedef int PVOID;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005709typedef int WINAPI;
5710#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005711
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005712HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5713HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5714HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005715BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5716BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5717void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005718
5719 static int
5720dyn_conpty_init(int verbose)
5721{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005722 static HMODULE hKerneldll = NULL;
5723 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005724 static struct
5725 {
5726 char *name;
5727 FARPROC *ptr;
5728 } conpty_entry[] =
5729 {
5730 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5731 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5732 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5733 {"InitializeProcThreadAttributeList",
5734 (FARPROC*)&pInitializeProcThreadAttributeList},
5735 {"UpdateProcThreadAttribute",
5736 (FARPROC*)&pUpdateProcThreadAttribute},
5737 {"DeleteProcThreadAttributeList",
5738 (FARPROC*)&pDeleteProcThreadAttributeList},
5739 {NULL, NULL}
5740 };
5741
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005742 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005743 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005744 if (verbose)
5745 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005746 return FAIL;
5747 }
5748
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005749 // No need to initialize twice.
5750 if (hKerneldll)
5751 return OK;
5752
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005753 hKerneldll = vimLoadLib("kernel32.dll");
5754 for (i = 0; conpty_entry[i].name != NULL
5755 && conpty_entry[i].ptr != NULL; ++i)
5756 {
5757 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5758 conpty_entry[i].name)) == NULL)
5759 {
5760 if (verbose)
5761 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005762 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005763 return FAIL;
5764 }
5765 }
5766
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005767 return OK;
5768}
5769
5770 static int
5771conpty_term_and_job_init(
5772 term_T *term,
5773 typval_T *argvar,
5774 char **argv,
5775 jobopt_T *opt,
5776 jobopt_T *orig_opt)
5777{
5778 WCHAR *cmd_wchar = NULL;
5779 WCHAR *cmd_wchar_copy = NULL;
5780 WCHAR *cwd_wchar = NULL;
5781 WCHAR *env_wchar = NULL;
5782 channel_T *channel = NULL;
5783 job_T *job = NULL;
5784 HANDLE jo = NULL;
5785 garray_T ga_cmd, ga_env;
5786 char_u *cmd = NULL;
5787 HRESULT hr;
5788 COORD consize;
5789 SIZE_T breq;
5790 PROCESS_INFORMATION proc_info;
5791 HANDLE i_theirs = NULL;
5792 HANDLE o_theirs = NULL;
5793 HANDLE i_ours = NULL;
5794 HANDLE o_ours = NULL;
5795
5796 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5797 ga_init2(&ga_env, (int)sizeof(char*), 20);
5798
5799 if (argvar->v_type == VAR_STRING)
5800 {
5801 cmd = argvar->vval.v_string;
5802 }
5803 else if (argvar->v_type == VAR_LIST)
5804 {
5805 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5806 goto failed;
5807 cmd = ga_cmd.ga_data;
5808 }
5809 if (cmd == NULL || *cmd == NUL)
5810 {
5811 emsg(_(e_invarg));
5812 goto failed;
5813 }
5814
5815 term->tl_arg0_cmd = vim_strsave(cmd);
5816
5817 cmd_wchar = enc_to_utf16(cmd, NULL);
5818
5819 if (cmd_wchar != NULL)
5820 {
5821 /* Request by CreateProcessW */
5822 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005823 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005824 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5825 }
5826
5827 ga_clear(&ga_cmd);
5828 if (cmd_wchar == NULL)
5829 goto failed;
5830 if (opt->jo_cwd != NULL)
5831 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5832
5833 win32_build_env(opt->jo_env, &ga_env, TRUE);
5834 env_wchar = ga_env.ga_data;
5835
5836 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5837 goto failed;
5838 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5839 goto failed;
5840
5841 consize.X = term->tl_cols;
5842 consize.Y = term->tl_rows;
5843 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
5844 &term->tl_conpty);
5845 if (FAILED(hr))
5846 goto failed;
5847
5848 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
5849
5850 /* Set up pipe inheritance safely: Vista or later. */
5851 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005852 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005853 if (!term->tl_siex.lpAttributeList)
5854 goto failed;
5855 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
5856 0, &breq))
5857 goto failed;
5858 if (!pUpdateProcThreadAttribute(
5859 term->tl_siex.lpAttributeList, 0,
5860 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
5861 sizeof(HPCON), NULL, NULL))
5862 goto failed;
5863
5864 channel = add_channel();
5865 if (channel == NULL)
5866 goto failed;
5867
5868 job = job_alloc();
5869 if (job == NULL)
5870 goto failed;
5871 if (argvar->v_type == VAR_STRING)
5872 {
5873 int argc;
5874
5875 build_argv_from_string(cmd, &job->jv_argv, &argc);
5876 }
5877 else
5878 {
5879 int argc;
5880
5881 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5882 }
5883
5884 if (opt->jo_set & JO_IN_BUF)
5885 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5886
5887 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
5888 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
5889 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
5890 | CREATE_DEFAULT_ERROR_MODE,
5891 env_wchar, cwd_wchar,
5892 &term->tl_siex.StartupInfo, &proc_info))
5893 goto failed;
5894
5895 CloseHandle(i_theirs);
5896 CloseHandle(o_theirs);
5897
5898 channel_set_pipes(channel,
5899 (sock_T)i_ours,
5900 (sock_T)o_ours,
5901 (sock_T)o_ours);
5902
5903 /* Write lines with CR instead of NL. */
5904 channel->ch_write_text_mode = TRUE;
5905
5906 /* Use to explicitly delete anonymous pipe handle. */
5907 channel->ch_anonymous_pipe = TRUE;
5908
5909 jo = CreateJobObject(NULL, NULL);
5910 if (jo == NULL)
5911 goto failed;
5912
5913 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
5914 {
5915 /* Failed, switch the way to terminate process with TerminateProcess. */
5916 CloseHandle(jo);
5917 jo = NULL;
5918 }
5919
5920 ResumeThread(proc_info.hThread);
5921 CloseHandle(proc_info.hThread);
5922
5923 vim_free(cmd_wchar);
5924 vim_free(cmd_wchar_copy);
5925 vim_free(cwd_wchar);
5926 vim_free(env_wchar);
5927
5928 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
5929 goto failed;
5930
5931#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5932 if (opt->jo_set2 & JO2_ANSI_COLORS)
5933 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5934 else
5935 init_vterm_ansi_colors(term->tl_vterm);
5936#endif
5937
5938 channel_set_job(channel, job, opt);
5939 job_set_options(job, opt);
5940
5941 job->jv_channel = channel;
5942 job->jv_proc_info = proc_info;
5943 job->jv_job_object = jo;
5944 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01005945 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005946 ++job->jv_refcount;
5947 term->tl_job = job;
5948
5949 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5950 * open the file here and handle it in. opt->jo_io was changed in
5951 * setup_job_options(), use the original flags here. */
5952 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5953 {
5954 char_u *fname = opt->jo_io_name[PART_OUT];
5955
5956 ch_log(channel, "Opening output file %s", fname);
5957 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5958 if (term->tl_out_fd == NULL)
5959 semsg(_(e_notopen), fname);
5960 }
5961
5962 return OK;
5963
5964failed:
5965 ga_clear(&ga_cmd);
5966 ga_clear(&ga_env);
5967 vim_free(cmd_wchar);
5968 vim_free(cmd_wchar_copy);
5969 vim_free(cwd_wchar);
5970 if (channel != NULL)
5971 channel_clear(channel);
5972 if (job != NULL)
5973 {
5974 job->jv_channel = NULL;
5975 job_cleanup(job);
5976 }
5977 term->tl_job = NULL;
5978 if (jo != NULL)
5979 CloseHandle(jo);
5980
5981 if (term->tl_siex.lpAttributeList != NULL)
5982 {
5983 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
5984 vim_free(term->tl_siex.lpAttributeList);
5985 }
5986 term->tl_siex.lpAttributeList = NULL;
5987 if (o_theirs != NULL)
5988 CloseHandle(o_theirs);
5989 if (o_ours != NULL)
5990 CloseHandle(o_ours);
5991 if (i_ours != NULL)
5992 CloseHandle(i_ours);
5993 if (i_theirs != NULL)
5994 CloseHandle(i_theirs);
5995 if (term->tl_conpty != NULL)
5996 pClosePseudoConsole(term->tl_conpty);
5997 term->tl_conpty = NULL;
5998 return FAIL;
5999}
6000
6001 static void
6002conpty_term_report_winsize(term_T *term, int rows, int cols)
6003{
6004 COORD consize;
6005
6006 consize.X = cols;
6007 consize.Y = rows;
6008 pResizePseudoConsole(term->tl_conpty, consize);
6009}
6010
6011 void
6012term_free_conpty(term_T *term)
6013{
6014 if (term->tl_siex.lpAttributeList != NULL)
6015 {
6016 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6017 vim_free(term->tl_siex.lpAttributeList);
6018 }
6019 term->tl_siex.lpAttributeList = NULL;
6020 if (term->tl_conpty != NULL)
6021 pClosePseudoConsole(term->tl_conpty);
6022 term->tl_conpty = NULL;
6023}
6024
6025 int
6026use_conpty(void)
6027{
6028 return has_conpty;
6029}
6030
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006031# ifndef PROTO
6032
6033#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6034#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006035#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006036
6037void* (*winpty_config_new)(UINT64, void*);
6038void* (*winpty_open)(void*, void*);
6039void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6040BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6041void (*winpty_config_set_mouse_mode)(void*, int);
6042void (*winpty_config_set_initial_size)(void*, int, int);
6043LPCWSTR (*winpty_conin_name)(void*);
6044LPCWSTR (*winpty_conout_name)(void*);
6045LPCWSTR (*winpty_conerr_name)(void*);
6046void (*winpty_free)(void*);
6047void (*winpty_config_free)(void*);
6048void (*winpty_spawn_config_free)(void*);
6049void (*winpty_error_free)(void*);
6050LPCWSTR (*winpty_error_msg)(void*);
6051BOOL (*winpty_set_size)(void*, int, int, void*);
6052HANDLE (*winpty_agent_process)(void*);
6053
6054#define WINPTY_DLL "winpty.dll"
6055
6056static HINSTANCE hWinPtyDLL = NULL;
6057# endif
6058
6059 static int
6060dyn_winpty_init(int verbose)
6061{
6062 int i;
6063 static struct
6064 {
6065 char *name;
6066 FARPROC *ptr;
6067 } winpty_entry[] =
6068 {
6069 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6070 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6071 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6072 {"winpty_config_set_mouse_mode",
6073 (FARPROC*)&winpty_config_set_mouse_mode},
6074 {"winpty_config_set_initial_size",
6075 (FARPROC*)&winpty_config_set_initial_size},
6076 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6077 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6078 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6079 {"winpty_free", (FARPROC*)&winpty_free},
6080 {"winpty_open", (FARPROC*)&winpty_open},
6081 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6082 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6083 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6084 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6085 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6086 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6087 {NULL, NULL}
6088 };
6089
6090 /* No need to initialize twice. */
6091 if (hWinPtyDLL)
6092 return OK;
6093 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6094 * winpty.dll. */
6095 if (*p_winptydll != NUL)
6096 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6097 if (!hWinPtyDLL)
6098 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6099 if (!hWinPtyDLL)
6100 {
6101 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006102 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006103 : (char_u *)WINPTY_DLL);
6104 return FAIL;
6105 }
6106 for (i = 0; winpty_entry[i].name != NULL
6107 && winpty_entry[i].ptr != NULL; ++i)
6108 {
6109 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6110 winpty_entry[i].name)) == NULL)
6111 {
6112 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006113 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006114 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006115 return FAIL;
6116 }
6117 }
6118
6119 return OK;
6120}
6121
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006122 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006123winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006124 term_T *term,
6125 typval_T *argvar,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006126 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006127 jobopt_T *opt,
6128 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006129{
6130 WCHAR *cmd_wchar = NULL;
6131 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006132 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006133 channel_T *channel = NULL;
6134 job_T *job = NULL;
6135 DWORD error;
6136 HANDLE jo = NULL;
6137 HANDLE child_process_handle;
6138 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006139 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006140 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006141 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006142 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006143
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006144 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6145 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006146
6147 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006148 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006149 cmd = argvar->vval.v_string;
6150 }
6151 else if (argvar->v_type == VAR_LIST)
6152 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006153 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006154 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006155 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006156 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006157 if (cmd == NULL || *cmd == NUL)
6158 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006159 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006160 goto failed;
6161 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006162
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006163 term->tl_arg0_cmd = vim_strsave(cmd);
6164
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006165 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006166 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006167 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006168 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006169 if (opt->jo_cwd != NULL)
6170 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006171
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006172 win32_build_env(opt->jo_env, &ga_env, TRUE);
6173 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006174
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006175 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6176 if (term->tl_winpty_config == NULL)
6177 goto failed;
6178
6179 winpty_config_set_mouse_mode(term->tl_winpty_config,
6180 WINPTY_MOUSE_MODE_FORCE);
6181 winpty_config_set_initial_size(term->tl_winpty_config,
6182 term->tl_cols, term->tl_rows);
6183 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6184 if (term->tl_winpty == NULL)
6185 goto failed;
6186
6187 spawn_config = winpty_spawn_config_new(
6188 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6189 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6190 NULL,
6191 cmd_wchar,
6192 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006193 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006194 &winpty_err);
6195 if (spawn_config == NULL)
6196 goto failed;
6197
6198 channel = add_channel();
6199 if (channel == NULL)
6200 goto failed;
6201
6202 job = job_alloc();
6203 if (job == NULL)
6204 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006205 if (argvar->v_type == VAR_STRING)
6206 {
6207 int argc;
6208
6209 build_argv_from_string(cmd, &job->jv_argv, &argc);
6210 }
6211 else
6212 {
6213 int argc;
6214
6215 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6216 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006217
6218 if (opt->jo_set & JO_IN_BUF)
6219 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6220
6221 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6222 &child_thread_handle, &error, &winpty_err))
6223 goto failed;
6224
6225 channel_set_pipes(channel,
6226 (sock_T)CreateFileW(
6227 winpty_conin_name(term->tl_winpty),
6228 GENERIC_WRITE, 0, NULL,
6229 OPEN_EXISTING, 0, NULL),
6230 (sock_T)CreateFileW(
6231 winpty_conout_name(term->tl_winpty),
6232 GENERIC_READ, 0, NULL,
6233 OPEN_EXISTING, 0, NULL),
6234 (sock_T)CreateFileW(
6235 winpty_conerr_name(term->tl_winpty),
6236 GENERIC_READ, 0, NULL,
6237 OPEN_EXISTING, 0, NULL));
6238
6239 /* Write lines with CR instead of NL. */
6240 channel->ch_write_text_mode = TRUE;
6241
6242 jo = CreateJobObject(NULL, NULL);
6243 if (jo == NULL)
6244 goto failed;
6245
6246 if (!AssignProcessToJobObject(jo, child_process_handle))
6247 {
6248 /* Failed, switch the way to terminate process with TerminateProcess. */
6249 CloseHandle(jo);
6250 jo = NULL;
6251 }
6252
6253 winpty_spawn_config_free(spawn_config);
6254 vim_free(cmd_wchar);
6255 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006256 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006257
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006258 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6259 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006260
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006261#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6262 if (opt->jo_set2 & JO2_ANSI_COLORS)
6263 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6264 else
6265 init_vterm_ansi_colors(term->tl_vterm);
6266#endif
6267
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006268 channel_set_job(channel, job, opt);
6269 job_set_options(job, opt);
6270
6271 job->jv_channel = channel;
6272 job->jv_proc_info.hProcess = child_process_handle;
6273 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6274 job->jv_job_object = jo;
6275 job->jv_status = JOB_STARTED;
6276 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006277 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006278 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006279 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006280 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006281 ++job->jv_refcount;
6282 term->tl_job = job;
6283
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006284 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6285 * open the file here and handle it in. opt->jo_io was changed in
6286 * setup_job_options(), use the original flags here. */
6287 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6288 {
6289 char_u *fname = opt->jo_io_name[PART_OUT];
6290
6291 ch_log(channel, "Opening output file %s", fname);
6292 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6293 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006294 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006295 }
6296
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006297 return OK;
6298
6299failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006300 ga_clear(&ga_cmd);
6301 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006302 vim_free(cmd_wchar);
6303 vim_free(cwd_wchar);
6304 if (spawn_config != NULL)
6305 winpty_spawn_config_free(spawn_config);
6306 if (channel != NULL)
6307 channel_clear(channel);
6308 if (job != NULL)
6309 {
6310 job->jv_channel = NULL;
6311 job_cleanup(job);
6312 }
6313 term->tl_job = NULL;
6314 if (jo != NULL)
6315 CloseHandle(jo);
6316 if (term->tl_winpty != NULL)
6317 winpty_free(term->tl_winpty);
6318 term->tl_winpty = NULL;
6319 if (term->tl_winpty_config != NULL)
6320 winpty_config_free(term->tl_winpty_config);
6321 term->tl_winpty_config = NULL;
6322 if (winpty_err != NULL)
6323 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006324 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006325 (short_u *)winpty_error_msg(winpty_err), NULL);
6326
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006327 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006328 winpty_error_free(winpty_err);
6329 }
6330 return FAIL;
6331}
6332
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006333/*
6334 * Create a new terminal of "rows" by "cols" cells.
6335 * Store a reference in "term".
6336 * Return OK or FAIL.
6337 */
6338 static int
6339term_and_job_init(
6340 term_T *term,
6341 typval_T *argvar,
6342 char **argv UNUSED,
6343 jobopt_T *opt,
6344 jobopt_T *orig_opt)
6345{
6346 int use_winpty = FALSE;
6347 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006348 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006349
6350 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6351 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6352
6353 if (!has_winpty && !has_conpty)
6354 // If neither is available give the errors for winpty, since when
6355 // conpty is not available it can't be installed either.
6356 return dyn_winpty_init(TRUE);
6357
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006358 if (opt->jo_tty_type != NUL)
6359 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006360
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006361 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006362 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006363 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006364 use_conpty = TRUE;
6365 else if (has_winpty)
6366 use_winpty = TRUE;
6367 // else: error
6368 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006369 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006370 {
6371 if (has_winpty)
6372 use_winpty = TRUE;
6373 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006374 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006375 {
6376 if (has_conpty)
6377 use_conpty = TRUE;
6378 else
6379 return dyn_conpty_init(TRUE);
6380 }
6381
6382 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006383 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006384
6385 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006386 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006387
6388 // error
6389 return dyn_winpty_init(TRUE);
6390}
6391
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006392 static int
6393create_pty_only(term_T *term, jobopt_T *options)
6394{
6395 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6396 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6397 char in_name[80], out_name[80];
6398 channel_T *channel = NULL;
6399
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006400 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6401 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006402
6403 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6404 GetCurrentProcessId(),
6405 curbuf->b_fnum);
6406 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6407 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6408 PIPE_UNLIMITED_INSTANCES,
6409 0, 0, NMPWAIT_NOWAIT, NULL);
6410 if (hPipeIn == INVALID_HANDLE_VALUE)
6411 goto failed;
6412
6413 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6414 GetCurrentProcessId(),
6415 curbuf->b_fnum);
6416 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6417 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6418 PIPE_UNLIMITED_INSTANCES,
6419 0, 0, 0, NULL);
6420 if (hPipeOut == INVALID_HANDLE_VALUE)
6421 goto failed;
6422
6423 ConnectNamedPipe(hPipeIn, NULL);
6424 ConnectNamedPipe(hPipeOut, NULL);
6425
6426 term->tl_job = job_alloc();
6427 if (term->tl_job == NULL)
6428 goto failed;
6429 ++term->tl_job->jv_refcount;
6430
6431 /* behave like the job is already finished */
6432 term->tl_job->jv_status = JOB_FINISHED;
6433
6434 channel = add_channel();
6435 if (channel == NULL)
6436 goto failed;
6437 term->tl_job->jv_channel = channel;
6438 channel->ch_keep_open = TRUE;
6439 channel->ch_named_pipe = TRUE;
6440
6441 channel_set_pipes(channel,
6442 (sock_T)hPipeIn,
6443 (sock_T)hPipeOut,
6444 (sock_T)hPipeOut);
6445 channel_set_job(channel, term->tl_job, options);
6446 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6447 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6448
6449 return OK;
6450
6451failed:
6452 if (hPipeIn != NULL)
6453 CloseHandle(hPipeIn);
6454 if (hPipeOut != NULL)
6455 CloseHandle(hPipeOut);
6456 return FAIL;
6457}
6458
6459/*
6460 * Free the terminal emulator part of "term".
6461 */
6462 static void
6463term_free_vterm(term_T *term)
6464{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006465 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006466 if (term->tl_winpty != NULL)
6467 winpty_free(term->tl_winpty);
6468 term->tl_winpty = NULL;
6469 if (term->tl_winpty_config != NULL)
6470 winpty_config_free(term->tl_winpty_config);
6471 term->tl_winpty_config = NULL;
6472 if (term->tl_vterm != NULL)
6473 vterm_free(term->tl_vterm);
6474 term->tl_vterm = NULL;
6475}
6476
6477/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006478 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006479 */
6480 static void
6481term_report_winsize(term_T *term, int rows, int cols)
6482{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006483 if (term->tl_conpty)
6484 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006485 if (term->tl_winpty)
6486 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6487}
6488
6489 int
6490terminal_enabled(void)
6491{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006492 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006493}
6494
6495# else
6496
6497/**************************************
6498 * 3. Unix-like implementation.
6499 */
6500
6501/*
6502 * Create a new terminal of "rows" by "cols" cells.
6503 * Start job for "cmd".
6504 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006505 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006506 * Return OK or FAIL.
6507 */
6508 static int
6509term_and_job_init(
6510 term_T *term,
6511 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006512 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006513 jobopt_T *opt,
6514 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006515{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006516 term->tl_arg0_cmd = NULL;
6517
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006518 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6519 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006520
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006521#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6522 if (opt->jo_set2 & JO2_ANSI_COLORS)
6523 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6524 else
6525 init_vterm_ansi_colors(term->tl_vterm);
6526#endif
6527
Bram Moolenaar13568252018-03-16 20:46:58 +01006528 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006529 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006530 if (term->tl_job != NULL)
6531 ++term->tl_job->jv_refcount;
6532
6533 return term->tl_job != NULL
6534 && term->tl_job->jv_channel != NULL
6535 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6536}
6537
6538 static int
6539create_pty_only(term_T *term, jobopt_T *opt)
6540{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006541 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6542 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006543
6544 term->tl_job = job_alloc();
6545 if (term->tl_job == NULL)
6546 return FAIL;
6547 ++term->tl_job->jv_refcount;
6548
6549 /* behave like the job is already finished */
6550 term->tl_job->jv_status = JOB_FINISHED;
6551
6552 return mch_create_pty_channel(term->tl_job, opt);
6553}
6554
6555/*
6556 * Free the terminal emulator part of "term".
6557 */
6558 static void
6559term_free_vterm(term_T *term)
6560{
6561 if (term->tl_vterm != NULL)
6562 vterm_free(term->tl_vterm);
6563 term->tl_vterm = NULL;
6564}
6565
6566/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006567 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006568 */
6569 static void
6570term_report_winsize(term_T *term, int rows, int cols)
6571{
6572 /* Use an ioctl() to report the new window size to the job. */
6573 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6574 {
6575 int fd = -1;
6576 int part;
6577
6578 for (part = PART_OUT; part < PART_COUNT; ++part)
6579 {
6580 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006581 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006582 break;
6583 }
6584 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6585 mch_signal_job(term->tl_job, (char_u *)"winch");
6586 }
6587}
6588
6589# endif
6590
6591#endif /* FEAT_TERMINAL */