blob: 7b2d43bf256c568dc7423c11f9a073003b9c6d9b [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;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200112 char_u *tl_api; // prefix for terminal API function
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200113
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100114 char_u *tl_arg0_cmd; // To format the status bar
115
Bram Moolenaar4f974752019-02-17 17:44:42 +0100116#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200117 void *tl_winpty_config;
118 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200119
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100120 HPCON tl_conpty;
121 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
122
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200123 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200124#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100125#if defined(FEAT_SESSION)
126 char_u *tl_command;
127#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100128 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200129
130 /* last known vterm size */
131 int tl_rows;
132 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200133
134 char_u *tl_title; /* NULL or allocated */
135 char_u *tl_status_text; /* NULL or allocated */
136
137 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200138 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200139 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200140 int tl_dirty_snapshot; /* text updated after making snapshot */
141#ifdef FEAT_TIMERS
142 int tl_timer_set;
143 proftime_T tl_timer_due;
144#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200145 int tl_postponed_scroll; /* to be scrolled up */
146
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200147 garray_T tl_scrollback;
148 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100149 garray_T tl_scrollback_postponed;
150
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200151 cellattr_T tl_default_color;
152
Bram Moolenaard96ff162018-02-18 22:13:29 +0100153 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
154 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
155
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200156 VTermPos tl_cursor_pos;
157 int tl_cursor_visible;
158 int tl_cursor_blink;
159 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
160 char_u *tl_cursor_color; /* NULL or allocated */
161
162 int tl_using_altscreen;
163};
164
165#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
166#define TMODE_LOOP 2 /* CTRL-W N used */
167
168/*
169 * List of all active terminals.
170 */
171static term_T *first_term = NULL;
172
173/* Terminal active in terminal_loop(). */
174static term_T *in_terminal_loop = NULL;
175
Bram Moolenaar4f974752019-02-17 17:44:42 +0100176#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100177static BOOL has_winpty = FALSE;
178static BOOL has_conpty = FALSE;
179#endif
180
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200181#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
182#define KEY_BUF_LEN 200
183
184/*
185 * Functions with separate implementation for MS-Windows and Unix-like systems.
186 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200187static 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 +0200188static int create_pty_only(term_T *term, jobopt_T *opt);
189static void term_report_winsize(term_T *term, int rows, int cols);
190static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100191#ifdef FEAT_GUI
192static void update_system_term(term_T *term);
193#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200194
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100195static void handle_postponed_scrollback(term_T *term);
196
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100197/* The character that we know (or assume) that the terminal expects for the
198 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200199static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200200
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100201/* "Terminal" highlight group colors. */
202static int term_default_cterm_fg = -1;
203static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200204
Bram Moolenaard317b382018-02-08 22:33:31 +0100205/* Store the last set and the desired cursor properties, so that we only update
206 * them when needed. Doing it unnecessary may result in flicker. */
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200207static char_u *last_set_cursor_color = NULL;
208static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100209static int last_set_cursor_shape = -1;
210static int desired_cursor_shape = -1;
211static int last_set_cursor_blink = -1;
212static int desired_cursor_blink = -1;
213
214
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200215/**************************************
216 * 1. Generic code for all systems.
217 */
218
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200219 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200220cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
221{
222 if (lhs_color != NULL && rhs_color != NULL)
223 return STRCMP(lhs_color, rhs_color) == 0;
224 return lhs_color == NULL && rhs_color == NULL;
225}
226
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200227 static void
228cursor_color_copy(char_u **to_color, char_u *from_color)
229{
230 // Avoid a free & alloc if the value is already right.
231 if (cursor_color_equal(*to_color, from_color))
232 return;
233 vim_free(*to_color);
234 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
235}
236
237 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200238cursor_color_get(char_u *color)
239{
240 return (color == NULL) ? (char_u *)"" : color;
241}
242
243
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200244/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200245 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200246 * current window.
247 * Sets "rows" and/or "cols" to zero when it should follow the window size.
248 * Return TRUE if the size is the minimum size: "24*80".
249 */
250 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200251parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200252{
253 int minsize = FALSE;
254
255 *rows = 0;
256 *cols = 0;
257
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200258 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200259 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200260 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200261
262 /* Syntax of value was already checked when it's set. */
263 if (p == NULL)
264 {
265 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200266 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200267 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200268 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200269 *cols = atoi((char *)p + 1);
270 }
271 return minsize;
272}
273
274/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200275 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200276 */
277 static void
278set_term_and_win_size(term_T *term)
279{
Bram Moolenaar13568252018-03-16 20:46:58 +0100280#ifdef FEAT_GUI
281 if (term->tl_system)
282 {
283 /* Use the whole screen for the system command. However, it will start
284 * at the command line and scroll up as needed, using tl_toprow. */
285 term->tl_rows = Rows;
286 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200287 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100288 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100289#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200290 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200291 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200292 if (term->tl_rows != 0)
293 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
294 if (term->tl_cols != 0)
295 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200296 }
297 if (term->tl_rows == 0)
298 term->tl_rows = curwin->w_height;
299 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200301 if (term->tl_cols == 0)
302 term->tl_cols = curwin->w_width;
303 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200304 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200305}
306
307/*
308 * Initialize job options for a terminal job.
309 * Caller may overrule some of them.
310 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100311 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200312init_job_options(jobopt_T *opt)
313{
314 clear_job_options(opt);
315
316 opt->jo_mode = MODE_RAW;
317 opt->jo_out_mode = MODE_RAW;
318 opt->jo_err_mode = MODE_RAW;
319 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
320}
321
322/*
323 * Set job options mandatory for a terminal job.
324 */
325 static void
326setup_job_options(jobopt_T *opt, int rows, int cols)
327{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100328#ifndef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200329 /* Win32: Redirecting the job output won't work, thus always connect stdout
330 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200331 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200332#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200333 {
334 /* Connect stdout to the terminal. */
335 opt->jo_io[PART_OUT] = JIO_BUFFER;
336 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
337 opt->jo_modifiable[PART_OUT] = 0;
338 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
339 }
340
Bram Moolenaar4f974752019-02-17 17:44:42 +0100341#ifndef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200342 /* Win32: Redirecting the job output won't work, thus always connect stderr
343 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200344 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200345#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346 {
347 /* Connect stderr to the terminal. */
348 opt->jo_io[PART_ERR] = JIO_BUFFER;
349 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
350 opt->jo_modifiable[PART_ERR] = 0;
351 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
352 }
353
354 opt->jo_pty = TRUE;
355 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
356 opt->jo_term_rows = rows;
357 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
358 opt->jo_term_cols = cols;
359}
360
361/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200362 * Flush messages on channels.
363 */
364 static void
365term_flush_messages()
366{
367 mch_check_messages();
368 parse_queued_messages();
369}
370
371/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100372 * Close a terminal buffer (and its window). Used when creating the terminal
373 * fails.
374 */
375 static void
376term_close_buffer(buf_T *buf, buf_T *old_curbuf)
377{
378 free_terminal(buf);
379 if (old_curbuf != NULL)
380 {
381 --curbuf->b_nwindows;
382 curbuf = old_curbuf;
383 curwin->w_buffer = curbuf;
384 ++curbuf->b_nwindows;
385 }
386
387 /* Wiping out the buffer will also close the window and call
388 * free_terminal(). */
389 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
390}
391
392/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200393 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100394 * Use either "argvar" or "argv", the other must be NULL.
395 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
396 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200397 * Returns NULL when failed.
398 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100399 buf_T *
400term_start(
401 typval_T *argvar,
402 char **argv,
403 jobopt_T *opt,
404 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200405{
406 exarg_T split_ea;
407 win_T *old_curwin = curwin;
408 term_T *term;
409 buf_T *old_curbuf = NULL;
410 int res;
411 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100412 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200413 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200414
415 if (check_restricted() || check_secure())
416 return NULL;
417
418 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
419 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
420 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
421 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
422 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100423 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200424 return NULL;
425 }
426
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200427 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 if (term == NULL)
429 return NULL;
430 term->tl_dirty_row_end = MAX_ROW;
431 term->tl_cursor_visible = TRUE;
432 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
433 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100434#ifdef FEAT_GUI
435 term->tl_system = (flags & TERM_START_SYSTEM);
436#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200437 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100438 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200439
440 vim_memset(&split_ea, 0, sizeof(split_ea));
441 if (opt->jo_curwin)
442 {
443 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100444 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200445 {
446 no_write_message();
447 vim_free(term);
448 return NULL;
449 }
450 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100451 ECMD_HIDE
452 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
453 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200454 {
455 vim_free(term);
456 return NULL;
457 }
458 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100459 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200460 {
461 buf_T *buf;
462
463 /* Create a new buffer without a window. Make it the current buffer for
464 * a moment to be able to do the initialisations. */
465 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
466 BLN_NEW | BLN_LISTED);
467 if (buf == NULL || ml_open(buf) == FAIL)
468 {
469 vim_free(term);
470 return NULL;
471 }
472 old_curbuf = curbuf;
473 --curbuf->b_nwindows;
474 curbuf = buf;
475 curwin->w_buffer = buf;
476 ++curbuf->b_nwindows;
477 }
478 else
479 {
480 /* Open a new window or tab. */
481 split_ea.cmdidx = CMD_new;
482 split_ea.cmd = (char_u *)"new";
483 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100484 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200485 {
486 split_ea.line2 = opt->jo_term_rows;
487 split_ea.addr_count = 1;
488 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100489 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200490 {
491 split_ea.line2 = opt->jo_term_cols;
492 split_ea.addr_count = 1;
493 }
494
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100495 if (vertical)
496 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200497 ex_splitview(&split_ea);
498 if (curwin == old_curwin)
499 {
500 /* split failed */
501 vim_free(term);
502 return NULL;
503 }
504 }
505 term->tl_buffer = curbuf;
506 curbuf->b_term = term;
507
508 if (!opt->jo_hidden)
509 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100510 /* Only one size was taken care of with :new, do the other one. With
511 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100512 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200513 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100514 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200515 win_setwidth(opt->jo_term_cols);
516 }
517
518 /* Link the new terminal in the list of active terminals. */
519 term->tl_next = first_term;
520 first_term = term;
521
522 if (opt->jo_term_name != NULL)
523 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100524 else if (argv != NULL)
525 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200526 else
527 {
528 int i;
529 size_t len;
530 char_u *cmd, *p;
531
532 if (argvar->v_type == VAR_STRING)
533 {
534 cmd = argvar->vval.v_string;
535 if (cmd == NULL)
536 cmd = (char_u *)"";
537 else if (STRCMP(cmd, "NONE") == 0)
538 cmd = (char_u *)"pty";
539 }
540 else if (argvar->v_type != VAR_LIST
541 || argvar->vval.v_list == NULL
542 || argvar->vval.v_list->lv_len < 1
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100543 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200544 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
545 cmd = (char_u*)"";
546
547 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200548 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200549
550 for (i = 0; p != NULL; ++i)
551 {
552 /* Prepend a ! to the command name to avoid the buffer name equals
553 * the executable, otherwise ":w!" would overwrite it. */
554 if (i == 0)
555 vim_snprintf((char *)p, len, "!%s", cmd);
556 else
557 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
558 if (buflist_findname(p) == NULL)
559 {
560 vim_free(curbuf->b_ffname);
561 curbuf->b_ffname = p;
562 break;
563 }
564 }
565 }
566 curbuf->b_fname = curbuf->b_ffname;
567
568 if (opt->jo_term_opencmd != NULL)
569 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
570
571 if (opt->jo_eof_chars != NULL)
572 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
573
574 set_string_option_direct((char_u *)"buftype", -1,
575 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200576 // Avoid that 'buftype' is reset when this buffer is entered.
577 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200578
579 /* Mark the buffer as not modifiable. It can only be made modifiable after
580 * the job finished. */
581 curbuf->b_p_ma = FALSE;
582
583 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100584#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200585 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
586#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200587 setup_job_options(opt, term->tl_rows, term->tl_cols);
588
Bram Moolenaar13568252018-03-16 20:46:58 +0100589 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100590 return curbuf;
591
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100592#if defined(FEAT_SESSION)
593 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100594 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100595 {
596 term->tl_command = vim_strsave((char_u *)"NONE");
597 }
598 else if (argvar->v_type == VAR_STRING)
599 {
600 char_u *cmd = argvar->vval.v_string;
601
602 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
603 term->tl_command = vim_strsave(cmd);
604 }
605 else if (argvar->v_type == VAR_LIST
606 && argvar->vval.v_list != NULL
607 && argvar->vval.v_list->lv_len > 0)
608 {
609 garray_T ga;
610 listitem_T *item;
611
612 ga_init2(&ga, 1, 100);
613 for (item = argvar->vval.v_list->lv_first;
614 item != NULL; item = item->li_next)
615 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100616 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100617 char_u *p;
618
619 if (s == NULL)
620 break;
621 p = vim_strsave_fnameescape(s, FALSE);
622 if (p == NULL)
623 break;
624 ga_concat(&ga, p);
625 vim_free(p);
626 ga_append(&ga, ' ');
627 }
628 if (item == NULL)
629 {
630 ga_append(&ga, NUL);
631 term->tl_command = ga.ga_data;
632 }
633 else
634 ga_clear(&ga);
635 }
636#endif
637
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100638 if (opt->jo_term_kill != NULL)
639 {
640 char_u *p = skiptowhite(opt->jo_term_kill);
641
642 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
643 }
644
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200645 if (opt->jo_term_api != NULL)
646 term->tl_api = vim_strsave(opt->jo_term_api);
647 else
648 term->tl_api = vim_strsave((char_u *)"Tapi_");
649
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200650 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100651 if (argv == NULL
652 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200653 && argvar->vval.v_string != NULL
654 && STRCMP(argvar->vval.v_string, "NONE") == 0)
655 res = create_pty_only(term, opt);
656 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200657 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200658
659 newbuf = curbuf;
660 if (res == OK)
661 {
662 /* Get and remember the size we ended up with. Update the pty. */
663 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
664 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100665#ifdef FEAT_GUI
666 if (term->tl_system)
667 {
668 /* display first line below typed command */
669 term->tl_toprow = msg_row + 1;
670 term->tl_dirty_row_end = 0;
671 }
672#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200673
674 /* Make sure we don't get stuck on sending keys to the job, it leads to
675 * a deadlock if the job is waiting for Vim to read. */
676 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
677
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200678 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200679 {
680 --curbuf->b_nwindows;
681 curbuf = old_curbuf;
682 curwin->w_buffer = curbuf;
683 ++curbuf->b_nwindows;
684 }
685 }
686 else
687 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100688 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200689 return NULL;
690 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100691
Bram Moolenaar13568252018-03-16 20:46:58 +0100692 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200693 return newbuf;
694}
695
696/*
697 * ":terminal": open a terminal window and execute a job in it.
698 */
699 void
700ex_terminal(exarg_T *eap)
701{
702 typval_T argvar[2];
703 jobopt_T opt;
704 char_u *cmd;
705 char_u *tofree = NULL;
706
707 init_job_options(&opt);
708
709 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100710 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200711 {
712 char_u *p, *ep;
713
714 cmd += 2;
715 p = skiptowhite(cmd);
716 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200717 if (ep != NULL)
718 {
719 if (ep < p)
720 p = ep;
721 else
722 ep = NULL;
723 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200724
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200725# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
726 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
727 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200728 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200729 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100730 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200731 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200732 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200733 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200734 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200735 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200736 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200737 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100738 opt.jo_term_norestore = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200739 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100740 {
741 opt.jo_set2 |= JO2_TERM_KILL;
742 opt.jo_term_kill = ep + 1;
743 p = skiptowhite(cmd);
744 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200745 else if (OPTARG_HAS("api"))
746 {
747 opt.jo_set2 |= JO2_TERM_API;
748 if (ep != NULL)
749 {
750 opt.jo_term_api = ep + 1;
751 p = skiptowhite(cmd);
752 }
753 else
754 opt.jo_term_api = NULL;
755 }
756 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200757 {
758 opt.jo_set2 |= JO2_TERM_ROWS;
759 opt.jo_term_rows = atoi((char *)ep + 1);
760 p = skiptowhite(cmd);
761 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200762 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200763 {
764 opt.jo_set2 |= JO2_TERM_COLS;
765 opt.jo_term_cols = atoi((char *)ep + 1);
766 p = skiptowhite(cmd);
767 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200768 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200769 {
770 char_u *buf = NULL;
771 char_u *keys;
772
773 p = skiptowhite(cmd);
774 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200775 keys = replace_termcodes(ep + 1, &buf,
776 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200777 opt.jo_set2 |= JO2_EOF_CHARS;
778 opt.jo_eof_chars = vim_strsave(keys);
779 vim_free(buf);
780 *p = ' ';
781 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100782#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100783 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
784 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100785 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100786 int tty_type = NUL;
787
788 p = skiptowhite(cmd);
789 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
790 tty_type = 'w';
791 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
792 tty_type = 'c';
793 else
794 {
795 semsg(e_invargval, "type");
796 goto theend;
797 }
798 opt.jo_set2 |= JO2_TTY_TYPE;
799 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100800 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100801#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200802 else
803 {
804 if (*p)
805 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100806 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100807 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200808 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200809# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200810 cmd = skipwhite(p);
811 }
812 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100813 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200814 /* Make a copy of 'shell', an autocommand may change the option. */
815 tofree = cmd = vim_strsave(p_sh);
816
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100817 /* default to close when the shell exits */
818 if (opt.jo_term_finish == NUL)
819 opt.jo_term_finish = 'c';
820 }
821
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200822 if (eap->addr_count > 0)
823 {
824 /* Write lines from current buffer to the job. */
825 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
826 opt.jo_io[PART_IN] = JIO_BUFFER;
827 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
828 opt.jo_in_top = eap->line1;
829 opt.jo_in_bot = eap->line2;
830 }
831
832 argvar[0].v_type = VAR_STRING;
833 argvar[0].vval.v_string = cmd;
834 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100835 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200836 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100837
838theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200839 vim_free(opt.jo_eof_chars);
840}
841
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100842#if defined(FEAT_SESSION) || defined(PROTO)
843/*
844 * Write a :terminal command to the session file to restore the terminal in
845 * window "wp".
846 * Return FAIL if writing fails.
847 */
848 int
849term_write_session(FILE *fd, win_T *wp)
850{
851 term_T *term = wp->w_buffer->b_term;
852
853 /* Create the terminal and run the command. This is not without
854 * risk, but let's assume the user only creates a session when this
855 * will be OK. */
856 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
857 term->tl_cols, term->tl_rows) < 0)
858 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100859#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100860 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
861 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100862#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100863 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
864 return FAIL;
865
866 return put_eol(fd);
867}
868
869/*
870 * Return TRUE if "buf" has a terminal that should be restored.
871 */
872 int
873term_should_restore(buf_T *buf)
874{
875 term_T *term = buf->b_term;
876
877 return term != NULL && (term->tl_command == NULL
878 || STRCMP(term->tl_command, "NONE") != 0);
879}
880#endif
881
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200882/*
883 * Free the scrollback buffer for "term".
884 */
885 static void
886free_scrollback(term_T *term)
887{
888 int i;
889
890 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
891 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
892 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100893 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
894 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
895 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200896}
897
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100898
899// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200900static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100901
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200902/*
903 * Free a terminal and everything it refers to.
904 * Kills the job if there is one.
905 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100906 * The actual terminal structure is freed later in free_unused_terminals(),
907 * because callbacks may wipe out a buffer while the terminal is still
908 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200909 */
910 void
911free_terminal(buf_T *buf)
912{
913 term_T *term = buf->b_term;
914 term_T *tp;
915
916 if (term == NULL)
917 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100918
919 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200920 if (first_term == term)
921 first_term = term->tl_next;
922 else
923 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
924 if (tp->tl_next == term)
925 {
926 tp->tl_next = term->tl_next;
927 break;
928 }
929
930 if (term->tl_job != NULL)
931 {
932 if (term->tl_job->jv_status != JOB_ENDED
933 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100934 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200935 job_stop(term->tl_job, NULL, "kill");
936 job_unref(term->tl_job);
937 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100938 term->tl_next = terminals_to_free;
939 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200940
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200941 buf->b_term = NULL;
942 if (in_terminal_loop == term)
943 in_terminal_loop = NULL;
944}
945
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100946 void
947free_unused_terminals()
948{
949 while (terminals_to_free != NULL)
950 {
951 term_T *term = terminals_to_free;
952
953 terminals_to_free = term->tl_next;
954
955 free_scrollback(term);
956
957 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200958 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100959 vim_free(term->tl_title);
960#ifdef FEAT_SESSION
961 vim_free(term->tl_command);
962#endif
963 vim_free(term->tl_kill);
964 vim_free(term->tl_status_text);
965 vim_free(term->tl_opencmd);
966 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100967 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100968#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100969 if (term->tl_out_fd != NULL)
970 fclose(term->tl_out_fd);
971#endif
972 vim_free(term->tl_cursor_color);
973 vim_free(term);
974 }
975}
976
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200977/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100978 * Get the part that is connected to the tty. Normally this is PART_IN, but
979 * when writing buffer lines to the job it can be another. This makes it
980 * possible to do "1,5term vim -".
981 */
982 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200983get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100984{
985#ifdef UNIX
986 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
987 int i;
988
989 for (i = 0; i < 3; ++i)
990 {
991 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
992
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +0100993 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100994 return parts[i];
995 }
996#endif
997 return PART_IN;
998}
999
1000/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001001 * Write job output "msg[len]" to the vterm.
1002 */
1003 static void
1004term_write_job_output(term_T *term, char_u *msg, size_t len)
1005{
1006 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001007 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001008
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001009 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001010
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001011 /* flush vterm buffer when vterm responded to control sequence */
1012 if (prevlen != vterm_output_get_buffer_current(vterm))
1013 {
1014 char buf[KEY_BUF_LEN];
1015 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1016
1017 if (curlen > 0)
1018 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1019 (char_u *)buf, (int)curlen, NULL);
1020 }
1021
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001022 /* this invokes the damage callbacks */
1023 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1024}
1025
1026 static void
1027update_cursor(term_T *term, int redraw)
1028{
1029 if (term->tl_normal_mode)
1030 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001031#ifdef FEAT_GUI
1032 if (term->tl_system)
1033 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1034 term->tl_cursor_pos.col);
1035 else
1036#endif
1037 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001038 if (redraw)
1039 {
1040 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1041 cursor_on();
1042 out_flush();
1043#ifdef FEAT_GUI
1044 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001045 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001046 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001047 gui_mch_flush();
1048 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001049#endif
1050 }
1051}
1052
1053/*
1054 * Invoked when "msg" output from a job was received. Write it to the terminal
1055 * of "buffer".
1056 */
1057 void
1058write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1059{
1060 size_t len = STRLEN(msg);
1061 term_T *term = buffer->b_term;
1062
Bram Moolenaar4f974752019-02-17 17:44:42 +01001063#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001064 /* Win32: Cannot redirect output of the job, intercept it here and write to
1065 * the file. */
1066 if (term->tl_out_fd != NULL)
1067 {
1068 ch_log(channel, "Writing %d bytes to output file", (int)len);
1069 fwrite(msg, len, 1, term->tl_out_fd);
1070 return;
1071 }
1072#endif
1073
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001074 if (term->tl_vterm == NULL)
1075 {
1076 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1077 return;
1078 }
1079 ch_log(channel, "writing %d bytes to terminal", (int)len);
1080 term_write_job_output(term, msg, len);
1081
Bram Moolenaar13568252018-03-16 20:46:58 +01001082#ifdef FEAT_GUI
1083 if (term->tl_system)
1084 {
1085 /* show system output, scrolling up the screen as needed */
1086 update_system_term(term);
1087 update_cursor(term, TRUE);
1088 }
1089 else
1090#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001091 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
1092 * contents, thus no screen update is needed. */
1093 if (!term->tl_normal_mode)
1094 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001095 // Don't use update_screen() when editing the command line, it gets
1096 // cleared.
1097 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001098 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001099 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001100 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001101 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001102 /* update_screen() can be slow, check the terminal wasn't closed
1103 * already */
1104 if (buffer == curbuf && curbuf->b_term != NULL)
1105 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001106 }
1107 else
1108 redraw_after_callback(TRUE);
1109 }
1110}
1111
1112/*
1113 * Send a mouse position and click to the vterm
1114 */
1115 static int
1116term_send_mouse(VTerm *vterm, int button, int pressed)
1117{
1118 VTermModifier mod = VTERM_MOD_NONE;
1119
1120 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001121 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001122 if (button != 0)
1123 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001124 return TRUE;
1125}
1126
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001127static int enter_mouse_col = -1;
1128static int enter_mouse_row = -1;
1129
1130/*
1131 * Handle a mouse click, drag or release.
1132 * Return TRUE when a mouse event is sent to the terminal.
1133 */
1134 static int
1135term_mouse_click(VTerm *vterm, int key)
1136{
1137#if defined(FEAT_CLIPBOARD)
1138 /* For modeless selection mouse drag and release events are ignored, unless
1139 * they are preceded with a mouse down event */
1140 static int ignore_drag_release = TRUE;
1141 VTermMouseState mouse_state;
1142
1143 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1144 if (mouse_state.flags == 0)
1145 {
1146 /* Terminal is not using the mouse, use modeless selection. */
1147 switch (key)
1148 {
1149 case K_LEFTDRAG:
1150 case K_LEFTRELEASE:
1151 case K_RIGHTDRAG:
1152 case K_RIGHTRELEASE:
1153 /* Ignore drag and release events when the button-down wasn't
1154 * seen before. */
1155 if (ignore_drag_release)
1156 {
1157 int save_mouse_col, save_mouse_row;
1158
1159 if (enter_mouse_col < 0)
1160 break;
1161
1162 /* mouse click in the window gave us focus, handle that
1163 * click now */
1164 save_mouse_col = mouse_col;
1165 save_mouse_row = mouse_row;
1166 mouse_col = enter_mouse_col;
1167 mouse_row = enter_mouse_row;
1168 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1169 mouse_col = save_mouse_col;
1170 mouse_row = save_mouse_row;
1171 }
1172 /* FALLTHROUGH */
1173 case K_LEFTMOUSE:
1174 case K_RIGHTMOUSE:
1175 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1176 ignore_drag_release = TRUE;
1177 else
1178 ignore_drag_release = FALSE;
1179 /* Should we call mouse_has() here? */
1180 if (clip_star.available)
1181 {
1182 int button, is_click, is_drag;
1183
1184 button = get_mouse_button(KEY2TERMCAP1(key),
1185 &is_click, &is_drag);
1186 if (mouse_model_popup() && button == MOUSE_LEFT
1187 && (mod_mask & MOD_MASK_SHIFT))
1188 {
1189 /* Translate shift-left to right button. */
1190 button = MOUSE_RIGHT;
1191 mod_mask &= ~MOD_MASK_SHIFT;
1192 }
1193 clip_modeless(button, is_click, is_drag);
1194 }
1195 break;
1196
1197 case K_MIDDLEMOUSE:
1198 if (clip_star.available)
1199 insert_reg('*', TRUE);
1200 break;
1201 }
1202 enter_mouse_col = -1;
1203 return FALSE;
1204 }
1205#endif
1206 enter_mouse_col = -1;
1207
1208 switch (key)
1209 {
1210 case K_LEFTMOUSE:
1211 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1212 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1213 case K_LEFTRELEASE:
1214 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1215 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1216 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1217 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1218 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1219 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1220 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1221 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1222 }
1223 return TRUE;
1224}
1225
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001226/*
1227 * Convert typed key "c" into bytes to send to the job.
1228 * Return the number of bytes in "buf".
1229 */
1230 static int
1231term_convert_key(term_T *term, int c, char *buf)
1232{
1233 VTerm *vterm = term->tl_vterm;
1234 VTermKey key = VTERM_KEY_NONE;
1235 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001236 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001237
1238 switch (c)
1239 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001240 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1241
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001242 /* don't use VTERM_KEY_BACKSPACE, it always
1243 * becomes 0x7f DEL */
1244 case K_BS: c = term_backspace_char; break;
1245
1246 case ESC: key = VTERM_KEY_ESCAPE; break;
1247 case K_DEL: key = VTERM_KEY_DEL; break;
1248 case K_DOWN: key = VTERM_KEY_DOWN; break;
1249 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1250 key = VTERM_KEY_DOWN; break;
1251 case K_END: key = VTERM_KEY_END; break;
1252 case K_S_END: mod = VTERM_MOD_SHIFT;
1253 key = VTERM_KEY_END; break;
1254 case K_C_END: mod = VTERM_MOD_CTRL;
1255 key = VTERM_KEY_END; break;
1256 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1257 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1258 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1259 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1260 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1261 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1262 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1263 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1264 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1265 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1266 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1267 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1268 case K_HOME: key = VTERM_KEY_HOME; break;
1269 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1270 key = VTERM_KEY_HOME; break;
1271 case K_C_HOME: mod = VTERM_MOD_CTRL;
1272 key = VTERM_KEY_HOME; break;
1273 case K_INS: key = VTERM_KEY_INS; break;
1274 case K_K0: key = VTERM_KEY_KP_0; break;
1275 case K_K1: key = VTERM_KEY_KP_1; break;
1276 case K_K2: key = VTERM_KEY_KP_2; break;
1277 case K_K3: key = VTERM_KEY_KP_3; break;
1278 case K_K4: key = VTERM_KEY_KP_4; break;
1279 case K_K5: key = VTERM_KEY_KP_5; break;
1280 case K_K6: key = VTERM_KEY_KP_6; break;
1281 case K_K7: key = VTERM_KEY_KP_7; break;
1282 case K_K8: key = VTERM_KEY_KP_8; break;
1283 case K_K9: key = VTERM_KEY_KP_9; break;
1284 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1285 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1286 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1287 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1288 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1289 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1290 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1291 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1292 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1293 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1294 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1295 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1296 case K_LEFT: key = VTERM_KEY_LEFT; break;
1297 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1298 key = VTERM_KEY_LEFT; break;
1299 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1300 key = VTERM_KEY_LEFT; break;
1301 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1302 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1303 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1304 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1305 key = VTERM_KEY_RIGHT; break;
1306 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1307 key = VTERM_KEY_RIGHT; break;
1308 case K_UP: key = VTERM_KEY_UP; break;
1309 case K_S_UP: mod = VTERM_MOD_SHIFT;
1310 key = VTERM_KEY_UP; break;
1311 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001312 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1313 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001314
Bram Moolenaara42ad572017-11-16 13:08:04 +01001315 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1316 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001317 case K_MOUSELEFT: /* TODO */ return 0;
1318 case K_MOUSERIGHT: /* TODO */ return 0;
1319
1320 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001321 case K_LEFTMOUSE_NM:
1322 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001323 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001324 case K_LEFTRELEASE_NM:
1325 case K_MOUSEMOVE:
1326 case K_MIDDLEMOUSE:
1327 case K_MIDDLEDRAG:
1328 case K_MIDDLERELEASE:
1329 case K_RIGHTMOUSE:
1330 case K_RIGHTDRAG:
1331 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1332 return 0;
1333 other = TRUE;
1334 break;
1335
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001336 case K_X1MOUSE: /* TODO */ return 0;
1337 case K_X1DRAG: /* TODO */ return 0;
1338 case K_X1RELEASE: /* TODO */ return 0;
1339 case K_X2MOUSE: /* TODO */ return 0;
1340 case K_X2DRAG: /* TODO */ return 0;
1341 case K_X2RELEASE: /* TODO */ return 0;
1342
1343 case K_IGNORE: return 0;
1344 case K_NOP: return 0;
1345 case K_UNDO: return 0;
1346 case K_HELP: return 0;
1347 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1348 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1349 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1350 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1351 case K_SELECT: return 0;
1352#ifdef FEAT_GUI
1353 case K_VER_SCROLLBAR: return 0;
1354 case K_HOR_SCROLLBAR: return 0;
1355#endif
1356#ifdef FEAT_GUI_TABLINE
1357 case K_TABLINE: return 0;
1358 case K_TABMENU: return 0;
1359#endif
1360#ifdef FEAT_NETBEANS_INTG
1361 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1362#endif
1363#ifdef FEAT_DND
1364 case K_DROP: return 0;
1365#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001366 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001367 case K_PS: vterm_keyboard_start_paste(vterm);
1368 other = TRUE;
1369 break;
1370 case K_PE: vterm_keyboard_end_paste(vterm);
1371 other = TRUE;
1372 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001373 }
1374
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001375 // add modifiers for the typed key
Bram Moolenaar459fd782019-10-13 16:43:39 +02001376 if (mod_mask & MOD_MASK_SHIFT)
1377 mod |= VTERM_MOD_SHIFT;
1378 if (mod_mask & MOD_MASK_CTRL)
1379 mod |= VTERM_MOD_CTRL;
1380 if (mod_mask & (MOD_MASK_ALT | MOD_MASK_META))
1381 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001382
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001383 /*
1384 * Convert special keys to vterm keys:
1385 * - Write keys to vterm: vterm_keyboard_key()
1386 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001387 */
1388 if (key != VTERM_KEY_NONE)
1389 /* Special key, let vterm convert it. */
1390 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001391 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001392 /* Normal character, let vterm convert it. */
1393 vterm_keyboard_unichar(vterm, c, mod);
1394
1395 /* Read back the converted escape sequence. */
1396 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1397}
1398
1399/*
1400 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001401 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001402 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001403 */
1404 static int
1405term_job_running_check(term_T *term, int check_job_status)
1406{
1407 /* Also consider the job finished when the channel is closed, to avoid a
1408 * race condition when updating the title. */
1409 if (term != NULL
1410 && term->tl_job != NULL
1411 && channel_is_open(term->tl_job->jv_channel))
1412 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001413 job_T *job = term->tl_job;
1414
1415 // Careful: Checking the job status may invoked callbacks, which close
1416 // the buffer and terminate "term". However, "job" will not be freed
1417 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001418 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001419 job_status(job);
1420 return (job->jv_status == JOB_STARTED
1421 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001422 }
1423 return FALSE;
1424}
1425
1426/*
1427 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001428 */
1429 int
1430term_job_running(term_T *term)
1431{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001432 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001433}
1434
1435/*
1436 * Return TRUE if "term" has an active channel and used ":term NONE".
1437 */
1438 int
1439term_none_open(term_T *term)
1440{
1441 /* Also consider the job finished when the channel is closed, to avoid a
1442 * race condition when updating the title. */
1443 return term != NULL
1444 && term->tl_job != NULL
1445 && channel_is_open(term->tl_job->jv_channel)
1446 && term->tl_job->jv_channel->ch_keep_open;
1447}
1448
1449/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001450 * Used when exiting: kill the job in "buf" if so desired.
1451 * Return OK when the job finished.
1452 * Return FAIL when the job is still running.
1453 */
1454 int
1455term_try_stop_job(buf_T *buf)
1456{
1457 int count;
1458 char *how = (char *)buf->b_term->tl_kill;
1459
1460#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1461 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1462 {
1463 char_u buff[DIALOG_MSG_SIZE];
1464 int ret;
1465
1466 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1467 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1468 if (ret == VIM_YES)
1469 how = "kill";
1470 else if (ret == VIM_CANCEL)
1471 return FAIL;
1472 }
1473#endif
1474 if (how == NULL || *how == NUL)
1475 return FAIL;
1476
1477 job_stop(buf->b_term->tl_job, NULL, how);
1478
Bram Moolenaar9172d232019-01-29 23:06:54 +01001479 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001480 for (count = 0; count < 100; ++count)
1481 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001482 job_T *job;
1483
1484 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001485 if (!buf_valid(buf)
1486 || buf->b_term == NULL
1487 || buf->b_term->tl_job == NULL)
1488 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001489 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001490
Bram Moolenaar9172d232019-01-29 23:06:54 +01001491 // Call job_status() to update jv_status. It may cause the job to be
1492 // cleaned up but it won't be freed.
1493 job_status(job);
1494 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001495 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001496
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001497 ui_delay(10L, FALSE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001498 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001499 }
1500 return FAIL;
1501}
1502
1503/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001504 * Add the last line of the scrollback buffer to the buffer in the window.
1505 */
1506 static void
1507add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1508{
1509 buf_T *buf = term->tl_buffer;
1510 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1511 linenr_T lnum = buf->b_ml.ml_line_count;
1512
Bram Moolenaar4f974752019-02-17 17:44:42 +01001513#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001514 if (!enc_utf8 && enc_codepage > 0)
1515 {
1516 WCHAR *ret = NULL;
1517 int length = 0;
1518
1519 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1520 &ret, &length);
1521 if (ret != NULL)
1522 {
1523 WideCharToMultiByte_alloc(enc_codepage, 0,
1524 ret, length, (char **)&text, &len, 0, 0);
1525 vim_free(ret);
1526 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1527 vim_free(text);
1528 }
1529 }
1530 else
1531#endif
1532 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1533 if (empty)
1534 {
1535 /* Delete the empty line that was in the empty buffer. */
1536 curbuf = buf;
1537 ml_delete(1, FALSE);
1538 curbuf = curwin->w_buffer;
1539 }
1540}
1541
1542 static void
1543cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1544{
1545 attr->width = cell->width;
1546 attr->attrs = cell->attrs;
1547 attr->fg = cell->fg;
1548 attr->bg = cell->bg;
1549}
1550
1551 static int
1552equal_celattr(cellattr_T *a, cellattr_T *b)
1553{
1554 /* Comparing the colors should be sufficient. */
1555 return a->fg.red == b->fg.red
1556 && a->fg.green == b->fg.green
1557 && a->fg.blue == b->fg.blue
1558 && a->bg.red == b->bg.red
1559 && a->bg.green == b->bg.green
1560 && a->bg.blue == b->bg.blue;
1561}
1562
Bram Moolenaard96ff162018-02-18 22:13:29 +01001563/*
1564 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1565 * line at this position. Otherwise at the end.
1566 */
1567 static int
1568add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1569{
1570 if (ga_grow(&term->tl_scrollback, 1) == OK)
1571 {
1572 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1573 + term->tl_scrollback.ga_len;
1574
1575 if (lnum > 0)
1576 {
1577 int i;
1578
1579 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1580 {
1581 *line = *(line - 1);
1582 --line;
1583 }
1584 }
1585 line->sb_cols = 0;
1586 line->sb_cells = NULL;
1587 line->sb_fill_attr = *fill_attr;
1588 ++term->tl_scrollback.ga_len;
1589 return OK;
1590 }
1591 return FALSE;
1592}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001593
1594/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001595 * Remove the terminal contents from the scrollback and the buffer.
1596 * Used before adding a new scrollback line or updating the buffer for lines
1597 * displayed in the terminal.
1598 */
1599 static void
1600cleanup_scrollback(term_T *term)
1601{
1602 sb_line_T *line;
1603 garray_T *gap;
1604
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001605 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001606 gap = &term->tl_scrollback;
1607 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1608 && gap->ga_len > 0)
1609 {
1610 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1611 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1612 vim_free(line->sb_cells);
1613 --gap->ga_len;
1614 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001615 curbuf = curwin->w_buffer;
1616 if (curbuf == term->tl_buffer)
1617 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001618}
1619
1620/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001621 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001622 */
1623 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001624update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001625{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001626 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627 int len;
1628 int lines_skipped = 0;
1629 VTermPos pos;
1630 VTermScreenCell cell;
1631 cellattr_T fill_attr, new_fill_attr;
1632 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001633
1634 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1635 "Adding terminal window snapshot to buffer");
1636
1637 /* First remove the lines that were appended before, they might be
1638 * outdated. */
1639 cleanup_scrollback(term);
1640
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001641 screen = vterm_obtain_screen(term->tl_vterm);
1642 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001643 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1644 {
1645 len = 0;
1646 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1647 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1648 && cell.chars[0] != NUL)
1649 {
1650 len = pos.col + 1;
1651 new_fill_attr = term->tl_default_color;
1652 }
1653 else
1654 /* Assume the last attr is the filler attr. */
1655 cell2cellattr(&cell, &new_fill_attr);
1656
1657 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1658 ++lines_skipped;
1659 else
1660 {
1661 while (lines_skipped > 0)
1662 {
1663 /* Line was skipped, add an empty line. */
1664 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001665 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001666 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001667 }
1668
1669 if (len == 0)
1670 p = NULL;
1671 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001672 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001673 if ((p != NULL || len == 0)
1674 && ga_grow(&term->tl_scrollback, 1) == OK)
1675 {
1676 garray_T ga;
1677 int width;
1678 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1679 + term->tl_scrollback.ga_len;
1680
1681 ga_init2(&ga, 1, 100);
1682 for (pos.col = 0; pos.col < len; pos.col += width)
1683 {
1684 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1685 {
1686 width = 1;
1687 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1688 if (ga_grow(&ga, 1) == OK)
1689 ga.ga_len += utf_char2bytes(' ',
1690 (char_u *)ga.ga_data + ga.ga_len);
1691 }
1692 else
1693 {
1694 width = cell.width;
1695
1696 cell2cellattr(&cell, &p[pos.col]);
1697
Bram Moolenaara79fd562018-12-20 20:47:32 +01001698 // Each character can be up to 6 bytes.
1699 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001700 {
1701 int i;
1702 int c;
1703
1704 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1705 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1706 (char_u *)ga.ga_data + ga.ga_len);
1707 }
1708 }
1709 }
1710 line->sb_cols = len;
1711 line->sb_cells = p;
1712 line->sb_fill_attr = new_fill_attr;
1713 fill_attr = new_fill_attr;
1714 ++term->tl_scrollback.ga_len;
1715
1716 if (ga_grow(&ga, 1) == FAIL)
1717 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1718 else
1719 {
1720 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1721 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1722 }
1723 ga_clear(&ga);
1724 }
1725 else
1726 vim_free(p);
1727 }
1728 }
1729
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001730 // Add trailing empty lines.
1731 for (pos.row = term->tl_scrollback.ga_len;
1732 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1733 ++pos.row)
1734 {
1735 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1736 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1737 }
1738
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001739 term->tl_dirty_snapshot = FALSE;
1740#ifdef FEAT_TIMERS
1741 term->tl_timer_set = FALSE;
1742#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001743}
1744
1745/*
1746 * If needed, add the current lines of the terminal to scrollback and to the
1747 * buffer. Called after the job has ended and when switching to
1748 * Terminal-Normal mode.
1749 * When "redraw" is TRUE redraw the windows that show the terminal.
1750 */
1751 static void
1752may_move_terminal_to_buffer(term_T *term, int redraw)
1753{
1754 win_T *wp;
1755
1756 if (term->tl_vterm == NULL)
1757 return;
1758
1759 /* Update the snapshot only if something changes or the buffer does not
1760 * have all the lines. */
1761 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1762 <= term->tl_scrollback_scrolled)
1763 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001764
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001765 /* Obtain the current background color. */
1766 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1767 &term->tl_default_color.fg, &term->tl_default_color.bg);
1768
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001769 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001770 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001771 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001772 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001773 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001774 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1775 wp->w_cursor.col = 0;
1776 wp->w_valid = 0;
1777 if (wp->w_cursor.lnum >= wp->w_height)
1778 {
1779 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001780
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001781 if (wp->w_topline < min_topline)
1782 wp->w_topline = min_topline;
1783 }
1784 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001785 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001786 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001787}
1788
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001789#if defined(FEAT_TIMERS) || defined(PROTO)
1790/*
1791 * Check if any terminal timer expired. If so, copy text from the terminal to
1792 * the buffer.
1793 * Return the time until the next timer will expire.
1794 */
1795 int
1796term_check_timers(int next_due_arg, proftime_T *now)
1797{
1798 term_T *term;
1799 int next_due = next_due_arg;
1800
1801 for (term = first_term; term != NULL; term = term->tl_next)
1802 {
1803 if (term->tl_timer_set && !term->tl_normal_mode)
1804 {
1805 long this_due = proftime_time_left(&term->tl_timer_due, now);
1806
1807 if (this_due <= 1)
1808 {
1809 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001810 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001811 }
1812 else if (next_due == -1 || next_due > this_due)
1813 next_due = this_due;
1814 }
1815 }
1816
1817 return next_due;
1818}
1819#endif
1820
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001821/*
1822 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1823 * otherwise end it.
1824 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001825 static void
1826set_terminal_mode(term_T *term, int normal_mode)
1827{
1828 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001829 if (!normal_mode)
1830 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001831 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001832 if (term->tl_buffer == curbuf)
1833 maketitle();
1834}
1835
1836/*
1837 * Called after the job if finished and Terminal mode is not active:
1838 * Move the vterm contents into the scrollback buffer and free the vterm.
1839 */
1840 static void
1841cleanup_vterm(term_T *term)
1842{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001843 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001844 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001845 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001846 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001847}
1848
1849/*
1850 * Switch from Terminal-Job mode to Terminal-Normal mode.
1851 * Suspends updating the terminal window.
1852 */
1853 static void
1854term_enter_normal_mode(void)
1855{
1856 term_T *term = curbuf->b_term;
1857
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001858 set_terminal_mode(term, TRUE);
1859
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001860 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001861 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001862
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001863 /* Move the window cursor to the position of the cursor in the
1864 * terminal. */
1865 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1866 + term->tl_cursor_pos.row + 1;
1867 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001868 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1869 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001870
1871 /* Display the same lines as in the terminal. */
1872 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1873}
1874
1875/*
1876 * Returns TRUE if the current window contains a terminal and we are in
1877 * Terminal-Normal mode.
1878 */
1879 int
1880term_in_normal_mode(void)
1881{
1882 term_T *term = curbuf->b_term;
1883
1884 return term != NULL && term->tl_normal_mode;
1885}
1886
1887/*
1888 * Switch from Terminal-Normal mode to Terminal-Job mode.
1889 * Restores updating the terminal window.
1890 */
1891 void
1892term_enter_job_mode()
1893{
1894 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001895
1896 set_terminal_mode(term, FALSE);
1897
1898 if (term->tl_channel_closed)
1899 cleanup_vterm(term);
1900 redraw_buf_and_status_later(curbuf, NOT_VALID);
1901}
1902
1903/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001904 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001905 * Note: while waiting a terminal may be closed and freed if the channel is
1906 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001907 */
1908 static int
1909term_vgetc()
1910{
1911 int c;
1912 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001913 int modify_other_keys =
1914 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001915
1916 State = TERMINAL;
1917 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001918#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001919 ctrl_break_was_pressed = FALSE;
1920#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001921 if (modify_other_keys)
1922 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001923 c = vgetc();
1924 got_int = FALSE;
1925 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001926 if (modify_other_keys)
1927 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001928 return c;
1929}
1930
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001931static int mouse_was_outside = FALSE;
1932
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001933/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001934 * Send keys to terminal.
1935 * Return FAIL when the key needs to be handled in Normal mode.
1936 * Return OK when the key was dropped or sent to the terminal.
1937 */
1938 int
1939send_keys_to_term(term_T *term, int c, int typed)
1940{
1941 char msg[KEY_BUF_LEN];
1942 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001943 int dragging_outside = FALSE;
1944
1945 /* Catch keys that need to be handled as in Normal mode. */
1946 switch (c)
1947 {
1948 case NUL:
1949 case K_ZERO:
1950 if (typed)
1951 stuffcharReadbuff(c);
1952 return FAIL;
1953
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001954 case K_TABLINE:
1955 stuffcharReadbuff(c);
1956 return FAIL;
1957
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001958 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001959 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001960 return FAIL;
1961
1962 case K_LEFTDRAG:
1963 case K_MIDDLEDRAG:
1964 case K_RIGHTDRAG:
1965 case K_X1DRAG:
1966 case K_X2DRAG:
1967 dragging_outside = mouse_was_outside;
1968 /* FALLTHROUGH */
1969 case K_LEFTMOUSE:
1970 case K_LEFTMOUSE_NM:
1971 case K_LEFTRELEASE:
1972 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001973 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001974 case K_MIDDLEMOUSE:
1975 case K_MIDDLERELEASE:
1976 case K_RIGHTMOUSE:
1977 case K_RIGHTRELEASE:
1978 case K_X1MOUSE:
1979 case K_X1RELEASE:
1980 case K_X2MOUSE:
1981 case K_X2RELEASE:
1982
1983 case K_MOUSEUP:
1984 case K_MOUSEDOWN:
1985 case K_MOUSELEFT:
1986 case K_MOUSERIGHT:
1987 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001988 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001989 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001990 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001991 || dragging_outside)
1992 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001993 /* click or scroll outside the current window or on status line
1994 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001995 if (typed)
1996 {
1997 stuffcharReadbuff(c);
1998 mouse_was_outside = TRUE;
1999 }
2000 return FAIL;
2001 }
2002 }
2003 if (typed)
2004 mouse_was_outside = FALSE;
2005
2006 /* Convert the typed key to a sequence of bytes for the job. */
2007 len = term_convert_key(term, c, msg);
2008 if (len > 0)
2009 /* TODO: if FAIL is returned, stop? */
2010 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2011 (char_u *)msg, (int)len, NULL);
2012
2013 return OK;
2014}
2015
2016 static void
2017position_cursor(win_T *wp, VTermPos *pos)
2018{
2019 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2020 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
2021 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2022}
2023
2024/*
2025 * Handle CTRL-W "": send register contents to the job.
2026 */
2027 static void
2028term_paste_register(int prev_c UNUSED)
2029{
2030 int c;
2031 list_T *l;
2032 listitem_T *item;
2033 long reglen = 0;
2034 int type;
2035
2036#ifdef FEAT_CMDL_INFO
2037 if (add_to_showcmd(prev_c))
2038 if (add_to_showcmd('"'))
2039 out_flush();
2040#endif
2041 c = term_vgetc();
2042#ifdef FEAT_CMDL_INFO
2043 clear_showcmd();
2044#endif
2045 if (!term_use_loop())
2046 /* job finished while waiting for a character */
2047 return;
2048
2049 /* CTRL-W "= prompt for expression to evaluate. */
2050 if (c == '=' && get_expr_register() != '=')
2051 return;
2052 if (!term_use_loop())
2053 /* job finished while waiting for a character */
2054 return;
2055
2056 l = (list_T *)get_reg_contents(c, GREG_LIST);
2057 if (l != NULL)
2058 {
2059 type = get_reg_type(c, &reglen);
2060 for (item = l->lv_first; item != NULL; item = item->li_next)
2061 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002062 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002063#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002064 char_u *tmp = s;
2065
2066 if (!enc_utf8 && enc_codepage > 0)
2067 {
2068 WCHAR *ret = NULL;
2069 int length = 0;
2070
2071 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2072 (int)STRLEN(s), &ret, &length);
2073 if (ret != NULL)
2074 {
2075 WideCharToMultiByte_alloc(CP_UTF8, 0,
2076 ret, length, (char **)&s, &length, 0, 0);
2077 vim_free(ret);
2078 }
2079 }
2080#endif
2081 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2082 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002083#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002084 if (tmp != s)
2085 vim_free(s);
2086#endif
2087
2088 if (item->li_next != NULL || type == MLINE)
2089 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2090 (char_u *)"\r", 1, NULL);
2091 }
2092 list_free(l);
2093 }
2094}
2095
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002096/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002097 * Return TRUE when waiting for a character in the terminal, the cursor of the
2098 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002099 */
2100 int
2101terminal_is_active()
2102{
2103 return in_terminal_loop != NULL;
2104}
2105
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002106#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002107 cursorentry_T *
2108term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2109{
2110 term_T *term = in_terminal_loop;
2111 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002112 int id;
2113 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002114
2115 vim_memset(&entry, 0, sizeof(entry));
2116 entry.shape = entry.mshape =
2117 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2118 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2119 SHAPE_BLOCK;
2120 entry.percentage = 20;
2121 if (term->tl_cursor_blink)
2122 {
2123 entry.blinkwait = 700;
2124 entry.blinkon = 400;
2125 entry.blinkoff = 250;
2126 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002127
2128 /* The "Terminal" highlight group overrules the defaults. */
2129 id = syn_name2id((char_u *)"Terminal");
2130 if (id != 0)
2131 {
2132 syn_id2colors(id, &term_fg, &term_bg);
2133 *fg = term_bg;
2134 }
2135 else
2136 *fg = gui.back_pixel;
2137
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002138 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002139 {
2140 if (id != 0)
2141 *bg = term_fg;
2142 else
2143 *bg = gui.norm_pixel;
2144 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002145 else
2146 *bg = color_name2handle(term->tl_cursor_color);
2147 entry.name = "n";
2148 entry.used_for = SHAPE_CURSOR;
2149
2150 return &entry;
2151}
2152#endif
2153
Bram Moolenaard317b382018-02-08 22:33:31 +01002154 static void
2155may_output_cursor_props(void)
2156{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002157 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002158 || last_set_cursor_shape != desired_cursor_shape
2159 || last_set_cursor_blink != desired_cursor_blink)
2160 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002161 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002162 last_set_cursor_shape = desired_cursor_shape;
2163 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002164 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002165 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2166 /* this will restore the initial cursor style, if possible */
2167 ui_cursor_shape_forced(TRUE);
2168 else
2169 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2170 }
2171}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002172
Bram Moolenaard317b382018-02-08 22:33:31 +01002173/*
2174 * Set the cursor color and shape, if not last set to these.
2175 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002176 static void
2177may_set_cursor_props(term_T *term)
2178{
2179#ifdef FEAT_GUI
2180 /* For the GUI the cursor properties are obtained with
2181 * term_get_cursor_shape(). */
2182 if (gui.in_use)
2183 return;
2184#endif
2185 if (in_terminal_loop == term)
2186 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002187 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002188 desired_cursor_shape = term->tl_cursor_shape;
2189 desired_cursor_blink = term->tl_cursor_blink;
2190 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002191 }
2192}
2193
Bram Moolenaard317b382018-02-08 22:33:31 +01002194/*
2195 * Reset the desired cursor properties and restore them when needed.
2196 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002197 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002198prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002199{
2200#ifdef FEAT_GUI
2201 if (gui.in_use)
2202 return;
2203#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002204 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002205 desired_cursor_shape = -1;
2206 desired_cursor_blink = -1;
2207 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002208}
2209
2210/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002211 * Returns TRUE if the current window contains a terminal and we are sending
2212 * keys to the job.
2213 * If "check_job_status" is TRUE update the job status.
2214 */
2215 static int
2216term_use_loop_check(int check_job_status)
2217{
2218 term_T *term = curbuf->b_term;
2219
2220 return term != NULL
2221 && !term->tl_normal_mode
2222 && term->tl_vterm != NULL
2223 && term_job_running_check(term, check_job_status);
2224}
2225
2226/*
2227 * Returns TRUE if the current window contains a terminal and we are sending
2228 * keys to the job.
2229 */
2230 int
2231term_use_loop(void)
2232{
2233 return term_use_loop_check(FALSE);
2234}
2235
2236/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002237 * Called when entering a window with the mouse. If this is a terminal window
2238 * we may want to change state.
2239 */
2240 void
2241term_win_entered()
2242{
2243 term_T *term = curbuf->b_term;
2244
2245 if (term != NULL)
2246 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002247 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002248 {
2249 reset_VIsual_and_resel();
2250 if (State & INSERT)
2251 stop_insert_mode = TRUE;
2252 }
2253 mouse_was_outside = FALSE;
2254 enter_mouse_col = mouse_col;
2255 enter_mouse_row = mouse_row;
2256 }
2257}
2258
2259/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002260 * Wait for input and send it to the job.
2261 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2262 * when there is no more typahead.
2263 * Return when the start of a CTRL-W command is typed or anything else that
2264 * should be handled as a Normal mode command.
2265 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2266 * the terminal was closed.
2267 */
2268 int
2269terminal_loop(int blocking)
2270{
2271 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002272 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002273 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002274 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002275#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002276 int tty_fd = curbuf->b_term->tl_job->jv_channel
2277 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002278#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002279 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002280
2281 /* Remember the terminal we are sending keys to. However, the terminal
2282 * might be closed while waiting for a character, e.g. typing "exit" in a
2283 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2284 * stored reference. */
2285 in_terminal_loop = curbuf->b_term;
2286
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002287 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002288 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002289 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002290 if (termwinkey == Ctrl_W)
2291 termwinkey = 0;
2292 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002293 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2294 may_set_cursor_props(curbuf->b_term);
2295
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002296 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002297 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002298#ifdef FEAT_GUI
2299 if (!curbuf->b_term->tl_system)
2300#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002301 // TODO: skip screen update when handling a sequence of keys.
2302 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002303 while (must_redraw != 0)
2304 if (update_screen(0) == FAIL)
2305 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002306 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002307 /* job finished while redrawing */
2308 break;
2309
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002310 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002311 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002312
2313 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002314 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002315 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002316 /* Job finished while waiting for a character. Push back the
2317 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002318 if (c != K_IGNORE)
2319 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002320 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002321 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002322 if (c == K_IGNORE)
2323 continue;
2324
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002325 // vgetc may not include CTRL in the key when modify_other_keys is set.
2326 raw_c = c;
2327 if ((mod_mask & MOD_MASK_CTRL)
2328 && ((c >= '`' && c <= 0x7f)
2329 || (c >= '@' && c <= '_')))
2330 c &= 0x1f;
2331
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002332#ifdef UNIX
2333 /*
2334 * The shell or another program may change the tty settings. Getting
2335 * them for every typed character is a bit of overhead, but it's needed
2336 * for the first character typed, e.g. when Vim starts in a shell.
2337 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002338 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002339 {
2340 ttyinfo_T info;
2341
2342 /* Get the current backspace character of the pty. */
2343 if (get_tty_info(tty_fd, &info) == OK)
2344 term_backspace_char = info.backspace;
2345 }
2346#endif
2347
Bram Moolenaar4f974752019-02-17 17:44:42 +01002348#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002349 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2350 * Use CTRL-BREAK to kill the job. */
2351 if (ctrl_break_was_pressed)
2352 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2353#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002354 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002355 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002356 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002357#ifdef FEAT_GUI
2358 && !curbuf->b_term->tl_system
2359#endif
2360 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002361 {
2362 int prev_c = c;
2363
2364#ifdef FEAT_CMDL_INFO
2365 if (add_to_showcmd(c))
2366 out_flush();
2367#endif
2368 c = term_vgetc();
2369#ifdef FEAT_CMDL_INFO
2370 clear_showcmd();
2371#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002372 if (!term_use_loop_check(TRUE)
2373 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002374 /* job finished while waiting for a character */
2375 break;
2376
2377 if (prev_c == Ctrl_BSL)
2378 {
2379 if (c == Ctrl_N)
2380 {
2381 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2382 term_enter_normal_mode();
2383 ret = FAIL;
2384 goto theend;
2385 }
2386 /* Send both keys to the terminal. */
2387 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2388 }
2389 else if (c == Ctrl_C)
2390 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002391 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002392 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2393 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002394 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002395 {
2396 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002397 /* "'termwinkey' .": send 'termwinkey' to the job */
2398 c = termwinkey == 0 ? Ctrl_W : termwinkey;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002399 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002400 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002401 {
2402 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2403 c = Ctrl_BSL;
2404 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002405 else if (c == 'N')
2406 {
2407 /* CTRL-W N : go to Terminal-Normal mode. */
2408 term_enter_normal_mode();
2409 ret = FAIL;
2410 goto theend;
2411 }
2412 else if (c == '"')
2413 {
2414 term_paste_register(prev_c);
2415 continue;
2416 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002417 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002418 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002419 char_u buf[MB_MAXBYTES + 2];
2420
2421 // Put the command into the typeahead buffer, when using the
2422 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2423 buf[0] = Ctrl_W;
2424 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2425 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002426 ret = OK;
2427 goto theend;
2428 }
2429 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002430# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002431 if (!enc_utf8 && has_mbyte && c >= 0x80)
2432 {
2433 WCHAR wc;
2434 char_u mb[3];
2435
2436 mb[0] = (unsigned)c >> 8;
2437 mb[1] = c;
2438 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2439 c = wc;
2440 }
2441# endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002442 if (send_keys_to_term(curbuf->b_term, raw_c, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002443 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002444 if (c == K_MOUSEMOVE)
2445 /* We are sure to come back here, don't reset the cursor color
2446 * and shape to avoid flickering. */
2447 restore_cursor = FALSE;
2448
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002449 ret = OK;
2450 goto theend;
2451 }
2452 }
2453 ret = FAIL;
2454
2455theend:
2456 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002457 if (restore_cursor)
2458 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002459
2460 /* Move a snapshot of the screen contents to the buffer, so that completion
2461 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002462 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2463 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002464
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002465 return ret;
2466}
2467
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002468 static void
2469may_toggle_cursor(term_T *term)
2470{
2471 if (in_terminal_loop == term)
2472 {
2473 if (term->tl_cursor_visible)
2474 cursor_on();
2475 else
2476 cursor_off();
2477 }
2478}
2479
2480/*
2481 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002482 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002483 */
2484 static int
2485color2index(VTermColor *color, int fg, int *boldp)
2486{
2487 int red = color->red;
2488 int blue = color->blue;
2489 int green = color->green;
2490
Bram Moolenaar46359e12017-11-29 22:33:38 +01002491 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002492 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002493 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002494 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002495 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002496 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002497 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002498 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2499 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2500 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002501 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002502 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2503 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2504 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2505 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2506 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2507 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2508 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2509 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2510 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2511 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2512 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002513 }
2514 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002515
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002516 if (t_colors >= 256)
2517 {
2518 if (red == blue && red == green)
2519 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002520 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002521 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002522 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2523 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2524 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002525 int i;
2526
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002527 if (red < 5)
2528 return 17; /* 00/00/00 */
2529 if (red > 245) /* ff/ff/ff */
2530 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002531 for (i = 0; i < 23; ++i)
2532 if (red < cutoff[i])
2533 return i + 233;
2534 return 256;
2535 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002536 {
2537 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2538 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002540 /* 216-color cube */
2541 for (ri = 0; ri < 5; ++ri)
2542 if (red < cutoff[ri])
2543 break;
2544 for (gi = 0; gi < 5; ++gi)
2545 if (green < cutoff[gi])
2546 break;
2547 for (bi = 0; bi < 5; ++bi)
2548 if (blue < cutoff[bi])
2549 break;
2550 return 17 + ri * 36 + gi * 6 + bi;
2551 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002552 }
2553 return 0;
2554}
2555
2556/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002557 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002558 */
2559 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002560vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002561{
2562 int attr = 0;
2563
2564 if (cellattrs.bold)
2565 attr |= HL_BOLD;
2566 if (cellattrs.underline)
2567 attr |= HL_UNDERLINE;
2568 if (cellattrs.italic)
2569 attr |= HL_ITALIC;
2570 if (cellattrs.strike)
2571 attr |= HL_STRIKETHROUGH;
2572 if (cellattrs.reverse)
2573 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002574 return attr;
2575}
2576
2577/*
2578 * Store Vterm attributes in "cell" from highlight flags.
2579 */
2580 static void
2581hl2vtermAttr(int attr, cellattr_T *cell)
2582{
2583 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2584 if (attr & HL_BOLD)
2585 cell->attrs.bold = 1;
2586 if (attr & HL_UNDERLINE)
2587 cell->attrs.underline = 1;
2588 if (attr & HL_ITALIC)
2589 cell->attrs.italic = 1;
2590 if (attr & HL_STRIKETHROUGH)
2591 cell->attrs.strike = 1;
2592 if (attr & HL_INVERSE)
2593 cell->attrs.reverse = 1;
2594}
2595
2596/*
2597 * Convert the attributes of a vterm cell into an attribute index.
2598 */
2599 static int
2600cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2601{
2602 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002603
2604#ifdef FEAT_GUI
2605 if (gui.in_use)
2606 {
2607 guicolor_T fg, bg;
2608
2609 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2610 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2611 return get_gui_attr_idx(attr, fg, bg);
2612 }
2613 else
2614#endif
2615#ifdef FEAT_TERMGUICOLORS
2616 if (p_tgc)
2617 {
2618 guicolor_T fg, bg;
2619
2620 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2621 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2622
2623 return get_tgc_attr_idx(attr, fg, bg);
2624 }
2625 else
2626#endif
2627 {
2628 int bold = MAYBE;
2629 int fg = color2index(&cellfg, TRUE, &bold);
2630 int bg = color2index(&cellbg, FALSE, &bold);
2631
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002632 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002633 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002634 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002635 if (fg == 0 && term_default_cterm_fg >= 0)
2636 fg = term_default_cterm_fg + 1;
2637 if (bg == 0 && term_default_cterm_bg >= 0)
2638 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002639 }
2640
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002641 /* with 8 colors set the bold attribute to get a bright foreground */
2642 if (bold == TRUE)
2643 attr |= HL_BOLD;
2644 return get_cterm_attr_idx(attr, fg, bg);
2645 }
2646 return 0;
2647}
2648
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002649 static void
2650set_dirty_snapshot(term_T *term)
2651{
2652 term->tl_dirty_snapshot = TRUE;
2653#ifdef FEAT_TIMERS
2654 if (!term->tl_normal_mode)
2655 {
2656 /* Update the snapshot after 100 msec of not getting updates. */
2657 profile_setlimit(100L, &term->tl_timer_due);
2658 term->tl_timer_set = TRUE;
2659 }
2660#endif
2661}
2662
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002663 static int
2664handle_damage(VTermRect rect, void *user)
2665{
2666 term_T *term = (term_T *)user;
2667
2668 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2669 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002670 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002671 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002672 return 1;
2673}
2674
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002675 static void
2676term_scroll_up(term_T *term, int start_row, int count)
2677{
2678 win_T *wp;
2679 VTermColor fg, bg;
2680 VTermScreenCellAttrs attr;
2681 int clear_attr;
2682
2683 /* Set the color to clear lines with. */
2684 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2685 &fg, &bg);
2686 vim_memset(&attr, 0, sizeof(attr));
2687 clear_attr = cell2attr(attr, fg, bg);
2688
2689 FOR_ALL_WINDOWS(wp)
2690 {
2691 if (wp->w_buffer == term->tl_buffer)
2692 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2693 }
2694}
2695
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002696 static int
2697handle_moverect(VTermRect dest, VTermRect src, void *user)
2698{
2699 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002700 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002701
2702 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002703 * redrawing the text. But avoid doing this multiple times, postpone until
2704 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002705 if (dest.start_col == src.start_col
2706 && dest.end_col == src.end_col
2707 && dest.start_row < src.start_row)
2708 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002709 if (dest.start_row == 0)
2710 term->tl_postponed_scroll += count;
2711 else
2712 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002713 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002714
2715 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2716 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002717 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002718
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002719 /* Note sure if the scrolling will work correctly, let's do a complete
2720 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002721 redraw_buf_later(term->tl_buffer, NOT_VALID);
2722 return 1;
2723}
2724
2725 static int
2726handle_movecursor(
2727 VTermPos pos,
2728 VTermPos oldpos UNUSED,
2729 int visible,
2730 void *user)
2731{
2732 term_T *term = (term_T *)user;
2733 win_T *wp;
2734
2735 term->tl_cursor_pos = pos;
2736 term->tl_cursor_visible = visible;
2737
2738 FOR_ALL_WINDOWS(wp)
2739 {
2740 if (wp->w_buffer == term->tl_buffer)
2741 position_cursor(wp, &pos);
2742 }
2743 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2744 {
2745 may_toggle_cursor(term);
2746 update_cursor(term, term->tl_cursor_visible);
2747 }
2748
2749 return 1;
2750}
2751
2752 static int
2753handle_settermprop(
2754 VTermProp prop,
2755 VTermValue *value,
2756 void *user)
2757{
2758 term_T *term = (term_T *)user;
2759
2760 switch (prop)
2761 {
2762 case VTERM_PROP_TITLE:
2763 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002764 // a blank title isn't useful, make it empty, so that "running" is
2765 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002766 if (*skipwhite((char_u *)value->string) == NUL)
2767 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002768 // Same as blank
2769 else if (term->tl_arg0_cmd != NULL
2770 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2771 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2772 term->tl_title = NULL;
2773 // Empty corrupted data of winpty
2774 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2775 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002776#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002777 else if (!enc_utf8 && enc_codepage > 0)
2778 {
2779 WCHAR *ret = NULL;
2780 int length = 0;
2781
2782 MultiByteToWideChar_alloc(CP_UTF8, 0,
2783 (char*)value->string, (int)STRLEN(value->string),
2784 &ret, &length);
2785 if (ret != NULL)
2786 {
2787 WideCharToMultiByte_alloc(enc_codepage, 0,
2788 ret, length, (char**)&term->tl_title,
2789 &length, 0, 0);
2790 vim_free(ret);
2791 }
2792 }
2793#endif
2794 else
2795 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002796 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002797 if (term == curbuf->b_term)
2798 maketitle();
2799 break;
2800
2801 case VTERM_PROP_CURSORVISIBLE:
2802 term->tl_cursor_visible = value->boolean;
2803 may_toggle_cursor(term);
2804 out_flush();
2805 break;
2806
2807 case VTERM_PROP_CURSORBLINK:
2808 term->tl_cursor_blink = value->boolean;
2809 may_set_cursor_props(term);
2810 break;
2811
2812 case VTERM_PROP_CURSORSHAPE:
2813 term->tl_cursor_shape = value->number;
2814 may_set_cursor_props(term);
2815 break;
2816
2817 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002818 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002819 may_set_cursor_props(term);
2820 break;
2821
2822 case VTERM_PROP_ALTSCREEN:
2823 /* TODO: do anything else? */
2824 term->tl_using_altscreen = value->boolean;
2825 break;
2826
2827 default:
2828 break;
2829 }
2830 /* Always return 1, otherwise vterm doesn't store the value internally. */
2831 return 1;
2832}
2833
2834/*
2835 * The job running in the terminal resized the terminal.
2836 */
2837 static int
2838handle_resize(int rows, int cols, void *user)
2839{
2840 term_T *term = (term_T *)user;
2841 win_T *wp;
2842
2843 term->tl_rows = rows;
2844 term->tl_cols = cols;
2845 if (term->tl_vterm_size_changed)
2846 /* Size was set by vterm_set_size(), don't set the window size. */
2847 term->tl_vterm_size_changed = FALSE;
2848 else
2849 {
2850 FOR_ALL_WINDOWS(wp)
2851 {
2852 if (wp->w_buffer == term->tl_buffer)
2853 {
2854 win_setheight_win(rows, wp);
2855 win_setwidth_win(cols, wp);
2856 }
2857 }
2858 redraw_buf_later(term->tl_buffer, NOT_VALID);
2859 }
2860 return 1;
2861}
2862
2863/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002864 * If the number of lines that are stored goes over 'termscrollback' then
2865 * delete the first 10%.
2866 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2867 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002868 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002869 static void
2870limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002871{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002872 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002873 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002874 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002875 int i;
2876
2877 curbuf = term->tl_buffer;
2878 for (i = 0; i < todo; ++i)
2879 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002880 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
2881 if (update_buffer)
2882 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002883 }
2884 curbuf = curwin->w_buffer;
2885
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002886 gap->ga_len -= todo;
2887 mch_memmove(gap->ga_data,
2888 (sb_line_T *)gap->ga_data + todo,
2889 sizeof(sb_line_T) * gap->ga_len);
2890 if (update_buffer)
2891 term->tl_scrollback_scrolled -= todo;
2892 }
2893}
2894
2895/*
2896 * Handle a line that is pushed off the top of the screen.
2897 */
2898 static int
2899handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2900{
2901 term_T *term = (term_T *)user;
2902 garray_T *gap;
2903 int update_buffer;
2904
2905 if (term->tl_normal_mode)
2906 {
2907 // In Terminal-Normal mode the user interacts with the buffer, thus we
2908 // must not change it. Postpone adding the scrollback lines.
2909 gap = &term->tl_scrollback_postponed;
2910 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002911 }
2912 else
2913 {
2914 // First remove the lines that were appended before, the pushed line
2915 // goes above it.
2916 cleanup_scrollback(term);
2917 gap = &term->tl_scrollback;
2918 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002919 }
2920
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002921 limit_scrollback(term, gap, update_buffer);
2922
2923 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002924 {
2925 cellattr_T *p = NULL;
2926 int len = 0;
2927 int i;
2928 int c;
2929 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002930 int text_len;
2931 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002932 sb_line_T *line;
2933 garray_T ga;
2934 cellattr_T fill_attr = term->tl_default_color;
2935
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002936 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002937 for (i = 0; i < cols; ++i)
2938 if (cells[i].chars[0] != 0)
2939 len = i + 1;
2940 else
2941 cell2cellattr(&cells[i], &fill_attr);
2942
2943 ga_init2(&ga, 1, 100);
2944 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002945 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002946 if (p != NULL)
2947 {
2948 for (col = 0; col < len; col += cells[col].width)
2949 {
2950 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2951 {
2952 ga.ga_len = 0;
2953 break;
2954 }
2955 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2956 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2957 (char_u *)ga.ga_data + ga.ga_len);
2958 cell2cellattr(&cells[col], &p[col]);
2959 }
2960 }
2961 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002962 {
2963 if (update_buffer)
2964 text = (char_u *)"";
2965 else
2966 text = vim_strsave((char_u *)"");
2967 text_len = 0;
2968 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002969 else
2970 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002971 text = ga.ga_data;
2972 text_len = ga.ga_len;
2973 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002974 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002975 if (update_buffer)
2976 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002977
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002978 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002979 line->sb_cols = len;
2980 line->sb_cells = p;
2981 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002982 if (update_buffer)
2983 {
2984 line->sb_text = NULL;
2985 ++term->tl_scrollback_scrolled;
2986 ga_clear(&ga); // free the text
2987 }
2988 else
2989 {
2990 line->sb_text = text;
2991 ga_init(&ga); // text is kept in tl_scrollback_postponed
2992 }
2993 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002994 }
2995 return 0; /* ignored */
2996}
2997
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002998/*
2999 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3000 * received and stored in tl_scrollback_postponed.
3001 */
3002 static void
3003handle_postponed_scrollback(term_T *term)
3004{
3005 int i;
3006
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003007 if (term->tl_scrollback_postponed.ga_len == 0)
3008 return;
3009 ch_log(NULL, "Moving postponed scrollback to scrollback");
3010
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003011 // First remove the lines that were appended before, the pushed lines go
3012 // above it.
3013 cleanup_scrollback(term);
3014
3015 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3016 {
3017 char_u *text;
3018 sb_line_T *pp_line;
3019 sb_line_T *line;
3020
3021 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3022 break;
3023 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3024
3025 text = pp_line->sb_text;
3026 if (text == NULL)
3027 text = (char_u *)"";
3028 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3029 vim_free(pp_line->sb_text);
3030
3031 line = (sb_line_T *)term->tl_scrollback.ga_data
3032 + term->tl_scrollback.ga_len;
3033 line->sb_cols = pp_line->sb_cols;
3034 line->sb_cells = pp_line->sb_cells;
3035 line->sb_fill_attr = pp_line->sb_fill_attr;
3036 line->sb_text = NULL;
3037 ++term->tl_scrollback_scrolled;
3038 ++term->tl_scrollback.ga_len;
3039 }
3040
3041 ga_clear(&term->tl_scrollback_postponed);
3042 limit_scrollback(term, &term->tl_scrollback, TRUE);
3043}
3044
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003045static VTermScreenCallbacks screen_callbacks = {
3046 handle_damage, /* damage */
3047 handle_moverect, /* moverect */
3048 handle_movecursor, /* movecursor */
3049 handle_settermprop, /* settermprop */
3050 NULL, /* bell */
3051 handle_resize, /* resize */
3052 handle_pushline, /* sb_pushline */
3053 NULL /* sb_popline */
3054};
3055
3056/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003057 * Do the work after the channel of a terminal was closed.
3058 * Must be called only when updating_screen is FALSE.
3059 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3060 */
3061 static int
3062term_after_channel_closed(term_T *term)
3063{
3064 /* Unless in Terminal-Normal mode: clear the vterm. */
3065 if (!term->tl_normal_mode)
3066 {
3067 int fnum = term->tl_buffer->b_fnum;
3068
3069 cleanup_vterm(term);
3070
3071 if (term->tl_finish == TL_FINISH_CLOSE)
3072 {
3073 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003074 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003075
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003076 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003077 ch_log(NULL, "terminal job finished, closing window");
3078 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003079 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003080 if (curwin == aucmd_win)
3081 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003082 if (do_set_w_closing)
3083 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003084 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003085 if (do_set_w_closing)
3086 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003087 aucmd_restbuf(&aco);
3088 return TRUE;
3089 }
3090 if (term->tl_finish == TL_FINISH_OPEN
3091 && term->tl_buffer->b_nwindows == 0)
3092 {
3093 char buf[50];
3094
3095 /* TODO: use term_opencmd */
3096 ch_log(NULL, "terminal job finished, opening window");
3097 vim_snprintf(buf, sizeof(buf),
3098 term->tl_opencmd == NULL
3099 ? "botright sbuf %d"
3100 : (char *)term->tl_opencmd, fnum);
3101 do_cmdline_cmd((char_u *)buf);
3102 }
3103 else
3104 ch_log(NULL, "terminal job finished");
3105 }
3106
3107 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3108 return FALSE;
3109}
3110
3111/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003112 * Called when a channel has been closed.
3113 * If this was a channel for a terminal window then finish it up.
3114 */
3115 void
3116term_channel_closed(channel_T *ch)
3117{
3118 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003119 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003120 int did_one = FALSE;
3121
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003122 for (term = first_term; term != NULL; term = next_term)
3123 {
3124 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003125 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003126 {
3127 term->tl_channel_closed = TRUE;
3128 did_one = TRUE;
3129
Bram Moolenaard23a8232018-02-10 18:45:26 +01003130 VIM_CLEAR(term->tl_title);
3131 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003132#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003133 if (term->tl_out_fd != NULL)
3134 {
3135 fclose(term->tl_out_fd);
3136 term->tl_out_fd = NULL;
3137 }
3138#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003139
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003140 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003141 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003142 /* Cannot open or close windows now. Can happen when
3143 * 'lazyredraw' is set. */
3144 term->tl_channel_recently_closed = TRUE;
3145 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003146 }
3147
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003148 if (term_after_channel_closed(term))
3149 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003150 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003151 }
3152
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153 if (did_one)
3154 {
3155 redraw_statuslines();
3156
3157 /* Need to break out of vgetc(). */
3158 ins_char_typebuf(K_IGNORE);
3159 typebuf_was_filled = TRUE;
3160
3161 term = curbuf->b_term;
3162 if (term != NULL)
3163 {
3164 if (term->tl_job == ch->ch_job)
3165 maketitle();
3166 update_cursor(term, term->tl_cursor_visible);
3167 }
3168 }
3169}
3170
3171/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003172 * To be called after resetting updating_screen: handle any terminal where the
3173 * channel was closed.
3174 */
3175 void
3176term_check_channel_closed_recently()
3177{
3178 term_T *term;
3179 term_T *next_term;
3180
3181 for (term = first_term; term != NULL; term = next_term)
3182 {
3183 next_term = term->tl_next;
3184 if (term->tl_channel_recently_closed)
3185 {
3186 term->tl_channel_recently_closed = FALSE;
3187 if (term_after_channel_closed(term))
3188 // start over, the list may have changed
3189 next_term = first_term;
3190 }
3191 }
3192}
3193
3194/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003195 * Fill one screen line from a line of the terminal.
3196 * Advances "pos" to past the last column.
3197 */
3198 static void
3199term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3200{
3201 int off = screen_get_current_line_off();
3202
3203 for (pos->col = 0; pos->col < max_col; )
3204 {
3205 VTermScreenCell cell;
3206 int c;
3207
3208 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3209 vim_memset(&cell, 0, sizeof(cell));
3210
3211 c = cell.chars[0];
3212 if (c == NUL)
3213 {
3214 ScreenLines[off] = ' ';
3215 if (enc_utf8)
3216 ScreenLinesUC[off] = NUL;
3217 }
3218 else
3219 {
3220 if (enc_utf8)
3221 {
3222 int i;
3223
3224 /* composing chars */
3225 for (i = 0; i < Screen_mco
3226 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3227 {
3228 ScreenLinesC[i][off] = cell.chars[i + 1];
3229 if (cell.chars[i + 1] == 0)
3230 break;
3231 }
3232 if (c >= 0x80 || (Screen_mco > 0
3233 && ScreenLinesC[0][off] != 0))
3234 {
3235 ScreenLines[off] = ' ';
3236 ScreenLinesUC[off] = c;
3237 }
3238 else
3239 {
3240 ScreenLines[off] = c;
3241 ScreenLinesUC[off] = NUL;
3242 }
3243 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003244#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003245 else if (has_mbyte && c >= 0x80)
3246 {
3247 char_u mb[MB_MAXBYTES+1];
3248 WCHAR wc = c;
3249
3250 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3251 (char*)mb, 2, 0, 0) > 1)
3252 {
3253 ScreenLines[off] = mb[0];
3254 ScreenLines[off + 1] = mb[1];
3255 cell.width = mb_ptr2cells(mb);
3256 }
3257 else
3258 ScreenLines[off] = c;
3259 }
3260#endif
3261 else
3262 ScreenLines[off] = c;
3263 }
3264 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3265
3266 ++pos->col;
3267 ++off;
3268 if (cell.width == 2)
3269 {
3270 if (enc_utf8)
3271 ScreenLinesUC[off] = NUL;
3272
3273 /* don't set the second byte to NUL for a DBCS encoding, it
3274 * has been set above */
3275 if (enc_utf8 || !has_mbyte)
3276 ScreenLines[off] = NUL;
3277
3278 ++pos->col;
3279 ++off;
3280 }
3281 }
3282}
3283
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003284#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003285 static void
3286update_system_term(term_T *term)
3287{
3288 VTermPos pos;
3289 VTermScreen *screen;
3290
3291 if (term->tl_vterm == NULL)
3292 return;
3293 screen = vterm_obtain_screen(term->tl_vterm);
3294
3295 /* Scroll up to make more room for terminal lines if needed. */
3296 while (term->tl_toprow > 0
3297 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3298 {
3299 int save_p_more = p_more;
3300
3301 p_more = FALSE;
3302 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003303 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003304 p_more = save_p_more;
3305 --term->tl_toprow;
3306 }
3307
3308 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3309 && pos.row < Rows; ++pos.row)
3310 {
3311 if (pos.row < term->tl_rows)
3312 {
3313 int max_col = MIN(Columns, term->tl_cols);
3314
3315 term_line2screenline(screen, &pos, max_col);
3316 }
3317 else
3318 pos.col = 0;
3319
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003320 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003321 }
3322
3323 term->tl_dirty_row_start = MAX_ROW;
3324 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003325}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003326#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003327
3328/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003329 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3330 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003331 * Terminal-Normal mode.
3332 */
3333 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003334term_do_update_window(win_T *wp)
3335{
3336 term_T *term = wp->w_buffer->b_term;
3337
3338 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3339}
3340
3341/*
3342 * Called to update a window that contains an active terminal.
3343 */
3344 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003345term_update_window(win_T *wp)
3346{
3347 term_T *term = wp->w_buffer->b_term;
3348 VTerm *vterm;
3349 VTermScreen *screen;
3350 VTermState *state;
3351 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003352 int rows, cols;
3353 int newrows, newcols;
3354 int minsize;
3355 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003356
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357 vterm = term->tl_vterm;
3358 screen = vterm_obtain_screen(vterm);
3359 state = vterm_obtain_state(vterm);
3360
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003361 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3362 * SOME_VALID only redraw what was marked dirty. */
3363 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003364 {
3365 term->tl_dirty_row_start = 0;
3366 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003367
3368 if (term->tl_postponed_scroll > 0
3369 && term->tl_postponed_scroll < term->tl_rows / 3)
3370 /* Scrolling is usually faster than redrawing, when there are only
3371 * a few lines to scroll. */
3372 term_scroll_up(term, 0, term->tl_postponed_scroll);
3373 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003374 }
3375
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003376 /*
3377 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003378 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003379 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003380 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003381
Bram Moolenaar498c2562018-04-15 23:45:15 +02003382 newrows = 99999;
3383 newcols = 99999;
3384 FOR_ALL_WINDOWS(twp)
3385 {
3386 /* When more than one window shows the same terminal, use the
3387 * smallest size. */
3388 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003389 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003390 newrows = MIN(newrows, twp->w_height);
3391 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003392 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003393 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003394 if (newrows == 99999 || newcols == 99999)
3395 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003396 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3397 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3398
3399 if (term->tl_rows != newrows || term->tl_cols != newcols)
3400 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003401 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003402 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003403 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003404 newrows);
3405 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003406
3407 // Updating the terminal size will cause the snapshot to be cleared.
3408 // When not in terminal_loop() we need to restore it.
3409 if (term != in_terminal_loop)
3410 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003411 }
3412
3413 /* The cursor may have been moved when resizing. */
3414 vterm_state_get_cursorpos(state, &pos);
3415 position_cursor(wp, &pos);
3416
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003417 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3418 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003419 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003420 if (pos.row < term->tl_rows)
3421 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003422 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003423
Bram Moolenaar13568252018-03-16 20:46:58 +01003424 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003425 }
3426 else
3427 pos.col = 0;
3428
Bram Moolenaarf118d482018-03-13 13:14:00 +01003429 screen_line(wp->w_winrow + pos.row
3430#ifdef FEAT_MENU
3431 + winbar_height(wp)
3432#endif
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003433 , wp->w_wincol, pos.col, wp->w_width, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003434 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003435 term->tl_dirty_row_start = MAX_ROW;
3436 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003437}
3438
3439/*
3440 * Return TRUE if "wp" is a terminal window where the job has finished.
3441 */
3442 int
3443term_is_finished(buf_T *buf)
3444{
3445 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3446}
3447
3448/*
3449 * Return TRUE if "wp" is a terminal window where the job has finished or we
3450 * are in Terminal-Normal mode, thus we show the buffer contents.
3451 */
3452 int
3453term_show_buffer(buf_T *buf)
3454{
3455 term_T *term = buf->b_term;
3456
3457 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3458}
3459
3460/*
3461 * The current buffer is going to be changed. If there is terminal
3462 * highlighting remove it now.
3463 */
3464 void
3465term_change_in_curbuf(void)
3466{
3467 term_T *term = curbuf->b_term;
3468
3469 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3470 {
3471 free_scrollback(term);
3472 redraw_buf_later(term->tl_buffer, NOT_VALID);
3473
3474 /* The buffer is now like a normal buffer, it cannot be easily
3475 * abandoned when changed. */
3476 set_string_option_direct((char_u *)"buftype", -1,
3477 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3478 }
3479}
3480
3481/*
3482 * Get the screen attribute for a position in the buffer.
3483 * Use a negative "col" to get the filler background color.
3484 */
3485 int
3486term_get_attr(buf_T *buf, linenr_T lnum, int col)
3487{
3488 term_T *term = buf->b_term;
3489 sb_line_T *line;
3490 cellattr_T *cellattr;
3491
3492 if (lnum > term->tl_scrollback.ga_len)
3493 cellattr = &term->tl_default_color;
3494 else
3495 {
3496 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3497 if (col < 0 || col >= line->sb_cols)
3498 cellattr = &line->sb_fill_attr;
3499 else
3500 cellattr = line->sb_cells + col;
3501 }
3502 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3503}
3504
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003505/*
3506 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003507 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003508 */
3509 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003510cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003511{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003512 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003513}
3514
3515/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003516 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003517 */
3518 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003519init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003520{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003521 VTermColor *fg, *bg;
3522 int fgval, bgval;
3523 int id;
3524
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003525 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3526 term->tl_default_color.width = 1;
3527 fg = &term->tl_default_color.fg;
3528 bg = &term->tl_default_color.bg;
3529
3530 /* Vterm uses a default black background. Set it to white when
3531 * 'background' is "light". */
3532 if (*p_bg == 'l')
3533 {
3534 fgval = 0;
3535 bgval = 255;
3536 }
3537 else
3538 {
3539 fgval = 255;
3540 bgval = 0;
3541 }
3542 fg->red = fg->green = fg->blue = fgval;
3543 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003544 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003545
3546 /* The "Terminal" highlight group overrules the defaults. */
3547 id = syn_name2id((char_u *)"Terminal");
3548
Bram Moolenaar46359e12017-11-29 22:33:38 +01003549 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003550#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3551 if (0
3552# ifdef FEAT_GUI
3553 || gui.in_use
3554# endif
3555# ifdef FEAT_TERMGUICOLORS
3556 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003557# ifdef FEAT_VTP
3558 /* Finally get INVALCOLOR on this execution path */
3559 || (!p_tgc && t_colors >= 256)
3560# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003561# endif
3562 )
3563 {
3564 guicolor_T fg_rgb = INVALCOLOR;
3565 guicolor_T bg_rgb = INVALCOLOR;
3566
3567 if (id != 0)
3568 syn_id2colors(id, &fg_rgb, &bg_rgb);
3569
3570# ifdef FEAT_GUI
3571 if (gui.in_use)
3572 {
3573 if (fg_rgb == INVALCOLOR)
3574 fg_rgb = gui.norm_pixel;
3575 if (bg_rgb == INVALCOLOR)
3576 bg_rgb = gui.back_pixel;
3577 }
3578# ifdef FEAT_TERMGUICOLORS
3579 else
3580# endif
3581# endif
3582# ifdef FEAT_TERMGUICOLORS
3583 {
3584 if (fg_rgb == INVALCOLOR)
3585 fg_rgb = cterm_normal_fg_gui_color;
3586 if (bg_rgb == INVALCOLOR)
3587 bg_rgb = cterm_normal_bg_gui_color;
3588 }
3589# endif
3590 if (fg_rgb != INVALCOLOR)
3591 {
3592 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3593
3594 fg->red = (unsigned)(rgb >> 16);
3595 fg->green = (unsigned)(rgb >> 8) & 255;
3596 fg->blue = (unsigned)rgb & 255;
3597 }
3598 if (bg_rgb != INVALCOLOR)
3599 {
3600 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3601
3602 bg->red = (unsigned)(rgb >> 16);
3603 bg->green = (unsigned)(rgb >> 8) & 255;
3604 bg->blue = (unsigned)rgb & 255;
3605 }
3606 }
3607 else
3608#endif
3609 if (id != 0 && t_colors >= 16)
3610 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003611 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003612 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003613 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003614 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003615 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003616 else
3617 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003618#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003619 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003620#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003621
3622 /* In an MS-Windows console we know the normal colors. */
3623 if (cterm_normal_fg_color > 0)
3624 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003625 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003626# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3627# ifdef VIMDLL
3628 if (!gui.in_use)
3629# endif
3630 {
3631 tmp = fg->red;
3632 fg->red = fg->blue;
3633 fg->blue = tmp;
3634 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003635# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003636 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003637# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003638 else
3639 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003640# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003641
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003642 if (cterm_normal_bg_color > 0)
3643 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003644 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003645# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3646# ifdef VIMDLL
3647 if (!gui.in_use)
3648# endif
3649 {
3650 tmp = fg->red;
3651 fg->red = fg->blue;
3652 fg->blue = tmp;
3653 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003654# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003655 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003656# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003657 else
3658 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003659# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003660 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003661}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003662
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003663#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3664/*
3665 * Set the 16 ANSI colors from array of RGB values
3666 */
3667 static void
3668set_vterm_palette(VTerm *vterm, long_u *rgb)
3669{
3670 int index = 0;
3671 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003672
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003673 for (; index < 16; index++)
3674 {
3675 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003676
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003677 color.red = (unsigned)(rgb[index] >> 16);
3678 color.green = (unsigned)(rgb[index] >> 8) & 255;
3679 color.blue = (unsigned)rgb[index] & 255;
3680 vterm_state_set_palette_color(state, index, &color);
3681 }
3682}
3683
3684/*
3685 * Set the ANSI color palette from a list of colors
3686 */
3687 static int
3688set_ansi_colors_list(VTerm *vterm, list_T *list)
3689{
3690 int n = 0;
3691 long_u rgb[16];
3692 listitem_T *li = list->lv_first;
3693
3694 for (; li != NULL && n < 16; li = li->li_next, n++)
3695 {
3696 char_u *color_name;
3697 guicolor_T guicolor;
3698
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003699 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003700 if (color_name == NULL)
3701 return FAIL;
3702
3703 guicolor = GUI_GET_COLOR(color_name);
3704 if (guicolor == INVALCOLOR)
3705 return FAIL;
3706
3707 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3708 }
3709
3710 if (n != 16 || li != NULL)
3711 return FAIL;
3712
3713 set_vterm_palette(vterm, rgb);
3714
3715 return OK;
3716}
3717
3718/*
3719 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3720 */
3721 static void
3722init_vterm_ansi_colors(VTerm *vterm)
3723{
3724 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3725
3726 if (var != NULL
3727 && (var->di_tv.v_type != VAR_LIST
3728 || var->di_tv.vval.v_list == NULL
3729 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003730 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003731}
3732#endif
3733
Bram Moolenaar52acb112018-03-18 19:20:22 +01003734/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003735 * Handles a "drop" command from the job in the terminal.
3736 * "item" is the file name, "item->li_next" may have options.
3737 */
3738 static void
3739handle_drop_command(listitem_T *item)
3740{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003741 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003742 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003743 int bufnr;
3744 win_T *wp;
3745 tabpage_T *tp;
3746 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003747 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003748
3749 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3750 FOR_ALL_TAB_WINDOWS(tp, wp)
3751 {
3752 if (wp->w_buffer->b_fnum == bufnr)
3753 {
3754 /* buffer is in a window already, go there */
3755 goto_tabpage_win(tp, wp);
3756 return;
3757 }
3758 }
3759
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003760 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003761
3762 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3763 && opt_item->li_tv.vval.v_dict != NULL)
3764 {
3765 dict_T *dict = opt_item->li_tv.vval.v_dict;
3766 char_u *p;
3767
Bram Moolenaar8f667172018-12-14 15:38:31 +01003768 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003769 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003770 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003771 if (p != NULL)
3772 {
3773 if (check_ff_value(p) == FAIL)
3774 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3775 else
3776 ea.force_ff = *p;
3777 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003778 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003779 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003780 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003781 if (p != NULL)
3782 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003783 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003784 if (ea.cmd != NULL)
3785 {
3786 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3787 ea.force_enc = 11;
3788 tofree = ea.cmd;
3789 }
3790 }
3791
Bram Moolenaar8f667172018-12-14 15:38:31 +01003792 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003793 if (p != NULL)
3794 get_bad_opt(p, &ea);
3795
3796 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3797 ea.force_bin = FORCE_BIN;
3798 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3799 ea.force_bin = FORCE_BIN;
3800 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3801 ea.force_bin = FORCE_NOBIN;
3802 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3803 ea.force_bin = FORCE_NOBIN;
3804 }
3805
3806 /* open in new window, like ":split fname" */
3807 if (ea.cmd == NULL)
3808 ea.cmd = (char_u *)"split";
3809 ea.arg = fname;
3810 ea.cmdidx = CMD_split;
3811 ex_splitview(&ea);
3812
3813 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003814}
3815
3816/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003817 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
3818 */
3819 static int
3820is_permitted_term_api(char_u *func, char_u *pat)
3821{
3822 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
3823}
3824
3825/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003826 * Handles a function call from the job running in a terminal.
3827 * "item" is the function name, "item->li_next" has the arguments.
3828 */
3829 static void
3830handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3831{
3832 char_u *func;
3833 typval_T argvars[2];
3834 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003835 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003836
3837 if (item->li_next == NULL)
3838 {
3839 ch_log(channel, "Missing function arguments for call");
3840 return;
3841 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003842 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003843
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003844 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003845 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003846 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003847 return;
3848 }
3849
3850 argvars[0].v_type = VAR_NUMBER;
3851 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3852 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003853 vim_memset(&funcexe, 0, sizeof(funcexe));
3854 funcexe.firstline = 1L;
3855 funcexe.lastline = 1L;
3856 funcexe.evaluate = TRUE;
3857 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003858 {
3859 clear_tv(&rettv);
3860 ch_log(channel, "Function %s called", func);
3861 }
3862 else
3863 ch_log(channel, "Calling function %s failed", func);
3864}
3865
3866/*
3867 * Called by libvterm when it cannot recognize an OSC sequence.
3868 * We recognize a terminal API command.
3869 */
3870 static int
3871parse_osc(const char *command, size_t cmdlen, void *user)
3872{
3873 term_T *term = (term_T *)user;
3874 js_read_T reader;
3875 typval_T tv;
3876 channel_T *channel = term->tl_job == NULL ? NULL
3877 : term->tl_job->jv_channel;
3878
3879 /* We recognize only OSC 5 1 ; {command} */
3880 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3881 return 0; /* not handled */
3882
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003883 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003884 if (reader.js_buf == NULL)
3885 return 1;
3886 reader.js_fill = NULL;
3887 reader.js_used = 0;
3888 if (json_decode(&reader, &tv, 0) == OK
3889 && tv.v_type == VAR_LIST
3890 && tv.vval.v_list != NULL)
3891 {
3892 listitem_T *item = tv.vval.v_list->lv_first;
3893
3894 if (item == NULL)
3895 ch_log(channel, "Missing command");
3896 else
3897 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003898 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003899
Bram Moolenaara997b452018-04-17 23:24:06 +02003900 /* Make sure an invoked command doesn't delete the buffer (and the
3901 * terminal) under our fingers. */
3902 ++term->tl_buffer->b_locked;
3903
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003904 item = item->li_next;
3905 if (item == NULL)
3906 ch_log(channel, "Missing argument for %s", cmd);
3907 else if (STRCMP(cmd, "drop") == 0)
3908 handle_drop_command(item);
3909 else if (STRCMP(cmd, "call") == 0)
3910 handle_call_command(term, channel, item);
3911 else
3912 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003913 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003914 }
3915 }
3916 else
3917 ch_log(channel, "Invalid JSON received");
3918
3919 vim_free(reader.js_buf);
3920 clear_tv(&tv);
3921 return 1;
3922}
3923
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003924/*
3925 * Called by libvterm when it cannot recognize a CSI sequence.
3926 * We recognize the window position report.
3927 */
3928 static int
3929parse_csi(
3930 const char *leader UNUSED,
3931 const long args[],
3932 int argcount,
3933 const char *intermed UNUSED,
3934 char command,
3935 void *user)
3936{
3937 term_T *term = (term_T *)user;
3938 char buf[100];
3939 int len;
3940 int x = 0;
3941 int y = 0;
3942 win_T *wp;
3943
3944 // We recognize only CSI 13 t
3945 if (command != 't' || argcount != 1 || args[0] != 13)
3946 return 0; // not handled
3947
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003948 // When getting the window position is not possible or it fails it results
3949 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02003950#if defined(FEAT_GUI) \
3951 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
3952 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003953 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003954#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003955
3956 FOR_ALL_WINDOWS(wp)
3957 if (wp->w_buffer == term->tl_buffer)
3958 break;
3959 if (wp != NULL)
3960 {
3961#ifdef FEAT_GUI
3962 if (gui.in_use)
3963 {
3964 x += wp->w_wincol * gui.char_width;
3965 y += W_WINROW(wp) * gui.char_height;
3966 }
3967 else
3968#endif
3969 {
3970 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003971 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003972 x += wp->w_wincol * 7;
3973 y += W_WINROW(wp) * 10;
3974 }
3975 }
3976
3977 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
3978 channel_send(term->tl_job->jv_channel, get_tty_part(term),
3979 (char_u *)buf, len, NULL);
3980 return 1;
3981}
3982
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003983static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003984 NULL, // text
3985 NULL, // control
3986 NULL, // escape
3987 parse_csi, // csi
3988 parse_osc, // osc
3989 NULL, // dcs
3990 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003991};
3992
3993/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003994 * Use Vim's allocation functions for vterm so profiling works.
3995 */
3996 static void *
3997vterm_malloc(size_t size, void *data UNUSED)
3998{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02003999 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004000}
4001
4002 static void
4003vterm_memfree(void *ptr, void *data UNUSED)
4004{
4005 vim_free(ptr);
4006}
4007
4008static VTermAllocatorFunctions vterm_allocator = {
4009 &vterm_malloc,
4010 &vterm_memfree
4011};
4012
4013/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004014 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004015 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004016 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004017 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004018create_vterm(term_T *term, int rows, int cols)
4019{
4020 VTerm *vterm;
4021 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004022 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004023 VTermValue value;
4024
Bram Moolenaar756ef112018-04-10 12:04:27 +02004025 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004026 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004027 if (vterm == NULL)
4028 return FAIL;
4029
4030 // Allocate screen and state here, so we can bail out if that fails.
4031 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004032 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004033 if (state == NULL || screen == NULL)
4034 {
4035 vterm_free(vterm);
4036 return FAIL;
4037 }
4038
Bram Moolenaar52acb112018-03-18 19:20:22 +01004039 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
4040 /* TODO: depends on 'encoding'. */
4041 vterm_set_utf8(vterm, 1);
4042
4043 init_default_colors(term);
4044
4045 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004046 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004047 &term->tl_default_color.fg,
4048 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004049
Bram Moolenaar9e587872019-05-13 20:27:23 +02004050 if (t_colors < 16)
4051 // Less than 16 colors: assume that bold means using a bright color for
4052 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004053 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4054
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004055 /* Required to initialize most things. */
4056 vterm_screen_reset(screen, 1 /* hard */);
4057
4058 /* Allow using alternate screen. */
4059 vterm_screen_enable_altscreen(screen, 1);
4060
4061 /* For unix do not use a blinking cursor. In an xterm this causes the
4062 * cursor to blink if it's blinking in the xterm.
4063 * For Windows we respect the system wide setting. */
Bram Moolenaar4f974752019-02-17 17:44:42 +01004064#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004065 if (GetCaretBlinkTime() == INFINITE)
4066 value.boolean = 0;
4067 else
4068 value.boolean = 1;
4069#else
4070 value.boolean = 0;
4071#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004072 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4073 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004074
4075 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004076}
4077
4078/*
4079 * Return the text to show for the buffer name and status.
4080 */
4081 char_u *
4082term_get_status_text(term_T *term)
4083{
4084 if (term->tl_status_text == NULL)
4085 {
4086 char_u *txt;
4087 size_t len;
4088
4089 if (term->tl_normal_mode)
4090 {
4091 if (term_job_running(term))
4092 txt = (char_u *)_("Terminal");
4093 else
4094 txt = (char_u *)_("Terminal-finished");
4095 }
4096 else if (term->tl_title != NULL)
4097 txt = term->tl_title;
4098 else if (term_none_open(term))
4099 txt = (char_u *)_("active");
4100 else if (term_job_running(term))
4101 txt = (char_u *)_("running");
4102 else
4103 txt = (char_u *)_("finished");
4104 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004105 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004106 if (term->tl_status_text != NULL)
4107 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4108 term->tl_buffer->b_fname, txt);
4109 }
4110 return term->tl_status_text;
4111}
4112
4113/*
4114 * Mark references in jobs of terminals.
4115 */
4116 int
4117set_ref_in_term(int copyID)
4118{
4119 int abort = FALSE;
4120 term_T *term;
4121 typval_T tv;
4122
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004123 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004124 if (term->tl_job != NULL)
4125 {
4126 tv.v_type = VAR_JOB;
4127 tv.vval.v_job = term->tl_job;
4128 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4129 }
4130 return abort;
4131}
4132
4133/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004134 * Cache "Terminal" highlight group colors.
4135 */
4136 void
4137set_terminal_default_colors(int cterm_fg, int cterm_bg)
4138{
4139 term_default_cterm_fg = cterm_fg - 1;
4140 term_default_cterm_bg = cterm_bg - 1;
4141}
4142
4143/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004144 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004145 * Returns NULL when the buffer is not for a terminal window and logs a message
4146 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004147 */
4148 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004149term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004150{
4151 buf_T *buf;
4152
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004153 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004154 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004155 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004156 --emsg_off;
4157 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004158 {
4159 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004160 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004161 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004162 return buf;
4163}
4164
Bram Moolenaard96ff162018-02-18 22:13:29 +01004165 static int
4166same_color(VTermColor *a, VTermColor *b)
4167{
4168 return a->red == b->red
4169 && a->green == b->green
4170 && a->blue == b->blue
4171 && a->ansi_index == b->ansi_index;
4172}
4173
4174 static void
4175dump_term_color(FILE *fd, VTermColor *color)
4176{
4177 fprintf(fd, "%02x%02x%02x%d",
4178 (int)color->red, (int)color->green, (int)color->blue,
4179 (int)color->ansi_index);
4180}
4181
4182/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004183 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004184 *
4185 * Each screen cell in full is:
4186 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4187 * {characters} is a space for an empty cell
4188 * For a double-width character "+" is changed to "*" and the next cell is
4189 * skipped.
4190 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4191 * when "&" use the same as the previous cell.
4192 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4193 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4194 * {color-idx} is a number from 0 to 255
4195 *
4196 * Screen cell with same width, attributes and color as the previous one:
4197 * |{characters}
4198 *
4199 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4200 *
4201 * Repeating the previous screen cell:
4202 * @{count}
4203 */
4204 void
4205f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4206{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004207 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004208 term_T *term;
4209 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004210 int max_height = 0;
4211 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004212 stat_T st;
4213 FILE *fd;
4214 VTermPos pos;
4215 VTermScreen *screen;
4216 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004217 VTermState *state;
4218 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004219
4220 if (check_restricted() || check_secure())
4221 return;
4222 if (buf == NULL)
4223 return;
4224 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004225 if (term->tl_vterm == NULL)
4226 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004227 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004228 return;
4229 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004230
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004231 if (argvars[2].v_type != VAR_UNKNOWN)
4232 {
4233 dict_T *d;
4234
4235 if (argvars[2].v_type != VAR_DICT)
4236 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004237 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004238 return;
4239 }
4240 d = argvars[2].vval.v_dict;
4241 if (d != NULL)
4242 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004243 max_height = dict_get_number(d, (char_u *)"rows");
4244 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004245 }
4246 }
4247
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004248 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004249 if (fname == NULL)
4250 return;
4251 if (mch_stat((char *)fname, &st) >= 0)
4252 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004253 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004254 return;
4255 }
4256
Bram Moolenaard96ff162018-02-18 22:13:29 +01004257 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4258 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004259 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004260 return;
4261 }
4262
4263 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4264
4265 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004266 state = vterm_obtain_state(term->tl_vterm);
4267 vterm_state_get_cursorpos(state, &cursor_pos);
4268
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004269 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4270 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004271 {
4272 int repeat = 0;
4273
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004274 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4275 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004276 {
4277 VTermScreenCell cell;
4278 int same_attr;
4279 int same_chars = TRUE;
4280 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004281 int is_cursor_pos = (pos.col == cursor_pos.col
4282 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004283
4284 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4285 vim_memset(&cell, 0, sizeof(cell));
4286
4287 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4288 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004289 int c = cell.chars[i];
4290 int pc = prev_cell.chars[i];
4291
4292 /* For the first character NUL is the same as space. */
4293 if (i == 0)
4294 {
4295 c = (c == NUL) ? ' ' : c;
4296 pc = (pc == NUL) ? ' ' : pc;
4297 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004298 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004299 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004300 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004301 break;
4302 }
4303 same_attr = vtermAttr2hl(cell.attrs)
4304 == vtermAttr2hl(prev_cell.attrs)
4305 && same_color(&cell.fg, &prev_cell.fg)
4306 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004307 if (same_chars && cell.width == prev_cell.width && same_attr
4308 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004309 {
4310 ++repeat;
4311 }
4312 else
4313 {
4314 if (repeat > 0)
4315 {
4316 fprintf(fd, "@%d", repeat);
4317 repeat = 0;
4318 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004319 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004320
4321 if (cell.chars[0] == NUL)
4322 fputs(" ", fd);
4323 else
4324 {
4325 char_u charbuf[10];
4326 int len;
4327
4328 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4329 && cell.chars[i] != NUL; ++i)
4330 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004331 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004332 fwrite(charbuf, len, 1, fd);
4333 }
4334 }
4335
4336 /* When only the characters differ we don't write anything, the
4337 * following "|", "@" or NL will indicate using the same
4338 * attributes. */
4339 if (cell.width != prev_cell.width || !same_attr)
4340 {
4341 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004342 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004343 else
4344 fputs("+", fd);
4345
4346 if (same_attr)
4347 {
4348 fputs("&", fd);
4349 }
4350 else
4351 {
4352 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4353 if (same_color(&cell.fg, &prev_cell.fg))
4354 fputs("&", fd);
4355 else
4356 {
4357 fputs("#", fd);
4358 dump_term_color(fd, &cell.fg);
4359 }
4360 if (same_color(&cell.bg, &prev_cell.bg))
4361 fputs("&", fd);
4362 else
4363 {
4364 fputs("#", fd);
4365 dump_term_color(fd, &cell.bg);
4366 }
4367 }
4368 }
4369
4370 prev_cell = cell;
4371 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004372
4373 if (cell.width == 2)
4374 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004375 }
4376 if (repeat > 0)
4377 fprintf(fd, "@%d", repeat);
4378 fputs("\n", fd);
4379 }
4380
4381 fclose(fd);
4382}
4383
4384/*
4385 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4386 */
4387 static void
4388dump_is_corrupt(garray_T *gap)
4389{
4390 ga_concat(gap, (char_u *)"CORRUPT");
4391}
4392
4393 static void
4394append_cell(garray_T *gap, cellattr_T *cell)
4395{
4396 if (ga_grow(gap, 1) == OK)
4397 {
4398 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4399 ++gap->ga_len;
4400 }
4401}
4402
4403/*
4404 * Read the dump file from "fd" and append lines to the current buffer.
4405 * Return the cell width of the longest line.
4406 */
4407 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004408read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004409{
4410 int c;
4411 garray_T ga_text;
4412 garray_T ga_cell;
4413 char_u *prev_char = NULL;
4414 int attr = 0;
4415 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004416 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004417 term_T *term = curbuf->b_term;
4418 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004419 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004420
4421 ga_init2(&ga_text, 1, 90);
4422 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4423 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004424 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004425 cursor_pos->row = -1;
4426 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004427
4428 c = fgetc(fd);
4429 for (;;)
4430 {
4431 if (c == EOF)
4432 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004433 if (c == '\r')
4434 {
4435 // DOS line endings? Ignore.
4436 c = fgetc(fd);
4437 }
4438 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004439 {
4440 /* End of a line: append it to the buffer. */
4441 if (ga_text.ga_data == NULL)
4442 dump_is_corrupt(&ga_text);
4443 if (ga_grow(&term->tl_scrollback, 1) == OK)
4444 {
4445 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4446 + term->tl_scrollback.ga_len;
4447
4448 if (max_cells < ga_cell.ga_len)
4449 max_cells = ga_cell.ga_len;
4450 line->sb_cols = ga_cell.ga_len;
4451 line->sb_cells = ga_cell.ga_data;
4452 line->sb_fill_attr = term->tl_default_color;
4453 ++term->tl_scrollback.ga_len;
4454 ga_init(&ga_cell);
4455
4456 ga_append(&ga_text, NUL);
4457 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4458 ga_text.ga_len, FALSE);
4459 }
4460 else
4461 ga_clear(&ga_cell);
4462 ga_text.ga_len = 0;
4463
4464 c = fgetc(fd);
4465 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004466 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004467 {
4468 int prev_len = ga_text.ga_len;
4469
Bram Moolenaar9271d052018-02-25 21:39:46 +01004470 if (c == '>')
4471 {
4472 if (cursor_pos->row != -1)
4473 dump_is_corrupt(&ga_text); /* duplicate cursor */
4474 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4475 cursor_pos->col = ga_cell.ga_len;
4476 }
4477
Bram Moolenaard96ff162018-02-18 22:13:29 +01004478 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4479 c = fgetc(fd);
4480 if (c != EOF)
4481 ga_append(&ga_text, c);
4482 for (;;)
4483 {
4484 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004485 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004486 || c == EOF || c == '\n')
4487 break;
4488 ga_append(&ga_text, c);
4489 }
4490
4491 /* save the character for repeating it */
4492 vim_free(prev_char);
4493 if (ga_text.ga_data != NULL)
4494 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4495 ga_text.ga_len - prev_len);
4496
Bram Moolenaar9271d052018-02-25 21:39:46 +01004497 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004498 {
4499 /* use all attributes from previous cell */
4500 }
4501 else if (c == '+' || c == '*')
4502 {
4503 int is_bg;
4504
4505 cell.width = c == '+' ? 1 : 2;
4506
4507 c = fgetc(fd);
4508 if (c == '&')
4509 {
4510 /* use same attr as previous cell */
4511 c = fgetc(fd);
4512 }
4513 else if (isdigit(c))
4514 {
4515 /* get the decimal attribute */
4516 attr = 0;
4517 while (isdigit(c))
4518 {
4519 attr = attr * 10 + (c - '0');
4520 c = fgetc(fd);
4521 }
4522 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004523
4524 /* is_bg == 0: fg, is_bg == 1: bg */
4525 for (is_bg = 0; is_bg <= 1; ++is_bg)
4526 {
4527 if (c == '&')
4528 {
4529 /* use same color as previous cell */
4530 c = fgetc(fd);
4531 }
4532 else if (c == '#')
4533 {
4534 int red, green, blue, index = 0;
4535
4536 c = fgetc(fd);
4537 red = hex2nr(c);
4538 c = fgetc(fd);
4539 red = (red << 4) + hex2nr(c);
4540 c = fgetc(fd);
4541 green = hex2nr(c);
4542 c = fgetc(fd);
4543 green = (green << 4) + hex2nr(c);
4544 c = fgetc(fd);
4545 blue = hex2nr(c);
4546 c = fgetc(fd);
4547 blue = (blue << 4) + hex2nr(c);
4548 c = fgetc(fd);
4549 if (!isdigit(c))
4550 dump_is_corrupt(&ga_text);
4551 while (isdigit(c))
4552 {
4553 index = index * 10 + (c - '0');
4554 c = fgetc(fd);
4555 }
4556
4557 if (is_bg)
4558 {
4559 cell.bg.red = red;
4560 cell.bg.green = green;
4561 cell.bg.blue = blue;
4562 cell.bg.ansi_index = index;
4563 }
4564 else
4565 {
4566 cell.fg.red = red;
4567 cell.fg.green = green;
4568 cell.fg.blue = blue;
4569 cell.fg.ansi_index = index;
4570 }
4571 }
4572 else
4573 dump_is_corrupt(&ga_text);
4574 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004575 }
4576 else
4577 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004578 }
4579 else
4580 dump_is_corrupt(&ga_text);
4581
4582 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004583 if (cell.width == 2)
4584 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004585 }
4586 else if (c == '@')
4587 {
4588 if (prev_char == NULL)
4589 dump_is_corrupt(&ga_text);
4590 else
4591 {
4592 int count = 0;
4593
4594 /* repeat previous character, get the count */
4595 for (;;)
4596 {
4597 c = fgetc(fd);
4598 if (!isdigit(c))
4599 break;
4600 count = count * 10 + (c - '0');
4601 }
4602
4603 while (count-- > 0)
4604 {
4605 ga_concat(&ga_text, prev_char);
4606 append_cell(&ga_cell, &cell);
4607 }
4608 }
4609 }
4610 else
4611 {
4612 dump_is_corrupt(&ga_text);
4613 c = fgetc(fd);
4614 }
4615 }
4616
4617 if (ga_text.ga_len > 0)
4618 {
4619 /* trailing characters after last NL */
4620 dump_is_corrupt(&ga_text);
4621 ga_append(&ga_text, NUL);
4622 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4623 ga_text.ga_len, FALSE);
4624 }
4625
4626 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004627 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004628 vim_free(prev_char);
4629
4630 return max_cells;
4631}
4632
4633/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004634 * Return an allocated string with at least "text_width" "=" characters and
4635 * "fname" inserted in the middle.
4636 */
4637 static char_u *
4638get_separator(int text_width, char_u *fname)
4639{
4640 int width = MAX(text_width, curwin->w_width);
4641 char_u *textline;
4642 int fname_size;
4643 char_u *p = fname;
4644 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004645 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004646
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004647 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004648 if (textline == NULL)
4649 return NULL;
4650
4651 fname_size = vim_strsize(fname);
4652 if (fname_size < width - 8)
4653 {
4654 /* enough room, don't use the full window width */
4655 width = MAX(text_width, fname_size + 8);
4656 }
4657 else if (fname_size > width - 8)
4658 {
4659 /* full name doesn't fit, use only the tail */
4660 p = gettail(fname);
4661 fname_size = vim_strsize(p);
4662 }
4663 /* skip characters until the name fits */
4664 while (fname_size > width - 8)
4665 {
4666 p += (*mb_ptr2len)(p);
4667 fname_size = vim_strsize(p);
4668 }
4669
4670 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4671 textline[i] = '=';
4672 textline[i++] = ' ';
4673
4674 STRCPY(textline + i, p);
4675 off = STRLEN(textline);
4676 textline[off] = ' ';
4677 for (i = 1; i < (width - fname_size) / 2; ++i)
4678 textline[off + i] = '=';
4679 textline[off + i] = NUL;
4680
4681 return textline;
4682}
4683
4684/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004685 * Common for "term_dumpdiff()" and "term_dumpload()".
4686 */
4687 static void
4688term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4689{
4690 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004691 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004692 char_u buf1[NUMBUFLEN];
4693 char_u buf2[NUMBUFLEN];
4694 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004695 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004696 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004697 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004698 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004699 char_u *textline = NULL;
4700
4701 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004702 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004703 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004704 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004705 if (fname1 == NULL || (do_diff && fname2 == NULL))
4706 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004707 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004708 return;
4709 }
4710 fd1 = mch_fopen((char *)fname1, READBIN);
4711 if (fd1 == NULL)
4712 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004713 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004714 return;
4715 }
4716 if (do_diff)
4717 {
4718 fd2 = mch_fopen((char *)fname2, READBIN);
4719 if (fd2 == NULL)
4720 {
4721 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004722 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004723 return;
4724 }
4725 }
4726
4727 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004728 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4729 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4730 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4731 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4732 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004733
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004734 if (opt.jo_term_name == NULL)
4735 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004736 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004737
Bram Moolenaar51e14382019-05-25 20:21:28 +02004738 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004739 if (fname_tofree != NULL)
4740 {
4741 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4742 opt.jo_term_name = fname_tofree;
4743 }
4744 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004745
Bram Moolenaar87abab92019-06-03 21:14:59 +02004746 if (opt.jo_bufnr_buf != NULL)
4747 {
4748 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4749
4750 // With "bufnr" argument: enter the window with this buffer and make it
4751 // empty.
4752 if (wp == NULL)
4753 semsg(_(e_invarg2), "bufnr");
4754 else
4755 {
4756 buf = curbuf;
4757 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4758 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02004759 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02004760 redraw_later(NOT_VALID);
4761 }
4762 }
4763 else
4764 // Create a new terminal window.
4765 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4766
Bram Moolenaard96ff162018-02-18 22:13:29 +01004767 if (buf != NULL && buf->b_term != NULL)
4768 {
4769 int i;
4770 linenr_T bot_lnum;
4771 linenr_T lnum;
4772 term_T *term = buf->b_term;
4773 int width;
4774 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004775 VTermPos cursor_pos1;
4776 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004777
Bram Moolenaar52acb112018-03-18 19:20:22 +01004778 init_default_colors(term);
4779
Bram Moolenaard96ff162018-02-18 22:13:29 +01004780 rettv->vval.v_number = buf->b_fnum;
4781
4782 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004783 width = read_dump_file(fd1, &cursor_pos1);
4784
4785 /* position the cursor */
4786 if (cursor_pos1.row >= 0)
4787 {
4788 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4789 coladvance(cursor_pos1.col);
4790 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004791
4792 /* Delete the empty line that was in the empty buffer. */
4793 ml_delete(1, FALSE);
4794
4795 /* For term_dumpload() we are done here. */
4796 if (!do_diff)
4797 goto theend;
4798
4799 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4800
Bram Moolenaar4a696342018-04-05 18:45:26 +02004801 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004802 if (textline == NULL)
4803 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004804 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4805 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4806 vim_free(textline);
4807
4808 textline = get_separator(width, fname2);
4809 if (textline == NULL)
4810 goto theend;
4811 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4812 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004813 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004814
4815 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004816 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004817 if (width2 > width)
4818 {
4819 vim_free(textline);
4820 textline = alloc(width2 + 1);
4821 if (textline == NULL)
4822 goto theend;
4823 width = width2;
4824 textline[width] = NUL;
4825 }
4826 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4827
4828 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4829 {
4830 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4831 {
4832 /* bottom part has fewer rows, fill with "-" */
4833 for (i = 0; i < width; ++i)
4834 textline[i] = '-';
4835 }
4836 else
4837 {
4838 char_u *line1;
4839 char_u *line2;
4840 char_u *p1;
4841 char_u *p2;
4842 int col;
4843 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4844 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4845 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4846 ->sb_cells;
4847
4848 /* Make a copy, getting the second line will invalidate it. */
4849 line1 = vim_strsave(ml_get(lnum));
4850 if (line1 == NULL)
4851 break;
4852 p1 = line1;
4853
4854 line2 = ml_get(lnum + bot_lnum);
4855 p2 = line2;
4856 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4857 {
4858 int len1 = utfc_ptr2len(p1);
4859 int len2 = utfc_ptr2len(p2);
4860
4861 textline[col] = ' ';
4862 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004863 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004864 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004865 else if (lnum == cursor_pos1.row + 1
4866 && col == cursor_pos1.col
4867 && (cursor_pos1.row != cursor_pos2.row
4868 || cursor_pos1.col != cursor_pos2.col))
4869 /* cursor in first but not in second */
4870 textline[col] = '>';
4871 else if (lnum == cursor_pos2.row + 1
4872 && col == cursor_pos2.col
4873 && (cursor_pos1.row != cursor_pos2.row
4874 || cursor_pos1.col != cursor_pos2.col))
4875 /* cursor in second but not in first */
4876 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004877 else if (cellattr1 != NULL && cellattr2 != NULL)
4878 {
4879 if ((cellattr1 + col)->width
4880 != (cellattr2 + col)->width)
4881 textline[col] = 'w';
4882 else if (!same_color(&(cellattr1 + col)->fg,
4883 &(cellattr2 + col)->fg))
4884 textline[col] = 'f';
4885 else if (!same_color(&(cellattr1 + col)->bg,
4886 &(cellattr2 + col)->bg))
4887 textline[col] = 'b';
4888 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4889 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4890 textline[col] = 'a';
4891 }
4892 p1 += len1;
4893 p2 += len2;
4894 /* TODO: handle different width */
4895 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004896
4897 while (col < width)
4898 {
4899 if (*p1 == NUL && *p2 == NUL)
4900 textline[col] = '?';
4901 else if (*p1 == NUL)
4902 {
4903 textline[col] = '+';
4904 p2 += utfc_ptr2len(p2);
4905 }
4906 else
4907 {
4908 textline[col] = '-';
4909 p1 += utfc_ptr2len(p1);
4910 }
4911 ++col;
4912 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004913
4914 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004915 }
4916 if (add_empty_scrollback(term, &term->tl_default_color,
4917 term->tl_top_diff_rows) == OK)
4918 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4919 ++bot_lnum;
4920 }
4921
4922 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4923 {
4924 /* bottom part has more rows, fill with "+" */
4925 for (i = 0; i < width; ++i)
4926 textline[i] = '+';
4927 if (add_empty_scrollback(term, &term->tl_default_color,
4928 term->tl_top_diff_rows) == OK)
4929 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4930 ++lnum;
4931 ++bot_lnum;
4932 }
4933
4934 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004935
4936 /* looks better without wrapping */
4937 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004938 }
4939
4940theend:
4941 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004942 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004943 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004944 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004945 fclose(fd2);
4946}
4947
4948/*
4949 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4950 * bottom files.
4951 * Return FAIL when this is not possible.
4952 */
4953 int
4954term_swap_diff()
4955{
4956 term_T *term = curbuf->b_term;
4957 linenr_T line_count;
4958 linenr_T top_rows;
4959 linenr_T bot_rows;
4960 linenr_T bot_start;
4961 linenr_T lnum;
4962 char_u *p;
4963 sb_line_T *sb_line;
4964
4965 if (term == NULL
4966 || !term_is_finished(curbuf)
4967 || term->tl_top_diff_rows == 0
4968 || term->tl_scrollback.ga_len == 0)
4969 return FAIL;
4970
4971 line_count = curbuf->b_ml.ml_line_count;
4972 top_rows = term->tl_top_diff_rows;
4973 bot_rows = term->tl_bot_diff_rows;
4974 bot_start = line_count - bot_rows;
4975 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4976
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004977 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01004978 for (lnum = 1; lnum <= top_rows; ++lnum)
4979 {
4980 p = vim_strsave(ml_get(1));
4981 if (p == NULL)
4982 return OK;
4983 ml_append(bot_start, p, 0, FALSE);
4984 ml_delete(1, FALSE);
4985 vim_free(p);
4986 }
4987
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004988 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01004989 for (lnum = 1; lnum <= bot_rows; ++lnum)
4990 {
4991 p = vim_strsave(ml_get(bot_start + lnum));
4992 if (p == NULL)
4993 return OK;
4994 ml_delete(bot_start + lnum, FALSE);
4995 ml_append(lnum - 1, p, 0, FALSE);
4996 vim_free(p);
4997 }
4998
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004999 // move top title to bottom
5000 p = vim_strsave(ml_get(bot_rows + 1));
5001 if (p == NULL)
5002 return OK;
5003 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5004 ml_delete(bot_rows + 1, FALSE);
5005 vim_free(p);
5006
5007 // move bottom title to top
5008 p = vim_strsave(ml_get(line_count - top_rows));
5009 if (p == NULL)
5010 return OK;
5011 ml_delete(line_count - top_rows, FALSE);
5012 ml_append(bot_rows, p, 0, FALSE);
5013 vim_free(p);
5014
Bram Moolenaard96ff162018-02-18 22:13:29 +01005015 if (top_rows == bot_rows)
5016 {
5017 /* rows counts are equal, can swap cell properties */
5018 for (lnum = 0; lnum < top_rows; ++lnum)
5019 {
5020 sb_line_T temp;
5021
5022 temp = *(sb_line + lnum);
5023 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5024 *(sb_line + bot_start + lnum) = temp;
5025 }
5026 }
5027 else
5028 {
5029 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005030 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005031
5032 /* need to copy cell properties into temp memory */
5033 if (temp != NULL)
5034 {
5035 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5036 mch_memmove(term->tl_scrollback.ga_data,
5037 temp + bot_start,
5038 sizeof(sb_line_T) * bot_rows);
5039 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5040 temp + top_rows,
5041 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5042 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5043 + line_count - top_rows,
5044 temp,
5045 sizeof(sb_line_T) * top_rows);
5046 vim_free(temp);
5047 }
5048 }
5049
5050 term->tl_top_diff_rows = bot_rows;
5051 term->tl_bot_diff_rows = top_rows;
5052
5053 update_screen(NOT_VALID);
5054 return OK;
5055}
5056
5057/*
5058 * "term_dumpdiff(filename, filename, options)" function
5059 */
5060 void
5061f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5062{
5063 term_load_dump(argvars, rettv, TRUE);
5064}
5065
5066/*
5067 * "term_dumpload(filename, options)" function
5068 */
5069 void
5070f_term_dumpload(typval_T *argvars, typval_T *rettv)
5071{
5072 term_load_dump(argvars, rettv, FALSE);
5073}
5074
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005075/*
5076 * "term_getaltscreen(buf)" function
5077 */
5078 void
5079f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5080{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005081 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005082
5083 if (buf == NULL)
5084 return;
5085 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5086}
5087
5088/*
5089 * "term_getattr(attr, name)" function
5090 */
5091 void
5092f_term_getattr(typval_T *argvars, typval_T *rettv)
5093{
5094 int attr;
5095 size_t i;
5096 char_u *name;
5097
5098 static struct {
5099 char *name;
5100 int attr;
5101 } attrs[] = {
5102 {"bold", HL_BOLD},
5103 {"italic", HL_ITALIC},
5104 {"underline", HL_UNDERLINE},
5105 {"strike", HL_STRIKETHROUGH},
5106 {"reverse", HL_INVERSE},
5107 };
5108
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005109 attr = tv_get_number(&argvars[0]);
5110 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005111 if (name == NULL)
5112 return;
5113
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005114 if (attr > HL_ALL)
5115 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005116 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5117 if (STRCMP(name, attrs[i].name) == 0)
5118 {
5119 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5120 break;
5121 }
5122}
5123
5124/*
5125 * "term_getcursor(buf)" function
5126 */
5127 void
5128f_term_getcursor(typval_T *argvars, typval_T *rettv)
5129{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005130 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005131 term_T *term;
5132 list_T *l;
5133 dict_T *d;
5134
5135 if (rettv_list_alloc(rettv) == FAIL)
5136 return;
5137 if (buf == NULL)
5138 return;
5139 term = buf->b_term;
5140
5141 l = rettv->vval.v_list;
5142 list_append_number(l, term->tl_cursor_pos.row + 1);
5143 list_append_number(l, term->tl_cursor_pos.col + 1);
5144
5145 d = dict_alloc();
5146 if (d != NULL)
5147 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005148 dict_add_number(d, "visible", term->tl_cursor_visible);
5149 dict_add_number(d, "blink", blink_state_is_inverted()
5150 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5151 dict_add_number(d, "shape", term->tl_cursor_shape);
5152 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005153 list_append_dict(l, d);
5154 }
5155}
5156
5157/*
5158 * "term_getjob(buf)" function
5159 */
5160 void
5161f_term_getjob(typval_T *argvars, typval_T *rettv)
5162{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005163 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005164
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005165 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005166 {
5167 rettv->v_type = VAR_SPECIAL;
5168 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005169 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005170 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005171
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005172 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005173 rettv->vval.v_job = buf->b_term->tl_job;
5174 if (rettv->vval.v_job != NULL)
5175 ++rettv->vval.v_job->jv_refcount;
5176}
5177
5178 static int
5179get_row_number(typval_T *tv, term_T *term)
5180{
5181 if (tv->v_type == VAR_STRING
5182 && tv->vval.v_string != NULL
5183 && STRCMP(tv->vval.v_string, ".") == 0)
5184 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005185 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005186}
5187
5188/*
5189 * "term_getline(buf, row)" function
5190 */
5191 void
5192f_term_getline(typval_T *argvars, typval_T *rettv)
5193{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005194 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005195 term_T *term;
5196 int row;
5197
5198 rettv->v_type = VAR_STRING;
5199 if (buf == NULL)
5200 return;
5201 term = buf->b_term;
5202 row = get_row_number(&argvars[1], term);
5203
5204 if (term->tl_vterm == NULL)
5205 {
5206 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5207
5208 /* vterm is finished, get the text from the buffer */
5209 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5210 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5211 }
5212 else
5213 {
5214 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5215 VTermRect rect;
5216 int len;
5217 char_u *p;
5218
5219 if (row < 0 || row >= term->tl_rows)
5220 return;
5221 len = term->tl_cols * MB_MAXBYTES + 1;
5222 p = alloc(len);
5223 if (p == NULL)
5224 return;
5225 rettv->vval.v_string = p;
5226
5227 rect.start_col = 0;
5228 rect.end_col = term->tl_cols;
5229 rect.start_row = row;
5230 rect.end_row = row + 1;
5231 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5232 }
5233}
5234
5235/*
5236 * "term_getscrolled(buf)" function
5237 */
5238 void
5239f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5240{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005241 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005242
5243 if (buf == NULL)
5244 return;
5245 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5246}
5247
5248/*
5249 * "term_getsize(buf)" function
5250 */
5251 void
5252f_term_getsize(typval_T *argvars, typval_T *rettv)
5253{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005254 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005255 list_T *l;
5256
5257 if (rettv_list_alloc(rettv) == FAIL)
5258 return;
5259 if (buf == NULL)
5260 return;
5261
5262 l = rettv->vval.v_list;
5263 list_append_number(l, buf->b_term->tl_rows);
5264 list_append_number(l, buf->b_term->tl_cols);
5265}
5266
5267/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005268 * "term_setsize(buf, rows, cols)" function
5269 */
5270 void
5271f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5272{
5273 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5274 term_T *term;
5275 varnumber_T rows, cols;
5276
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005277 if (buf == NULL)
5278 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005279 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005280 return;
5281 }
5282 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005283 return;
5284 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005285 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005286 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005287 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005288 cols = cols <= 0 ? term->tl_cols : cols;
5289 vterm_set_size(term->tl_vterm, rows, cols);
5290 /* handle_resize() will resize the windows */
5291
5292 /* Get and remember the size we ended up with. Update the pty. */
5293 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5294 term_report_winsize(term, term->tl_rows, term->tl_cols);
5295}
5296
5297/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005298 * "term_getstatus(buf)" function
5299 */
5300 void
5301f_term_getstatus(typval_T *argvars, typval_T *rettv)
5302{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005303 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005304 term_T *term;
5305 char_u val[100];
5306
5307 rettv->v_type = VAR_STRING;
5308 if (buf == NULL)
5309 return;
5310 term = buf->b_term;
5311
5312 if (term_job_running(term))
5313 STRCPY(val, "running");
5314 else
5315 STRCPY(val, "finished");
5316 if (term->tl_normal_mode)
5317 STRCAT(val, ",normal");
5318 rettv->vval.v_string = vim_strsave(val);
5319}
5320
5321/*
5322 * "term_gettitle(buf)" function
5323 */
5324 void
5325f_term_gettitle(typval_T *argvars, typval_T *rettv)
5326{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005327 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005328
5329 rettv->v_type = VAR_STRING;
5330 if (buf == NULL)
5331 return;
5332
5333 if (buf->b_term->tl_title != NULL)
5334 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5335}
5336
5337/*
5338 * "term_gettty(buf)" function
5339 */
5340 void
5341f_term_gettty(typval_T *argvars, typval_T *rettv)
5342{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005343 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005344 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005345 int num = 0;
5346
5347 rettv->v_type = VAR_STRING;
5348 if (buf == NULL)
5349 return;
5350 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005351 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005352
5353 switch (num)
5354 {
5355 case 0:
5356 if (buf->b_term->tl_job != NULL)
5357 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005358 break;
5359 case 1:
5360 if (buf->b_term->tl_job != NULL)
5361 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005362 break;
5363 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005364 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005365 return;
5366 }
5367 if (p != NULL)
5368 rettv->vval.v_string = vim_strsave(p);
5369}
5370
5371/*
5372 * "term_list()" function
5373 */
5374 void
5375f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5376{
5377 term_T *tp;
5378 list_T *l;
5379
5380 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5381 return;
5382
5383 l = rettv->vval.v_list;
5384 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5385 if (tp != NULL && tp->tl_buffer != NULL)
5386 if (list_append_number(l,
5387 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5388 return;
5389}
5390
5391/*
5392 * "term_scrape(buf, row)" function
5393 */
5394 void
5395f_term_scrape(typval_T *argvars, typval_T *rettv)
5396{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005397 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005398 VTermScreen *screen = NULL;
5399 VTermPos pos;
5400 list_T *l;
5401 term_T *term;
5402 char_u *p;
5403 sb_line_T *line;
5404
5405 if (rettv_list_alloc(rettv) == FAIL)
5406 return;
5407 if (buf == NULL)
5408 return;
5409 term = buf->b_term;
5410
5411 l = rettv->vval.v_list;
5412 pos.row = get_row_number(&argvars[1], term);
5413
5414 if (term->tl_vterm != NULL)
5415 {
5416 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005417 if (screen == NULL) // can't really happen
5418 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005419 p = NULL;
5420 line = NULL;
5421 }
5422 else
5423 {
5424 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5425
5426 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5427 return;
5428 p = ml_get_buf(buf, lnum + 1, FALSE);
5429 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5430 }
5431
5432 for (pos.col = 0; pos.col < term->tl_cols; )
5433 {
5434 dict_T *dcell;
5435 int width;
5436 VTermScreenCellAttrs attrs;
5437 VTermColor fg, bg;
5438 char_u rgb[8];
5439 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5440 int off = 0;
5441 int i;
5442
5443 if (screen == NULL)
5444 {
5445 cellattr_T *cellattr;
5446 int len;
5447
5448 /* vterm has finished, get the cell from scrollback */
5449 if (pos.col >= line->sb_cols)
5450 break;
5451 cellattr = line->sb_cells + pos.col;
5452 width = cellattr->width;
5453 attrs = cellattr->attrs;
5454 fg = cellattr->fg;
5455 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005456 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005457 mch_memmove(mbs, p, len);
5458 mbs[len] = NUL;
5459 p += len;
5460 }
5461 else
5462 {
5463 VTermScreenCell cell;
5464 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5465 break;
5466 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5467 {
5468 if (cell.chars[i] == 0)
5469 break;
5470 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5471 }
5472 mbs[off] = NUL;
5473 width = cell.width;
5474 attrs = cell.attrs;
5475 fg = cell.fg;
5476 bg = cell.bg;
5477 }
5478 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005479 if (dcell == NULL)
5480 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005481 list_append_dict(l, dcell);
5482
Bram Moolenaare0be1672018-07-08 16:50:37 +02005483 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005484
5485 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5486 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005487 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005488 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5489 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005490 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005491
Bram Moolenaare0be1672018-07-08 16:50:37 +02005492 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5493 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005494
5495 ++pos.col;
5496 if (width == 2)
5497 ++pos.col;
5498 }
5499}
5500
5501/*
5502 * "term_sendkeys(buf, keys)" function
5503 */
5504 void
5505f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5506{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005507 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005508 char_u *msg;
5509 term_T *term;
5510
5511 rettv->v_type = VAR_UNKNOWN;
5512 if (buf == NULL)
5513 return;
5514
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005515 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005516 if (msg == NULL)
5517 return;
5518 term = buf->b_term;
5519 if (term->tl_vterm == NULL)
5520 return;
5521
5522 while (*msg != NUL)
5523 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005524 int c;
5525
5526 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5527 {
5528 c = TO_SPECIAL(msg[1], msg[2]);
5529 msg += 3;
5530 }
5531 else
5532 {
5533 c = PTR2CHAR(msg);
5534 msg += MB_CPTR2LEN(msg);
5535 }
5536 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005537 }
5538}
5539
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005540#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5541/*
5542 * "term_getansicolors(buf)" function
5543 */
5544 void
5545f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5546{
5547 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5548 term_T *term;
5549 VTermState *state;
5550 VTermColor color;
5551 char_u hexbuf[10];
5552 int index;
5553 list_T *list;
5554
5555 if (rettv_list_alloc(rettv) == FAIL)
5556 return;
5557
5558 if (buf == NULL)
5559 return;
5560 term = buf->b_term;
5561 if (term->tl_vterm == NULL)
5562 return;
5563
5564 list = rettv->vval.v_list;
5565 state = vterm_obtain_state(term->tl_vterm);
5566 for (index = 0; index < 16; index++)
5567 {
5568 vterm_state_get_palette_color(state, index, &color);
5569 sprintf((char *)hexbuf, "#%02x%02x%02x",
5570 color.red, color.green, color.blue);
5571 if (list_append_string(list, hexbuf, 7) == FAIL)
5572 return;
5573 }
5574}
5575
5576/*
5577 * "term_setansicolors(buf, list)" function
5578 */
5579 void
5580f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5581{
5582 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5583 term_T *term;
5584
5585 if (buf == NULL)
5586 return;
5587 term = buf->b_term;
5588 if (term->tl_vterm == NULL)
5589 return;
5590
5591 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5592 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005593 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005594 return;
5595 }
5596
5597 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005598 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005599}
5600#endif
5601
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005602/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005603 * "term_setapi(buf, api)" function
5604 */
5605 void
5606f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5607{
5608 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5609 term_T *term;
5610 char_u *api;
5611
5612 if (buf == NULL)
5613 return;
5614 term = buf->b_term;
5615 vim_free(term->tl_api);
5616 api = tv_get_string_chk(&argvars[1]);
5617 if (api != NULL)
5618 term->tl_api = vim_strsave(api);
5619 else
5620 term->tl_api = NULL;
5621}
5622
5623/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005624 * "term_setrestore(buf, command)" function
5625 */
5626 void
5627f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5628{
5629#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005630 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005631 term_T *term;
5632 char_u *cmd;
5633
5634 if (buf == NULL)
5635 return;
5636 term = buf->b_term;
5637 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005638 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005639 if (cmd != NULL)
5640 term->tl_command = vim_strsave(cmd);
5641 else
5642 term->tl_command = NULL;
5643#endif
5644}
5645
5646/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005647 * "term_setkill(buf, how)" function
5648 */
5649 void
5650f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5651{
5652 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5653 term_T *term;
5654 char_u *how;
5655
5656 if (buf == NULL)
5657 return;
5658 term = buf->b_term;
5659 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005660 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005661 if (how != NULL)
5662 term->tl_kill = vim_strsave(how);
5663 else
5664 term->tl_kill = NULL;
5665}
5666
5667/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005668 * "term_start(command, options)" function
5669 */
5670 void
5671f_term_start(typval_T *argvars, typval_T *rettv)
5672{
5673 jobopt_T opt;
5674 buf_T *buf;
5675
5676 init_job_options(&opt);
5677 if (argvars[1].v_type != VAR_UNKNOWN
5678 && get_job_options(&argvars[1], &opt,
5679 JO_TIMEOUT_ALL + JO_STOPONEXIT
5680 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5681 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5682 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5683 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005684 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005685 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005686 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005687 return;
5688
Bram Moolenaar13568252018-03-16 20:46:58 +01005689 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005690
5691 if (buf != NULL && buf->b_term != NULL)
5692 rettv->vval.v_number = buf->b_fnum;
5693}
5694
5695/*
5696 * "term_wait" function
5697 */
5698 void
5699f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5700{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005701 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005702
5703 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005704 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005705 if (buf->b_term->tl_job == NULL)
5706 {
5707 ch_log(NULL, "term_wait(): no job to wait for");
5708 return;
5709 }
5710 if (buf->b_term->tl_job->jv_channel == NULL)
5711 /* channel is closed, nothing to do */
5712 return;
5713
5714 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005715 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005716 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5717 {
5718 /* The job is dead, keep reading channel I/O until the channel is
5719 * closed. buf->b_term may become NULL if the terminal was closed while
5720 * waiting. */
5721 ch_log(NULL, "term_wait(): waiting for channel to close");
5722 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5723 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005724 term_flush_messages();
5725
Bram Moolenaard45aa552018-05-21 22:50:29 +02005726 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005727 if (!buf_valid(buf))
5728 /* If the terminal is closed when the channel is closed the
5729 * buffer disappears. */
5730 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005731 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005732
5733 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005734 }
5735 else
5736 {
5737 long wait = 10L;
5738
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005739 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005740
5741 /* Wait for some time for any channel I/O. */
5742 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005743 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005744 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005745
5746 /* Flushing messages on channels is hopefully sufficient.
5747 * TODO: is there a better way? */
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005748 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005749 }
5750}
5751
5752/*
5753 * Called when a channel has sent all the lines to a terminal.
5754 * Send a CTRL-D to mark the end of the text.
5755 */
5756 void
5757term_send_eof(channel_T *ch)
5758{
5759 term_T *term;
5760
5761 for (term = first_term; term != NULL; term = term->tl_next)
5762 if (term->tl_job == ch->ch_job)
5763 {
5764 if (term->tl_eof_chars != NULL)
5765 {
5766 channel_send(ch, PART_IN, term->tl_eof_chars,
5767 (int)STRLEN(term->tl_eof_chars), NULL);
5768 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5769 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005770# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005771 else
5772 /* Default: CTRL-D */
5773 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5774# endif
5775 }
5776}
5777
Bram Moolenaar113e1072019-01-20 15:30:40 +01005778#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005779 job_T *
5780term_getjob(term_T *term)
5781{
5782 return term != NULL ? term->tl_job : NULL;
5783}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005784#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005785
Bram Moolenaar4f974752019-02-17 17:44:42 +01005786# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005787
5788/**************************************
5789 * 2. MS-Windows implementation.
5790 */
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005791#ifdef PROTO
5792typedef int COORD;
5793typedef int DWORD;
5794typedef int HANDLE;
5795typedef int *DWORD_PTR;
5796typedef int HPCON;
5797typedef int HRESULT;
5798typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005799typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005800typedef int PSIZE_T;
5801typedef int PVOID;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005802typedef int WINAPI;
5803#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005804
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005805HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5806HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5807HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005808BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5809BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5810void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005811
5812 static int
5813dyn_conpty_init(int verbose)
5814{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005815 static HMODULE hKerneldll = NULL;
5816 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005817 static struct
5818 {
5819 char *name;
5820 FARPROC *ptr;
5821 } conpty_entry[] =
5822 {
5823 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5824 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5825 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5826 {"InitializeProcThreadAttributeList",
5827 (FARPROC*)&pInitializeProcThreadAttributeList},
5828 {"UpdateProcThreadAttribute",
5829 (FARPROC*)&pUpdateProcThreadAttribute},
5830 {"DeleteProcThreadAttributeList",
5831 (FARPROC*)&pDeleteProcThreadAttributeList},
5832 {NULL, NULL}
5833 };
5834
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005835 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005836 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005837 if (verbose)
5838 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005839 return FAIL;
5840 }
5841
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005842 // No need to initialize twice.
5843 if (hKerneldll)
5844 return OK;
5845
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005846 hKerneldll = vimLoadLib("kernel32.dll");
5847 for (i = 0; conpty_entry[i].name != NULL
5848 && conpty_entry[i].ptr != NULL; ++i)
5849 {
5850 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5851 conpty_entry[i].name)) == NULL)
5852 {
5853 if (verbose)
5854 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005855 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005856 return FAIL;
5857 }
5858 }
5859
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005860 return OK;
5861}
5862
5863 static int
5864conpty_term_and_job_init(
5865 term_T *term,
5866 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005867 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005868 jobopt_T *opt,
5869 jobopt_T *orig_opt)
5870{
5871 WCHAR *cmd_wchar = NULL;
5872 WCHAR *cmd_wchar_copy = NULL;
5873 WCHAR *cwd_wchar = NULL;
5874 WCHAR *env_wchar = NULL;
5875 channel_T *channel = NULL;
5876 job_T *job = NULL;
5877 HANDLE jo = NULL;
5878 garray_T ga_cmd, ga_env;
5879 char_u *cmd = NULL;
5880 HRESULT hr;
5881 COORD consize;
5882 SIZE_T breq;
5883 PROCESS_INFORMATION proc_info;
5884 HANDLE i_theirs = NULL;
5885 HANDLE o_theirs = NULL;
5886 HANDLE i_ours = NULL;
5887 HANDLE o_ours = NULL;
5888
5889 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5890 ga_init2(&ga_env, (int)sizeof(char*), 20);
5891
5892 if (argvar->v_type == VAR_STRING)
5893 {
5894 cmd = argvar->vval.v_string;
5895 }
5896 else if (argvar->v_type == VAR_LIST)
5897 {
5898 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5899 goto failed;
5900 cmd = ga_cmd.ga_data;
5901 }
5902 if (cmd == NULL || *cmd == NUL)
5903 {
5904 emsg(_(e_invarg));
5905 goto failed;
5906 }
5907
5908 term->tl_arg0_cmd = vim_strsave(cmd);
5909
5910 cmd_wchar = enc_to_utf16(cmd, NULL);
5911
5912 if (cmd_wchar != NULL)
5913 {
5914 /* Request by CreateProcessW */
5915 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005916 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005917 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5918 }
5919
5920 ga_clear(&ga_cmd);
5921 if (cmd_wchar == NULL)
5922 goto failed;
5923 if (opt->jo_cwd != NULL)
5924 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5925
5926 win32_build_env(opt->jo_env, &ga_env, TRUE);
5927 env_wchar = ga_env.ga_data;
5928
5929 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5930 goto failed;
5931 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5932 goto failed;
5933
5934 consize.X = term->tl_cols;
5935 consize.Y = term->tl_rows;
5936 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
5937 &term->tl_conpty);
5938 if (FAILED(hr))
5939 goto failed;
5940
5941 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
5942
5943 /* Set up pipe inheritance safely: Vista or later. */
5944 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005945 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005946 if (!term->tl_siex.lpAttributeList)
5947 goto failed;
5948 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
5949 0, &breq))
5950 goto failed;
5951 if (!pUpdateProcThreadAttribute(
5952 term->tl_siex.lpAttributeList, 0,
5953 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
5954 sizeof(HPCON), NULL, NULL))
5955 goto failed;
5956
5957 channel = add_channel();
5958 if (channel == NULL)
5959 goto failed;
5960
5961 job = job_alloc();
5962 if (job == NULL)
5963 goto failed;
5964 if (argvar->v_type == VAR_STRING)
5965 {
5966 int argc;
5967
5968 build_argv_from_string(cmd, &job->jv_argv, &argc);
5969 }
5970 else
5971 {
5972 int argc;
5973
5974 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5975 }
5976
5977 if (opt->jo_set & JO_IN_BUF)
5978 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5979
5980 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
5981 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
5982 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
5983 | CREATE_DEFAULT_ERROR_MODE,
5984 env_wchar, cwd_wchar,
5985 &term->tl_siex.StartupInfo, &proc_info))
5986 goto failed;
5987
5988 CloseHandle(i_theirs);
5989 CloseHandle(o_theirs);
5990
5991 channel_set_pipes(channel,
5992 (sock_T)i_ours,
5993 (sock_T)o_ours,
5994 (sock_T)o_ours);
5995
5996 /* Write lines with CR instead of NL. */
5997 channel->ch_write_text_mode = TRUE;
5998
5999 /* Use to explicitly delete anonymous pipe handle. */
6000 channel->ch_anonymous_pipe = TRUE;
6001
6002 jo = CreateJobObject(NULL, NULL);
6003 if (jo == NULL)
6004 goto failed;
6005
6006 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6007 {
6008 /* Failed, switch the way to terminate process with TerminateProcess. */
6009 CloseHandle(jo);
6010 jo = NULL;
6011 }
6012
6013 ResumeThread(proc_info.hThread);
6014 CloseHandle(proc_info.hThread);
6015
6016 vim_free(cmd_wchar);
6017 vim_free(cmd_wchar_copy);
6018 vim_free(cwd_wchar);
6019 vim_free(env_wchar);
6020
6021 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6022 goto failed;
6023
6024#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6025 if (opt->jo_set2 & JO2_ANSI_COLORS)
6026 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6027 else
6028 init_vterm_ansi_colors(term->tl_vterm);
6029#endif
6030
6031 channel_set_job(channel, job, opt);
6032 job_set_options(job, opt);
6033
6034 job->jv_channel = channel;
6035 job->jv_proc_info = proc_info;
6036 job->jv_job_object = jo;
6037 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006038 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006039 ++job->jv_refcount;
6040 term->tl_job = job;
6041
6042 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6043 * open the file here and handle it in. opt->jo_io was changed in
6044 * setup_job_options(), use the original flags here. */
6045 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6046 {
6047 char_u *fname = opt->jo_io_name[PART_OUT];
6048
6049 ch_log(channel, "Opening output file %s", fname);
6050 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6051 if (term->tl_out_fd == NULL)
6052 semsg(_(e_notopen), fname);
6053 }
6054
6055 return OK;
6056
6057failed:
6058 ga_clear(&ga_cmd);
6059 ga_clear(&ga_env);
6060 vim_free(cmd_wchar);
6061 vim_free(cmd_wchar_copy);
6062 vim_free(cwd_wchar);
6063 if (channel != NULL)
6064 channel_clear(channel);
6065 if (job != NULL)
6066 {
6067 job->jv_channel = NULL;
6068 job_cleanup(job);
6069 }
6070 term->tl_job = NULL;
6071 if (jo != NULL)
6072 CloseHandle(jo);
6073
6074 if (term->tl_siex.lpAttributeList != NULL)
6075 {
6076 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6077 vim_free(term->tl_siex.lpAttributeList);
6078 }
6079 term->tl_siex.lpAttributeList = NULL;
6080 if (o_theirs != NULL)
6081 CloseHandle(o_theirs);
6082 if (o_ours != NULL)
6083 CloseHandle(o_ours);
6084 if (i_ours != NULL)
6085 CloseHandle(i_ours);
6086 if (i_theirs != NULL)
6087 CloseHandle(i_theirs);
6088 if (term->tl_conpty != NULL)
6089 pClosePseudoConsole(term->tl_conpty);
6090 term->tl_conpty = NULL;
6091 return FAIL;
6092}
6093
6094 static void
6095conpty_term_report_winsize(term_T *term, int rows, int cols)
6096{
6097 COORD consize;
6098
6099 consize.X = cols;
6100 consize.Y = rows;
6101 pResizePseudoConsole(term->tl_conpty, consize);
6102}
6103
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006104 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006105term_free_conpty(term_T *term)
6106{
6107 if (term->tl_siex.lpAttributeList != NULL)
6108 {
6109 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6110 vim_free(term->tl_siex.lpAttributeList);
6111 }
6112 term->tl_siex.lpAttributeList = NULL;
6113 if (term->tl_conpty != NULL)
6114 pClosePseudoConsole(term->tl_conpty);
6115 term->tl_conpty = NULL;
6116}
6117
6118 int
6119use_conpty(void)
6120{
6121 return has_conpty;
6122}
6123
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006124# ifndef PROTO
6125
6126#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6127#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006128#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006129
6130void* (*winpty_config_new)(UINT64, void*);
6131void* (*winpty_open)(void*, void*);
6132void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6133BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6134void (*winpty_config_set_mouse_mode)(void*, int);
6135void (*winpty_config_set_initial_size)(void*, int, int);
6136LPCWSTR (*winpty_conin_name)(void*);
6137LPCWSTR (*winpty_conout_name)(void*);
6138LPCWSTR (*winpty_conerr_name)(void*);
6139void (*winpty_free)(void*);
6140void (*winpty_config_free)(void*);
6141void (*winpty_spawn_config_free)(void*);
6142void (*winpty_error_free)(void*);
6143LPCWSTR (*winpty_error_msg)(void*);
6144BOOL (*winpty_set_size)(void*, int, int, void*);
6145HANDLE (*winpty_agent_process)(void*);
6146
6147#define WINPTY_DLL "winpty.dll"
6148
6149static HINSTANCE hWinPtyDLL = NULL;
6150# endif
6151
6152 static int
6153dyn_winpty_init(int verbose)
6154{
6155 int i;
6156 static struct
6157 {
6158 char *name;
6159 FARPROC *ptr;
6160 } winpty_entry[] =
6161 {
6162 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6163 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6164 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6165 {"winpty_config_set_mouse_mode",
6166 (FARPROC*)&winpty_config_set_mouse_mode},
6167 {"winpty_config_set_initial_size",
6168 (FARPROC*)&winpty_config_set_initial_size},
6169 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6170 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6171 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6172 {"winpty_free", (FARPROC*)&winpty_free},
6173 {"winpty_open", (FARPROC*)&winpty_open},
6174 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6175 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6176 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6177 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6178 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6179 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6180 {NULL, NULL}
6181 };
6182
6183 /* No need to initialize twice. */
6184 if (hWinPtyDLL)
6185 return OK;
6186 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6187 * winpty.dll. */
6188 if (*p_winptydll != NUL)
6189 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6190 if (!hWinPtyDLL)
6191 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6192 if (!hWinPtyDLL)
6193 {
6194 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006195 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006196 : (char_u *)WINPTY_DLL);
6197 return FAIL;
6198 }
6199 for (i = 0; winpty_entry[i].name != NULL
6200 && winpty_entry[i].ptr != NULL; ++i)
6201 {
6202 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6203 winpty_entry[i].name)) == NULL)
6204 {
6205 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006206 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006207 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006208 return FAIL;
6209 }
6210 }
6211
6212 return OK;
6213}
6214
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006215 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006216winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006217 term_T *term,
6218 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006219 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006220 jobopt_T *opt,
6221 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006222{
6223 WCHAR *cmd_wchar = NULL;
6224 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006225 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006226 channel_T *channel = NULL;
6227 job_T *job = NULL;
6228 DWORD error;
6229 HANDLE jo = NULL;
6230 HANDLE child_process_handle;
6231 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006232 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006233 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006234 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006235 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006236
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006237 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6238 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006239
6240 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006241 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006242 cmd = argvar->vval.v_string;
6243 }
6244 else if (argvar->v_type == VAR_LIST)
6245 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006246 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006247 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006248 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006249 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006250 if (cmd == NULL || *cmd == NUL)
6251 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006252 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006253 goto failed;
6254 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006255
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006256 term->tl_arg0_cmd = vim_strsave(cmd);
6257
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006258 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006259 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006260 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006261 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006262 if (opt->jo_cwd != NULL)
6263 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006264
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006265 win32_build_env(opt->jo_env, &ga_env, TRUE);
6266 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006267
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006268 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6269 if (term->tl_winpty_config == NULL)
6270 goto failed;
6271
6272 winpty_config_set_mouse_mode(term->tl_winpty_config,
6273 WINPTY_MOUSE_MODE_FORCE);
6274 winpty_config_set_initial_size(term->tl_winpty_config,
6275 term->tl_cols, term->tl_rows);
6276 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6277 if (term->tl_winpty == NULL)
6278 goto failed;
6279
6280 spawn_config = winpty_spawn_config_new(
6281 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6282 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6283 NULL,
6284 cmd_wchar,
6285 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006286 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006287 &winpty_err);
6288 if (spawn_config == NULL)
6289 goto failed;
6290
6291 channel = add_channel();
6292 if (channel == NULL)
6293 goto failed;
6294
6295 job = job_alloc();
6296 if (job == NULL)
6297 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006298 if (argvar->v_type == VAR_STRING)
6299 {
6300 int argc;
6301
6302 build_argv_from_string(cmd, &job->jv_argv, &argc);
6303 }
6304 else
6305 {
6306 int argc;
6307
6308 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6309 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006310
6311 if (opt->jo_set & JO_IN_BUF)
6312 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6313
6314 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6315 &child_thread_handle, &error, &winpty_err))
6316 goto failed;
6317
6318 channel_set_pipes(channel,
6319 (sock_T)CreateFileW(
6320 winpty_conin_name(term->tl_winpty),
6321 GENERIC_WRITE, 0, NULL,
6322 OPEN_EXISTING, 0, NULL),
6323 (sock_T)CreateFileW(
6324 winpty_conout_name(term->tl_winpty),
6325 GENERIC_READ, 0, NULL,
6326 OPEN_EXISTING, 0, NULL),
6327 (sock_T)CreateFileW(
6328 winpty_conerr_name(term->tl_winpty),
6329 GENERIC_READ, 0, NULL,
6330 OPEN_EXISTING, 0, NULL));
6331
6332 /* Write lines with CR instead of NL. */
6333 channel->ch_write_text_mode = TRUE;
6334
6335 jo = CreateJobObject(NULL, NULL);
6336 if (jo == NULL)
6337 goto failed;
6338
6339 if (!AssignProcessToJobObject(jo, child_process_handle))
6340 {
6341 /* Failed, switch the way to terminate process with TerminateProcess. */
6342 CloseHandle(jo);
6343 jo = NULL;
6344 }
6345
6346 winpty_spawn_config_free(spawn_config);
6347 vim_free(cmd_wchar);
6348 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006349 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006350
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006351 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6352 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006353
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006354#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6355 if (opt->jo_set2 & JO2_ANSI_COLORS)
6356 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6357 else
6358 init_vterm_ansi_colors(term->tl_vterm);
6359#endif
6360
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006361 channel_set_job(channel, job, opt);
6362 job_set_options(job, opt);
6363
6364 job->jv_channel = channel;
6365 job->jv_proc_info.hProcess = child_process_handle;
6366 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6367 job->jv_job_object = jo;
6368 job->jv_status = JOB_STARTED;
6369 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006370 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006371 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006372 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006373 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006374 ++job->jv_refcount;
6375 term->tl_job = job;
6376
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006377 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6378 * open the file here and handle it in. opt->jo_io was changed in
6379 * setup_job_options(), use the original flags here. */
6380 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6381 {
6382 char_u *fname = opt->jo_io_name[PART_OUT];
6383
6384 ch_log(channel, "Opening output file %s", fname);
6385 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6386 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006387 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006388 }
6389
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006390 return OK;
6391
6392failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006393 ga_clear(&ga_cmd);
6394 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006395 vim_free(cmd_wchar);
6396 vim_free(cwd_wchar);
6397 if (spawn_config != NULL)
6398 winpty_spawn_config_free(spawn_config);
6399 if (channel != NULL)
6400 channel_clear(channel);
6401 if (job != NULL)
6402 {
6403 job->jv_channel = NULL;
6404 job_cleanup(job);
6405 }
6406 term->tl_job = NULL;
6407 if (jo != NULL)
6408 CloseHandle(jo);
6409 if (term->tl_winpty != NULL)
6410 winpty_free(term->tl_winpty);
6411 term->tl_winpty = NULL;
6412 if (term->tl_winpty_config != NULL)
6413 winpty_config_free(term->tl_winpty_config);
6414 term->tl_winpty_config = NULL;
6415 if (winpty_err != NULL)
6416 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006417 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006418 (short_u *)winpty_error_msg(winpty_err), NULL);
6419
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006420 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006421 winpty_error_free(winpty_err);
6422 }
6423 return FAIL;
6424}
6425
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006426/*
6427 * Create a new terminal of "rows" by "cols" cells.
6428 * Store a reference in "term".
6429 * Return OK or FAIL.
6430 */
6431 static int
6432term_and_job_init(
6433 term_T *term,
6434 typval_T *argvar,
6435 char **argv UNUSED,
6436 jobopt_T *opt,
6437 jobopt_T *orig_opt)
6438{
6439 int use_winpty = FALSE;
6440 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006441 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006442
6443 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6444 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6445
6446 if (!has_winpty && !has_conpty)
6447 // If neither is available give the errors for winpty, since when
6448 // conpty is not available it can't be installed either.
6449 return dyn_winpty_init(TRUE);
6450
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006451 if (opt->jo_tty_type != NUL)
6452 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006453
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006454 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006455 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006456 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006457 use_conpty = TRUE;
6458 else if (has_winpty)
6459 use_winpty = TRUE;
6460 // else: error
6461 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006462 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006463 {
6464 if (has_winpty)
6465 use_winpty = TRUE;
6466 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006467 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006468 {
6469 if (has_conpty)
6470 use_conpty = TRUE;
6471 else
6472 return dyn_conpty_init(TRUE);
6473 }
6474
6475 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006476 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006477
6478 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006479 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006480
6481 // error
6482 return dyn_winpty_init(TRUE);
6483}
6484
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006485 static int
6486create_pty_only(term_T *term, jobopt_T *options)
6487{
6488 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6489 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6490 char in_name[80], out_name[80];
6491 channel_T *channel = NULL;
6492
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006493 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6494 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006495
6496 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6497 GetCurrentProcessId(),
6498 curbuf->b_fnum);
6499 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6500 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6501 PIPE_UNLIMITED_INSTANCES,
6502 0, 0, NMPWAIT_NOWAIT, NULL);
6503 if (hPipeIn == INVALID_HANDLE_VALUE)
6504 goto failed;
6505
6506 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6507 GetCurrentProcessId(),
6508 curbuf->b_fnum);
6509 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6510 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6511 PIPE_UNLIMITED_INSTANCES,
6512 0, 0, 0, NULL);
6513 if (hPipeOut == INVALID_HANDLE_VALUE)
6514 goto failed;
6515
6516 ConnectNamedPipe(hPipeIn, NULL);
6517 ConnectNamedPipe(hPipeOut, NULL);
6518
6519 term->tl_job = job_alloc();
6520 if (term->tl_job == NULL)
6521 goto failed;
6522 ++term->tl_job->jv_refcount;
6523
6524 /* behave like the job is already finished */
6525 term->tl_job->jv_status = JOB_FINISHED;
6526
6527 channel = add_channel();
6528 if (channel == NULL)
6529 goto failed;
6530 term->tl_job->jv_channel = channel;
6531 channel->ch_keep_open = TRUE;
6532 channel->ch_named_pipe = TRUE;
6533
6534 channel_set_pipes(channel,
6535 (sock_T)hPipeIn,
6536 (sock_T)hPipeOut,
6537 (sock_T)hPipeOut);
6538 channel_set_job(channel, term->tl_job, options);
6539 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6540 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6541
6542 return OK;
6543
6544failed:
6545 if (hPipeIn != NULL)
6546 CloseHandle(hPipeIn);
6547 if (hPipeOut != NULL)
6548 CloseHandle(hPipeOut);
6549 return FAIL;
6550}
6551
6552/*
6553 * Free the terminal emulator part of "term".
6554 */
6555 static void
6556term_free_vterm(term_T *term)
6557{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006558 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006559 if (term->tl_winpty != NULL)
6560 winpty_free(term->tl_winpty);
6561 term->tl_winpty = NULL;
6562 if (term->tl_winpty_config != NULL)
6563 winpty_config_free(term->tl_winpty_config);
6564 term->tl_winpty_config = NULL;
6565 if (term->tl_vterm != NULL)
6566 vterm_free(term->tl_vterm);
6567 term->tl_vterm = NULL;
6568}
6569
6570/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006571 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006572 */
6573 static void
6574term_report_winsize(term_T *term, int rows, int cols)
6575{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006576 if (term->tl_conpty)
6577 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006578 if (term->tl_winpty)
6579 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6580}
6581
6582 int
6583terminal_enabled(void)
6584{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006585 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006586}
6587
6588# else
6589
6590/**************************************
6591 * 3. Unix-like implementation.
6592 */
6593
6594/*
6595 * Create a new terminal of "rows" by "cols" cells.
6596 * Start job for "cmd".
6597 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006598 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006599 * Return OK or FAIL.
6600 */
6601 static int
6602term_and_job_init(
6603 term_T *term,
6604 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006605 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006606 jobopt_T *opt,
6607 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006608{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006609 term->tl_arg0_cmd = NULL;
6610
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006611 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6612 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006613
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006614#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6615 if (opt->jo_set2 & JO2_ANSI_COLORS)
6616 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6617 else
6618 init_vterm_ansi_colors(term->tl_vterm);
6619#endif
6620
Bram Moolenaar13568252018-03-16 20:46:58 +01006621 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006622 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006623 if (term->tl_job != NULL)
6624 ++term->tl_job->jv_refcount;
6625
6626 return term->tl_job != NULL
6627 && term->tl_job->jv_channel != NULL
6628 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6629}
6630
6631 static int
6632create_pty_only(term_T *term, jobopt_T *opt)
6633{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006634 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6635 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006636
6637 term->tl_job = job_alloc();
6638 if (term->tl_job == NULL)
6639 return FAIL;
6640 ++term->tl_job->jv_refcount;
6641
6642 /* behave like the job is already finished */
6643 term->tl_job->jv_status = JOB_FINISHED;
6644
6645 return mch_create_pty_channel(term->tl_job, opt);
6646}
6647
6648/*
6649 * Free the terminal emulator part of "term".
6650 */
6651 static void
6652term_free_vterm(term_T *term)
6653{
6654 if (term->tl_vterm != NULL)
6655 vterm_free(term->tl_vterm);
6656 term->tl_vterm = NULL;
6657}
6658
6659/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006660 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006661 */
6662 static void
6663term_report_winsize(term_T *term, int rows, int cols)
6664{
6665 /* Use an ioctl() to report the new window size to the job. */
6666 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6667 {
6668 int fd = -1;
6669 int part;
6670
6671 for (part = PART_OUT; part < PART_COUNT; ++part)
6672 {
6673 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006674 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006675 break;
6676 }
6677 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6678 mch_signal_job(term->tl_job, (char_u *)"winch");
6679 }
6680}
6681
6682# endif
6683
6684#endif /* FEAT_TERMINAL */