blob: 6d9fb2431744db5b8e136a46b0ef8f47021719f9 [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020039 */
40
41#include "vim.h"
42
43#if defined(FEAT_TERMINAL) || defined(PROTO)
44
45#ifndef MIN
46# define MIN(x,y) ((x) < (y) ? (x) : (y))
47#endif
48#ifndef MAX
49# define MAX(x,y) ((x) > (y) ? (x) : (y))
50#endif
51
52#include "libvterm/include/vterm.h"
53
54/* This is VTermScreenCell without the characters, thus much smaller. */
55typedef struct {
56 VTermScreenCellAttrs attrs;
57 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010058 VTermColor fg;
59 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060} cellattr_T;
61
62typedef struct sb_line_S {
Bram Moolenaar29ae2232019-02-14 21:22:01 +010063 int sb_cols; // can differ per line
64 cellattr_T *sb_cells; // allocated
65 cellattr_T sb_fill_attr; // for short line
66 char_u *sb_text; // for tl_scrollback_postponed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067} sb_line_T;
68
Bram Moolenaar4f974752019-02-17 17:44:42 +010069#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010070# ifndef HPCON
71# define HPCON VOID*
72# endif
73# ifndef EXTENDED_STARTUPINFO_PRESENT
74# define EXTENDED_STARTUPINFO_PRESENT 0x00080000
75# endif
76# ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
77# define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE 0x00020016
78# endif
79typedef struct _DYN_STARTUPINFOEXW
80{
81 STARTUPINFOW StartupInfo;
82 LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
83} DYN_STARTUPINFOEXW, *PDYN_STARTUPINFOEXW;
84#endif
85
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020086/* typedef term_T in structs.h */
87struct terminal_S {
88 term_T *tl_next;
89
90 VTerm *tl_vterm;
91 job_T *tl_job;
92 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010093#if defined(FEAT_GUI)
94 int tl_system; /* when non-zero used for :!cmd output */
95 int tl_toprow; /* row with first line of system terminal */
96#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
98 /* Set when setting the size of a vterm, reset after redrawing. */
99 int tl_vterm_size_changed;
100
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200101 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
102 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200103 int tl_channel_recently_closed; // still need to handle tl_finish
104
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100105 int tl_finish;
106#define TL_FINISH_UNSET NUL
107#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
108#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
109#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200110 char_u *tl_opencmd;
111 char_u *tl_eof_chars;
112
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100113 char_u *tl_arg0_cmd; // To format the status bar
114
Bram Moolenaar4f974752019-02-17 17:44:42 +0100115#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200116 void *tl_winpty_config;
117 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200118
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100119 HPCON tl_conpty;
120 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
121
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200122 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200123#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100124#if defined(FEAT_SESSION)
125 char_u *tl_command;
126#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100127 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200128
129 /* last known vterm size */
130 int tl_rows;
131 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200132
133 char_u *tl_title; /* NULL or allocated */
134 char_u *tl_status_text; /* NULL or allocated */
135
136 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200137 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200138 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200139 int tl_dirty_snapshot; /* text updated after making snapshot */
140#ifdef FEAT_TIMERS
141 int tl_timer_set;
142 proftime_T tl_timer_due;
143#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200144 int tl_postponed_scroll; /* to be scrolled up */
145
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200146 garray_T tl_scrollback;
147 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100148 garray_T tl_scrollback_postponed;
149
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200150 cellattr_T tl_default_color;
151
Bram Moolenaard96ff162018-02-18 22:13:29 +0100152 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
153 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
154
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200155 VTermPos tl_cursor_pos;
156 int tl_cursor_visible;
157 int tl_cursor_blink;
158 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
159 char_u *tl_cursor_color; /* NULL or allocated */
160
161 int tl_using_altscreen;
162};
163
164#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
165#define TMODE_LOOP 2 /* CTRL-W N used */
166
167/*
168 * List of all active terminals.
169 */
170static term_T *first_term = NULL;
171
172/* Terminal active in terminal_loop(). */
173static term_T *in_terminal_loop = NULL;
174
Bram Moolenaar4f974752019-02-17 17:44:42 +0100175#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100176static BOOL has_winpty = FALSE;
177static BOOL has_conpty = FALSE;
178#endif
179
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200180#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
181#define KEY_BUF_LEN 200
182
183/*
184 * Functions with separate implementation for MS-Windows and Unix-like systems.
185 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200186static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200187static int create_pty_only(term_T *term, jobopt_T *opt);
188static void term_report_winsize(term_T *term, int rows, int cols);
189static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100190#ifdef FEAT_GUI
191static void update_system_term(term_T *term);
192#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100194static void handle_postponed_scrollback(term_T *term);
195
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100196/* The character that we know (or assume) that the terminal expects for the
197 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200198static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200199
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100200/* "Terminal" highlight group colors. */
201static int term_default_cterm_fg = -1;
202static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200203
Bram Moolenaard317b382018-02-08 22:33:31 +0100204/* Store the last set and the desired cursor properties, so that we only update
205 * them when needed. Doing it unnecessary may result in flicker. */
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200206static char_u *last_set_cursor_color = NULL;
207static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100208static int last_set_cursor_shape = -1;
209static int desired_cursor_shape = -1;
210static int last_set_cursor_blink = -1;
211static int desired_cursor_blink = -1;
212
213
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200214/**************************************
215 * 1. Generic code for all systems.
216 */
217
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200218 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200219cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
220{
221 if (lhs_color != NULL && rhs_color != NULL)
222 return STRCMP(lhs_color, rhs_color) == 0;
223 return lhs_color == NULL && rhs_color == NULL;
224}
225
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200226 static void
227cursor_color_copy(char_u **to_color, char_u *from_color)
228{
229 // Avoid a free & alloc if the value is already right.
230 if (cursor_color_equal(*to_color, from_color))
231 return;
232 vim_free(*to_color);
233 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
234}
235
236 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200237cursor_color_get(char_u *color)
238{
239 return (color == NULL) ? (char_u *)"" : color;
240}
241
242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200243/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200244 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200245 * current window.
246 * Sets "rows" and/or "cols" to zero when it should follow the window size.
247 * Return TRUE if the size is the minimum size: "24*80".
248 */
249 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200250parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200251{
252 int minsize = FALSE;
253
254 *rows = 0;
255 *cols = 0;
256
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200257 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200258 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200259 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200260
261 /* Syntax of value was already checked when it's set. */
262 if (p == NULL)
263 {
264 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200265 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200266 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200267 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200268 *cols = atoi((char *)p + 1);
269 }
270 return minsize;
271}
272
273/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200274 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200275 */
276 static void
277set_term_and_win_size(term_T *term)
278{
Bram Moolenaar13568252018-03-16 20:46:58 +0100279#ifdef FEAT_GUI
280 if (term->tl_system)
281 {
282 /* Use the whole screen for the system command. However, it will start
283 * at the command line and scroll up as needed, using tl_toprow. */
284 term->tl_rows = Rows;
285 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200286 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100287 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100288#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200289 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200290 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200291 if (term->tl_rows != 0)
292 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
293 if (term->tl_cols != 0)
294 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200295 }
296 if (term->tl_rows == 0)
297 term->tl_rows = curwin->w_height;
298 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200299 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 if (term->tl_cols == 0)
301 term->tl_cols = curwin->w_width;
302 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200303 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200304}
305
306/*
307 * Initialize job options for a terminal job.
308 * Caller may overrule some of them.
309 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100310 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311init_job_options(jobopt_T *opt)
312{
313 clear_job_options(opt);
314
315 opt->jo_mode = MODE_RAW;
316 opt->jo_out_mode = MODE_RAW;
317 opt->jo_err_mode = MODE_RAW;
318 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
319}
320
321/*
322 * Set job options mandatory for a terminal job.
323 */
324 static void
325setup_job_options(jobopt_T *opt, int rows, int cols)
326{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100327#ifndef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200328 /* Win32: Redirecting the job output won't work, thus always connect stdout
329 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200330 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200331#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200332 {
333 /* Connect stdout to the terminal. */
334 opt->jo_io[PART_OUT] = JIO_BUFFER;
335 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
336 opt->jo_modifiable[PART_OUT] = 0;
337 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
338 }
339
Bram Moolenaar4f974752019-02-17 17:44:42 +0100340#ifndef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200341 /* Win32: Redirecting the job output won't work, thus always connect stderr
342 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200343 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200344#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200345 {
346 /* Connect stderr to the terminal. */
347 opt->jo_io[PART_ERR] = JIO_BUFFER;
348 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
349 opt->jo_modifiable[PART_ERR] = 0;
350 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
351 }
352
353 opt->jo_pty = TRUE;
354 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
355 opt->jo_term_rows = rows;
356 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
357 opt->jo_term_cols = cols;
358}
359
360/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200361 * Flush messages on channels.
362 */
363 static void
364term_flush_messages()
365{
366 mch_check_messages();
367 parse_queued_messages();
368}
369
370/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100371 * Close a terminal buffer (and its window). Used when creating the terminal
372 * fails.
373 */
374 static void
375term_close_buffer(buf_T *buf, buf_T *old_curbuf)
376{
377 free_terminal(buf);
378 if (old_curbuf != NULL)
379 {
380 --curbuf->b_nwindows;
381 curbuf = old_curbuf;
382 curwin->w_buffer = curbuf;
383 ++curbuf->b_nwindows;
384 }
385
386 /* Wiping out the buffer will also close the window and call
387 * free_terminal(). */
388 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
389}
390
391/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200392 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100393 * Use either "argvar" or "argv", the other must be NULL.
394 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
395 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200396 * Returns NULL when failed.
397 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100398 buf_T *
399term_start(
400 typval_T *argvar,
401 char **argv,
402 jobopt_T *opt,
403 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200404{
405 exarg_T split_ea;
406 win_T *old_curwin = curwin;
407 term_T *term;
408 buf_T *old_curbuf = NULL;
409 int res;
410 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100411 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200412 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200413
414 if (check_restricted() || check_secure())
415 return NULL;
416
417 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
418 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
419 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
420 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
421 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100422 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200423 return NULL;
424 }
425
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200426 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200427 if (term == NULL)
428 return NULL;
429 term->tl_dirty_row_end = MAX_ROW;
430 term->tl_cursor_visible = TRUE;
431 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
432 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100433#ifdef FEAT_GUI
434 term->tl_system = (flags & TERM_START_SYSTEM);
435#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200436 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100437 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200438
439 vim_memset(&split_ea, 0, sizeof(split_ea));
440 if (opt->jo_curwin)
441 {
442 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100443 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200444 {
445 no_write_message();
446 vim_free(term);
447 return NULL;
448 }
449 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100450 ECMD_HIDE
451 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
452 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200453 {
454 vim_free(term);
455 return NULL;
456 }
457 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100458 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200459 {
460 buf_T *buf;
461
462 /* Create a new buffer without a window. Make it the current buffer for
463 * a moment to be able to do the initialisations. */
464 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
465 BLN_NEW | BLN_LISTED);
466 if (buf == NULL || ml_open(buf) == FAIL)
467 {
468 vim_free(term);
469 return NULL;
470 }
471 old_curbuf = curbuf;
472 --curbuf->b_nwindows;
473 curbuf = buf;
474 curwin->w_buffer = buf;
475 ++curbuf->b_nwindows;
476 }
477 else
478 {
479 /* Open a new window or tab. */
480 split_ea.cmdidx = CMD_new;
481 split_ea.cmd = (char_u *)"new";
482 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100483 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200484 {
485 split_ea.line2 = opt->jo_term_rows;
486 split_ea.addr_count = 1;
487 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100488 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200489 {
490 split_ea.line2 = opt->jo_term_cols;
491 split_ea.addr_count = 1;
492 }
493
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100494 if (vertical)
495 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200496 ex_splitview(&split_ea);
497 if (curwin == old_curwin)
498 {
499 /* split failed */
500 vim_free(term);
501 return NULL;
502 }
503 }
504 term->tl_buffer = curbuf;
505 curbuf->b_term = term;
506
507 if (!opt->jo_hidden)
508 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100509 /* Only one size was taken care of with :new, do the other one. With
510 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100511 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200512 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100513 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200514 win_setwidth(opt->jo_term_cols);
515 }
516
517 /* Link the new terminal in the list of active terminals. */
518 term->tl_next = first_term;
519 first_term = term;
520
521 if (opt->jo_term_name != NULL)
522 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100523 else if (argv != NULL)
524 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200525 else
526 {
527 int i;
528 size_t len;
529 char_u *cmd, *p;
530
531 if (argvar->v_type == VAR_STRING)
532 {
533 cmd = argvar->vval.v_string;
534 if (cmd == NULL)
535 cmd = (char_u *)"";
536 else if (STRCMP(cmd, "NONE") == 0)
537 cmd = (char_u *)"pty";
538 }
539 else if (argvar->v_type != VAR_LIST
540 || argvar->vval.v_list == NULL
541 || argvar->vval.v_list->lv_len < 1
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100542 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200543 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
544 cmd = (char_u*)"";
545
546 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200547 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200548
549 for (i = 0; p != NULL; ++i)
550 {
551 /* Prepend a ! to the command name to avoid the buffer name equals
552 * the executable, otherwise ":w!" would overwrite it. */
553 if (i == 0)
554 vim_snprintf((char *)p, len, "!%s", cmd);
555 else
556 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
557 if (buflist_findname(p) == NULL)
558 {
559 vim_free(curbuf->b_ffname);
560 curbuf->b_ffname = p;
561 break;
562 }
563 }
564 }
565 curbuf->b_fname = curbuf->b_ffname;
566
567 if (opt->jo_term_opencmd != NULL)
568 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
569
570 if (opt->jo_eof_chars != NULL)
571 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
572
573 set_string_option_direct((char_u *)"buftype", -1,
574 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200575 // Avoid that 'buftype' is reset when this buffer is entered.
576 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200577
578 /* Mark the buffer as not modifiable. It can only be made modifiable after
579 * the job finished. */
580 curbuf->b_p_ma = FALSE;
581
582 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100583#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200584 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
585#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200586 setup_job_options(opt, term->tl_rows, term->tl_cols);
587
Bram Moolenaar13568252018-03-16 20:46:58 +0100588 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100589 return curbuf;
590
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100591#if defined(FEAT_SESSION)
592 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100593 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100594 {
595 term->tl_command = vim_strsave((char_u *)"NONE");
596 }
597 else if (argvar->v_type == VAR_STRING)
598 {
599 char_u *cmd = argvar->vval.v_string;
600
601 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
602 term->tl_command = vim_strsave(cmd);
603 }
604 else if (argvar->v_type == VAR_LIST
605 && argvar->vval.v_list != NULL
606 && argvar->vval.v_list->lv_len > 0)
607 {
608 garray_T ga;
609 listitem_T *item;
610
611 ga_init2(&ga, 1, 100);
612 for (item = argvar->vval.v_list->lv_first;
613 item != NULL; item = item->li_next)
614 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100615 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100616 char_u *p;
617
618 if (s == NULL)
619 break;
620 p = vim_strsave_fnameescape(s, FALSE);
621 if (p == NULL)
622 break;
623 ga_concat(&ga, p);
624 vim_free(p);
625 ga_append(&ga, ' ');
626 }
627 if (item == NULL)
628 {
629 ga_append(&ga, NUL);
630 term->tl_command = ga.ga_data;
631 }
632 else
633 ga_clear(&ga);
634 }
635#endif
636
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100637 if (opt->jo_term_kill != NULL)
638 {
639 char_u *p = skiptowhite(opt->jo_term_kill);
640
641 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
642 }
643
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200644 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100645 if (argv == NULL
646 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200647 && argvar->vval.v_string != NULL
648 && STRCMP(argvar->vval.v_string, "NONE") == 0)
649 res = create_pty_only(term, opt);
650 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200651 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200652
653 newbuf = curbuf;
654 if (res == OK)
655 {
656 /* Get and remember the size we ended up with. Update the pty. */
657 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
658 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100659#ifdef FEAT_GUI
660 if (term->tl_system)
661 {
662 /* display first line below typed command */
663 term->tl_toprow = msg_row + 1;
664 term->tl_dirty_row_end = 0;
665 }
666#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200667
668 /* Make sure we don't get stuck on sending keys to the job, it leads to
669 * a deadlock if the job is waiting for Vim to read. */
670 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
671
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200672 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200673 {
674 --curbuf->b_nwindows;
675 curbuf = old_curbuf;
676 curwin->w_buffer = curbuf;
677 ++curbuf->b_nwindows;
678 }
679 }
680 else
681 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100682 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200683 return NULL;
684 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100685
Bram Moolenaar13568252018-03-16 20:46:58 +0100686 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200687 return newbuf;
688}
689
690/*
691 * ":terminal": open a terminal window and execute a job in it.
692 */
693 void
694ex_terminal(exarg_T *eap)
695{
696 typval_T argvar[2];
697 jobopt_T opt;
698 char_u *cmd;
699 char_u *tofree = NULL;
700
701 init_job_options(&opt);
702
703 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100704 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200705 {
706 char_u *p, *ep;
707
708 cmd += 2;
709 p = skiptowhite(cmd);
710 ep = vim_strchr(cmd, '=');
711 if (ep != NULL && ep < p)
712 p = ep;
713
714 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
715 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100716 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
717 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200718 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
719 opt.jo_term_finish = 'o';
720 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
721 opt.jo_curwin = 1;
722 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
723 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100724 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
725 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100726 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
727 && ep != NULL)
728 {
729 opt.jo_set2 |= JO2_TERM_KILL;
730 opt.jo_term_kill = ep + 1;
731 p = skiptowhite(cmd);
732 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200733 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
734 && ep != NULL && isdigit(ep[1]))
735 {
736 opt.jo_set2 |= JO2_TERM_ROWS;
737 opt.jo_term_rows = atoi((char *)ep + 1);
738 p = skiptowhite(cmd);
739 }
740 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
741 && ep != NULL && isdigit(ep[1]))
742 {
743 opt.jo_set2 |= JO2_TERM_COLS;
744 opt.jo_term_cols = atoi((char *)ep + 1);
745 p = skiptowhite(cmd);
746 }
747 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
748 && ep != NULL)
749 {
750 char_u *buf = NULL;
751 char_u *keys;
752
753 p = skiptowhite(cmd);
754 *p = NUL;
755 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
756 opt.jo_set2 |= JO2_EOF_CHARS;
757 opt.jo_eof_chars = vim_strsave(keys);
758 vim_free(buf);
759 *p = ' ';
760 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100761#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100762 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
763 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100764 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100765 int tty_type = NUL;
766
767 p = skiptowhite(cmd);
768 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
769 tty_type = 'w';
770 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
771 tty_type = 'c';
772 else
773 {
774 semsg(e_invargval, "type");
775 goto theend;
776 }
777 opt.jo_set2 |= JO2_TTY_TYPE;
778 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100779 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100780#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200781 else
782 {
783 if (*p)
784 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100785 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100786 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200787 }
788 cmd = skipwhite(p);
789 }
790 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100791 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200792 /* Make a copy of 'shell', an autocommand may change the option. */
793 tofree = cmd = vim_strsave(p_sh);
794
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100795 /* default to close when the shell exits */
796 if (opt.jo_term_finish == NUL)
797 opt.jo_term_finish = 'c';
798 }
799
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200800 if (eap->addr_count > 0)
801 {
802 /* Write lines from current buffer to the job. */
803 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
804 opt.jo_io[PART_IN] = JIO_BUFFER;
805 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
806 opt.jo_in_top = eap->line1;
807 opt.jo_in_bot = eap->line2;
808 }
809
810 argvar[0].v_type = VAR_STRING;
811 argvar[0].vval.v_string = cmd;
812 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100813 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200814 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100815
816theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200817 vim_free(opt.jo_eof_chars);
818}
819
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100820#if defined(FEAT_SESSION) || defined(PROTO)
821/*
822 * Write a :terminal command to the session file to restore the terminal in
823 * window "wp".
824 * Return FAIL if writing fails.
825 */
826 int
827term_write_session(FILE *fd, win_T *wp)
828{
829 term_T *term = wp->w_buffer->b_term;
830
831 /* Create the terminal and run the command. This is not without
832 * risk, but let's assume the user only creates a session when this
833 * will be OK. */
834 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
835 term->tl_cols, term->tl_rows) < 0)
836 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100837#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100838 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
839 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100840#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100841 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
842 return FAIL;
843
844 return put_eol(fd);
845}
846
847/*
848 * Return TRUE if "buf" has a terminal that should be restored.
849 */
850 int
851term_should_restore(buf_T *buf)
852{
853 term_T *term = buf->b_term;
854
855 return term != NULL && (term->tl_command == NULL
856 || STRCMP(term->tl_command, "NONE") != 0);
857}
858#endif
859
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200860/*
861 * Free the scrollback buffer for "term".
862 */
863 static void
864free_scrollback(term_T *term)
865{
866 int i;
867
868 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
869 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
870 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100871 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
872 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
873 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200874}
875
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100876
877// Terminals that need to be freed soon.
878term_T *terminals_to_free = NULL;
879
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200880/*
881 * Free a terminal and everything it refers to.
882 * Kills the job if there is one.
883 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100884 * The actual terminal structure is freed later in free_unused_terminals(),
885 * because callbacks may wipe out a buffer while the terminal is still
886 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200887 */
888 void
889free_terminal(buf_T *buf)
890{
891 term_T *term = buf->b_term;
892 term_T *tp;
893
894 if (term == NULL)
895 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100896
897 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200898 if (first_term == term)
899 first_term = term->tl_next;
900 else
901 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
902 if (tp->tl_next == term)
903 {
904 tp->tl_next = term->tl_next;
905 break;
906 }
907
908 if (term->tl_job != NULL)
909 {
910 if (term->tl_job->jv_status != JOB_ENDED
911 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100912 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200913 job_stop(term->tl_job, NULL, "kill");
914 job_unref(term->tl_job);
915 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100916 term->tl_next = terminals_to_free;
917 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200918
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200919 buf->b_term = NULL;
920 if (in_terminal_loop == term)
921 in_terminal_loop = NULL;
922}
923
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100924 void
925free_unused_terminals()
926{
927 while (terminals_to_free != NULL)
928 {
929 term_T *term = terminals_to_free;
930
931 terminals_to_free = term->tl_next;
932
933 free_scrollback(term);
934
935 term_free_vterm(term);
936 vim_free(term->tl_title);
937#ifdef FEAT_SESSION
938 vim_free(term->tl_command);
939#endif
940 vim_free(term->tl_kill);
941 vim_free(term->tl_status_text);
942 vim_free(term->tl_opencmd);
943 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100944 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100945#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100946 if (term->tl_out_fd != NULL)
947 fclose(term->tl_out_fd);
948#endif
949 vim_free(term->tl_cursor_color);
950 vim_free(term);
951 }
952}
953
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200954/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100955 * Get the part that is connected to the tty. Normally this is PART_IN, but
956 * when writing buffer lines to the job it can be another. This makes it
957 * possible to do "1,5term vim -".
958 */
959 static ch_part_T
960get_tty_part(term_T *term)
961{
962#ifdef UNIX
963 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
964 int i;
965
966 for (i = 0; i < 3; ++i)
967 {
968 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
969
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +0100970 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100971 return parts[i];
972 }
973#endif
974 return PART_IN;
975}
976
977/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200978 * Write job output "msg[len]" to the vterm.
979 */
980 static void
981term_write_job_output(term_T *term, char_u *msg, size_t len)
982{
983 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100984 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200985
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100986 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200987
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100988 /* flush vterm buffer when vterm responded to control sequence */
989 if (prevlen != vterm_output_get_buffer_current(vterm))
990 {
991 char buf[KEY_BUF_LEN];
992 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
993
994 if (curlen > 0)
995 channel_send(term->tl_job->jv_channel, get_tty_part(term),
996 (char_u *)buf, (int)curlen, NULL);
997 }
998
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200999 /* this invokes the damage callbacks */
1000 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1001}
1002
1003 static void
1004update_cursor(term_T *term, int redraw)
1005{
1006 if (term->tl_normal_mode)
1007 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001008#ifdef FEAT_GUI
1009 if (term->tl_system)
1010 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1011 term->tl_cursor_pos.col);
1012 else
1013#endif
1014 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001015 if (redraw)
1016 {
1017 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1018 cursor_on();
1019 out_flush();
1020#ifdef FEAT_GUI
1021 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001022 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001023 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001024 gui_mch_flush();
1025 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001026#endif
1027 }
1028}
1029
1030/*
1031 * Invoked when "msg" output from a job was received. Write it to the terminal
1032 * of "buffer".
1033 */
1034 void
1035write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1036{
1037 size_t len = STRLEN(msg);
1038 term_T *term = buffer->b_term;
1039
Bram Moolenaar4f974752019-02-17 17:44:42 +01001040#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001041 /* Win32: Cannot redirect output of the job, intercept it here and write to
1042 * the file. */
1043 if (term->tl_out_fd != NULL)
1044 {
1045 ch_log(channel, "Writing %d bytes to output file", (int)len);
1046 fwrite(msg, len, 1, term->tl_out_fd);
1047 return;
1048 }
1049#endif
1050
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001051 if (term->tl_vterm == NULL)
1052 {
1053 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1054 return;
1055 }
1056 ch_log(channel, "writing %d bytes to terminal", (int)len);
1057 term_write_job_output(term, msg, len);
1058
Bram Moolenaar13568252018-03-16 20:46:58 +01001059#ifdef FEAT_GUI
1060 if (term->tl_system)
1061 {
1062 /* show system output, scrolling up the screen as needed */
1063 update_system_term(term);
1064 update_cursor(term, TRUE);
1065 }
1066 else
1067#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001068 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
1069 * contents, thus no screen update is needed. */
1070 if (!term->tl_normal_mode)
1071 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001072 // Don't use update_screen() when editing the command line, it gets
1073 // cleared.
1074 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001075 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001076 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001077 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001078 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001079 /* update_screen() can be slow, check the terminal wasn't closed
1080 * already */
1081 if (buffer == curbuf && curbuf->b_term != NULL)
1082 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001083 }
1084 else
1085 redraw_after_callback(TRUE);
1086 }
1087}
1088
1089/*
1090 * Send a mouse position and click to the vterm
1091 */
1092 static int
1093term_send_mouse(VTerm *vterm, int button, int pressed)
1094{
1095 VTermModifier mod = VTERM_MOD_NONE;
1096
1097 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001098 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001099 if (button != 0)
1100 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001101 return TRUE;
1102}
1103
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001104static int enter_mouse_col = -1;
1105static int enter_mouse_row = -1;
1106
1107/*
1108 * Handle a mouse click, drag or release.
1109 * Return TRUE when a mouse event is sent to the terminal.
1110 */
1111 static int
1112term_mouse_click(VTerm *vterm, int key)
1113{
1114#if defined(FEAT_CLIPBOARD)
1115 /* For modeless selection mouse drag and release events are ignored, unless
1116 * they are preceded with a mouse down event */
1117 static int ignore_drag_release = TRUE;
1118 VTermMouseState mouse_state;
1119
1120 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1121 if (mouse_state.flags == 0)
1122 {
1123 /* Terminal is not using the mouse, use modeless selection. */
1124 switch (key)
1125 {
1126 case K_LEFTDRAG:
1127 case K_LEFTRELEASE:
1128 case K_RIGHTDRAG:
1129 case K_RIGHTRELEASE:
1130 /* Ignore drag and release events when the button-down wasn't
1131 * seen before. */
1132 if (ignore_drag_release)
1133 {
1134 int save_mouse_col, save_mouse_row;
1135
1136 if (enter_mouse_col < 0)
1137 break;
1138
1139 /* mouse click in the window gave us focus, handle that
1140 * click now */
1141 save_mouse_col = mouse_col;
1142 save_mouse_row = mouse_row;
1143 mouse_col = enter_mouse_col;
1144 mouse_row = enter_mouse_row;
1145 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1146 mouse_col = save_mouse_col;
1147 mouse_row = save_mouse_row;
1148 }
1149 /* FALLTHROUGH */
1150 case K_LEFTMOUSE:
1151 case K_RIGHTMOUSE:
1152 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1153 ignore_drag_release = TRUE;
1154 else
1155 ignore_drag_release = FALSE;
1156 /* Should we call mouse_has() here? */
1157 if (clip_star.available)
1158 {
1159 int button, is_click, is_drag;
1160
1161 button = get_mouse_button(KEY2TERMCAP1(key),
1162 &is_click, &is_drag);
1163 if (mouse_model_popup() && button == MOUSE_LEFT
1164 && (mod_mask & MOD_MASK_SHIFT))
1165 {
1166 /* Translate shift-left to right button. */
1167 button = MOUSE_RIGHT;
1168 mod_mask &= ~MOD_MASK_SHIFT;
1169 }
1170 clip_modeless(button, is_click, is_drag);
1171 }
1172 break;
1173
1174 case K_MIDDLEMOUSE:
1175 if (clip_star.available)
1176 insert_reg('*', TRUE);
1177 break;
1178 }
1179 enter_mouse_col = -1;
1180 return FALSE;
1181 }
1182#endif
1183 enter_mouse_col = -1;
1184
1185 switch (key)
1186 {
1187 case K_LEFTMOUSE:
1188 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1189 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1190 case K_LEFTRELEASE:
1191 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1192 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1193 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1194 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1195 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1196 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1197 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1198 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1199 }
1200 return TRUE;
1201}
1202
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001203/*
1204 * Convert typed key "c" into bytes to send to the job.
1205 * Return the number of bytes in "buf".
1206 */
1207 static int
1208term_convert_key(term_T *term, int c, char *buf)
1209{
1210 VTerm *vterm = term->tl_vterm;
1211 VTermKey key = VTERM_KEY_NONE;
1212 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001213 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001214
1215 switch (c)
1216 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001217 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1218
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001219 /* don't use VTERM_KEY_BACKSPACE, it always
1220 * becomes 0x7f DEL */
1221 case K_BS: c = term_backspace_char; break;
1222
1223 case ESC: key = VTERM_KEY_ESCAPE; break;
1224 case K_DEL: key = VTERM_KEY_DEL; break;
1225 case K_DOWN: key = VTERM_KEY_DOWN; break;
1226 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1227 key = VTERM_KEY_DOWN; break;
1228 case K_END: key = VTERM_KEY_END; break;
1229 case K_S_END: mod = VTERM_MOD_SHIFT;
1230 key = VTERM_KEY_END; break;
1231 case K_C_END: mod = VTERM_MOD_CTRL;
1232 key = VTERM_KEY_END; break;
1233 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1234 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1235 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1236 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1237 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1238 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1239 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1240 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1241 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1242 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1243 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1244 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1245 case K_HOME: key = VTERM_KEY_HOME; break;
1246 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1247 key = VTERM_KEY_HOME; break;
1248 case K_C_HOME: mod = VTERM_MOD_CTRL;
1249 key = VTERM_KEY_HOME; break;
1250 case K_INS: key = VTERM_KEY_INS; break;
1251 case K_K0: key = VTERM_KEY_KP_0; break;
1252 case K_K1: key = VTERM_KEY_KP_1; break;
1253 case K_K2: key = VTERM_KEY_KP_2; break;
1254 case K_K3: key = VTERM_KEY_KP_3; break;
1255 case K_K4: key = VTERM_KEY_KP_4; break;
1256 case K_K5: key = VTERM_KEY_KP_5; break;
1257 case K_K6: key = VTERM_KEY_KP_6; break;
1258 case K_K7: key = VTERM_KEY_KP_7; break;
1259 case K_K8: key = VTERM_KEY_KP_8; break;
1260 case K_K9: key = VTERM_KEY_KP_9; break;
1261 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1262 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1263 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1264 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1265 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1266 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1267 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1268 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1269 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1270 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1271 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1272 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1273 case K_LEFT: key = VTERM_KEY_LEFT; break;
1274 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1275 key = VTERM_KEY_LEFT; break;
1276 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1277 key = VTERM_KEY_LEFT; break;
1278 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1279 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1280 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1281 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1282 key = VTERM_KEY_RIGHT; break;
1283 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1284 key = VTERM_KEY_RIGHT; break;
1285 case K_UP: key = VTERM_KEY_UP; break;
1286 case K_S_UP: mod = VTERM_MOD_SHIFT;
1287 key = VTERM_KEY_UP; break;
1288 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001289 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1290 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001291
Bram Moolenaara42ad572017-11-16 13:08:04 +01001292 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1293 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001294 case K_MOUSELEFT: /* TODO */ return 0;
1295 case K_MOUSERIGHT: /* TODO */ return 0;
1296
1297 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001298 case K_LEFTMOUSE_NM:
1299 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001300 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001301 case K_LEFTRELEASE_NM:
1302 case K_MOUSEMOVE:
1303 case K_MIDDLEMOUSE:
1304 case K_MIDDLEDRAG:
1305 case K_MIDDLERELEASE:
1306 case K_RIGHTMOUSE:
1307 case K_RIGHTDRAG:
1308 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1309 return 0;
1310 other = TRUE;
1311 break;
1312
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001313 case K_X1MOUSE: /* TODO */ return 0;
1314 case K_X1DRAG: /* TODO */ return 0;
1315 case K_X1RELEASE: /* TODO */ return 0;
1316 case K_X2MOUSE: /* TODO */ return 0;
1317 case K_X2DRAG: /* TODO */ return 0;
1318 case K_X2RELEASE: /* TODO */ return 0;
1319
1320 case K_IGNORE: return 0;
1321 case K_NOP: return 0;
1322 case K_UNDO: return 0;
1323 case K_HELP: return 0;
1324 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1325 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1326 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1327 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1328 case K_SELECT: return 0;
1329#ifdef FEAT_GUI
1330 case K_VER_SCROLLBAR: return 0;
1331 case K_HOR_SCROLLBAR: return 0;
1332#endif
1333#ifdef FEAT_GUI_TABLINE
1334 case K_TABLINE: return 0;
1335 case K_TABMENU: return 0;
1336#endif
1337#ifdef FEAT_NETBEANS_INTG
1338 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1339#endif
1340#ifdef FEAT_DND
1341 case K_DROP: return 0;
1342#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001343 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001344 case K_PS: vterm_keyboard_start_paste(vterm);
1345 other = TRUE;
1346 break;
1347 case K_PE: vterm_keyboard_end_paste(vterm);
1348 other = TRUE;
1349 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001350 }
1351
1352 /*
1353 * Convert special keys to vterm keys:
1354 * - Write keys to vterm: vterm_keyboard_key()
1355 * - Write output to channel.
1356 * TODO: use mod_mask
1357 */
1358 if (key != VTERM_KEY_NONE)
1359 /* Special key, let vterm convert it. */
1360 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001361 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001362 /* Normal character, let vterm convert it. */
1363 vterm_keyboard_unichar(vterm, c, mod);
1364
1365 /* Read back the converted escape sequence. */
1366 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1367}
1368
1369/*
1370 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001371 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001372 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001373 */
1374 static int
1375term_job_running_check(term_T *term, int check_job_status)
1376{
1377 /* Also consider the job finished when the channel is closed, to avoid a
1378 * race condition when updating the title. */
1379 if (term != NULL
1380 && term->tl_job != NULL
1381 && channel_is_open(term->tl_job->jv_channel))
1382 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001383 job_T *job = term->tl_job;
1384
1385 // Careful: Checking the job status may invoked callbacks, which close
1386 // the buffer and terminate "term". However, "job" will not be freed
1387 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001388 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001389 job_status(job);
1390 return (job->jv_status == JOB_STARTED
1391 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001392 }
1393 return FALSE;
1394}
1395
1396/*
1397 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001398 */
1399 int
1400term_job_running(term_T *term)
1401{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001402 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001403}
1404
1405/*
1406 * Return TRUE if "term" has an active channel and used ":term NONE".
1407 */
1408 int
1409term_none_open(term_T *term)
1410{
1411 /* Also consider the job finished when the channel is closed, to avoid a
1412 * race condition when updating the title. */
1413 return term != NULL
1414 && term->tl_job != NULL
1415 && channel_is_open(term->tl_job->jv_channel)
1416 && term->tl_job->jv_channel->ch_keep_open;
1417}
1418
1419/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001420 * Used when exiting: kill the job in "buf" if so desired.
1421 * Return OK when the job finished.
1422 * Return FAIL when the job is still running.
1423 */
1424 int
1425term_try_stop_job(buf_T *buf)
1426{
1427 int count;
1428 char *how = (char *)buf->b_term->tl_kill;
1429
1430#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1431 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1432 {
1433 char_u buff[DIALOG_MSG_SIZE];
1434 int ret;
1435
1436 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1437 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1438 if (ret == VIM_YES)
1439 how = "kill";
1440 else if (ret == VIM_CANCEL)
1441 return FAIL;
1442 }
1443#endif
1444 if (how == NULL || *how == NUL)
1445 return FAIL;
1446
1447 job_stop(buf->b_term->tl_job, NULL, how);
1448
Bram Moolenaar9172d232019-01-29 23:06:54 +01001449 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001450 for (count = 0; count < 100; ++count)
1451 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001452 job_T *job;
1453
1454 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001455 if (!buf_valid(buf)
1456 || buf->b_term == NULL
1457 || buf->b_term->tl_job == NULL)
1458 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001459 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001460
Bram Moolenaar9172d232019-01-29 23:06:54 +01001461 // Call job_status() to update jv_status. It may cause the job to be
1462 // cleaned up but it won't be freed.
1463 job_status(job);
1464 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001465 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001466
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001467 ui_delay(10L, FALSE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001468 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001469 }
1470 return FAIL;
1471}
1472
1473/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001474 * Add the last line of the scrollback buffer to the buffer in the window.
1475 */
1476 static void
1477add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1478{
1479 buf_T *buf = term->tl_buffer;
1480 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1481 linenr_T lnum = buf->b_ml.ml_line_count;
1482
Bram Moolenaar4f974752019-02-17 17:44:42 +01001483#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001484 if (!enc_utf8 && enc_codepage > 0)
1485 {
1486 WCHAR *ret = NULL;
1487 int length = 0;
1488
1489 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1490 &ret, &length);
1491 if (ret != NULL)
1492 {
1493 WideCharToMultiByte_alloc(enc_codepage, 0,
1494 ret, length, (char **)&text, &len, 0, 0);
1495 vim_free(ret);
1496 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1497 vim_free(text);
1498 }
1499 }
1500 else
1501#endif
1502 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1503 if (empty)
1504 {
1505 /* Delete the empty line that was in the empty buffer. */
1506 curbuf = buf;
1507 ml_delete(1, FALSE);
1508 curbuf = curwin->w_buffer;
1509 }
1510}
1511
1512 static void
1513cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1514{
1515 attr->width = cell->width;
1516 attr->attrs = cell->attrs;
1517 attr->fg = cell->fg;
1518 attr->bg = cell->bg;
1519}
1520
1521 static int
1522equal_celattr(cellattr_T *a, cellattr_T *b)
1523{
1524 /* Comparing the colors should be sufficient. */
1525 return a->fg.red == b->fg.red
1526 && a->fg.green == b->fg.green
1527 && a->fg.blue == b->fg.blue
1528 && a->bg.red == b->bg.red
1529 && a->bg.green == b->bg.green
1530 && a->bg.blue == b->bg.blue;
1531}
1532
Bram Moolenaard96ff162018-02-18 22:13:29 +01001533/*
1534 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1535 * line at this position. Otherwise at the end.
1536 */
1537 static int
1538add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1539{
1540 if (ga_grow(&term->tl_scrollback, 1) == OK)
1541 {
1542 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1543 + term->tl_scrollback.ga_len;
1544
1545 if (lnum > 0)
1546 {
1547 int i;
1548
1549 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1550 {
1551 *line = *(line - 1);
1552 --line;
1553 }
1554 }
1555 line->sb_cols = 0;
1556 line->sb_cells = NULL;
1557 line->sb_fill_attr = *fill_attr;
1558 ++term->tl_scrollback.ga_len;
1559 return OK;
1560 }
1561 return FALSE;
1562}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001563
1564/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001565 * Remove the terminal contents from the scrollback and the buffer.
1566 * Used before adding a new scrollback line or updating the buffer for lines
1567 * displayed in the terminal.
1568 */
1569 static void
1570cleanup_scrollback(term_T *term)
1571{
1572 sb_line_T *line;
1573 garray_T *gap;
1574
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001575 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001576 gap = &term->tl_scrollback;
1577 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1578 && gap->ga_len > 0)
1579 {
1580 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1581 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1582 vim_free(line->sb_cells);
1583 --gap->ga_len;
1584 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001585 curbuf = curwin->w_buffer;
1586 if (curbuf == term->tl_buffer)
1587 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001588}
1589
1590/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001591 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001592 */
1593 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001594update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001595{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001596 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001597 int len;
1598 int lines_skipped = 0;
1599 VTermPos pos;
1600 VTermScreenCell cell;
1601 cellattr_T fill_attr, new_fill_attr;
1602 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001603
1604 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1605 "Adding terminal window snapshot to buffer");
1606
1607 /* First remove the lines that were appended before, they might be
1608 * outdated. */
1609 cleanup_scrollback(term);
1610
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001611 screen = vterm_obtain_screen(term->tl_vterm);
1612 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001613 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1614 {
1615 len = 0;
1616 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1617 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1618 && cell.chars[0] != NUL)
1619 {
1620 len = pos.col + 1;
1621 new_fill_attr = term->tl_default_color;
1622 }
1623 else
1624 /* Assume the last attr is the filler attr. */
1625 cell2cellattr(&cell, &new_fill_attr);
1626
1627 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1628 ++lines_skipped;
1629 else
1630 {
1631 while (lines_skipped > 0)
1632 {
1633 /* Line was skipped, add an empty line. */
1634 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001635 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001636 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001637 }
1638
1639 if (len == 0)
1640 p = NULL;
1641 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001642 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001643 if ((p != NULL || len == 0)
1644 && ga_grow(&term->tl_scrollback, 1) == OK)
1645 {
1646 garray_T ga;
1647 int width;
1648 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1649 + term->tl_scrollback.ga_len;
1650
1651 ga_init2(&ga, 1, 100);
1652 for (pos.col = 0; pos.col < len; pos.col += width)
1653 {
1654 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1655 {
1656 width = 1;
1657 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1658 if (ga_grow(&ga, 1) == OK)
1659 ga.ga_len += utf_char2bytes(' ',
1660 (char_u *)ga.ga_data + ga.ga_len);
1661 }
1662 else
1663 {
1664 width = cell.width;
1665
1666 cell2cellattr(&cell, &p[pos.col]);
1667
Bram Moolenaara79fd562018-12-20 20:47:32 +01001668 // Each character can be up to 6 bytes.
1669 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001670 {
1671 int i;
1672 int c;
1673
1674 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1675 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1676 (char_u *)ga.ga_data + ga.ga_len);
1677 }
1678 }
1679 }
1680 line->sb_cols = len;
1681 line->sb_cells = p;
1682 line->sb_fill_attr = new_fill_attr;
1683 fill_attr = new_fill_attr;
1684 ++term->tl_scrollback.ga_len;
1685
1686 if (ga_grow(&ga, 1) == FAIL)
1687 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1688 else
1689 {
1690 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1691 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1692 }
1693 ga_clear(&ga);
1694 }
1695 else
1696 vim_free(p);
1697 }
1698 }
1699
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001700 // Add trailing empty lines.
1701 for (pos.row = term->tl_scrollback.ga_len;
1702 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1703 ++pos.row)
1704 {
1705 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1706 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1707 }
1708
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001709 term->tl_dirty_snapshot = FALSE;
1710#ifdef FEAT_TIMERS
1711 term->tl_timer_set = FALSE;
1712#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001713}
1714
1715/*
1716 * If needed, add the current lines of the terminal to scrollback and to the
1717 * buffer. Called after the job has ended and when switching to
1718 * Terminal-Normal mode.
1719 * When "redraw" is TRUE redraw the windows that show the terminal.
1720 */
1721 static void
1722may_move_terminal_to_buffer(term_T *term, int redraw)
1723{
1724 win_T *wp;
1725
1726 if (term->tl_vterm == NULL)
1727 return;
1728
1729 /* Update the snapshot only if something changes or the buffer does not
1730 * have all the lines. */
1731 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1732 <= term->tl_scrollback_scrolled)
1733 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001734
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001735 /* Obtain the current background color. */
1736 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1737 &term->tl_default_color.fg, &term->tl_default_color.bg);
1738
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001739 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001740 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001741 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001742 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001743 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001744 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1745 wp->w_cursor.col = 0;
1746 wp->w_valid = 0;
1747 if (wp->w_cursor.lnum >= wp->w_height)
1748 {
1749 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001750
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001751 if (wp->w_topline < min_topline)
1752 wp->w_topline = min_topline;
1753 }
1754 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001755 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001756 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001757}
1758
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001759#if defined(FEAT_TIMERS) || defined(PROTO)
1760/*
1761 * Check if any terminal timer expired. If so, copy text from the terminal to
1762 * the buffer.
1763 * Return the time until the next timer will expire.
1764 */
1765 int
1766term_check_timers(int next_due_arg, proftime_T *now)
1767{
1768 term_T *term;
1769 int next_due = next_due_arg;
1770
1771 for (term = first_term; term != NULL; term = term->tl_next)
1772 {
1773 if (term->tl_timer_set && !term->tl_normal_mode)
1774 {
1775 long this_due = proftime_time_left(&term->tl_timer_due, now);
1776
1777 if (this_due <= 1)
1778 {
1779 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001780 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001781 }
1782 else if (next_due == -1 || next_due > this_due)
1783 next_due = this_due;
1784 }
1785 }
1786
1787 return next_due;
1788}
1789#endif
1790
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001791/*
1792 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1793 * otherwise end it.
1794 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001795 static void
1796set_terminal_mode(term_T *term, int normal_mode)
1797{
1798 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001799 if (!normal_mode)
1800 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001801 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001802 if (term->tl_buffer == curbuf)
1803 maketitle();
1804}
1805
1806/*
1807 * Called after the job if finished and Terminal mode is not active:
1808 * Move the vterm contents into the scrollback buffer and free the vterm.
1809 */
1810 static void
1811cleanup_vterm(term_T *term)
1812{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001813 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001814 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001815 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001816 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001817}
1818
1819/*
1820 * Switch from Terminal-Job mode to Terminal-Normal mode.
1821 * Suspends updating the terminal window.
1822 */
1823 static void
1824term_enter_normal_mode(void)
1825{
1826 term_T *term = curbuf->b_term;
1827
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001828 set_terminal_mode(term, TRUE);
1829
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001830 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001831 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001832
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001833 /* Move the window cursor to the position of the cursor in the
1834 * terminal. */
1835 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1836 + term->tl_cursor_pos.row + 1;
1837 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001838 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1839 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001840
1841 /* Display the same lines as in the terminal. */
1842 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1843}
1844
1845/*
1846 * Returns TRUE if the current window contains a terminal and we are in
1847 * Terminal-Normal mode.
1848 */
1849 int
1850term_in_normal_mode(void)
1851{
1852 term_T *term = curbuf->b_term;
1853
1854 return term != NULL && term->tl_normal_mode;
1855}
1856
1857/*
1858 * Switch from Terminal-Normal mode to Terminal-Job mode.
1859 * Restores updating the terminal window.
1860 */
1861 void
1862term_enter_job_mode()
1863{
1864 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001865
1866 set_terminal_mode(term, FALSE);
1867
1868 if (term->tl_channel_closed)
1869 cleanup_vterm(term);
1870 redraw_buf_and_status_later(curbuf, NOT_VALID);
1871}
1872
1873/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001874 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875 * Note: while waiting a terminal may be closed and freed if the channel is
1876 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001877 */
1878 static int
1879term_vgetc()
1880{
1881 int c;
1882 int save_State = State;
1883
1884 State = TERMINAL;
1885 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001886#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001887 ctrl_break_was_pressed = FALSE;
1888#endif
1889 c = vgetc();
1890 got_int = FALSE;
1891 State = save_State;
1892 return c;
1893}
1894
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001895static int mouse_was_outside = FALSE;
1896
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001898 * Send keys to terminal.
1899 * Return FAIL when the key needs to be handled in Normal mode.
1900 * Return OK when the key was dropped or sent to the terminal.
1901 */
1902 int
1903send_keys_to_term(term_T *term, int c, int typed)
1904{
1905 char msg[KEY_BUF_LEN];
1906 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001907 int dragging_outside = FALSE;
1908
1909 /* Catch keys that need to be handled as in Normal mode. */
1910 switch (c)
1911 {
1912 case NUL:
1913 case K_ZERO:
1914 if (typed)
1915 stuffcharReadbuff(c);
1916 return FAIL;
1917
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001918 case K_TABLINE:
1919 stuffcharReadbuff(c);
1920 return FAIL;
1921
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001922 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001923 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001924 return FAIL;
1925
1926 case K_LEFTDRAG:
1927 case K_MIDDLEDRAG:
1928 case K_RIGHTDRAG:
1929 case K_X1DRAG:
1930 case K_X2DRAG:
1931 dragging_outside = mouse_was_outside;
1932 /* FALLTHROUGH */
1933 case K_LEFTMOUSE:
1934 case K_LEFTMOUSE_NM:
1935 case K_LEFTRELEASE:
1936 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001937 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001938 case K_MIDDLEMOUSE:
1939 case K_MIDDLERELEASE:
1940 case K_RIGHTMOUSE:
1941 case K_RIGHTRELEASE:
1942 case K_X1MOUSE:
1943 case K_X1RELEASE:
1944 case K_X2MOUSE:
1945 case K_X2RELEASE:
1946
1947 case K_MOUSEUP:
1948 case K_MOUSEDOWN:
1949 case K_MOUSELEFT:
1950 case K_MOUSERIGHT:
1951 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001952 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001953 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001954 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001955 || dragging_outside)
1956 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001957 /* click or scroll outside the current window or on status line
1958 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001959 if (typed)
1960 {
1961 stuffcharReadbuff(c);
1962 mouse_was_outside = TRUE;
1963 }
1964 return FAIL;
1965 }
1966 }
1967 if (typed)
1968 mouse_was_outside = FALSE;
1969
1970 /* Convert the typed key to a sequence of bytes for the job. */
1971 len = term_convert_key(term, c, msg);
1972 if (len > 0)
1973 /* TODO: if FAIL is returned, stop? */
1974 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1975 (char_u *)msg, (int)len, NULL);
1976
1977 return OK;
1978}
1979
1980 static void
1981position_cursor(win_T *wp, VTermPos *pos)
1982{
1983 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1984 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1985 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1986}
1987
1988/*
1989 * Handle CTRL-W "": send register contents to the job.
1990 */
1991 static void
1992term_paste_register(int prev_c UNUSED)
1993{
1994 int c;
1995 list_T *l;
1996 listitem_T *item;
1997 long reglen = 0;
1998 int type;
1999
2000#ifdef FEAT_CMDL_INFO
2001 if (add_to_showcmd(prev_c))
2002 if (add_to_showcmd('"'))
2003 out_flush();
2004#endif
2005 c = term_vgetc();
2006#ifdef FEAT_CMDL_INFO
2007 clear_showcmd();
2008#endif
2009 if (!term_use_loop())
2010 /* job finished while waiting for a character */
2011 return;
2012
2013 /* CTRL-W "= prompt for expression to evaluate. */
2014 if (c == '=' && get_expr_register() != '=')
2015 return;
2016 if (!term_use_loop())
2017 /* job finished while waiting for a character */
2018 return;
2019
2020 l = (list_T *)get_reg_contents(c, GREG_LIST);
2021 if (l != NULL)
2022 {
2023 type = get_reg_type(c, &reglen);
2024 for (item = l->lv_first; item != NULL; item = item->li_next)
2025 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002026 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002027#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 char_u *tmp = s;
2029
2030 if (!enc_utf8 && enc_codepage > 0)
2031 {
2032 WCHAR *ret = NULL;
2033 int length = 0;
2034
2035 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2036 (int)STRLEN(s), &ret, &length);
2037 if (ret != NULL)
2038 {
2039 WideCharToMultiByte_alloc(CP_UTF8, 0,
2040 ret, length, (char **)&s, &length, 0, 0);
2041 vim_free(ret);
2042 }
2043 }
2044#endif
2045 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2046 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002047#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002048 if (tmp != s)
2049 vim_free(s);
2050#endif
2051
2052 if (item->li_next != NULL || type == MLINE)
2053 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2054 (char_u *)"\r", 1, NULL);
2055 }
2056 list_free(l);
2057 }
2058}
2059
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002060/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002061 * Return TRUE when waiting for a character in the terminal, the cursor of the
2062 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002063 */
2064 int
2065terminal_is_active()
2066{
2067 return in_terminal_loop != NULL;
2068}
2069
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002070#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002071 cursorentry_T *
2072term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2073{
2074 term_T *term = in_terminal_loop;
2075 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002076 int id;
2077 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002078
2079 vim_memset(&entry, 0, sizeof(entry));
2080 entry.shape = entry.mshape =
2081 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2082 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2083 SHAPE_BLOCK;
2084 entry.percentage = 20;
2085 if (term->tl_cursor_blink)
2086 {
2087 entry.blinkwait = 700;
2088 entry.blinkon = 400;
2089 entry.blinkoff = 250;
2090 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002091
2092 /* The "Terminal" highlight group overrules the defaults. */
2093 id = syn_name2id((char_u *)"Terminal");
2094 if (id != 0)
2095 {
2096 syn_id2colors(id, &term_fg, &term_bg);
2097 *fg = term_bg;
2098 }
2099 else
2100 *fg = gui.back_pixel;
2101
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002102 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002103 {
2104 if (id != 0)
2105 *bg = term_fg;
2106 else
2107 *bg = gui.norm_pixel;
2108 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002109 else
2110 *bg = color_name2handle(term->tl_cursor_color);
2111 entry.name = "n";
2112 entry.used_for = SHAPE_CURSOR;
2113
2114 return &entry;
2115}
2116#endif
2117
Bram Moolenaard317b382018-02-08 22:33:31 +01002118 static void
2119may_output_cursor_props(void)
2120{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002121 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002122 || last_set_cursor_shape != desired_cursor_shape
2123 || last_set_cursor_blink != desired_cursor_blink)
2124 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002125 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002126 last_set_cursor_shape = desired_cursor_shape;
2127 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002128 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002129 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2130 /* this will restore the initial cursor style, if possible */
2131 ui_cursor_shape_forced(TRUE);
2132 else
2133 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2134 }
2135}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002136
Bram Moolenaard317b382018-02-08 22:33:31 +01002137/*
2138 * Set the cursor color and shape, if not last set to these.
2139 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002140 static void
2141may_set_cursor_props(term_T *term)
2142{
2143#ifdef FEAT_GUI
2144 /* For the GUI the cursor properties are obtained with
2145 * term_get_cursor_shape(). */
2146 if (gui.in_use)
2147 return;
2148#endif
2149 if (in_terminal_loop == term)
2150 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002151 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002152 desired_cursor_shape = term->tl_cursor_shape;
2153 desired_cursor_blink = term->tl_cursor_blink;
2154 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002155 }
2156}
2157
Bram Moolenaard317b382018-02-08 22:33:31 +01002158/*
2159 * Reset the desired cursor properties and restore them when needed.
2160 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002161 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002162prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002163{
2164#ifdef FEAT_GUI
2165 if (gui.in_use)
2166 return;
2167#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002168 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002169 desired_cursor_shape = -1;
2170 desired_cursor_blink = -1;
2171 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002172}
2173
2174/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002175 * Returns TRUE if the current window contains a terminal and we are sending
2176 * keys to the job.
2177 * If "check_job_status" is TRUE update the job status.
2178 */
2179 static int
2180term_use_loop_check(int check_job_status)
2181{
2182 term_T *term = curbuf->b_term;
2183
2184 return term != NULL
2185 && !term->tl_normal_mode
2186 && term->tl_vterm != NULL
2187 && term_job_running_check(term, check_job_status);
2188}
2189
2190/*
2191 * Returns TRUE if the current window contains a terminal and we are sending
2192 * keys to the job.
2193 */
2194 int
2195term_use_loop(void)
2196{
2197 return term_use_loop_check(FALSE);
2198}
2199
2200/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002201 * Called when entering a window with the mouse. If this is a terminal window
2202 * we may want to change state.
2203 */
2204 void
2205term_win_entered()
2206{
2207 term_T *term = curbuf->b_term;
2208
2209 if (term != NULL)
2210 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002211 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002212 {
2213 reset_VIsual_and_resel();
2214 if (State & INSERT)
2215 stop_insert_mode = TRUE;
2216 }
2217 mouse_was_outside = FALSE;
2218 enter_mouse_col = mouse_col;
2219 enter_mouse_row = mouse_row;
2220 }
2221}
2222
2223/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002224 * Wait for input and send it to the job.
2225 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2226 * when there is no more typahead.
2227 * Return when the start of a CTRL-W command is typed or anything else that
2228 * should be handled as a Normal mode command.
2229 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2230 * the terminal was closed.
2231 */
2232 int
2233terminal_loop(int blocking)
2234{
2235 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002236 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002237 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002238#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002239 int tty_fd = curbuf->b_term->tl_job->jv_channel
2240 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002241#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002242 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002243
2244 /* Remember the terminal we are sending keys to. However, the terminal
2245 * might be closed while waiting for a character, e.g. typing "exit" in a
2246 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2247 * stored reference. */
2248 in_terminal_loop = curbuf->b_term;
2249
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002250 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002251 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002252 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002253 if (termwinkey == Ctrl_W)
2254 termwinkey = 0;
2255 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002256 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2257 may_set_cursor_props(curbuf->b_term);
2258
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002259 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002260 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002261#ifdef FEAT_GUI
2262 if (!curbuf->b_term->tl_system)
2263#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002264 // TODO: skip screen update when handling a sequence of keys.
2265 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002266 while (must_redraw != 0)
2267 if (update_screen(0) == FAIL)
2268 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002269 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002270 /* job finished while redrawing */
2271 break;
2272
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002273 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002274 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002275
2276 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002277 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002278 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002279 /* Job finished while waiting for a character. Push back the
2280 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002281 if (c != K_IGNORE)
2282 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002283 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002284 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002285 if (c == K_IGNORE)
2286 continue;
2287
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002288#ifdef UNIX
2289 /*
2290 * The shell or another program may change the tty settings. Getting
2291 * them for every typed character is a bit of overhead, but it's needed
2292 * for the first character typed, e.g. when Vim starts in a shell.
2293 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002294 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002295 {
2296 ttyinfo_T info;
2297
2298 /* Get the current backspace character of the pty. */
2299 if (get_tty_info(tty_fd, &info) == OK)
2300 term_backspace_char = info.backspace;
2301 }
2302#endif
2303
Bram Moolenaar4f974752019-02-17 17:44:42 +01002304#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002305 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2306 * Use CTRL-BREAK to kill the job. */
2307 if (ctrl_break_was_pressed)
2308 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2309#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002310 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002311 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002312 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002313#ifdef FEAT_GUI
2314 && !curbuf->b_term->tl_system
2315#endif
2316 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002317 {
2318 int prev_c = c;
2319
2320#ifdef FEAT_CMDL_INFO
2321 if (add_to_showcmd(c))
2322 out_flush();
2323#endif
2324 c = term_vgetc();
2325#ifdef FEAT_CMDL_INFO
2326 clear_showcmd();
2327#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002328 if (!term_use_loop_check(TRUE)
2329 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002330 /* job finished while waiting for a character */
2331 break;
2332
2333 if (prev_c == Ctrl_BSL)
2334 {
2335 if (c == Ctrl_N)
2336 {
2337 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2338 term_enter_normal_mode();
2339 ret = FAIL;
2340 goto theend;
2341 }
2342 /* Send both keys to the terminal. */
2343 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2344 }
2345 else if (c == Ctrl_C)
2346 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002347 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002348 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2349 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002350 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002351 {
2352 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002353 /* "'termwinkey' .": send 'termwinkey' to the job */
2354 c = termwinkey == 0 ? Ctrl_W : termwinkey;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002355 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002356 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002357 {
2358 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2359 c = Ctrl_BSL;
2360 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002361 else if (c == 'N')
2362 {
2363 /* CTRL-W N : go to Terminal-Normal mode. */
2364 term_enter_normal_mode();
2365 ret = FAIL;
2366 goto theend;
2367 }
2368 else if (c == '"')
2369 {
2370 term_paste_register(prev_c);
2371 continue;
2372 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002373 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002374 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002375 char_u buf[MB_MAXBYTES + 2];
2376
2377 // Put the command into the typeahead buffer, when using the
2378 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2379 buf[0] = Ctrl_W;
2380 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2381 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002382 ret = OK;
2383 goto theend;
2384 }
2385 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002386# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002387 if (!enc_utf8 && has_mbyte && c >= 0x80)
2388 {
2389 WCHAR wc;
2390 char_u mb[3];
2391
2392 mb[0] = (unsigned)c >> 8;
2393 mb[1] = c;
2394 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2395 c = wc;
2396 }
2397# endif
2398 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2399 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002400 if (c == K_MOUSEMOVE)
2401 /* We are sure to come back here, don't reset the cursor color
2402 * and shape to avoid flickering. */
2403 restore_cursor = FALSE;
2404
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002405 ret = OK;
2406 goto theend;
2407 }
2408 }
2409 ret = FAIL;
2410
2411theend:
2412 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002413 if (restore_cursor)
2414 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002415
2416 /* Move a snapshot of the screen contents to the buffer, so that completion
2417 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002418 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2419 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002420
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002421 return ret;
2422}
2423
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002424 static void
2425may_toggle_cursor(term_T *term)
2426{
2427 if (in_terminal_loop == term)
2428 {
2429 if (term->tl_cursor_visible)
2430 cursor_on();
2431 else
2432 cursor_off();
2433 }
2434}
2435
2436/*
2437 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002438 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002439 */
2440 static int
2441color2index(VTermColor *color, int fg, int *boldp)
2442{
2443 int red = color->red;
2444 int blue = color->blue;
2445 int green = color->green;
2446
Bram Moolenaar46359e12017-11-29 22:33:38 +01002447 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002448 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002449 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002450 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002451 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002452 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002453 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002454 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2455 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2456 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002457 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002458 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2459 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2460 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2461 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2462 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2463 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2464 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2465 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2466 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2467 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2468 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002469 }
2470 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002471
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002472 if (t_colors >= 256)
2473 {
2474 if (red == blue && red == green)
2475 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002476 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002477 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002478 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2479 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2480 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002481 int i;
2482
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002483 if (red < 5)
2484 return 17; /* 00/00/00 */
2485 if (red > 245) /* ff/ff/ff */
2486 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002487 for (i = 0; i < 23; ++i)
2488 if (red < cutoff[i])
2489 return i + 233;
2490 return 256;
2491 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002492 {
2493 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2494 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002495
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002496 /* 216-color cube */
2497 for (ri = 0; ri < 5; ++ri)
2498 if (red < cutoff[ri])
2499 break;
2500 for (gi = 0; gi < 5; ++gi)
2501 if (green < cutoff[gi])
2502 break;
2503 for (bi = 0; bi < 5; ++bi)
2504 if (blue < cutoff[bi])
2505 break;
2506 return 17 + ri * 36 + gi * 6 + bi;
2507 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002508 }
2509 return 0;
2510}
2511
2512/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002513 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002514 */
2515 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002516vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002517{
2518 int attr = 0;
2519
2520 if (cellattrs.bold)
2521 attr |= HL_BOLD;
2522 if (cellattrs.underline)
2523 attr |= HL_UNDERLINE;
2524 if (cellattrs.italic)
2525 attr |= HL_ITALIC;
2526 if (cellattrs.strike)
2527 attr |= HL_STRIKETHROUGH;
2528 if (cellattrs.reverse)
2529 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002530 return attr;
2531}
2532
2533/*
2534 * Store Vterm attributes in "cell" from highlight flags.
2535 */
2536 static void
2537hl2vtermAttr(int attr, cellattr_T *cell)
2538{
2539 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2540 if (attr & HL_BOLD)
2541 cell->attrs.bold = 1;
2542 if (attr & HL_UNDERLINE)
2543 cell->attrs.underline = 1;
2544 if (attr & HL_ITALIC)
2545 cell->attrs.italic = 1;
2546 if (attr & HL_STRIKETHROUGH)
2547 cell->attrs.strike = 1;
2548 if (attr & HL_INVERSE)
2549 cell->attrs.reverse = 1;
2550}
2551
2552/*
2553 * Convert the attributes of a vterm cell into an attribute index.
2554 */
2555 static int
2556cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2557{
2558 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002559
2560#ifdef FEAT_GUI
2561 if (gui.in_use)
2562 {
2563 guicolor_T fg, bg;
2564
2565 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2566 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2567 return get_gui_attr_idx(attr, fg, bg);
2568 }
2569 else
2570#endif
2571#ifdef FEAT_TERMGUICOLORS
2572 if (p_tgc)
2573 {
2574 guicolor_T fg, bg;
2575
2576 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2577 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2578
2579 return get_tgc_attr_idx(attr, fg, bg);
2580 }
2581 else
2582#endif
2583 {
2584 int bold = MAYBE;
2585 int fg = color2index(&cellfg, TRUE, &bold);
2586 int bg = color2index(&cellbg, FALSE, &bold);
2587
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002588 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002589 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002590 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002591 if (fg == 0 && term_default_cterm_fg >= 0)
2592 fg = term_default_cterm_fg + 1;
2593 if (bg == 0 && term_default_cterm_bg >= 0)
2594 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002595 }
2596
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002597 /* with 8 colors set the bold attribute to get a bright foreground */
2598 if (bold == TRUE)
2599 attr |= HL_BOLD;
2600 return get_cterm_attr_idx(attr, fg, bg);
2601 }
2602 return 0;
2603}
2604
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002605 static void
2606set_dirty_snapshot(term_T *term)
2607{
2608 term->tl_dirty_snapshot = TRUE;
2609#ifdef FEAT_TIMERS
2610 if (!term->tl_normal_mode)
2611 {
2612 /* Update the snapshot after 100 msec of not getting updates. */
2613 profile_setlimit(100L, &term->tl_timer_due);
2614 term->tl_timer_set = TRUE;
2615 }
2616#endif
2617}
2618
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002619 static int
2620handle_damage(VTermRect rect, void *user)
2621{
2622 term_T *term = (term_T *)user;
2623
2624 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2625 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002626 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002627 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002628 return 1;
2629}
2630
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002631 static void
2632term_scroll_up(term_T *term, int start_row, int count)
2633{
2634 win_T *wp;
2635 VTermColor fg, bg;
2636 VTermScreenCellAttrs attr;
2637 int clear_attr;
2638
2639 /* Set the color to clear lines with. */
2640 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2641 &fg, &bg);
2642 vim_memset(&attr, 0, sizeof(attr));
2643 clear_attr = cell2attr(attr, fg, bg);
2644
2645 FOR_ALL_WINDOWS(wp)
2646 {
2647 if (wp->w_buffer == term->tl_buffer)
2648 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2649 }
2650}
2651
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002652 static int
2653handle_moverect(VTermRect dest, VTermRect src, void *user)
2654{
2655 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002656 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002657
2658 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002659 * redrawing the text. But avoid doing this multiple times, postpone until
2660 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002661 if (dest.start_col == src.start_col
2662 && dest.end_col == src.end_col
2663 && dest.start_row < src.start_row)
2664 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002665 if (dest.start_row == 0)
2666 term->tl_postponed_scroll += count;
2667 else
2668 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002669 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002670
2671 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2672 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002673 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002674
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002675 /* Note sure if the scrolling will work correctly, let's do a complete
2676 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002677 redraw_buf_later(term->tl_buffer, NOT_VALID);
2678 return 1;
2679}
2680
2681 static int
2682handle_movecursor(
2683 VTermPos pos,
2684 VTermPos oldpos UNUSED,
2685 int visible,
2686 void *user)
2687{
2688 term_T *term = (term_T *)user;
2689 win_T *wp;
2690
2691 term->tl_cursor_pos = pos;
2692 term->tl_cursor_visible = visible;
2693
2694 FOR_ALL_WINDOWS(wp)
2695 {
2696 if (wp->w_buffer == term->tl_buffer)
2697 position_cursor(wp, &pos);
2698 }
2699 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2700 {
2701 may_toggle_cursor(term);
2702 update_cursor(term, term->tl_cursor_visible);
2703 }
2704
2705 return 1;
2706}
2707
2708 static int
2709handle_settermprop(
2710 VTermProp prop,
2711 VTermValue *value,
2712 void *user)
2713{
2714 term_T *term = (term_T *)user;
2715
2716 switch (prop)
2717 {
2718 case VTERM_PROP_TITLE:
2719 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002720 // a blank title isn't useful, make it empty, so that "running" is
2721 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002722 if (*skipwhite((char_u *)value->string) == NUL)
2723 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002724 // Same as blank
2725 else if (term->tl_arg0_cmd != NULL
2726 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2727 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2728 term->tl_title = NULL;
2729 // Empty corrupted data of winpty
2730 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2731 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002732#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002733 else if (!enc_utf8 && enc_codepage > 0)
2734 {
2735 WCHAR *ret = NULL;
2736 int length = 0;
2737
2738 MultiByteToWideChar_alloc(CP_UTF8, 0,
2739 (char*)value->string, (int)STRLEN(value->string),
2740 &ret, &length);
2741 if (ret != NULL)
2742 {
2743 WideCharToMultiByte_alloc(enc_codepage, 0,
2744 ret, length, (char**)&term->tl_title,
2745 &length, 0, 0);
2746 vim_free(ret);
2747 }
2748 }
2749#endif
2750 else
2751 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002752 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002753 if (term == curbuf->b_term)
2754 maketitle();
2755 break;
2756
2757 case VTERM_PROP_CURSORVISIBLE:
2758 term->tl_cursor_visible = value->boolean;
2759 may_toggle_cursor(term);
2760 out_flush();
2761 break;
2762
2763 case VTERM_PROP_CURSORBLINK:
2764 term->tl_cursor_blink = value->boolean;
2765 may_set_cursor_props(term);
2766 break;
2767
2768 case VTERM_PROP_CURSORSHAPE:
2769 term->tl_cursor_shape = value->number;
2770 may_set_cursor_props(term);
2771 break;
2772
2773 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002774 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002775 may_set_cursor_props(term);
2776 break;
2777
2778 case VTERM_PROP_ALTSCREEN:
2779 /* TODO: do anything else? */
2780 term->tl_using_altscreen = value->boolean;
2781 break;
2782
2783 default:
2784 break;
2785 }
2786 /* Always return 1, otherwise vterm doesn't store the value internally. */
2787 return 1;
2788}
2789
2790/*
2791 * The job running in the terminal resized the terminal.
2792 */
2793 static int
2794handle_resize(int rows, int cols, void *user)
2795{
2796 term_T *term = (term_T *)user;
2797 win_T *wp;
2798
2799 term->tl_rows = rows;
2800 term->tl_cols = cols;
2801 if (term->tl_vterm_size_changed)
2802 /* Size was set by vterm_set_size(), don't set the window size. */
2803 term->tl_vterm_size_changed = FALSE;
2804 else
2805 {
2806 FOR_ALL_WINDOWS(wp)
2807 {
2808 if (wp->w_buffer == term->tl_buffer)
2809 {
2810 win_setheight_win(rows, wp);
2811 win_setwidth_win(cols, wp);
2812 }
2813 }
2814 redraw_buf_later(term->tl_buffer, NOT_VALID);
2815 }
2816 return 1;
2817}
2818
2819/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002820 * If the number of lines that are stored goes over 'termscrollback' then
2821 * delete the first 10%.
2822 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2823 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002824 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002825 static void
2826limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002827{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002828 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002829 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002830 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002831 int i;
2832
2833 curbuf = term->tl_buffer;
2834 for (i = 0; i < todo; ++i)
2835 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002836 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
2837 if (update_buffer)
2838 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002839 }
2840 curbuf = curwin->w_buffer;
2841
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002842 gap->ga_len -= todo;
2843 mch_memmove(gap->ga_data,
2844 (sb_line_T *)gap->ga_data + todo,
2845 sizeof(sb_line_T) * gap->ga_len);
2846 if (update_buffer)
2847 term->tl_scrollback_scrolled -= todo;
2848 }
2849}
2850
2851/*
2852 * Handle a line that is pushed off the top of the screen.
2853 */
2854 static int
2855handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2856{
2857 term_T *term = (term_T *)user;
2858 garray_T *gap;
2859 int update_buffer;
2860
2861 if (term->tl_normal_mode)
2862 {
2863 // In Terminal-Normal mode the user interacts with the buffer, thus we
2864 // must not change it. Postpone adding the scrollback lines.
2865 gap = &term->tl_scrollback_postponed;
2866 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002867 }
2868 else
2869 {
2870 // First remove the lines that were appended before, the pushed line
2871 // goes above it.
2872 cleanup_scrollback(term);
2873 gap = &term->tl_scrollback;
2874 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002875 }
2876
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002877 limit_scrollback(term, gap, update_buffer);
2878
2879 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880 {
2881 cellattr_T *p = NULL;
2882 int len = 0;
2883 int i;
2884 int c;
2885 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002886 int text_len;
2887 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888 sb_line_T *line;
2889 garray_T ga;
2890 cellattr_T fill_attr = term->tl_default_color;
2891
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002892 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002893 for (i = 0; i < cols; ++i)
2894 if (cells[i].chars[0] != 0)
2895 len = i + 1;
2896 else
2897 cell2cellattr(&cells[i], &fill_attr);
2898
2899 ga_init2(&ga, 1, 100);
2900 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002901 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002902 if (p != NULL)
2903 {
2904 for (col = 0; col < len; col += cells[col].width)
2905 {
2906 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2907 {
2908 ga.ga_len = 0;
2909 break;
2910 }
2911 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2912 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2913 (char_u *)ga.ga_data + ga.ga_len);
2914 cell2cellattr(&cells[col], &p[col]);
2915 }
2916 }
2917 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002918 {
2919 if (update_buffer)
2920 text = (char_u *)"";
2921 else
2922 text = vim_strsave((char_u *)"");
2923 text_len = 0;
2924 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 else
2926 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002927 text = ga.ga_data;
2928 text_len = ga.ga_len;
2929 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002930 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002931 if (update_buffer)
2932 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002933
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002934 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002935 line->sb_cols = len;
2936 line->sb_cells = p;
2937 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002938 if (update_buffer)
2939 {
2940 line->sb_text = NULL;
2941 ++term->tl_scrollback_scrolled;
2942 ga_clear(&ga); // free the text
2943 }
2944 else
2945 {
2946 line->sb_text = text;
2947 ga_init(&ga); // text is kept in tl_scrollback_postponed
2948 }
2949 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002950 }
2951 return 0; /* ignored */
2952}
2953
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002954/*
2955 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
2956 * received and stored in tl_scrollback_postponed.
2957 */
2958 static void
2959handle_postponed_scrollback(term_T *term)
2960{
2961 int i;
2962
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01002963 if (term->tl_scrollback_postponed.ga_len == 0)
2964 return;
2965 ch_log(NULL, "Moving postponed scrollback to scrollback");
2966
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002967 // First remove the lines that were appended before, the pushed lines go
2968 // above it.
2969 cleanup_scrollback(term);
2970
2971 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
2972 {
2973 char_u *text;
2974 sb_line_T *pp_line;
2975 sb_line_T *line;
2976
2977 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
2978 break;
2979 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
2980
2981 text = pp_line->sb_text;
2982 if (text == NULL)
2983 text = (char_u *)"";
2984 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
2985 vim_free(pp_line->sb_text);
2986
2987 line = (sb_line_T *)term->tl_scrollback.ga_data
2988 + term->tl_scrollback.ga_len;
2989 line->sb_cols = pp_line->sb_cols;
2990 line->sb_cells = pp_line->sb_cells;
2991 line->sb_fill_attr = pp_line->sb_fill_attr;
2992 line->sb_text = NULL;
2993 ++term->tl_scrollback_scrolled;
2994 ++term->tl_scrollback.ga_len;
2995 }
2996
2997 ga_clear(&term->tl_scrollback_postponed);
2998 limit_scrollback(term, &term->tl_scrollback, TRUE);
2999}
3000
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003001static VTermScreenCallbacks screen_callbacks = {
3002 handle_damage, /* damage */
3003 handle_moverect, /* moverect */
3004 handle_movecursor, /* movecursor */
3005 handle_settermprop, /* settermprop */
3006 NULL, /* bell */
3007 handle_resize, /* resize */
3008 handle_pushline, /* sb_pushline */
3009 NULL /* sb_popline */
3010};
3011
3012/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003013 * Do the work after the channel of a terminal was closed.
3014 * Must be called only when updating_screen is FALSE.
3015 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3016 */
3017 static int
3018term_after_channel_closed(term_T *term)
3019{
3020 /* Unless in Terminal-Normal mode: clear the vterm. */
3021 if (!term->tl_normal_mode)
3022 {
3023 int fnum = term->tl_buffer->b_fnum;
3024
3025 cleanup_vterm(term);
3026
3027 if (term->tl_finish == TL_FINISH_CLOSE)
3028 {
3029 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003030 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003031
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003032 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003033 ch_log(NULL, "terminal job finished, closing window");
3034 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003035 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003036 if (curwin == aucmd_win)
3037 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003038 if (do_set_w_closing)
3039 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003040 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003041 if (do_set_w_closing)
3042 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003043 aucmd_restbuf(&aco);
3044 return TRUE;
3045 }
3046 if (term->tl_finish == TL_FINISH_OPEN
3047 && term->tl_buffer->b_nwindows == 0)
3048 {
3049 char buf[50];
3050
3051 /* TODO: use term_opencmd */
3052 ch_log(NULL, "terminal job finished, opening window");
3053 vim_snprintf(buf, sizeof(buf),
3054 term->tl_opencmd == NULL
3055 ? "botright sbuf %d"
3056 : (char *)term->tl_opencmd, fnum);
3057 do_cmdline_cmd((char_u *)buf);
3058 }
3059 else
3060 ch_log(NULL, "terminal job finished");
3061 }
3062
3063 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3064 return FALSE;
3065}
3066
3067/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003068 * Called when a channel has been closed.
3069 * If this was a channel for a terminal window then finish it up.
3070 */
3071 void
3072term_channel_closed(channel_T *ch)
3073{
3074 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003075 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003076 int did_one = FALSE;
3077
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003078 for (term = first_term; term != NULL; term = next_term)
3079 {
3080 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003081 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003082 {
3083 term->tl_channel_closed = TRUE;
3084 did_one = TRUE;
3085
Bram Moolenaard23a8232018-02-10 18:45:26 +01003086 VIM_CLEAR(term->tl_title);
3087 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003088#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003089 if (term->tl_out_fd != NULL)
3090 {
3091 fclose(term->tl_out_fd);
3092 term->tl_out_fd = NULL;
3093 }
3094#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003096 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003098 /* Cannot open or close windows now. Can happen when
3099 * 'lazyredraw' is set. */
3100 term->tl_channel_recently_closed = TRUE;
3101 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003102 }
3103
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003104 if (term_after_channel_closed(term))
3105 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003106 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003107 }
3108
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003109 if (did_one)
3110 {
3111 redraw_statuslines();
3112
3113 /* Need to break out of vgetc(). */
3114 ins_char_typebuf(K_IGNORE);
3115 typebuf_was_filled = TRUE;
3116
3117 term = curbuf->b_term;
3118 if (term != NULL)
3119 {
3120 if (term->tl_job == ch->ch_job)
3121 maketitle();
3122 update_cursor(term, term->tl_cursor_visible);
3123 }
3124 }
3125}
3126
3127/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003128 * To be called after resetting updating_screen: handle any terminal where the
3129 * channel was closed.
3130 */
3131 void
3132term_check_channel_closed_recently()
3133{
3134 term_T *term;
3135 term_T *next_term;
3136
3137 for (term = first_term; term != NULL; term = next_term)
3138 {
3139 next_term = term->tl_next;
3140 if (term->tl_channel_recently_closed)
3141 {
3142 term->tl_channel_recently_closed = FALSE;
3143 if (term_after_channel_closed(term))
3144 // start over, the list may have changed
3145 next_term = first_term;
3146 }
3147 }
3148}
3149
3150/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003151 * Fill one screen line from a line of the terminal.
3152 * Advances "pos" to past the last column.
3153 */
3154 static void
3155term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3156{
3157 int off = screen_get_current_line_off();
3158
3159 for (pos->col = 0; pos->col < max_col; )
3160 {
3161 VTermScreenCell cell;
3162 int c;
3163
3164 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3165 vim_memset(&cell, 0, sizeof(cell));
3166
3167 c = cell.chars[0];
3168 if (c == NUL)
3169 {
3170 ScreenLines[off] = ' ';
3171 if (enc_utf8)
3172 ScreenLinesUC[off] = NUL;
3173 }
3174 else
3175 {
3176 if (enc_utf8)
3177 {
3178 int i;
3179
3180 /* composing chars */
3181 for (i = 0; i < Screen_mco
3182 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3183 {
3184 ScreenLinesC[i][off] = cell.chars[i + 1];
3185 if (cell.chars[i + 1] == 0)
3186 break;
3187 }
3188 if (c >= 0x80 || (Screen_mco > 0
3189 && ScreenLinesC[0][off] != 0))
3190 {
3191 ScreenLines[off] = ' ';
3192 ScreenLinesUC[off] = c;
3193 }
3194 else
3195 {
3196 ScreenLines[off] = c;
3197 ScreenLinesUC[off] = NUL;
3198 }
3199 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003200#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003201 else if (has_mbyte && c >= 0x80)
3202 {
3203 char_u mb[MB_MAXBYTES+1];
3204 WCHAR wc = c;
3205
3206 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3207 (char*)mb, 2, 0, 0) > 1)
3208 {
3209 ScreenLines[off] = mb[0];
3210 ScreenLines[off + 1] = mb[1];
3211 cell.width = mb_ptr2cells(mb);
3212 }
3213 else
3214 ScreenLines[off] = c;
3215 }
3216#endif
3217 else
3218 ScreenLines[off] = c;
3219 }
3220 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3221
3222 ++pos->col;
3223 ++off;
3224 if (cell.width == 2)
3225 {
3226 if (enc_utf8)
3227 ScreenLinesUC[off] = NUL;
3228
3229 /* don't set the second byte to NUL for a DBCS encoding, it
3230 * has been set above */
3231 if (enc_utf8 || !has_mbyte)
3232 ScreenLines[off] = NUL;
3233
3234 ++pos->col;
3235 ++off;
3236 }
3237 }
3238}
3239
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003240#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003241 static void
3242update_system_term(term_T *term)
3243{
3244 VTermPos pos;
3245 VTermScreen *screen;
3246
3247 if (term->tl_vterm == NULL)
3248 return;
3249 screen = vterm_obtain_screen(term->tl_vterm);
3250
3251 /* Scroll up to make more room for terminal lines if needed. */
3252 while (term->tl_toprow > 0
3253 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3254 {
3255 int save_p_more = p_more;
3256
3257 p_more = FALSE;
3258 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003259 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003260 p_more = save_p_more;
3261 --term->tl_toprow;
3262 }
3263
3264 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3265 && pos.row < Rows; ++pos.row)
3266 {
3267 if (pos.row < term->tl_rows)
3268 {
3269 int max_col = MIN(Columns, term->tl_cols);
3270
3271 term_line2screenline(screen, &pos, max_col);
3272 }
3273 else
3274 pos.col = 0;
3275
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003276 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003277 }
3278
3279 term->tl_dirty_row_start = MAX_ROW;
3280 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003281}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003282#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003283
3284/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003285 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3286 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003287 * Terminal-Normal mode.
3288 */
3289 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003290term_do_update_window(win_T *wp)
3291{
3292 term_T *term = wp->w_buffer->b_term;
3293
3294 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3295}
3296
3297/*
3298 * Called to update a window that contains an active terminal.
3299 */
3300 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003301term_update_window(win_T *wp)
3302{
3303 term_T *term = wp->w_buffer->b_term;
3304 VTerm *vterm;
3305 VTermScreen *screen;
3306 VTermState *state;
3307 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003308 int rows, cols;
3309 int newrows, newcols;
3310 int minsize;
3311 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003312
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003313 vterm = term->tl_vterm;
3314 screen = vterm_obtain_screen(vterm);
3315 state = vterm_obtain_state(vterm);
3316
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003317 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3318 * SOME_VALID only redraw what was marked dirty. */
3319 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003320 {
3321 term->tl_dirty_row_start = 0;
3322 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003323
3324 if (term->tl_postponed_scroll > 0
3325 && term->tl_postponed_scroll < term->tl_rows / 3)
3326 /* Scrolling is usually faster than redrawing, when there are only
3327 * a few lines to scroll. */
3328 term_scroll_up(term, 0, term->tl_postponed_scroll);
3329 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003330 }
3331
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003332 /*
3333 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003334 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003335 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003336 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003337
Bram Moolenaar498c2562018-04-15 23:45:15 +02003338 newrows = 99999;
3339 newcols = 99999;
3340 FOR_ALL_WINDOWS(twp)
3341 {
3342 /* When more than one window shows the same terminal, use the
3343 * smallest size. */
3344 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003345 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003346 newrows = MIN(newrows, twp->w_height);
3347 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003348 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003349 }
3350 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3351 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3352
3353 if (term->tl_rows != newrows || term->tl_cols != newcols)
3354 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003355 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003356 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003358 newrows);
3359 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003360
3361 // Updating the terminal size will cause the snapshot to be cleared.
3362 // When not in terminal_loop() we need to restore it.
3363 if (term != in_terminal_loop)
3364 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003365 }
3366
3367 /* The cursor may have been moved when resizing. */
3368 vterm_state_get_cursorpos(state, &pos);
3369 position_cursor(wp, &pos);
3370
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003371 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3372 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003373 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003374 if (pos.row < term->tl_rows)
3375 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003376 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003377
Bram Moolenaar13568252018-03-16 20:46:58 +01003378 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003379 }
3380 else
3381 pos.col = 0;
3382
Bram Moolenaarf118d482018-03-13 13:14:00 +01003383 screen_line(wp->w_winrow + pos.row
3384#ifdef FEAT_MENU
3385 + winbar_height(wp)
3386#endif
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003387 , wp->w_wincol, pos.col, wp->w_width, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003388 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003389 term->tl_dirty_row_start = MAX_ROW;
3390 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003391}
3392
3393/*
3394 * Return TRUE if "wp" is a terminal window where the job has finished.
3395 */
3396 int
3397term_is_finished(buf_T *buf)
3398{
3399 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3400}
3401
3402/*
3403 * Return TRUE if "wp" is a terminal window where the job has finished or we
3404 * are in Terminal-Normal mode, thus we show the buffer contents.
3405 */
3406 int
3407term_show_buffer(buf_T *buf)
3408{
3409 term_T *term = buf->b_term;
3410
3411 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3412}
3413
3414/*
3415 * The current buffer is going to be changed. If there is terminal
3416 * highlighting remove it now.
3417 */
3418 void
3419term_change_in_curbuf(void)
3420{
3421 term_T *term = curbuf->b_term;
3422
3423 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3424 {
3425 free_scrollback(term);
3426 redraw_buf_later(term->tl_buffer, NOT_VALID);
3427
3428 /* The buffer is now like a normal buffer, it cannot be easily
3429 * abandoned when changed. */
3430 set_string_option_direct((char_u *)"buftype", -1,
3431 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3432 }
3433}
3434
3435/*
3436 * Get the screen attribute for a position in the buffer.
3437 * Use a negative "col" to get the filler background color.
3438 */
3439 int
3440term_get_attr(buf_T *buf, linenr_T lnum, int col)
3441{
3442 term_T *term = buf->b_term;
3443 sb_line_T *line;
3444 cellattr_T *cellattr;
3445
3446 if (lnum > term->tl_scrollback.ga_len)
3447 cellattr = &term->tl_default_color;
3448 else
3449 {
3450 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3451 if (col < 0 || col >= line->sb_cols)
3452 cellattr = &line->sb_fill_attr;
3453 else
3454 cellattr = line->sb_cells + col;
3455 }
3456 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3457}
3458
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003459/*
3460 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003461 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003462 */
3463 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003464cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003465{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003466 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003467}
3468
3469/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003470 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003471 */
3472 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003473init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003474{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003475 VTermColor *fg, *bg;
3476 int fgval, bgval;
3477 int id;
3478
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003479 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3480 term->tl_default_color.width = 1;
3481 fg = &term->tl_default_color.fg;
3482 bg = &term->tl_default_color.bg;
3483
3484 /* Vterm uses a default black background. Set it to white when
3485 * 'background' is "light". */
3486 if (*p_bg == 'l')
3487 {
3488 fgval = 0;
3489 bgval = 255;
3490 }
3491 else
3492 {
3493 fgval = 255;
3494 bgval = 0;
3495 }
3496 fg->red = fg->green = fg->blue = fgval;
3497 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003498 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003499
3500 /* The "Terminal" highlight group overrules the defaults. */
3501 id = syn_name2id((char_u *)"Terminal");
3502
Bram Moolenaar46359e12017-11-29 22:33:38 +01003503 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003504#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3505 if (0
3506# ifdef FEAT_GUI
3507 || gui.in_use
3508# endif
3509# ifdef FEAT_TERMGUICOLORS
3510 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003511# ifdef FEAT_VTP
3512 /* Finally get INVALCOLOR on this execution path */
3513 || (!p_tgc && t_colors >= 256)
3514# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003515# endif
3516 )
3517 {
3518 guicolor_T fg_rgb = INVALCOLOR;
3519 guicolor_T bg_rgb = INVALCOLOR;
3520
3521 if (id != 0)
3522 syn_id2colors(id, &fg_rgb, &bg_rgb);
3523
3524# ifdef FEAT_GUI
3525 if (gui.in_use)
3526 {
3527 if (fg_rgb == INVALCOLOR)
3528 fg_rgb = gui.norm_pixel;
3529 if (bg_rgb == INVALCOLOR)
3530 bg_rgb = gui.back_pixel;
3531 }
3532# ifdef FEAT_TERMGUICOLORS
3533 else
3534# endif
3535# endif
3536# ifdef FEAT_TERMGUICOLORS
3537 {
3538 if (fg_rgb == INVALCOLOR)
3539 fg_rgb = cterm_normal_fg_gui_color;
3540 if (bg_rgb == INVALCOLOR)
3541 bg_rgb = cterm_normal_bg_gui_color;
3542 }
3543# endif
3544 if (fg_rgb != INVALCOLOR)
3545 {
3546 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3547
3548 fg->red = (unsigned)(rgb >> 16);
3549 fg->green = (unsigned)(rgb >> 8) & 255;
3550 fg->blue = (unsigned)rgb & 255;
3551 }
3552 if (bg_rgb != INVALCOLOR)
3553 {
3554 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3555
3556 bg->red = (unsigned)(rgb >> 16);
3557 bg->green = (unsigned)(rgb >> 8) & 255;
3558 bg->blue = (unsigned)rgb & 255;
3559 }
3560 }
3561 else
3562#endif
3563 if (id != 0 && t_colors >= 16)
3564 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003565 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003566 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003567 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003568 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003569 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003570 else
3571 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003572#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003573 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003574#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003575
3576 /* In an MS-Windows console we know the normal colors. */
3577 if (cterm_normal_fg_color > 0)
3578 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003579 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003580# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3581# ifdef VIMDLL
3582 if (!gui.in_use)
3583# endif
3584 {
3585 tmp = fg->red;
3586 fg->red = fg->blue;
3587 fg->blue = tmp;
3588 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003589# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003590 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003591# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003592 else
3593 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003594# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003595
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003596 if (cterm_normal_bg_color > 0)
3597 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003598 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003599# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3600# ifdef VIMDLL
3601 if (!gui.in_use)
3602# endif
3603 {
3604 tmp = fg->red;
3605 fg->red = fg->blue;
3606 fg->blue = tmp;
3607 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003608# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003609 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003610# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003611 else
3612 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003613# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003614 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003615}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003616
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003617#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3618/*
3619 * Set the 16 ANSI colors from array of RGB values
3620 */
3621 static void
3622set_vterm_palette(VTerm *vterm, long_u *rgb)
3623{
3624 int index = 0;
3625 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003626
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003627 for (; index < 16; index++)
3628 {
3629 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003630
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003631 color.red = (unsigned)(rgb[index] >> 16);
3632 color.green = (unsigned)(rgb[index] >> 8) & 255;
3633 color.blue = (unsigned)rgb[index] & 255;
3634 vterm_state_set_palette_color(state, index, &color);
3635 }
3636}
3637
3638/*
3639 * Set the ANSI color palette from a list of colors
3640 */
3641 static int
3642set_ansi_colors_list(VTerm *vterm, list_T *list)
3643{
3644 int n = 0;
3645 long_u rgb[16];
3646 listitem_T *li = list->lv_first;
3647
3648 for (; li != NULL && n < 16; li = li->li_next, n++)
3649 {
3650 char_u *color_name;
3651 guicolor_T guicolor;
3652
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003653 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003654 if (color_name == NULL)
3655 return FAIL;
3656
3657 guicolor = GUI_GET_COLOR(color_name);
3658 if (guicolor == INVALCOLOR)
3659 return FAIL;
3660
3661 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3662 }
3663
3664 if (n != 16 || li != NULL)
3665 return FAIL;
3666
3667 set_vterm_palette(vterm, rgb);
3668
3669 return OK;
3670}
3671
3672/*
3673 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3674 */
3675 static void
3676init_vterm_ansi_colors(VTerm *vterm)
3677{
3678 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3679
3680 if (var != NULL
3681 && (var->di_tv.v_type != VAR_LIST
3682 || var->di_tv.vval.v_list == NULL
3683 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003684 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003685}
3686#endif
3687
Bram Moolenaar52acb112018-03-18 19:20:22 +01003688/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003689 * Handles a "drop" command from the job in the terminal.
3690 * "item" is the file name, "item->li_next" may have options.
3691 */
3692 static void
3693handle_drop_command(listitem_T *item)
3694{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003695 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003696 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003697 int bufnr;
3698 win_T *wp;
3699 tabpage_T *tp;
3700 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003701 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003702
3703 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3704 FOR_ALL_TAB_WINDOWS(tp, wp)
3705 {
3706 if (wp->w_buffer->b_fnum == bufnr)
3707 {
3708 /* buffer is in a window already, go there */
3709 goto_tabpage_win(tp, wp);
3710 return;
3711 }
3712 }
3713
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003714 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003715
3716 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3717 && opt_item->li_tv.vval.v_dict != NULL)
3718 {
3719 dict_T *dict = opt_item->li_tv.vval.v_dict;
3720 char_u *p;
3721
Bram Moolenaar8f667172018-12-14 15:38:31 +01003722 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003723 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003724 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003725 if (p != NULL)
3726 {
3727 if (check_ff_value(p) == FAIL)
3728 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3729 else
3730 ea.force_ff = *p;
3731 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003732 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003733 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003734 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003735 if (p != NULL)
3736 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003737 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003738 if (ea.cmd != NULL)
3739 {
3740 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3741 ea.force_enc = 11;
3742 tofree = ea.cmd;
3743 }
3744 }
3745
Bram Moolenaar8f667172018-12-14 15:38:31 +01003746 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003747 if (p != NULL)
3748 get_bad_opt(p, &ea);
3749
3750 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3751 ea.force_bin = FORCE_BIN;
3752 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3753 ea.force_bin = FORCE_BIN;
3754 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3755 ea.force_bin = FORCE_NOBIN;
3756 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3757 ea.force_bin = FORCE_NOBIN;
3758 }
3759
3760 /* open in new window, like ":split fname" */
3761 if (ea.cmd == NULL)
3762 ea.cmd = (char_u *)"split";
3763 ea.arg = fname;
3764 ea.cmdidx = CMD_split;
3765 ex_splitview(&ea);
3766
3767 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003768}
3769
3770/*
3771 * Handles a function call from the job running in a terminal.
3772 * "item" is the function name, "item->li_next" has the arguments.
3773 */
3774 static void
3775handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3776{
3777 char_u *func;
3778 typval_T argvars[2];
3779 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003780 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003781
3782 if (item->li_next == NULL)
3783 {
3784 ch_log(channel, "Missing function arguments for call");
3785 return;
3786 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003787 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003788
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003789 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003790 {
3791 ch_log(channel, "Invalid function name: %s", func);
3792 return;
3793 }
3794
3795 argvars[0].v_type = VAR_NUMBER;
3796 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3797 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003798 vim_memset(&funcexe, 0, sizeof(funcexe));
3799 funcexe.firstline = 1L;
3800 funcexe.lastline = 1L;
3801 funcexe.evaluate = TRUE;
3802 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003803 {
3804 clear_tv(&rettv);
3805 ch_log(channel, "Function %s called", func);
3806 }
3807 else
3808 ch_log(channel, "Calling function %s failed", func);
3809}
3810
3811/*
3812 * Called by libvterm when it cannot recognize an OSC sequence.
3813 * We recognize a terminal API command.
3814 */
3815 static int
3816parse_osc(const char *command, size_t cmdlen, void *user)
3817{
3818 term_T *term = (term_T *)user;
3819 js_read_T reader;
3820 typval_T tv;
3821 channel_T *channel = term->tl_job == NULL ? NULL
3822 : term->tl_job->jv_channel;
3823
3824 /* We recognize only OSC 5 1 ; {command} */
3825 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3826 return 0; /* not handled */
3827
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003828 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003829 if (reader.js_buf == NULL)
3830 return 1;
3831 reader.js_fill = NULL;
3832 reader.js_used = 0;
3833 if (json_decode(&reader, &tv, 0) == OK
3834 && tv.v_type == VAR_LIST
3835 && tv.vval.v_list != NULL)
3836 {
3837 listitem_T *item = tv.vval.v_list->lv_first;
3838
3839 if (item == NULL)
3840 ch_log(channel, "Missing command");
3841 else
3842 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003843 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003844
Bram Moolenaara997b452018-04-17 23:24:06 +02003845 /* Make sure an invoked command doesn't delete the buffer (and the
3846 * terminal) under our fingers. */
3847 ++term->tl_buffer->b_locked;
3848
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003849 item = item->li_next;
3850 if (item == NULL)
3851 ch_log(channel, "Missing argument for %s", cmd);
3852 else if (STRCMP(cmd, "drop") == 0)
3853 handle_drop_command(item);
3854 else if (STRCMP(cmd, "call") == 0)
3855 handle_call_command(term, channel, item);
3856 else
3857 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003858 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003859 }
3860 }
3861 else
3862 ch_log(channel, "Invalid JSON received");
3863
3864 vim_free(reader.js_buf);
3865 clear_tv(&tv);
3866 return 1;
3867}
3868
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003869/*
3870 * Called by libvterm when it cannot recognize a CSI sequence.
3871 * We recognize the window position report.
3872 */
3873 static int
3874parse_csi(
3875 const char *leader UNUSED,
3876 const long args[],
3877 int argcount,
3878 const char *intermed UNUSED,
3879 char command,
3880 void *user)
3881{
3882 term_T *term = (term_T *)user;
3883 char buf[100];
3884 int len;
3885 int x = 0;
3886 int y = 0;
3887 win_T *wp;
3888
3889 // We recognize only CSI 13 t
3890 if (command != 't' || argcount != 1 || args[0] != 13)
3891 return 0; // not handled
3892
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003893 // When getting the window position is not possible or it fails it results
3894 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02003895#if defined(FEAT_GUI) \
3896 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
3897 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003898 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003899#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003900
3901 FOR_ALL_WINDOWS(wp)
3902 if (wp->w_buffer == term->tl_buffer)
3903 break;
3904 if (wp != NULL)
3905 {
3906#ifdef FEAT_GUI
3907 if (gui.in_use)
3908 {
3909 x += wp->w_wincol * gui.char_width;
3910 y += W_WINROW(wp) * gui.char_height;
3911 }
3912 else
3913#endif
3914 {
3915 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003916 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003917 x += wp->w_wincol * 7;
3918 y += W_WINROW(wp) * 10;
3919 }
3920 }
3921
3922 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
3923 channel_send(term->tl_job->jv_channel, get_tty_part(term),
3924 (char_u *)buf, len, NULL);
3925 return 1;
3926}
3927
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003928static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003929 NULL, // text
3930 NULL, // control
3931 NULL, // escape
3932 parse_csi, // csi
3933 parse_osc, // osc
3934 NULL, // dcs
3935 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003936};
3937
3938/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003939 * Use Vim's allocation functions for vterm so profiling works.
3940 */
3941 static void *
3942vterm_malloc(size_t size, void *data UNUSED)
3943{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02003944 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003945}
3946
3947 static void
3948vterm_memfree(void *ptr, void *data UNUSED)
3949{
3950 vim_free(ptr);
3951}
3952
3953static VTermAllocatorFunctions vterm_allocator = {
3954 &vterm_malloc,
3955 &vterm_memfree
3956};
3957
3958/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003959 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003960 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01003961 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003962 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01003963create_vterm(term_T *term, int rows, int cols)
3964{
3965 VTerm *vterm;
3966 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003967 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003968 VTermValue value;
3969
Bram Moolenaar756ef112018-04-10 12:04:27 +02003970 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003971 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003972 if (vterm == NULL)
3973 return FAIL;
3974
3975 // Allocate screen and state here, so we can bail out if that fails.
3976 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003977 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003978 if (state == NULL || screen == NULL)
3979 {
3980 vterm_free(vterm);
3981 return FAIL;
3982 }
3983
Bram Moolenaar52acb112018-03-18 19:20:22 +01003984 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3985 /* TODO: depends on 'encoding'. */
3986 vterm_set_utf8(vterm, 1);
3987
3988 init_default_colors(term);
3989
3990 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003991 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01003992 &term->tl_default_color.fg,
3993 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003994
Bram Moolenaar9e587872019-05-13 20:27:23 +02003995 if (t_colors < 16)
3996 // Less than 16 colors: assume that bold means using a bright color for
3997 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003998 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3999
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004000 /* Required to initialize most things. */
4001 vterm_screen_reset(screen, 1 /* hard */);
4002
4003 /* Allow using alternate screen. */
4004 vterm_screen_enable_altscreen(screen, 1);
4005
4006 /* For unix do not use a blinking cursor. In an xterm this causes the
4007 * cursor to blink if it's blinking in the xterm.
4008 * For Windows we respect the system wide setting. */
Bram Moolenaar4f974752019-02-17 17:44:42 +01004009#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004010 if (GetCaretBlinkTime() == INFINITE)
4011 value.boolean = 0;
4012 else
4013 value.boolean = 1;
4014#else
4015 value.boolean = 0;
4016#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004017 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4018 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004019
4020 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004021}
4022
4023/*
4024 * Return the text to show for the buffer name and status.
4025 */
4026 char_u *
4027term_get_status_text(term_T *term)
4028{
4029 if (term->tl_status_text == NULL)
4030 {
4031 char_u *txt;
4032 size_t len;
4033
4034 if (term->tl_normal_mode)
4035 {
4036 if (term_job_running(term))
4037 txt = (char_u *)_("Terminal");
4038 else
4039 txt = (char_u *)_("Terminal-finished");
4040 }
4041 else if (term->tl_title != NULL)
4042 txt = term->tl_title;
4043 else if (term_none_open(term))
4044 txt = (char_u *)_("active");
4045 else if (term_job_running(term))
4046 txt = (char_u *)_("running");
4047 else
4048 txt = (char_u *)_("finished");
4049 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004050 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004051 if (term->tl_status_text != NULL)
4052 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4053 term->tl_buffer->b_fname, txt);
4054 }
4055 return term->tl_status_text;
4056}
4057
4058/*
4059 * Mark references in jobs of terminals.
4060 */
4061 int
4062set_ref_in_term(int copyID)
4063{
4064 int abort = FALSE;
4065 term_T *term;
4066 typval_T tv;
4067
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004068 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004069 if (term->tl_job != NULL)
4070 {
4071 tv.v_type = VAR_JOB;
4072 tv.vval.v_job = term->tl_job;
4073 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4074 }
4075 return abort;
4076}
4077
4078/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004079 * Cache "Terminal" highlight group colors.
4080 */
4081 void
4082set_terminal_default_colors(int cterm_fg, int cterm_bg)
4083{
4084 term_default_cterm_fg = cterm_fg - 1;
4085 term_default_cterm_bg = cterm_bg - 1;
4086}
4087
4088/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004089 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004090 * Returns NULL when the buffer is not for a terminal window and logs a message
4091 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004092 */
4093 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004094term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004095{
4096 buf_T *buf;
4097
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004098 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004099 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004100 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004101 --emsg_off;
4102 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004103 {
4104 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004105 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004106 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004107 return buf;
4108}
4109
Bram Moolenaard96ff162018-02-18 22:13:29 +01004110 static int
4111same_color(VTermColor *a, VTermColor *b)
4112{
4113 return a->red == b->red
4114 && a->green == b->green
4115 && a->blue == b->blue
4116 && a->ansi_index == b->ansi_index;
4117}
4118
4119 static void
4120dump_term_color(FILE *fd, VTermColor *color)
4121{
4122 fprintf(fd, "%02x%02x%02x%d",
4123 (int)color->red, (int)color->green, (int)color->blue,
4124 (int)color->ansi_index);
4125}
4126
4127/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004128 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004129 *
4130 * Each screen cell in full is:
4131 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4132 * {characters} is a space for an empty cell
4133 * For a double-width character "+" is changed to "*" and the next cell is
4134 * skipped.
4135 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4136 * when "&" use the same as the previous cell.
4137 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4138 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4139 * {color-idx} is a number from 0 to 255
4140 *
4141 * Screen cell with same width, attributes and color as the previous one:
4142 * |{characters}
4143 *
4144 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4145 *
4146 * Repeating the previous screen cell:
4147 * @{count}
4148 */
4149 void
4150f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4151{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004152 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004153 term_T *term;
4154 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004155 int max_height = 0;
4156 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004157 stat_T st;
4158 FILE *fd;
4159 VTermPos pos;
4160 VTermScreen *screen;
4161 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004162 VTermState *state;
4163 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004164
4165 if (check_restricted() || check_secure())
4166 return;
4167 if (buf == NULL)
4168 return;
4169 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004170 if (term->tl_vterm == NULL)
4171 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004172 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004173 return;
4174 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004175
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004176 if (argvars[2].v_type != VAR_UNKNOWN)
4177 {
4178 dict_T *d;
4179
4180 if (argvars[2].v_type != VAR_DICT)
4181 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004182 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004183 return;
4184 }
4185 d = argvars[2].vval.v_dict;
4186 if (d != NULL)
4187 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004188 max_height = dict_get_number(d, (char_u *)"rows");
4189 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004190 }
4191 }
4192
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004193 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004194 if (fname == NULL)
4195 return;
4196 if (mch_stat((char *)fname, &st) >= 0)
4197 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004198 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004199 return;
4200 }
4201
Bram Moolenaard96ff162018-02-18 22:13:29 +01004202 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4203 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004204 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004205 return;
4206 }
4207
4208 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4209
4210 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004211 state = vterm_obtain_state(term->tl_vterm);
4212 vterm_state_get_cursorpos(state, &cursor_pos);
4213
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004214 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4215 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004216 {
4217 int repeat = 0;
4218
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004219 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4220 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004221 {
4222 VTermScreenCell cell;
4223 int same_attr;
4224 int same_chars = TRUE;
4225 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004226 int is_cursor_pos = (pos.col == cursor_pos.col
4227 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004228
4229 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4230 vim_memset(&cell, 0, sizeof(cell));
4231
4232 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4233 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004234 int c = cell.chars[i];
4235 int pc = prev_cell.chars[i];
4236
4237 /* For the first character NUL is the same as space. */
4238 if (i == 0)
4239 {
4240 c = (c == NUL) ? ' ' : c;
4241 pc = (pc == NUL) ? ' ' : pc;
4242 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004243 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004244 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004245 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004246 break;
4247 }
4248 same_attr = vtermAttr2hl(cell.attrs)
4249 == vtermAttr2hl(prev_cell.attrs)
4250 && same_color(&cell.fg, &prev_cell.fg)
4251 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004252 if (same_chars && cell.width == prev_cell.width && same_attr
4253 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004254 {
4255 ++repeat;
4256 }
4257 else
4258 {
4259 if (repeat > 0)
4260 {
4261 fprintf(fd, "@%d", repeat);
4262 repeat = 0;
4263 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004264 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004265
4266 if (cell.chars[0] == NUL)
4267 fputs(" ", fd);
4268 else
4269 {
4270 char_u charbuf[10];
4271 int len;
4272
4273 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4274 && cell.chars[i] != NUL; ++i)
4275 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004276 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004277 fwrite(charbuf, len, 1, fd);
4278 }
4279 }
4280
4281 /* When only the characters differ we don't write anything, the
4282 * following "|", "@" or NL will indicate using the same
4283 * attributes. */
4284 if (cell.width != prev_cell.width || !same_attr)
4285 {
4286 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004287 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004288 else
4289 fputs("+", fd);
4290
4291 if (same_attr)
4292 {
4293 fputs("&", fd);
4294 }
4295 else
4296 {
4297 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4298 if (same_color(&cell.fg, &prev_cell.fg))
4299 fputs("&", fd);
4300 else
4301 {
4302 fputs("#", fd);
4303 dump_term_color(fd, &cell.fg);
4304 }
4305 if (same_color(&cell.bg, &prev_cell.bg))
4306 fputs("&", fd);
4307 else
4308 {
4309 fputs("#", fd);
4310 dump_term_color(fd, &cell.bg);
4311 }
4312 }
4313 }
4314
4315 prev_cell = cell;
4316 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004317
4318 if (cell.width == 2)
4319 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004320 }
4321 if (repeat > 0)
4322 fprintf(fd, "@%d", repeat);
4323 fputs("\n", fd);
4324 }
4325
4326 fclose(fd);
4327}
4328
4329/*
4330 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4331 */
4332 static void
4333dump_is_corrupt(garray_T *gap)
4334{
4335 ga_concat(gap, (char_u *)"CORRUPT");
4336}
4337
4338 static void
4339append_cell(garray_T *gap, cellattr_T *cell)
4340{
4341 if (ga_grow(gap, 1) == OK)
4342 {
4343 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4344 ++gap->ga_len;
4345 }
4346}
4347
4348/*
4349 * Read the dump file from "fd" and append lines to the current buffer.
4350 * Return the cell width of the longest line.
4351 */
4352 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004353read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004354{
4355 int c;
4356 garray_T ga_text;
4357 garray_T ga_cell;
4358 char_u *prev_char = NULL;
4359 int attr = 0;
4360 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004361 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004362 term_T *term = curbuf->b_term;
4363 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004364 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004365
4366 ga_init2(&ga_text, 1, 90);
4367 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4368 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004369 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004370 cursor_pos->row = -1;
4371 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004372
4373 c = fgetc(fd);
4374 for (;;)
4375 {
4376 if (c == EOF)
4377 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004378 if (c == '\r')
4379 {
4380 // DOS line endings? Ignore.
4381 c = fgetc(fd);
4382 }
4383 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004384 {
4385 /* End of a line: append it to the buffer. */
4386 if (ga_text.ga_data == NULL)
4387 dump_is_corrupt(&ga_text);
4388 if (ga_grow(&term->tl_scrollback, 1) == OK)
4389 {
4390 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4391 + term->tl_scrollback.ga_len;
4392
4393 if (max_cells < ga_cell.ga_len)
4394 max_cells = ga_cell.ga_len;
4395 line->sb_cols = ga_cell.ga_len;
4396 line->sb_cells = ga_cell.ga_data;
4397 line->sb_fill_attr = term->tl_default_color;
4398 ++term->tl_scrollback.ga_len;
4399 ga_init(&ga_cell);
4400
4401 ga_append(&ga_text, NUL);
4402 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4403 ga_text.ga_len, FALSE);
4404 }
4405 else
4406 ga_clear(&ga_cell);
4407 ga_text.ga_len = 0;
4408
4409 c = fgetc(fd);
4410 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004411 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004412 {
4413 int prev_len = ga_text.ga_len;
4414
Bram Moolenaar9271d052018-02-25 21:39:46 +01004415 if (c == '>')
4416 {
4417 if (cursor_pos->row != -1)
4418 dump_is_corrupt(&ga_text); /* duplicate cursor */
4419 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4420 cursor_pos->col = ga_cell.ga_len;
4421 }
4422
Bram Moolenaard96ff162018-02-18 22:13:29 +01004423 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4424 c = fgetc(fd);
4425 if (c != EOF)
4426 ga_append(&ga_text, c);
4427 for (;;)
4428 {
4429 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004430 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004431 || c == EOF || c == '\n')
4432 break;
4433 ga_append(&ga_text, c);
4434 }
4435
4436 /* save the character for repeating it */
4437 vim_free(prev_char);
4438 if (ga_text.ga_data != NULL)
4439 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4440 ga_text.ga_len - prev_len);
4441
Bram Moolenaar9271d052018-02-25 21:39:46 +01004442 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004443 {
4444 /* use all attributes from previous cell */
4445 }
4446 else if (c == '+' || c == '*')
4447 {
4448 int is_bg;
4449
4450 cell.width = c == '+' ? 1 : 2;
4451
4452 c = fgetc(fd);
4453 if (c == '&')
4454 {
4455 /* use same attr as previous cell */
4456 c = fgetc(fd);
4457 }
4458 else if (isdigit(c))
4459 {
4460 /* get the decimal attribute */
4461 attr = 0;
4462 while (isdigit(c))
4463 {
4464 attr = attr * 10 + (c - '0');
4465 c = fgetc(fd);
4466 }
4467 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004468
4469 /* is_bg == 0: fg, is_bg == 1: bg */
4470 for (is_bg = 0; is_bg <= 1; ++is_bg)
4471 {
4472 if (c == '&')
4473 {
4474 /* use same color as previous cell */
4475 c = fgetc(fd);
4476 }
4477 else if (c == '#')
4478 {
4479 int red, green, blue, index = 0;
4480
4481 c = fgetc(fd);
4482 red = hex2nr(c);
4483 c = fgetc(fd);
4484 red = (red << 4) + hex2nr(c);
4485 c = fgetc(fd);
4486 green = hex2nr(c);
4487 c = fgetc(fd);
4488 green = (green << 4) + hex2nr(c);
4489 c = fgetc(fd);
4490 blue = hex2nr(c);
4491 c = fgetc(fd);
4492 blue = (blue << 4) + hex2nr(c);
4493 c = fgetc(fd);
4494 if (!isdigit(c))
4495 dump_is_corrupt(&ga_text);
4496 while (isdigit(c))
4497 {
4498 index = index * 10 + (c - '0');
4499 c = fgetc(fd);
4500 }
4501
4502 if (is_bg)
4503 {
4504 cell.bg.red = red;
4505 cell.bg.green = green;
4506 cell.bg.blue = blue;
4507 cell.bg.ansi_index = index;
4508 }
4509 else
4510 {
4511 cell.fg.red = red;
4512 cell.fg.green = green;
4513 cell.fg.blue = blue;
4514 cell.fg.ansi_index = index;
4515 }
4516 }
4517 else
4518 dump_is_corrupt(&ga_text);
4519 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004520 }
4521 else
4522 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004523 }
4524 else
4525 dump_is_corrupt(&ga_text);
4526
4527 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004528 if (cell.width == 2)
4529 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004530 }
4531 else if (c == '@')
4532 {
4533 if (prev_char == NULL)
4534 dump_is_corrupt(&ga_text);
4535 else
4536 {
4537 int count = 0;
4538
4539 /* repeat previous character, get the count */
4540 for (;;)
4541 {
4542 c = fgetc(fd);
4543 if (!isdigit(c))
4544 break;
4545 count = count * 10 + (c - '0');
4546 }
4547
4548 while (count-- > 0)
4549 {
4550 ga_concat(&ga_text, prev_char);
4551 append_cell(&ga_cell, &cell);
4552 }
4553 }
4554 }
4555 else
4556 {
4557 dump_is_corrupt(&ga_text);
4558 c = fgetc(fd);
4559 }
4560 }
4561
4562 if (ga_text.ga_len > 0)
4563 {
4564 /* trailing characters after last NL */
4565 dump_is_corrupt(&ga_text);
4566 ga_append(&ga_text, NUL);
4567 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4568 ga_text.ga_len, FALSE);
4569 }
4570
4571 ga_clear(&ga_text);
4572 vim_free(prev_char);
4573
4574 return max_cells;
4575}
4576
4577/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004578 * Return an allocated string with at least "text_width" "=" characters and
4579 * "fname" inserted in the middle.
4580 */
4581 static char_u *
4582get_separator(int text_width, char_u *fname)
4583{
4584 int width = MAX(text_width, curwin->w_width);
4585 char_u *textline;
4586 int fname_size;
4587 char_u *p = fname;
4588 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004589 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004590
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004591 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004592 if (textline == NULL)
4593 return NULL;
4594
4595 fname_size = vim_strsize(fname);
4596 if (fname_size < width - 8)
4597 {
4598 /* enough room, don't use the full window width */
4599 width = MAX(text_width, fname_size + 8);
4600 }
4601 else if (fname_size > width - 8)
4602 {
4603 /* full name doesn't fit, use only the tail */
4604 p = gettail(fname);
4605 fname_size = vim_strsize(p);
4606 }
4607 /* skip characters until the name fits */
4608 while (fname_size > width - 8)
4609 {
4610 p += (*mb_ptr2len)(p);
4611 fname_size = vim_strsize(p);
4612 }
4613
4614 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4615 textline[i] = '=';
4616 textline[i++] = ' ';
4617
4618 STRCPY(textline + i, p);
4619 off = STRLEN(textline);
4620 textline[off] = ' ';
4621 for (i = 1; i < (width - fname_size) / 2; ++i)
4622 textline[off + i] = '=';
4623 textline[off + i] = NUL;
4624
4625 return textline;
4626}
4627
4628/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004629 * Common for "term_dumpdiff()" and "term_dumpload()".
4630 */
4631 static void
4632term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4633{
4634 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004635 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004636 char_u buf1[NUMBUFLEN];
4637 char_u buf2[NUMBUFLEN];
4638 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004639 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004640 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004641 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004642 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004643 char_u *textline = NULL;
4644
4645 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004646 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004647 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004648 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004649 if (fname1 == NULL || (do_diff && fname2 == NULL))
4650 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004651 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004652 return;
4653 }
4654 fd1 = mch_fopen((char *)fname1, READBIN);
4655 if (fd1 == NULL)
4656 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004657 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004658 return;
4659 }
4660 if (do_diff)
4661 {
4662 fd2 = mch_fopen((char *)fname2, READBIN);
4663 if (fd2 == NULL)
4664 {
4665 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004666 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004667 return;
4668 }
4669 }
4670
4671 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004672 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4673 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4674 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4675 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4676 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004677
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004678 if (opt.jo_term_name == NULL)
4679 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004680 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004681
Bram Moolenaar51e14382019-05-25 20:21:28 +02004682 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004683 if (fname_tofree != NULL)
4684 {
4685 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4686 opt.jo_term_name = fname_tofree;
4687 }
4688 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004689
Bram Moolenaar87abab92019-06-03 21:14:59 +02004690 if (opt.jo_bufnr_buf != NULL)
4691 {
4692 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4693
4694 // With "bufnr" argument: enter the window with this buffer and make it
4695 // empty.
4696 if (wp == NULL)
4697 semsg(_(e_invarg2), "bufnr");
4698 else
4699 {
4700 buf = curbuf;
4701 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4702 ml_delete((linenr_T)1, FALSE);
4703 ga_clear(&curbuf->b_term->tl_scrollback);
4704 redraw_later(NOT_VALID);
4705 }
4706 }
4707 else
4708 // Create a new terminal window.
4709 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4710
Bram Moolenaard96ff162018-02-18 22:13:29 +01004711 if (buf != NULL && buf->b_term != NULL)
4712 {
4713 int i;
4714 linenr_T bot_lnum;
4715 linenr_T lnum;
4716 term_T *term = buf->b_term;
4717 int width;
4718 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004719 VTermPos cursor_pos1;
4720 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004721
Bram Moolenaar52acb112018-03-18 19:20:22 +01004722 init_default_colors(term);
4723
Bram Moolenaard96ff162018-02-18 22:13:29 +01004724 rettv->vval.v_number = buf->b_fnum;
4725
4726 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004727 width = read_dump_file(fd1, &cursor_pos1);
4728
4729 /* position the cursor */
4730 if (cursor_pos1.row >= 0)
4731 {
4732 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4733 coladvance(cursor_pos1.col);
4734 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004735
4736 /* Delete the empty line that was in the empty buffer. */
4737 ml_delete(1, FALSE);
4738
4739 /* For term_dumpload() we are done here. */
4740 if (!do_diff)
4741 goto theend;
4742
4743 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4744
Bram Moolenaar4a696342018-04-05 18:45:26 +02004745 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004746 if (textline == NULL)
4747 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004748 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4749 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4750 vim_free(textline);
4751
4752 textline = get_separator(width, fname2);
4753 if (textline == NULL)
4754 goto theend;
4755 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4756 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004757 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004758
4759 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004760 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004761 if (width2 > width)
4762 {
4763 vim_free(textline);
4764 textline = alloc(width2 + 1);
4765 if (textline == NULL)
4766 goto theend;
4767 width = width2;
4768 textline[width] = NUL;
4769 }
4770 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4771
4772 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4773 {
4774 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4775 {
4776 /* bottom part has fewer rows, fill with "-" */
4777 for (i = 0; i < width; ++i)
4778 textline[i] = '-';
4779 }
4780 else
4781 {
4782 char_u *line1;
4783 char_u *line2;
4784 char_u *p1;
4785 char_u *p2;
4786 int col;
4787 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4788 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4789 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4790 ->sb_cells;
4791
4792 /* Make a copy, getting the second line will invalidate it. */
4793 line1 = vim_strsave(ml_get(lnum));
4794 if (line1 == NULL)
4795 break;
4796 p1 = line1;
4797
4798 line2 = ml_get(lnum + bot_lnum);
4799 p2 = line2;
4800 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4801 {
4802 int len1 = utfc_ptr2len(p1);
4803 int len2 = utfc_ptr2len(p2);
4804
4805 textline[col] = ' ';
4806 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004807 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004808 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004809 else if (lnum == cursor_pos1.row + 1
4810 && col == cursor_pos1.col
4811 && (cursor_pos1.row != cursor_pos2.row
4812 || cursor_pos1.col != cursor_pos2.col))
4813 /* cursor in first but not in second */
4814 textline[col] = '>';
4815 else if (lnum == cursor_pos2.row + 1
4816 && col == cursor_pos2.col
4817 && (cursor_pos1.row != cursor_pos2.row
4818 || cursor_pos1.col != cursor_pos2.col))
4819 /* cursor in second but not in first */
4820 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004821 else if (cellattr1 != NULL && cellattr2 != NULL)
4822 {
4823 if ((cellattr1 + col)->width
4824 != (cellattr2 + col)->width)
4825 textline[col] = 'w';
4826 else if (!same_color(&(cellattr1 + col)->fg,
4827 &(cellattr2 + col)->fg))
4828 textline[col] = 'f';
4829 else if (!same_color(&(cellattr1 + col)->bg,
4830 &(cellattr2 + col)->bg))
4831 textline[col] = 'b';
4832 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4833 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4834 textline[col] = 'a';
4835 }
4836 p1 += len1;
4837 p2 += len2;
4838 /* TODO: handle different width */
4839 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004840
4841 while (col < width)
4842 {
4843 if (*p1 == NUL && *p2 == NUL)
4844 textline[col] = '?';
4845 else if (*p1 == NUL)
4846 {
4847 textline[col] = '+';
4848 p2 += utfc_ptr2len(p2);
4849 }
4850 else
4851 {
4852 textline[col] = '-';
4853 p1 += utfc_ptr2len(p1);
4854 }
4855 ++col;
4856 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004857
4858 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004859 }
4860 if (add_empty_scrollback(term, &term->tl_default_color,
4861 term->tl_top_diff_rows) == OK)
4862 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4863 ++bot_lnum;
4864 }
4865
4866 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4867 {
4868 /* bottom part has more rows, fill with "+" */
4869 for (i = 0; i < width; ++i)
4870 textline[i] = '+';
4871 if (add_empty_scrollback(term, &term->tl_default_color,
4872 term->tl_top_diff_rows) == OK)
4873 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4874 ++lnum;
4875 ++bot_lnum;
4876 }
4877
4878 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004879
4880 /* looks better without wrapping */
4881 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004882 }
4883
4884theend:
4885 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004886 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004887 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004888 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004889 fclose(fd2);
4890}
4891
4892/*
4893 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4894 * bottom files.
4895 * Return FAIL when this is not possible.
4896 */
4897 int
4898term_swap_diff()
4899{
4900 term_T *term = curbuf->b_term;
4901 linenr_T line_count;
4902 linenr_T top_rows;
4903 linenr_T bot_rows;
4904 linenr_T bot_start;
4905 linenr_T lnum;
4906 char_u *p;
4907 sb_line_T *sb_line;
4908
4909 if (term == NULL
4910 || !term_is_finished(curbuf)
4911 || term->tl_top_diff_rows == 0
4912 || term->tl_scrollback.ga_len == 0)
4913 return FAIL;
4914
4915 line_count = curbuf->b_ml.ml_line_count;
4916 top_rows = term->tl_top_diff_rows;
4917 bot_rows = term->tl_bot_diff_rows;
4918 bot_start = line_count - bot_rows;
4919 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4920
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004921 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01004922 for (lnum = 1; lnum <= top_rows; ++lnum)
4923 {
4924 p = vim_strsave(ml_get(1));
4925 if (p == NULL)
4926 return OK;
4927 ml_append(bot_start, p, 0, FALSE);
4928 ml_delete(1, FALSE);
4929 vim_free(p);
4930 }
4931
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004932 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01004933 for (lnum = 1; lnum <= bot_rows; ++lnum)
4934 {
4935 p = vim_strsave(ml_get(bot_start + lnum));
4936 if (p == NULL)
4937 return OK;
4938 ml_delete(bot_start + lnum, FALSE);
4939 ml_append(lnum - 1, p, 0, FALSE);
4940 vim_free(p);
4941 }
4942
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004943 // move top title to bottom
4944 p = vim_strsave(ml_get(bot_rows + 1));
4945 if (p == NULL)
4946 return OK;
4947 ml_append(line_count - top_rows - 1, p, 0, FALSE);
4948 ml_delete(bot_rows + 1, FALSE);
4949 vim_free(p);
4950
4951 // move bottom title to top
4952 p = vim_strsave(ml_get(line_count - top_rows));
4953 if (p == NULL)
4954 return OK;
4955 ml_delete(line_count - top_rows, FALSE);
4956 ml_append(bot_rows, p, 0, FALSE);
4957 vim_free(p);
4958
Bram Moolenaard96ff162018-02-18 22:13:29 +01004959 if (top_rows == bot_rows)
4960 {
4961 /* rows counts are equal, can swap cell properties */
4962 for (lnum = 0; lnum < top_rows; ++lnum)
4963 {
4964 sb_line_T temp;
4965
4966 temp = *(sb_line + lnum);
4967 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4968 *(sb_line + bot_start + lnum) = temp;
4969 }
4970 }
4971 else
4972 {
4973 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004974 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004975
4976 /* need to copy cell properties into temp memory */
4977 if (temp != NULL)
4978 {
4979 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4980 mch_memmove(term->tl_scrollback.ga_data,
4981 temp + bot_start,
4982 sizeof(sb_line_T) * bot_rows);
4983 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4984 temp + top_rows,
4985 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4986 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4987 + line_count - top_rows,
4988 temp,
4989 sizeof(sb_line_T) * top_rows);
4990 vim_free(temp);
4991 }
4992 }
4993
4994 term->tl_top_diff_rows = bot_rows;
4995 term->tl_bot_diff_rows = top_rows;
4996
4997 update_screen(NOT_VALID);
4998 return OK;
4999}
5000
5001/*
5002 * "term_dumpdiff(filename, filename, options)" function
5003 */
5004 void
5005f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5006{
5007 term_load_dump(argvars, rettv, TRUE);
5008}
5009
5010/*
5011 * "term_dumpload(filename, options)" function
5012 */
5013 void
5014f_term_dumpload(typval_T *argvars, typval_T *rettv)
5015{
5016 term_load_dump(argvars, rettv, FALSE);
5017}
5018
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005019/*
5020 * "term_getaltscreen(buf)" function
5021 */
5022 void
5023f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5024{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005025 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005026
5027 if (buf == NULL)
5028 return;
5029 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5030}
5031
5032/*
5033 * "term_getattr(attr, name)" function
5034 */
5035 void
5036f_term_getattr(typval_T *argvars, typval_T *rettv)
5037{
5038 int attr;
5039 size_t i;
5040 char_u *name;
5041
5042 static struct {
5043 char *name;
5044 int attr;
5045 } attrs[] = {
5046 {"bold", HL_BOLD},
5047 {"italic", HL_ITALIC},
5048 {"underline", HL_UNDERLINE},
5049 {"strike", HL_STRIKETHROUGH},
5050 {"reverse", HL_INVERSE},
5051 };
5052
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005053 attr = tv_get_number(&argvars[0]);
5054 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005055 if (name == NULL)
5056 return;
5057
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005058 if (attr > HL_ALL)
5059 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005060 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5061 if (STRCMP(name, attrs[i].name) == 0)
5062 {
5063 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5064 break;
5065 }
5066}
5067
5068/*
5069 * "term_getcursor(buf)" function
5070 */
5071 void
5072f_term_getcursor(typval_T *argvars, typval_T *rettv)
5073{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005074 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005075 term_T *term;
5076 list_T *l;
5077 dict_T *d;
5078
5079 if (rettv_list_alloc(rettv) == FAIL)
5080 return;
5081 if (buf == NULL)
5082 return;
5083 term = buf->b_term;
5084
5085 l = rettv->vval.v_list;
5086 list_append_number(l, term->tl_cursor_pos.row + 1);
5087 list_append_number(l, term->tl_cursor_pos.col + 1);
5088
5089 d = dict_alloc();
5090 if (d != NULL)
5091 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005092 dict_add_number(d, "visible", term->tl_cursor_visible);
5093 dict_add_number(d, "blink", blink_state_is_inverted()
5094 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5095 dict_add_number(d, "shape", term->tl_cursor_shape);
5096 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005097 list_append_dict(l, d);
5098 }
5099}
5100
5101/*
5102 * "term_getjob(buf)" function
5103 */
5104 void
5105f_term_getjob(typval_T *argvars, typval_T *rettv)
5106{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005107 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005108
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005109 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005110 {
5111 rettv->v_type = VAR_SPECIAL;
5112 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005113 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005114 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005115
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005116 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005117 rettv->vval.v_job = buf->b_term->tl_job;
5118 if (rettv->vval.v_job != NULL)
5119 ++rettv->vval.v_job->jv_refcount;
5120}
5121
5122 static int
5123get_row_number(typval_T *tv, term_T *term)
5124{
5125 if (tv->v_type == VAR_STRING
5126 && tv->vval.v_string != NULL
5127 && STRCMP(tv->vval.v_string, ".") == 0)
5128 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005129 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005130}
5131
5132/*
5133 * "term_getline(buf, row)" function
5134 */
5135 void
5136f_term_getline(typval_T *argvars, typval_T *rettv)
5137{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005138 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005139 term_T *term;
5140 int row;
5141
5142 rettv->v_type = VAR_STRING;
5143 if (buf == NULL)
5144 return;
5145 term = buf->b_term;
5146 row = get_row_number(&argvars[1], term);
5147
5148 if (term->tl_vterm == NULL)
5149 {
5150 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5151
5152 /* vterm is finished, get the text from the buffer */
5153 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5154 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5155 }
5156 else
5157 {
5158 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5159 VTermRect rect;
5160 int len;
5161 char_u *p;
5162
5163 if (row < 0 || row >= term->tl_rows)
5164 return;
5165 len = term->tl_cols * MB_MAXBYTES + 1;
5166 p = alloc(len);
5167 if (p == NULL)
5168 return;
5169 rettv->vval.v_string = p;
5170
5171 rect.start_col = 0;
5172 rect.end_col = term->tl_cols;
5173 rect.start_row = row;
5174 rect.end_row = row + 1;
5175 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5176 }
5177}
5178
5179/*
5180 * "term_getscrolled(buf)" function
5181 */
5182 void
5183f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5184{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005185 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005186
5187 if (buf == NULL)
5188 return;
5189 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5190}
5191
5192/*
5193 * "term_getsize(buf)" function
5194 */
5195 void
5196f_term_getsize(typval_T *argvars, typval_T *rettv)
5197{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005198 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005199 list_T *l;
5200
5201 if (rettv_list_alloc(rettv) == FAIL)
5202 return;
5203 if (buf == NULL)
5204 return;
5205
5206 l = rettv->vval.v_list;
5207 list_append_number(l, buf->b_term->tl_rows);
5208 list_append_number(l, buf->b_term->tl_cols);
5209}
5210
5211/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005212 * "term_setsize(buf, rows, cols)" function
5213 */
5214 void
5215f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5216{
5217 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5218 term_T *term;
5219 varnumber_T rows, cols;
5220
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005221 if (buf == NULL)
5222 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005223 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005224 return;
5225 }
5226 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005227 return;
5228 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005229 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005230 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005231 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005232 cols = cols <= 0 ? term->tl_cols : cols;
5233 vterm_set_size(term->tl_vterm, rows, cols);
5234 /* handle_resize() will resize the windows */
5235
5236 /* Get and remember the size we ended up with. Update the pty. */
5237 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5238 term_report_winsize(term, term->tl_rows, term->tl_cols);
5239}
5240
5241/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005242 * "term_getstatus(buf)" function
5243 */
5244 void
5245f_term_getstatus(typval_T *argvars, typval_T *rettv)
5246{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005247 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005248 term_T *term;
5249 char_u val[100];
5250
5251 rettv->v_type = VAR_STRING;
5252 if (buf == NULL)
5253 return;
5254 term = buf->b_term;
5255
5256 if (term_job_running(term))
5257 STRCPY(val, "running");
5258 else
5259 STRCPY(val, "finished");
5260 if (term->tl_normal_mode)
5261 STRCAT(val, ",normal");
5262 rettv->vval.v_string = vim_strsave(val);
5263}
5264
5265/*
5266 * "term_gettitle(buf)" function
5267 */
5268 void
5269f_term_gettitle(typval_T *argvars, typval_T *rettv)
5270{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005271 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005272
5273 rettv->v_type = VAR_STRING;
5274 if (buf == NULL)
5275 return;
5276
5277 if (buf->b_term->tl_title != NULL)
5278 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5279}
5280
5281/*
5282 * "term_gettty(buf)" function
5283 */
5284 void
5285f_term_gettty(typval_T *argvars, typval_T *rettv)
5286{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005287 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005288 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005289 int num = 0;
5290
5291 rettv->v_type = VAR_STRING;
5292 if (buf == NULL)
5293 return;
5294 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005295 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005296
5297 switch (num)
5298 {
5299 case 0:
5300 if (buf->b_term->tl_job != NULL)
5301 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005302 break;
5303 case 1:
5304 if (buf->b_term->tl_job != NULL)
5305 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005306 break;
5307 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005308 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005309 return;
5310 }
5311 if (p != NULL)
5312 rettv->vval.v_string = vim_strsave(p);
5313}
5314
5315/*
5316 * "term_list()" function
5317 */
5318 void
5319f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5320{
5321 term_T *tp;
5322 list_T *l;
5323
5324 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5325 return;
5326
5327 l = rettv->vval.v_list;
5328 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5329 if (tp != NULL && tp->tl_buffer != NULL)
5330 if (list_append_number(l,
5331 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5332 return;
5333}
5334
5335/*
5336 * "term_scrape(buf, row)" function
5337 */
5338 void
5339f_term_scrape(typval_T *argvars, typval_T *rettv)
5340{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005341 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005342 VTermScreen *screen = NULL;
5343 VTermPos pos;
5344 list_T *l;
5345 term_T *term;
5346 char_u *p;
5347 sb_line_T *line;
5348
5349 if (rettv_list_alloc(rettv) == FAIL)
5350 return;
5351 if (buf == NULL)
5352 return;
5353 term = buf->b_term;
5354
5355 l = rettv->vval.v_list;
5356 pos.row = get_row_number(&argvars[1], term);
5357
5358 if (term->tl_vterm != NULL)
5359 {
5360 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005361 if (screen == NULL) // can't really happen
5362 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005363 p = NULL;
5364 line = NULL;
5365 }
5366 else
5367 {
5368 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5369
5370 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5371 return;
5372 p = ml_get_buf(buf, lnum + 1, FALSE);
5373 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5374 }
5375
5376 for (pos.col = 0; pos.col < term->tl_cols; )
5377 {
5378 dict_T *dcell;
5379 int width;
5380 VTermScreenCellAttrs attrs;
5381 VTermColor fg, bg;
5382 char_u rgb[8];
5383 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5384 int off = 0;
5385 int i;
5386
5387 if (screen == NULL)
5388 {
5389 cellattr_T *cellattr;
5390 int len;
5391
5392 /* vterm has finished, get the cell from scrollback */
5393 if (pos.col >= line->sb_cols)
5394 break;
5395 cellattr = line->sb_cells + pos.col;
5396 width = cellattr->width;
5397 attrs = cellattr->attrs;
5398 fg = cellattr->fg;
5399 bg = cellattr->bg;
5400 len = MB_PTR2LEN(p);
5401 mch_memmove(mbs, p, len);
5402 mbs[len] = NUL;
5403 p += len;
5404 }
5405 else
5406 {
5407 VTermScreenCell cell;
5408 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5409 break;
5410 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5411 {
5412 if (cell.chars[i] == 0)
5413 break;
5414 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5415 }
5416 mbs[off] = NUL;
5417 width = cell.width;
5418 attrs = cell.attrs;
5419 fg = cell.fg;
5420 bg = cell.bg;
5421 }
5422 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005423 if (dcell == NULL)
5424 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005425 list_append_dict(l, dcell);
5426
Bram Moolenaare0be1672018-07-08 16:50:37 +02005427 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005428
5429 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5430 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005431 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005432 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5433 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005434 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005435
Bram Moolenaare0be1672018-07-08 16:50:37 +02005436 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5437 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005438
5439 ++pos.col;
5440 if (width == 2)
5441 ++pos.col;
5442 }
5443}
5444
5445/*
5446 * "term_sendkeys(buf, keys)" function
5447 */
5448 void
5449f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5450{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005451 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005452 char_u *msg;
5453 term_T *term;
5454
5455 rettv->v_type = VAR_UNKNOWN;
5456 if (buf == NULL)
5457 return;
5458
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005459 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005460 if (msg == NULL)
5461 return;
5462 term = buf->b_term;
5463 if (term->tl_vterm == NULL)
5464 return;
5465
5466 while (*msg != NUL)
5467 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005468 int c;
5469
5470 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5471 {
5472 c = TO_SPECIAL(msg[1], msg[2]);
5473 msg += 3;
5474 }
5475 else
5476 {
5477 c = PTR2CHAR(msg);
5478 msg += MB_CPTR2LEN(msg);
5479 }
5480 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005481 }
5482}
5483
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005484#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5485/*
5486 * "term_getansicolors(buf)" function
5487 */
5488 void
5489f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5490{
5491 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5492 term_T *term;
5493 VTermState *state;
5494 VTermColor color;
5495 char_u hexbuf[10];
5496 int index;
5497 list_T *list;
5498
5499 if (rettv_list_alloc(rettv) == FAIL)
5500 return;
5501
5502 if (buf == NULL)
5503 return;
5504 term = buf->b_term;
5505 if (term->tl_vterm == NULL)
5506 return;
5507
5508 list = rettv->vval.v_list;
5509 state = vterm_obtain_state(term->tl_vterm);
5510 for (index = 0; index < 16; index++)
5511 {
5512 vterm_state_get_palette_color(state, index, &color);
5513 sprintf((char *)hexbuf, "#%02x%02x%02x",
5514 color.red, color.green, color.blue);
5515 if (list_append_string(list, hexbuf, 7) == FAIL)
5516 return;
5517 }
5518}
5519
5520/*
5521 * "term_setansicolors(buf, list)" function
5522 */
5523 void
5524f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5525{
5526 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5527 term_T *term;
5528
5529 if (buf == NULL)
5530 return;
5531 term = buf->b_term;
5532 if (term->tl_vterm == NULL)
5533 return;
5534
5535 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5536 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005537 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005538 return;
5539 }
5540
5541 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005542 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005543}
5544#endif
5545
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005546/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005547 * "term_setrestore(buf, command)" function
5548 */
5549 void
5550f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5551{
5552#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005553 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005554 term_T *term;
5555 char_u *cmd;
5556
5557 if (buf == NULL)
5558 return;
5559 term = buf->b_term;
5560 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005561 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005562 if (cmd != NULL)
5563 term->tl_command = vim_strsave(cmd);
5564 else
5565 term->tl_command = NULL;
5566#endif
5567}
5568
5569/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005570 * "term_setkill(buf, how)" function
5571 */
5572 void
5573f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5574{
5575 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5576 term_T *term;
5577 char_u *how;
5578
5579 if (buf == NULL)
5580 return;
5581 term = buf->b_term;
5582 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005583 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005584 if (how != NULL)
5585 term->tl_kill = vim_strsave(how);
5586 else
5587 term->tl_kill = NULL;
5588}
5589
5590/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005591 * "term_start(command, options)" function
5592 */
5593 void
5594f_term_start(typval_T *argvars, typval_T *rettv)
5595{
5596 jobopt_T opt;
5597 buf_T *buf;
5598
5599 init_job_options(&opt);
5600 if (argvars[1].v_type != VAR_UNKNOWN
5601 && get_job_options(&argvars[1], &opt,
5602 JO_TIMEOUT_ALL + JO_STOPONEXIT
5603 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5604 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5605 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5606 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005607 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005608 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01005609 + JO2_ANSI_COLORS + JO2_TTY_TYPE) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005610 return;
5611
Bram Moolenaar13568252018-03-16 20:46:58 +01005612 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005613
5614 if (buf != NULL && buf->b_term != NULL)
5615 rettv->vval.v_number = buf->b_fnum;
5616}
5617
5618/*
5619 * "term_wait" function
5620 */
5621 void
5622f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5623{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005624 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005625
5626 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005627 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005628 if (buf->b_term->tl_job == NULL)
5629 {
5630 ch_log(NULL, "term_wait(): no job to wait for");
5631 return;
5632 }
5633 if (buf->b_term->tl_job->jv_channel == NULL)
5634 /* channel is closed, nothing to do */
5635 return;
5636
5637 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005638 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005639 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5640 {
5641 /* The job is dead, keep reading channel I/O until the channel is
5642 * closed. buf->b_term may become NULL if the terminal was closed while
5643 * waiting. */
5644 ch_log(NULL, "term_wait(): waiting for channel to close");
5645 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5646 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005647 term_flush_messages();
5648
Bram Moolenaard45aa552018-05-21 22:50:29 +02005649 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005650 if (!buf_valid(buf))
5651 /* If the terminal is closed when the channel is closed the
5652 * buffer disappears. */
5653 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005654 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005655
5656 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005657 }
5658 else
5659 {
5660 long wait = 10L;
5661
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005662 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005663
5664 /* Wait for some time for any channel I/O. */
5665 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005666 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005667 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005668
5669 /* Flushing messages on channels is hopefully sufficient.
5670 * TODO: is there a better way? */
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005671 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005672 }
5673}
5674
5675/*
5676 * Called when a channel has sent all the lines to a terminal.
5677 * Send a CTRL-D to mark the end of the text.
5678 */
5679 void
5680term_send_eof(channel_T *ch)
5681{
5682 term_T *term;
5683
5684 for (term = first_term; term != NULL; term = term->tl_next)
5685 if (term->tl_job == ch->ch_job)
5686 {
5687 if (term->tl_eof_chars != NULL)
5688 {
5689 channel_send(ch, PART_IN, term->tl_eof_chars,
5690 (int)STRLEN(term->tl_eof_chars), NULL);
5691 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5692 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005693# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005694 else
5695 /* Default: CTRL-D */
5696 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5697# endif
5698 }
5699}
5700
Bram Moolenaar113e1072019-01-20 15:30:40 +01005701#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005702 job_T *
5703term_getjob(term_T *term)
5704{
5705 return term != NULL ? term->tl_job : NULL;
5706}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005707#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005708
Bram Moolenaar4f974752019-02-17 17:44:42 +01005709# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005710
5711/**************************************
5712 * 2. MS-Windows implementation.
5713 */
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005714#ifdef PROTO
5715typedef int COORD;
5716typedef int DWORD;
5717typedef int HANDLE;
5718typedef int *DWORD_PTR;
5719typedef int HPCON;
5720typedef int HRESULT;
5721typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005722typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005723typedef int PSIZE_T;
5724typedef int PVOID;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005725typedef int WINAPI;
5726#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005727
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005728HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5729HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5730HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005731BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5732BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5733void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005734
5735 static int
5736dyn_conpty_init(int verbose)
5737{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005738 static HMODULE hKerneldll = NULL;
5739 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005740 static struct
5741 {
5742 char *name;
5743 FARPROC *ptr;
5744 } conpty_entry[] =
5745 {
5746 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5747 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5748 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5749 {"InitializeProcThreadAttributeList",
5750 (FARPROC*)&pInitializeProcThreadAttributeList},
5751 {"UpdateProcThreadAttribute",
5752 (FARPROC*)&pUpdateProcThreadAttribute},
5753 {"DeleteProcThreadAttributeList",
5754 (FARPROC*)&pDeleteProcThreadAttributeList},
5755 {NULL, NULL}
5756 };
5757
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005758 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005759 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005760 if (verbose)
5761 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005762 return FAIL;
5763 }
5764
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005765 // No need to initialize twice.
5766 if (hKerneldll)
5767 return OK;
5768
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005769 hKerneldll = vimLoadLib("kernel32.dll");
5770 for (i = 0; conpty_entry[i].name != NULL
5771 && conpty_entry[i].ptr != NULL; ++i)
5772 {
5773 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5774 conpty_entry[i].name)) == NULL)
5775 {
5776 if (verbose)
5777 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005778 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005779 return FAIL;
5780 }
5781 }
5782
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005783 return OK;
5784}
5785
5786 static int
5787conpty_term_and_job_init(
5788 term_T *term,
5789 typval_T *argvar,
5790 char **argv,
5791 jobopt_T *opt,
5792 jobopt_T *orig_opt)
5793{
5794 WCHAR *cmd_wchar = NULL;
5795 WCHAR *cmd_wchar_copy = NULL;
5796 WCHAR *cwd_wchar = NULL;
5797 WCHAR *env_wchar = NULL;
5798 channel_T *channel = NULL;
5799 job_T *job = NULL;
5800 HANDLE jo = NULL;
5801 garray_T ga_cmd, ga_env;
5802 char_u *cmd = NULL;
5803 HRESULT hr;
5804 COORD consize;
5805 SIZE_T breq;
5806 PROCESS_INFORMATION proc_info;
5807 HANDLE i_theirs = NULL;
5808 HANDLE o_theirs = NULL;
5809 HANDLE i_ours = NULL;
5810 HANDLE o_ours = NULL;
5811
5812 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5813 ga_init2(&ga_env, (int)sizeof(char*), 20);
5814
5815 if (argvar->v_type == VAR_STRING)
5816 {
5817 cmd = argvar->vval.v_string;
5818 }
5819 else if (argvar->v_type == VAR_LIST)
5820 {
5821 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5822 goto failed;
5823 cmd = ga_cmd.ga_data;
5824 }
5825 if (cmd == NULL || *cmd == NUL)
5826 {
5827 emsg(_(e_invarg));
5828 goto failed;
5829 }
5830
5831 term->tl_arg0_cmd = vim_strsave(cmd);
5832
5833 cmd_wchar = enc_to_utf16(cmd, NULL);
5834
5835 if (cmd_wchar != NULL)
5836 {
5837 /* Request by CreateProcessW */
5838 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005839 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005840 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5841 }
5842
5843 ga_clear(&ga_cmd);
5844 if (cmd_wchar == NULL)
5845 goto failed;
5846 if (opt->jo_cwd != NULL)
5847 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5848
5849 win32_build_env(opt->jo_env, &ga_env, TRUE);
5850 env_wchar = ga_env.ga_data;
5851
5852 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5853 goto failed;
5854 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5855 goto failed;
5856
5857 consize.X = term->tl_cols;
5858 consize.Y = term->tl_rows;
5859 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
5860 &term->tl_conpty);
5861 if (FAILED(hr))
5862 goto failed;
5863
5864 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
5865
5866 /* Set up pipe inheritance safely: Vista or later. */
5867 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005868 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005869 if (!term->tl_siex.lpAttributeList)
5870 goto failed;
5871 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
5872 0, &breq))
5873 goto failed;
5874 if (!pUpdateProcThreadAttribute(
5875 term->tl_siex.lpAttributeList, 0,
5876 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
5877 sizeof(HPCON), NULL, NULL))
5878 goto failed;
5879
5880 channel = add_channel();
5881 if (channel == NULL)
5882 goto failed;
5883
5884 job = job_alloc();
5885 if (job == NULL)
5886 goto failed;
5887 if (argvar->v_type == VAR_STRING)
5888 {
5889 int argc;
5890
5891 build_argv_from_string(cmd, &job->jv_argv, &argc);
5892 }
5893 else
5894 {
5895 int argc;
5896
5897 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5898 }
5899
5900 if (opt->jo_set & JO_IN_BUF)
5901 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5902
5903 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
5904 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
5905 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
5906 | CREATE_DEFAULT_ERROR_MODE,
5907 env_wchar, cwd_wchar,
5908 &term->tl_siex.StartupInfo, &proc_info))
5909 goto failed;
5910
5911 CloseHandle(i_theirs);
5912 CloseHandle(o_theirs);
5913
5914 channel_set_pipes(channel,
5915 (sock_T)i_ours,
5916 (sock_T)o_ours,
5917 (sock_T)o_ours);
5918
5919 /* Write lines with CR instead of NL. */
5920 channel->ch_write_text_mode = TRUE;
5921
5922 /* Use to explicitly delete anonymous pipe handle. */
5923 channel->ch_anonymous_pipe = TRUE;
5924
5925 jo = CreateJobObject(NULL, NULL);
5926 if (jo == NULL)
5927 goto failed;
5928
5929 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
5930 {
5931 /* Failed, switch the way to terminate process with TerminateProcess. */
5932 CloseHandle(jo);
5933 jo = NULL;
5934 }
5935
5936 ResumeThread(proc_info.hThread);
5937 CloseHandle(proc_info.hThread);
5938
5939 vim_free(cmd_wchar);
5940 vim_free(cmd_wchar_copy);
5941 vim_free(cwd_wchar);
5942 vim_free(env_wchar);
5943
5944 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
5945 goto failed;
5946
5947#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5948 if (opt->jo_set2 & JO2_ANSI_COLORS)
5949 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5950 else
5951 init_vterm_ansi_colors(term->tl_vterm);
5952#endif
5953
5954 channel_set_job(channel, job, opt);
5955 job_set_options(job, opt);
5956
5957 job->jv_channel = channel;
5958 job->jv_proc_info = proc_info;
5959 job->jv_job_object = jo;
5960 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01005961 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005962 ++job->jv_refcount;
5963 term->tl_job = job;
5964
5965 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5966 * open the file here and handle it in. opt->jo_io was changed in
5967 * setup_job_options(), use the original flags here. */
5968 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5969 {
5970 char_u *fname = opt->jo_io_name[PART_OUT];
5971
5972 ch_log(channel, "Opening output file %s", fname);
5973 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5974 if (term->tl_out_fd == NULL)
5975 semsg(_(e_notopen), fname);
5976 }
5977
5978 return OK;
5979
5980failed:
5981 ga_clear(&ga_cmd);
5982 ga_clear(&ga_env);
5983 vim_free(cmd_wchar);
5984 vim_free(cmd_wchar_copy);
5985 vim_free(cwd_wchar);
5986 if (channel != NULL)
5987 channel_clear(channel);
5988 if (job != NULL)
5989 {
5990 job->jv_channel = NULL;
5991 job_cleanup(job);
5992 }
5993 term->tl_job = NULL;
5994 if (jo != NULL)
5995 CloseHandle(jo);
5996
5997 if (term->tl_siex.lpAttributeList != NULL)
5998 {
5999 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6000 vim_free(term->tl_siex.lpAttributeList);
6001 }
6002 term->tl_siex.lpAttributeList = NULL;
6003 if (o_theirs != NULL)
6004 CloseHandle(o_theirs);
6005 if (o_ours != NULL)
6006 CloseHandle(o_ours);
6007 if (i_ours != NULL)
6008 CloseHandle(i_ours);
6009 if (i_theirs != NULL)
6010 CloseHandle(i_theirs);
6011 if (term->tl_conpty != NULL)
6012 pClosePseudoConsole(term->tl_conpty);
6013 term->tl_conpty = NULL;
6014 return FAIL;
6015}
6016
6017 static void
6018conpty_term_report_winsize(term_T *term, int rows, int cols)
6019{
6020 COORD consize;
6021
6022 consize.X = cols;
6023 consize.Y = rows;
6024 pResizePseudoConsole(term->tl_conpty, consize);
6025}
6026
6027 void
6028term_free_conpty(term_T *term)
6029{
6030 if (term->tl_siex.lpAttributeList != NULL)
6031 {
6032 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6033 vim_free(term->tl_siex.lpAttributeList);
6034 }
6035 term->tl_siex.lpAttributeList = NULL;
6036 if (term->tl_conpty != NULL)
6037 pClosePseudoConsole(term->tl_conpty);
6038 term->tl_conpty = NULL;
6039}
6040
6041 int
6042use_conpty(void)
6043{
6044 return has_conpty;
6045}
6046
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006047# ifndef PROTO
6048
6049#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6050#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006051#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006052
6053void* (*winpty_config_new)(UINT64, void*);
6054void* (*winpty_open)(void*, void*);
6055void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6056BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6057void (*winpty_config_set_mouse_mode)(void*, int);
6058void (*winpty_config_set_initial_size)(void*, int, int);
6059LPCWSTR (*winpty_conin_name)(void*);
6060LPCWSTR (*winpty_conout_name)(void*);
6061LPCWSTR (*winpty_conerr_name)(void*);
6062void (*winpty_free)(void*);
6063void (*winpty_config_free)(void*);
6064void (*winpty_spawn_config_free)(void*);
6065void (*winpty_error_free)(void*);
6066LPCWSTR (*winpty_error_msg)(void*);
6067BOOL (*winpty_set_size)(void*, int, int, void*);
6068HANDLE (*winpty_agent_process)(void*);
6069
6070#define WINPTY_DLL "winpty.dll"
6071
6072static HINSTANCE hWinPtyDLL = NULL;
6073# endif
6074
6075 static int
6076dyn_winpty_init(int verbose)
6077{
6078 int i;
6079 static struct
6080 {
6081 char *name;
6082 FARPROC *ptr;
6083 } winpty_entry[] =
6084 {
6085 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6086 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6087 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6088 {"winpty_config_set_mouse_mode",
6089 (FARPROC*)&winpty_config_set_mouse_mode},
6090 {"winpty_config_set_initial_size",
6091 (FARPROC*)&winpty_config_set_initial_size},
6092 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6093 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6094 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6095 {"winpty_free", (FARPROC*)&winpty_free},
6096 {"winpty_open", (FARPROC*)&winpty_open},
6097 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6098 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6099 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6100 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6101 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6102 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6103 {NULL, NULL}
6104 };
6105
6106 /* No need to initialize twice. */
6107 if (hWinPtyDLL)
6108 return OK;
6109 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6110 * winpty.dll. */
6111 if (*p_winptydll != NUL)
6112 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6113 if (!hWinPtyDLL)
6114 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6115 if (!hWinPtyDLL)
6116 {
6117 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006118 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006119 : (char_u *)WINPTY_DLL);
6120 return FAIL;
6121 }
6122 for (i = 0; winpty_entry[i].name != NULL
6123 && winpty_entry[i].ptr != NULL; ++i)
6124 {
6125 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6126 winpty_entry[i].name)) == NULL)
6127 {
6128 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006129 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006130 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006131 return FAIL;
6132 }
6133 }
6134
6135 return OK;
6136}
6137
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006138 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006139winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006140 term_T *term,
6141 typval_T *argvar,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006142 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006143 jobopt_T *opt,
6144 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006145{
6146 WCHAR *cmd_wchar = NULL;
6147 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006148 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006149 channel_T *channel = NULL;
6150 job_T *job = NULL;
6151 DWORD error;
6152 HANDLE jo = NULL;
6153 HANDLE child_process_handle;
6154 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006155 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006156 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006157 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006158 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006159
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006160 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6161 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006162
6163 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006164 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006165 cmd = argvar->vval.v_string;
6166 }
6167 else if (argvar->v_type == VAR_LIST)
6168 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006169 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006170 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006171 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006172 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006173 if (cmd == NULL || *cmd == NUL)
6174 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006175 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006176 goto failed;
6177 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006178
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006179 term->tl_arg0_cmd = vim_strsave(cmd);
6180
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006181 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006182 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006183 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006184 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006185 if (opt->jo_cwd != NULL)
6186 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006187
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006188 win32_build_env(opt->jo_env, &ga_env, TRUE);
6189 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006190
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006191 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6192 if (term->tl_winpty_config == NULL)
6193 goto failed;
6194
6195 winpty_config_set_mouse_mode(term->tl_winpty_config,
6196 WINPTY_MOUSE_MODE_FORCE);
6197 winpty_config_set_initial_size(term->tl_winpty_config,
6198 term->tl_cols, term->tl_rows);
6199 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6200 if (term->tl_winpty == NULL)
6201 goto failed;
6202
6203 spawn_config = winpty_spawn_config_new(
6204 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6205 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6206 NULL,
6207 cmd_wchar,
6208 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006209 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006210 &winpty_err);
6211 if (spawn_config == NULL)
6212 goto failed;
6213
6214 channel = add_channel();
6215 if (channel == NULL)
6216 goto failed;
6217
6218 job = job_alloc();
6219 if (job == NULL)
6220 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006221 if (argvar->v_type == VAR_STRING)
6222 {
6223 int argc;
6224
6225 build_argv_from_string(cmd, &job->jv_argv, &argc);
6226 }
6227 else
6228 {
6229 int argc;
6230
6231 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6232 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006233
6234 if (opt->jo_set & JO_IN_BUF)
6235 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6236
6237 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6238 &child_thread_handle, &error, &winpty_err))
6239 goto failed;
6240
6241 channel_set_pipes(channel,
6242 (sock_T)CreateFileW(
6243 winpty_conin_name(term->tl_winpty),
6244 GENERIC_WRITE, 0, NULL,
6245 OPEN_EXISTING, 0, NULL),
6246 (sock_T)CreateFileW(
6247 winpty_conout_name(term->tl_winpty),
6248 GENERIC_READ, 0, NULL,
6249 OPEN_EXISTING, 0, NULL),
6250 (sock_T)CreateFileW(
6251 winpty_conerr_name(term->tl_winpty),
6252 GENERIC_READ, 0, NULL,
6253 OPEN_EXISTING, 0, NULL));
6254
6255 /* Write lines with CR instead of NL. */
6256 channel->ch_write_text_mode = TRUE;
6257
6258 jo = CreateJobObject(NULL, NULL);
6259 if (jo == NULL)
6260 goto failed;
6261
6262 if (!AssignProcessToJobObject(jo, child_process_handle))
6263 {
6264 /* Failed, switch the way to terminate process with TerminateProcess. */
6265 CloseHandle(jo);
6266 jo = NULL;
6267 }
6268
6269 winpty_spawn_config_free(spawn_config);
6270 vim_free(cmd_wchar);
6271 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006272 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006273
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006274 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6275 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006276
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006277#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6278 if (opt->jo_set2 & JO2_ANSI_COLORS)
6279 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6280 else
6281 init_vterm_ansi_colors(term->tl_vterm);
6282#endif
6283
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006284 channel_set_job(channel, job, opt);
6285 job_set_options(job, opt);
6286
6287 job->jv_channel = channel;
6288 job->jv_proc_info.hProcess = child_process_handle;
6289 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6290 job->jv_job_object = jo;
6291 job->jv_status = JOB_STARTED;
6292 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006293 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006294 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006295 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006296 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006297 ++job->jv_refcount;
6298 term->tl_job = job;
6299
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006300 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6301 * open the file here and handle it in. opt->jo_io was changed in
6302 * setup_job_options(), use the original flags here. */
6303 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6304 {
6305 char_u *fname = opt->jo_io_name[PART_OUT];
6306
6307 ch_log(channel, "Opening output file %s", fname);
6308 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6309 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006310 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006311 }
6312
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006313 return OK;
6314
6315failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006316 ga_clear(&ga_cmd);
6317 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006318 vim_free(cmd_wchar);
6319 vim_free(cwd_wchar);
6320 if (spawn_config != NULL)
6321 winpty_spawn_config_free(spawn_config);
6322 if (channel != NULL)
6323 channel_clear(channel);
6324 if (job != NULL)
6325 {
6326 job->jv_channel = NULL;
6327 job_cleanup(job);
6328 }
6329 term->tl_job = NULL;
6330 if (jo != NULL)
6331 CloseHandle(jo);
6332 if (term->tl_winpty != NULL)
6333 winpty_free(term->tl_winpty);
6334 term->tl_winpty = NULL;
6335 if (term->tl_winpty_config != NULL)
6336 winpty_config_free(term->tl_winpty_config);
6337 term->tl_winpty_config = NULL;
6338 if (winpty_err != NULL)
6339 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006340 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006341 (short_u *)winpty_error_msg(winpty_err), NULL);
6342
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006343 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006344 winpty_error_free(winpty_err);
6345 }
6346 return FAIL;
6347}
6348
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006349/*
6350 * Create a new terminal of "rows" by "cols" cells.
6351 * Store a reference in "term".
6352 * Return OK or FAIL.
6353 */
6354 static int
6355term_and_job_init(
6356 term_T *term,
6357 typval_T *argvar,
6358 char **argv UNUSED,
6359 jobopt_T *opt,
6360 jobopt_T *orig_opt)
6361{
6362 int use_winpty = FALSE;
6363 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006364 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006365
6366 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6367 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6368
6369 if (!has_winpty && !has_conpty)
6370 // If neither is available give the errors for winpty, since when
6371 // conpty is not available it can't be installed either.
6372 return dyn_winpty_init(TRUE);
6373
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006374 if (opt->jo_tty_type != NUL)
6375 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006376
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006377 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006378 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006379 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006380 use_conpty = TRUE;
6381 else if (has_winpty)
6382 use_winpty = TRUE;
6383 // else: error
6384 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006385 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006386 {
6387 if (has_winpty)
6388 use_winpty = TRUE;
6389 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006390 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006391 {
6392 if (has_conpty)
6393 use_conpty = TRUE;
6394 else
6395 return dyn_conpty_init(TRUE);
6396 }
6397
6398 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006399 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006400
6401 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006402 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006403
6404 // error
6405 return dyn_winpty_init(TRUE);
6406}
6407
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006408 static int
6409create_pty_only(term_T *term, jobopt_T *options)
6410{
6411 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6412 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6413 char in_name[80], out_name[80];
6414 channel_T *channel = NULL;
6415
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006416 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6417 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006418
6419 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6420 GetCurrentProcessId(),
6421 curbuf->b_fnum);
6422 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6423 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6424 PIPE_UNLIMITED_INSTANCES,
6425 0, 0, NMPWAIT_NOWAIT, NULL);
6426 if (hPipeIn == INVALID_HANDLE_VALUE)
6427 goto failed;
6428
6429 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6430 GetCurrentProcessId(),
6431 curbuf->b_fnum);
6432 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6433 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6434 PIPE_UNLIMITED_INSTANCES,
6435 0, 0, 0, NULL);
6436 if (hPipeOut == INVALID_HANDLE_VALUE)
6437 goto failed;
6438
6439 ConnectNamedPipe(hPipeIn, NULL);
6440 ConnectNamedPipe(hPipeOut, NULL);
6441
6442 term->tl_job = job_alloc();
6443 if (term->tl_job == NULL)
6444 goto failed;
6445 ++term->tl_job->jv_refcount;
6446
6447 /* behave like the job is already finished */
6448 term->tl_job->jv_status = JOB_FINISHED;
6449
6450 channel = add_channel();
6451 if (channel == NULL)
6452 goto failed;
6453 term->tl_job->jv_channel = channel;
6454 channel->ch_keep_open = TRUE;
6455 channel->ch_named_pipe = TRUE;
6456
6457 channel_set_pipes(channel,
6458 (sock_T)hPipeIn,
6459 (sock_T)hPipeOut,
6460 (sock_T)hPipeOut);
6461 channel_set_job(channel, term->tl_job, options);
6462 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6463 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6464
6465 return OK;
6466
6467failed:
6468 if (hPipeIn != NULL)
6469 CloseHandle(hPipeIn);
6470 if (hPipeOut != NULL)
6471 CloseHandle(hPipeOut);
6472 return FAIL;
6473}
6474
6475/*
6476 * Free the terminal emulator part of "term".
6477 */
6478 static void
6479term_free_vterm(term_T *term)
6480{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006481 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006482 if (term->tl_winpty != NULL)
6483 winpty_free(term->tl_winpty);
6484 term->tl_winpty = NULL;
6485 if (term->tl_winpty_config != NULL)
6486 winpty_config_free(term->tl_winpty_config);
6487 term->tl_winpty_config = NULL;
6488 if (term->tl_vterm != NULL)
6489 vterm_free(term->tl_vterm);
6490 term->tl_vterm = NULL;
6491}
6492
6493/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006494 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006495 */
6496 static void
6497term_report_winsize(term_T *term, int rows, int cols)
6498{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006499 if (term->tl_conpty)
6500 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006501 if (term->tl_winpty)
6502 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6503}
6504
6505 int
6506terminal_enabled(void)
6507{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006508 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006509}
6510
6511# else
6512
6513/**************************************
6514 * 3. Unix-like implementation.
6515 */
6516
6517/*
6518 * Create a new terminal of "rows" by "cols" cells.
6519 * Start job for "cmd".
6520 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006521 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006522 * Return OK or FAIL.
6523 */
6524 static int
6525term_and_job_init(
6526 term_T *term,
6527 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006528 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006529 jobopt_T *opt,
6530 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006531{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006532 term->tl_arg0_cmd = NULL;
6533
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006534 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6535 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006536
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006537#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6538 if (opt->jo_set2 & JO2_ANSI_COLORS)
6539 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6540 else
6541 init_vterm_ansi_colors(term->tl_vterm);
6542#endif
6543
Bram Moolenaar13568252018-03-16 20:46:58 +01006544 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006545 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006546 if (term->tl_job != NULL)
6547 ++term->tl_job->jv_refcount;
6548
6549 return term->tl_job != NULL
6550 && term->tl_job->jv_channel != NULL
6551 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6552}
6553
6554 static int
6555create_pty_only(term_T *term, jobopt_T *opt)
6556{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006557 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6558 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006559
6560 term->tl_job = job_alloc();
6561 if (term->tl_job == NULL)
6562 return FAIL;
6563 ++term->tl_job->jv_refcount;
6564
6565 /* behave like the job is already finished */
6566 term->tl_job->jv_status = JOB_FINISHED;
6567
6568 return mch_create_pty_channel(term->tl_job, opt);
6569}
6570
6571/*
6572 * Free the terminal emulator part of "term".
6573 */
6574 static void
6575term_free_vterm(term_T *term)
6576{
6577 if (term->tl_vterm != NULL)
6578 vterm_free(term->tl_vterm);
6579 term->tl_vterm = NULL;
6580}
6581
6582/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006583 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006584 */
6585 static void
6586term_report_winsize(term_T *term, int rows, int cols)
6587{
6588 /* Use an ioctl() to report the new window size to the job. */
6589 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6590 {
6591 int fd = -1;
6592 int part;
6593
6594 for (part = PART_OUT; part < PART_COUNT; ++part)
6595 {
6596 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006597 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006598 break;
6599 }
6600 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6601 mch_signal_job(term->tl_job, (char_u *)"winch");
6602 }
6603}
6604
6605# endif
6606
6607#endif /* FEAT_TERMINAL */