blob: b50198ca5ae6d739585cad278d95303de353dbb1 [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 Moolenaar8f7ab4b2019-10-23 23:16:45 +02001497 ui_delay(10L, TRUE);
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 Moolenaar4d14bac2019-10-20 21:15:15 +02003076 // If this is the last normal window: exit Vim.
3077 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3078 {
3079 exarg_T ea;
3080
3081 vim_memset(&ea, 0, sizeof(ea));
3082 ex_quit(&ea);
3083 return TRUE;
3084 }
3085
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003086 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003087 ch_log(NULL, "terminal job finished, closing window");
3088 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003089 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003090 if (curwin == aucmd_win)
3091 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003092 if (do_set_w_closing)
3093 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003094 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003095 if (do_set_w_closing)
3096 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003097 aucmd_restbuf(&aco);
3098 return TRUE;
3099 }
3100 if (term->tl_finish == TL_FINISH_OPEN
3101 && term->tl_buffer->b_nwindows == 0)
3102 {
3103 char buf[50];
3104
3105 /* TODO: use term_opencmd */
3106 ch_log(NULL, "terminal job finished, opening window");
3107 vim_snprintf(buf, sizeof(buf),
3108 term->tl_opencmd == NULL
3109 ? "botright sbuf %d"
3110 : (char *)term->tl_opencmd, fnum);
3111 do_cmdline_cmd((char_u *)buf);
3112 }
3113 else
3114 ch_log(NULL, "terminal job finished");
3115 }
3116
3117 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3118 return FALSE;
3119}
3120
3121/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003122 * Called when a channel has been closed.
3123 * If this was a channel for a terminal window then finish it up.
3124 */
3125 void
3126term_channel_closed(channel_T *ch)
3127{
3128 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003129 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130 int did_one = FALSE;
3131
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003132 for (term = first_term; term != NULL; term = next_term)
3133 {
3134 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003135 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003136 {
3137 term->tl_channel_closed = TRUE;
3138 did_one = TRUE;
3139
Bram Moolenaard23a8232018-02-10 18:45:26 +01003140 VIM_CLEAR(term->tl_title);
3141 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003142#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003143 if (term->tl_out_fd != NULL)
3144 {
3145 fclose(term->tl_out_fd);
3146 term->tl_out_fd = NULL;
3147 }
3148#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003149
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003150 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003151 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003152 /* Cannot open or close windows now. Can happen when
3153 * 'lazyredraw' is set. */
3154 term->tl_channel_recently_closed = TRUE;
3155 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156 }
3157
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003158 if (term_after_channel_closed(term))
3159 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003160 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003161 }
3162
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003163 if (did_one)
3164 {
3165 redraw_statuslines();
3166
3167 /* Need to break out of vgetc(). */
3168 ins_char_typebuf(K_IGNORE);
3169 typebuf_was_filled = TRUE;
3170
3171 term = curbuf->b_term;
3172 if (term != NULL)
3173 {
3174 if (term->tl_job == ch->ch_job)
3175 maketitle();
3176 update_cursor(term, term->tl_cursor_visible);
3177 }
3178 }
3179}
3180
3181/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003182 * To be called after resetting updating_screen: handle any terminal where the
3183 * channel was closed.
3184 */
3185 void
3186term_check_channel_closed_recently()
3187{
3188 term_T *term;
3189 term_T *next_term;
3190
3191 for (term = first_term; term != NULL; term = next_term)
3192 {
3193 next_term = term->tl_next;
3194 if (term->tl_channel_recently_closed)
3195 {
3196 term->tl_channel_recently_closed = FALSE;
3197 if (term_after_channel_closed(term))
3198 // start over, the list may have changed
3199 next_term = first_term;
3200 }
3201 }
3202}
3203
3204/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003205 * Fill one screen line from a line of the terminal.
3206 * Advances "pos" to past the last column.
3207 */
3208 static void
3209term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3210{
3211 int off = screen_get_current_line_off();
3212
3213 for (pos->col = 0; pos->col < max_col; )
3214 {
3215 VTermScreenCell cell;
3216 int c;
3217
3218 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3219 vim_memset(&cell, 0, sizeof(cell));
3220
3221 c = cell.chars[0];
3222 if (c == NUL)
3223 {
3224 ScreenLines[off] = ' ';
3225 if (enc_utf8)
3226 ScreenLinesUC[off] = NUL;
3227 }
3228 else
3229 {
3230 if (enc_utf8)
3231 {
3232 int i;
3233
3234 /* composing chars */
3235 for (i = 0; i < Screen_mco
3236 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3237 {
3238 ScreenLinesC[i][off] = cell.chars[i + 1];
3239 if (cell.chars[i + 1] == 0)
3240 break;
3241 }
3242 if (c >= 0x80 || (Screen_mco > 0
3243 && ScreenLinesC[0][off] != 0))
3244 {
3245 ScreenLines[off] = ' ';
3246 ScreenLinesUC[off] = c;
3247 }
3248 else
3249 {
3250 ScreenLines[off] = c;
3251 ScreenLinesUC[off] = NUL;
3252 }
3253 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003254#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003255 else if (has_mbyte && c >= 0x80)
3256 {
3257 char_u mb[MB_MAXBYTES+1];
3258 WCHAR wc = c;
3259
3260 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3261 (char*)mb, 2, 0, 0) > 1)
3262 {
3263 ScreenLines[off] = mb[0];
3264 ScreenLines[off + 1] = mb[1];
3265 cell.width = mb_ptr2cells(mb);
3266 }
3267 else
3268 ScreenLines[off] = c;
3269 }
3270#endif
3271 else
3272 ScreenLines[off] = c;
3273 }
3274 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3275
3276 ++pos->col;
3277 ++off;
3278 if (cell.width == 2)
3279 {
3280 if (enc_utf8)
3281 ScreenLinesUC[off] = NUL;
3282
3283 /* don't set the second byte to NUL for a DBCS encoding, it
3284 * has been set above */
3285 if (enc_utf8 || !has_mbyte)
3286 ScreenLines[off] = NUL;
3287
3288 ++pos->col;
3289 ++off;
3290 }
3291 }
3292}
3293
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003294#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003295 static void
3296update_system_term(term_T *term)
3297{
3298 VTermPos pos;
3299 VTermScreen *screen;
3300
3301 if (term->tl_vterm == NULL)
3302 return;
3303 screen = vterm_obtain_screen(term->tl_vterm);
3304
3305 /* Scroll up to make more room for terminal lines if needed. */
3306 while (term->tl_toprow > 0
3307 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3308 {
3309 int save_p_more = p_more;
3310
3311 p_more = FALSE;
3312 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003313 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003314 p_more = save_p_more;
3315 --term->tl_toprow;
3316 }
3317
3318 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3319 && pos.row < Rows; ++pos.row)
3320 {
3321 if (pos.row < term->tl_rows)
3322 {
3323 int max_col = MIN(Columns, term->tl_cols);
3324
3325 term_line2screenline(screen, &pos, max_col);
3326 }
3327 else
3328 pos.col = 0;
3329
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003330 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003331 }
3332
3333 term->tl_dirty_row_start = MAX_ROW;
3334 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003335}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003336#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003337
3338/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003339 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3340 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003341 * Terminal-Normal mode.
3342 */
3343 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003344term_do_update_window(win_T *wp)
3345{
3346 term_T *term = wp->w_buffer->b_term;
3347
3348 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3349}
3350
3351/*
3352 * Called to update a window that contains an active terminal.
3353 */
3354 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003355term_update_window(win_T *wp)
3356{
3357 term_T *term = wp->w_buffer->b_term;
3358 VTerm *vterm;
3359 VTermScreen *screen;
3360 VTermState *state;
3361 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003362 int rows, cols;
3363 int newrows, newcols;
3364 int minsize;
3365 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003366
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003367 vterm = term->tl_vterm;
3368 screen = vterm_obtain_screen(vterm);
3369 state = vterm_obtain_state(vterm);
3370
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003371 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3372 * SOME_VALID only redraw what was marked dirty. */
3373 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003374 {
3375 term->tl_dirty_row_start = 0;
3376 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003377
3378 if (term->tl_postponed_scroll > 0
3379 && term->tl_postponed_scroll < term->tl_rows / 3)
3380 /* Scrolling is usually faster than redrawing, when there are only
3381 * a few lines to scroll. */
3382 term_scroll_up(term, 0, term->tl_postponed_scroll);
3383 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003384 }
3385
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003386 /*
3387 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003388 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003389 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003390 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003391
Bram Moolenaar498c2562018-04-15 23:45:15 +02003392 newrows = 99999;
3393 newcols = 99999;
3394 FOR_ALL_WINDOWS(twp)
3395 {
3396 /* When more than one window shows the same terminal, use the
3397 * smallest size. */
3398 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003399 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003400 newrows = MIN(newrows, twp->w_height);
3401 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003402 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003403 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003404 if (newrows == 99999 || newcols == 99999)
3405 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003406 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3407 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3408
3409 if (term->tl_rows != newrows || term->tl_cols != newcols)
3410 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003411 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003412 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003413 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003414 newrows);
3415 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003416
3417 // Updating the terminal size will cause the snapshot to be cleared.
3418 // When not in terminal_loop() we need to restore it.
3419 if (term != in_terminal_loop)
3420 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003421 }
3422
3423 /* The cursor may have been moved when resizing. */
3424 vterm_state_get_cursorpos(state, &pos);
3425 position_cursor(wp, &pos);
3426
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003427 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3428 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003429 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003430 if (pos.row < term->tl_rows)
3431 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003432 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003433
Bram Moolenaar13568252018-03-16 20:46:58 +01003434 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003435 }
3436 else
3437 pos.col = 0;
3438
Bram Moolenaarf118d482018-03-13 13:14:00 +01003439 screen_line(wp->w_winrow + pos.row
3440#ifdef FEAT_MENU
3441 + winbar_height(wp)
3442#endif
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003443 , wp->w_wincol, pos.col, wp->w_width, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003444 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003445 term->tl_dirty_row_start = MAX_ROW;
3446 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003447}
3448
3449/*
3450 * Return TRUE if "wp" is a terminal window where the job has finished.
3451 */
3452 int
3453term_is_finished(buf_T *buf)
3454{
3455 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3456}
3457
3458/*
3459 * Return TRUE if "wp" is a terminal window where the job has finished or we
3460 * are in Terminal-Normal mode, thus we show the buffer contents.
3461 */
3462 int
3463term_show_buffer(buf_T *buf)
3464{
3465 term_T *term = buf->b_term;
3466
3467 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3468}
3469
3470/*
3471 * The current buffer is going to be changed. If there is terminal
3472 * highlighting remove it now.
3473 */
3474 void
3475term_change_in_curbuf(void)
3476{
3477 term_T *term = curbuf->b_term;
3478
3479 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3480 {
3481 free_scrollback(term);
3482 redraw_buf_later(term->tl_buffer, NOT_VALID);
3483
3484 /* The buffer is now like a normal buffer, it cannot be easily
3485 * abandoned when changed. */
3486 set_string_option_direct((char_u *)"buftype", -1,
3487 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3488 }
3489}
3490
3491/*
3492 * Get the screen attribute for a position in the buffer.
3493 * Use a negative "col" to get the filler background color.
3494 */
3495 int
3496term_get_attr(buf_T *buf, linenr_T lnum, int col)
3497{
3498 term_T *term = buf->b_term;
3499 sb_line_T *line;
3500 cellattr_T *cellattr;
3501
3502 if (lnum > term->tl_scrollback.ga_len)
3503 cellattr = &term->tl_default_color;
3504 else
3505 {
3506 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3507 if (col < 0 || col >= line->sb_cols)
3508 cellattr = &line->sb_fill_attr;
3509 else
3510 cellattr = line->sb_cells + col;
3511 }
3512 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3513}
3514
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003515/*
3516 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003517 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003518 */
3519 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003520cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003521{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003522 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003523}
3524
3525/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003526 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003527 */
3528 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003529init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003530{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003531 VTermColor *fg, *bg;
3532 int fgval, bgval;
3533 int id;
3534
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003535 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3536 term->tl_default_color.width = 1;
3537 fg = &term->tl_default_color.fg;
3538 bg = &term->tl_default_color.bg;
3539
3540 /* Vterm uses a default black background. Set it to white when
3541 * 'background' is "light". */
3542 if (*p_bg == 'l')
3543 {
3544 fgval = 0;
3545 bgval = 255;
3546 }
3547 else
3548 {
3549 fgval = 255;
3550 bgval = 0;
3551 }
3552 fg->red = fg->green = fg->blue = fgval;
3553 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003554 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003555
3556 /* The "Terminal" highlight group overrules the defaults. */
3557 id = syn_name2id((char_u *)"Terminal");
3558
Bram Moolenaar46359e12017-11-29 22:33:38 +01003559 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003560#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3561 if (0
3562# ifdef FEAT_GUI
3563 || gui.in_use
3564# endif
3565# ifdef FEAT_TERMGUICOLORS
3566 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003567# ifdef FEAT_VTP
3568 /* Finally get INVALCOLOR on this execution path */
3569 || (!p_tgc && t_colors >= 256)
3570# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003571# endif
3572 )
3573 {
3574 guicolor_T fg_rgb = INVALCOLOR;
3575 guicolor_T bg_rgb = INVALCOLOR;
3576
3577 if (id != 0)
3578 syn_id2colors(id, &fg_rgb, &bg_rgb);
3579
3580# ifdef FEAT_GUI
3581 if (gui.in_use)
3582 {
3583 if (fg_rgb == INVALCOLOR)
3584 fg_rgb = gui.norm_pixel;
3585 if (bg_rgb == INVALCOLOR)
3586 bg_rgb = gui.back_pixel;
3587 }
3588# ifdef FEAT_TERMGUICOLORS
3589 else
3590# endif
3591# endif
3592# ifdef FEAT_TERMGUICOLORS
3593 {
3594 if (fg_rgb == INVALCOLOR)
3595 fg_rgb = cterm_normal_fg_gui_color;
3596 if (bg_rgb == INVALCOLOR)
3597 bg_rgb = cterm_normal_bg_gui_color;
3598 }
3599# endif
3600 if (fg_rgb != INVALCOLOR)
3601 {
3602 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3603
3604 fg->red = (unsigned)(rgb >> 16);
3605 fg->green = (unsigned)(rgb >> 8) & 255;
3606 fg->blue = (unsigned)rgb & 255;
3607 }
3608 if (bg_rgb != INVALCOLOR)
3609 {
3610 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3611
3612 bg->red = (unsigned)(rgb >> 16);
3613 bg->green = (unsigned)(rgb >> 8) & 255;
3614 bg->blue = (unsigned)rgb & 255;
3615 }
3616 }
3617 else
3618#endif
3619 if (id != 0 && t_colors >= 16)
3620 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003621 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003622 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003623 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003624 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003625 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003626 else
3627 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003628#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003629 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003630#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003631
3632 /* In an MS-Windows console we know the normal colors. */
3633 if (cterm_normal_fg_color > 0)
3634 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003635 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003636# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3637# ifdef VIMDLL
3638 if (!gui.in_use)
3639# endif
3640 {
3641 tmp = fg->red;
3642 fg->red = fg->blue;
3643 fg->blue = tmp;
3644 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003645# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003646 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003647# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003648 else
3649 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003650# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003651
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003652 if (cterm_normal_bg_color > 0)
3653 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003654 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003655# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3656# ifdef VIMDLL
3657 if (!gui.in_use)
3658# endif
3659 {
3660 tmp = fg->red;
3661 fg->red = fg->blue;
3662 fg->blue = tmp;
3663 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003664# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003665 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003666# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003667 else
3668 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003669# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003670 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003671}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003672
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003673#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3674/*
3675 * Set the 16 ANSI colors from array of RGB values
3676 */
3677 static void
3678set_vterm_palette(VTerm *vterm, long_u *rgb)
3679{
3680 int index = 0;
3681 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003682
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003683 for (; index < 16; index++)
3684 {
3685 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003686
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003687 color.red = (unsigned)(rgb[index] >> 16);
3688 color.green = (unsigned)(rgb[index] >> 8) & 255;
3689 color.blue = (unsigned)rgb[index] & 255;
3690 vterm_state_set_palette_color(state, index, &color);
3691 }
3692}
3693
3694/*
3695 * Set the ANSI color palette from a list of colors
3696 */
3697 static int
3698set_ansi_colors_list(VTerm *vterm, list_T *list)
3699{
3700 int n = 0;
3701 long_u rgb[16];
3702 listitem_T *li = list->lv_first;
3703
3704 for (; li != NULL && n < 16; li = li->li_next, n++)
3705 {
3706 char_u *color_name;
3707 guicolor_T guicolor;
3708
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003709 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003710 if (color_name == NULL)
3711 return FAIL;
3712
3713 guicolor = GUI_GET_COLOR(color_name);
3714 if (guicolor == INVALCOLOR)
3715 return FAIL;
3716
3717 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3718 }
3719
3720 if (n != 16 || li != NULL)
3721 return FAIL;
3722
3723 set_vterm_palette(vterm, rgb);
3724
3725 return OK;
3726}
3727
3728/*
3729 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3730 */
3731 static void
3732init_vterm_ansi_colors(VTerm *vterm)
3733{
3734 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3735
3736 if (var != NULL
3737 && (var->di_tv.v_type != VAR_LIST
3738 || var->di_tv.vval.v_list == NULL
3739 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003740 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003741}
3742#endif
3743
Bram Moolenaar52acb112018-03-18 19:20:22 +01003744/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003745 * Handles a "drop" command from the job in the terminal.
3746 * "item" is the file name, "item->li_next" may have options.
3747 */
3748 static void
3749handle_drop_command(listitem_T *item)
3750{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003751 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003752 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003753 int bufnr;
3754 win_T *wp;
3755 tabpage_T *tp;
3756 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003757 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003758
3759 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3760 FOR_ALL_TAB_WINDOWS(tp, wp)
3761 {
3762 if (wp->w_buffer->b_fnum == bufnr)
3763 {
3764 /* buffer is in a window already, go there */
3765 goto_tabpage_win(tp, wp);
3766 return;
3767 }
3768 }
3769
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003770 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003771
3772 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3773 && opt_item->li_tv.vval.v_dict != NULL)
3774 {
3775 dict_T *dict = opt_item->li_tv.vval.v_dict;
3776 char_u *p;
3777
Bram Moolenaar8f667172018-12-14 15:38:31 +01003778 p = dict_get_string(dict, (char_u *)"ff", 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 *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003781 if (p != NULL)
3782 {
3783 if (check_ff_value(p) == FAIL)
3784 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3785 else
3786 ea.force_ff = *p;
3787 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003788 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003789 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003790 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003791 if (p != NULL)
3792 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003793 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003794 if (ea.cmd != NULL)
3795 {
3796 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3797 ea.force_enc = 11;
3798 tofree = ea.cmd;
3799 }
3800 }
3801
Bram Moolenaar8f667172018-12-14 15:38:31 +01003802 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003803 if (p != NULL)
3804 get_bad_opt(p, &ea);
3805
3806 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3807 ea.force_bin = FORCE_BIN;
3808 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3809 ea.force_bin = FORCE_BIN;
3810 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3811 ea.force_bin = FORCE_NOBIN;
3812 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3813 ea.force_bin = FORCE_NOBIN;
3814 }
3815
3816 /* open in new window, like ":split fname" */
3817 if (ea.cmd == NULL)
3818 ea.cmd = (char_u *)"split";
3819 ea.arg = fname;
3820 ea.cmdidx = CMD_split;
3821 ex_splitview(&ea);
3822
3823 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003824}
3825
3826/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003827 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
3828 */
3829 static int
3830is_permitted_term_api(char_u *func, char_u *pat)
3831{
3832 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
3833}
3834
3835/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003836 * Handles a function call from the job running in a terminal.
3837 * "item" is the function name, "item->li_next" has the arguments.
3838 */
3839 static void
3840handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3841{
3842 char_u *func;
3843 typval_T argvars[2];
3844 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003845 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003846
3847 if (item->li_next == NULL)
3848 {
3849 ch_log(channel, "Missing function arguments for call");
3850 return;
3851 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003852 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003853
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003854 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003855 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003856 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003857 return;
3858 }
3859
3860 argvars[0].v_type = VAR_NUMBER;
3861 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3862 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003863 vim_memset(&funcexe, 0, sizeof(funcexe));
3864 funcexe.firstline = 1L;
3865 funcexe.lastline = 1L;
3866 funcexe.evaluate = TRUE;
3867 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003868 {
3869 clear_tv(&rettv);
3870 ch_log(channel, "Function %s called", func);
3871 }
3872 else
3873 ch_log(channel, "Calling function %s failed", func);
3874}
3875
3876/*
3877 * Called by libvterm when it cannot recognize an OSC sequence.
3878 * We recognize a terminal API command.
3879 */
3880 static int
3881parse_osc(const char *command, size_t cmdlen, void *user)
3882{
3883 term_T *term = (term_T *)user;
3884 js_read_T reader;
3885 typval_T tv;
3886 channel_T *channel = term->tl_job == NULL ? NULL
3887 : term->tl_job->jv_channel;
3888
3889 /* We recognize only OSC 5 1 ; {command} */
3890 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3891 return 0; /* not handled */
3892
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003893 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003894 if (reader.js_buf == NULL)
3895 return 1;
3896 reader.js_fill = NULL;
3897 reader.js_used = 0;
3898 if (json_decode(&reader, &tv, 0) == OK
3899 && tv.v_type == VAR_LIST
3900 && tv.vval.v_list != NULL)
3901 {
3902 listitem_T *item = tv.vval.v_list->lv_first;
3903
3904 if (item == NULL)
3905 ch_log(channel, "Missing command");
3906 else
3907 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003908 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003909
Bram Moolenaara997b452018-04-17 23:24:06 +02003910 /* Make sure an invoked command doesn't delete the buffer (and the
3911 * terminal) under our fingers. */
3912 ++term->tl_buffer->b_locked;
3913
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003914 item = item->li_next;
3915 if (item == NULL)
3916 ch_log(channel, "Missing argument for %s", cmd);
3917 else if (STRCMP(cmd, "drop") == 0)
3918 handle_drop_command(item);
3919 else if (STRCMP(cmd, "call") == 0)
3920 handle_call_command(term, channel, item);
3921 else
3922 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003923 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003924 }
3925 }
3926 else
3927 ch_log(channel, "Invalid JSON received");
3928
3929 vim_free(reader.js_buf);
3930 clear_tv(&tv);
3931 return 1;
3932}
3933
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003934/*
3935 * Called by libvterm when it cannot recognize a CSI sequence.
3936 * We recognize the window position report.
3937 */
3938 static int
3939parse_csi(
3940 const char *leader UNUSED,
3941 const long args[],
3942 int argcount,
3943 const char *intermed UNUSED,
3944 char command,
3945 void *user)
3946{
3947 term_T *term = (term_T *)user;
3948 char buf[100];
3949 int len;
3950 int x = 0;
3951 int y = 0;
3952 win_T *wp;
3953
3954 // We recognize only CSI 13 t
3955 if (command != 't' || argcount != 1 || args[0] != 13)
3956 return 0; // not handled
3957
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003958 // When getting the window position is not possible or it fails it results
3959 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02003960#if defined(FEAT_GUI) \
3961 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
3962 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003963 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003964#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003965
3966 FOR_ALL_WINDOWS(wp)
3967 if (wp->w_buffer == term->tl_buffer)
3968 break;
3969 if (wp != NULL)
3970 {
3971#ifdef FEAT_GUI
3972 if (gui.in_use)
3973 {
3974 x += wp->w_wincol * gui.char_width;
3975 y += W_WINROW(wp) * gui.char_height;
3976 }
3977 else
3978#endif
3979 {
3980 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003981 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003982 x += wp->w_wincol * 7;
3983 y += W_WINROW(wp) * 10;
3984 }
3985 }
3986
3987 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
3988 channel_send(term->tl_job->jv_channel, get_tty_part(term),
3989 (char_u *)buf, len, NULL);
3990 return 1;
3991}
3992
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003993static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003994 NULL, // text
3995 NULL, // control
3996 NULL, // escape
3997 parse_csi, // csi
3998 parse_osc, // osc
3999 NULL, // dcs
4000 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004001};
4002
4003/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004004 * Use Vim's allocation functions for vterm so profiling works.
4005 */
4006 static void *
4007vterm_malloc(size_t size, void *data UNUSED)
4008{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004009 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004010}
4011
4012 static void
4013vterm_memfree(void *ptr, void *data UNUSED)
4014{
4015 vim_free(ptr);
4016}
4017
4018static VTermAllocatorFunctions vterm_allocator = {
4019 &vterm_malloc,
4020 &vterm_memfree
4021};
4022
4023/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004024 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004025 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004026 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004027 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004028create_vterm(term_T *term, int rows, int cols)
4029{
4030 VTerm *vterm;
4031 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004032 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004033 VTermValue value;
4034
Bram Moolenaar756ef112018-04-10 12:04:27 +02004035 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004036 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004037 if (vterm == NULL)
4038 return FAIL;
4039
4040 // Allocate screen and state here, so we can bail out if that fails.
4041 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004042 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004043 if (state == NULL || screen == NULL)
4044 {
4045 vterm_free(vterm);
4046 return FAIL;
4047 }
4048
Bram Moolenaar52acb112018-03-18 19:20:22 +01004049 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
4050 /* TODO: depends on 'encoding'. */
4051 vterm_set_utf8(vterm, 1);
4052
4053 init_default_colors(term);
4054
4055 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004056 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004057 &term->tl_default_color.fg,
4058 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004059
Bram Moolenaar9e587872019-05-13 20:27:23 +02004060 if (t_colors < 16)
4061 // Less than 16 colors: assume that bold means using a bright color for
4062 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004063 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4064
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004065 /* Required to initialize most things. */
4066 vterm_screen_reset(screen, 1 /* hard */);
4067
4068 /* Allow using alternate screen. */
4069 vterm_screen_enable_altscreen(screen, 1);
4070
4071 /* For unix do not use a blinking cursor. In an xterm this causes the
4072 * cursor to blink if it's blinking in the xterm.
4073 * For Windows we respect the system wide setting. */
Bram Moolenaar4f974752019-02-17 17:44:42 +01004074#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004075 if (GetCaretBlinkTime() == INFINITE)
4076 value.boolean = 0;
4077 else
4078 value.boolean = 1;
4079#else
4080 value.boolean = 0;
4081#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004082 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4083 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004084
4085 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004086}
4087
4088/*
4089 * Return the text to show for the buffer name and status.
4090 */
4091 char_u *
4092term_get_status_text(term_T *term)
4093{
4094 if (term->tl_status_text == NULL)
4095 {
4096 char_u *txt;
4097 size_t len;
4098
4099 if (term->tl_normal_mode)
4100 {
4101 if (term_job_running(term))
4102 txt = (char_u *)_("Terminal");
4103 else
4104 txt = (char_u *)_("Terminal-finished");
4105 }
4106 else if (term->tl_title != NULL)
4107 txt = term->tl_title;
4108 else if (term_none_open(term))
4109 txt = (char_u *)_("active");
4110 else if (term_job_running(term))
4111 txt = (char_u *)_("running");
4112 else
4113 txt = (char_u *)_("finished");
4114 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004115 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004116 if (term->tl_status_text != NULL)
4117 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4118 term->tl_buffer->b_fname, txt);
4119 }
4120 return term->tl_status_text;
4121}
4122
4123/*
4124 * Mark references in jobs of terminals.
4125 */
4126 int
4127set_ref_in_term(int copyID)
4128{
4129 int abort = FALSE;
4130 term_T *term;
4131 typval_T tv;
4132
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004133 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004134 if (term->tl_job != NULL)
4135 {
4136 tv.v_type = VAR_JOB;
4137 tv.vval.v_job = term->tl_job;
4138 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4139 }
4140 return abort;
4141}
4142
4143/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004144 * Cache "Terminal" highlight group colors.
4145 */
4146 void
4147set_terminal_default_colors(int cterm_fg, int cterm_bg)
4148{
4149 term_default_cterm_fg = cterm_fg - 1;
4150 term_default_cterm_bg = cterm_bg - 1;
4151}
4152
4153/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004154 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004155 * Returns NULL when the buffer is not for a terminal window and logs a message
4156 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004157 */
4158 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004159term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004160{
4161 buf_T *buf;
4162
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004163 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004164 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004165 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004166 --emsg_off;
4167 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004168 {
4169 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004170 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004171 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004172 return buf;
4173}
4174
Bram Moolenaard96ff162018-02-18 22:13:29 +01004175 static int
4176same_color(VTermColor *a, VTermColor *b)
4177{
4178 return a->red == b->red
4179 && a->green == b->green
4180 && a->blue == b->blue
4181 && a->ansi_index == b->ansi_index;
4182}
4183
4184 static void
4185dump_term_color(FILE *fd, VTermColor *color)
4186{
4187 fprintf(fd, "%02x%02x%02x%d",
4188 (int)color->red, (int)color->green, (int)color->blue,
4189 (int)color->ansi_index);
4190}
4191
4192/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004193 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004194 *
4195 * Each screen cell in full is:
4196 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4197 * {characters} is a space for an empty cell
4198 * For a double-width character "+" is changed to "*" and the next cell is
4199 * skipped.
4200 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4201 * when "&" use the same as the previous cell.
4202 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4203 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4204 * {color-idx} is a number from 0 to 255
4205 *
4206 * Screen cell with same width, attributes and color as the previous one:
4207 * |{characters}
4208 *
4209 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4210 *
4211 * Repeating the previous screen cell:
4212 * @{count}
4213 */
4214 void
4215f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4216{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004217 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004218 term_T *term;
4219 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004220 int max_height = 0;
4221 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004222 stat_T st;
4223 FILE *fd;
4224 VTermPos pos;
4225 VTermScreen *screen;
4226 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004227 VTermState *state;
4228 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004229
4230 if (check_restricted() || check_secure())
4231 return;
4232 if (buf == NULL)
4233 return;
4234 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004235 if (term->tl_vterm == NULL)
4236 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004237 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004238 return;
4239 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004240
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004241 if (argvars[2].v_type != VAR_UNKNOWN)
4242 {
4243 dict_T *d;
4244
4245 if (argvars[2].v_type != VAR_DICT)
4246 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004247 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004248 return;
4249 }
4250 d = argvars[2].vval.v_dict;
4251 if (d != NULL)
4252 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004253 max_height = dict_get_number(d, (char_u *)"rows");
4254 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004255 }
4256 }
4257
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004258 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004259 if (fname == NULL)
4260 return;
4261 if (mch_stat((char *)fname, &st) >= 0)
4262 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004263 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004264 return;
4265 }
4266
Bram Moolenaard96ff162018-02-18 22:13:29 +01004267 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4268 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004269 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004270 return;
4271 }
4272
4273 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4274
4275 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004276 state = vterm_obtain_state(term->tl_vterm);
4277 vterm_state_get_cursorpos(state, &cursor_pos);
4278
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004279 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4280 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004281 {
4282 int repeat = 0;
4283
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004284 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4285 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004286 {
4287 VTermScreenCell cell;
4288 int same_attr;
4289 int same_chars = TRUE;
4290 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004291 int is_cursor_pos = (pos.col == cursor_pos.col
4292 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004293
4294 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4295 vim_memset(&cell, 0, sizeof(cell));
4296
4297 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4298 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004299 int c = cell.chars[i];
4300 int pc = prev_cell.chars[i];
4301
4302 /* For the first character NUL is the same as space. */
4303 if (i == 0)
4304 {
4305 c = (c == NUL) ? ' ' : c;
4306 pc = (pc == NUL) ? ' ' : pc;
4307 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004308 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004309 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004310 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004311 break;
4312 }
4313 same_attr = vtermAttr2hl(cell.attrs)
4314 == vtermAttr2hl(prev_cell.attrs)
4315 && same_color(&cell.fg, &prev_cell.fg)
4316 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004317 if (same_chars && cell.width == prev_cell.width && same_attr
4318 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004319 {
4320 ++repeat;
4321 }
4322 else
4323 {
4324 if (repeat > 0)
4325 {
4326 fprintf(fd, "@%d", repeat);
4327 repeat = 0;
4328 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004329 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004330
4331 if (cell.chars[0] == NUL)
4332 fputs(" ", fd);
4333 else
4334 {
4335 char_u charbuf[10];
4336 int len;
4337
4338 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4339 && cell.chars[i] != NUL; ++i)
4340 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004341 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004342 fwrite(charbuf, len, 1, fd);
4343 }
4344 }
4345
4346 /* When only the characters differ we don't write anything, the
4347 * following "|", "@" or NL will indicate using the same
4348 * attributes. */
4349 if (cell.width != prev_cell.width || !same_attr)
4350 {
4351 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004352 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004353 else
4354 fputs("+", fd);
4355
4356 if (same_attr)
4357 {
4358 fputs("&", fd);
4359 }
4360 else
4361 {
4362 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4363 if (same_color(&cell.fg, &prev_cell.fg))
4364 fputs("&", fd);
4365 else
4366 {
4367 fputs("#", fd);
4368 dump_term_color(fd, &cell.fg);
4369 }
4370 if (same_color(&cell.bg, &prev_cell.bg))
4371 fputs("&", fd);
4372 else
4373 {
4374 fputs("#", fd);
4375 dump_term_color(fd, &cell.bg);
4376 }
4377 }
4378 }
4379
4380 prev_cell = cell;
4381 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004382
4383 if (cell.width == 2)
4384 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004385 }
4386 if (repeat > 0)
4387 fprintf(fd, "@%d", repeat);
4388 fputs("\n", fd);
4389 }
4390
4391 fclose(fd);
4392}
4393
4394/*
4395 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4396 */
4397 static void
4398dump_is_corrupt(garray_T *gap)
4399{
4400 ga_concat(gap, (char_u *)"CORRUPT");
4401}
4402
4403 static void
4404append_cell(garray_T *gap, cellattr_T *cell)
4405{
4406 if (ga_grow(gap, 1) == OK)
4407 {
4408 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4409 ++gap->ga_len;
4410 }
4411}
4412
4413/*
4414 * Read the dump file from "fd" and append lines to the current buffer.
4415 * Return the cell width of the longest line.
4416 */
4417 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004418read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004419{
4420 int c;
4421 garray_T ga_text;
4422 garray_T ga_cell;
4423 char_u *prev_char = NULL;
4424 int attr = 0;
4425 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004426 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004427 term_T *term = curbuf->b_term;
4428 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004429 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004430
4431 ga_init2(&ga_text, 1, 90);
4432 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4433 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004434 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004435 cursor_pos->row = -1;
4436 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004437
4438 c = fgetc(fd);
4439 for (;;)
4440 {
4441 if (c == EOF)
4442 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004443 if (c == '\r')
4444 {
4445 // DOS line endings? Ignore.
4446 c = fgetc(fd);
4447 }
4448 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004449 {
4450 /* End of a line: append it to the buffer. */
4451 if (ga_text.ga_data == NULL)
4452 dump_is_corrupt(&ga_text);
4453 if (ga_grow(&term->tl_scrollback, 1) == OK)
4454 {
4455 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4456 + term->tl_scrollback.ga_len;
4457
4458 if (max_cells < ga_cell.ga_len)
4459 max_cells = ga_cell.ga_len;
4460 line->sb_cols = ga_cell.ga_len;
4461 line->sb_cells = ga_cell.ga_data;
4462 line->sb_fill_attr = term->tl_default_color;
4463 ++term->tl_scrollback.ga_len;
4464 ga_init(&ga_cell);
4465
4466 ga_append(&ga_text, NUL);
4467 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4468 ga_text.ga_len, FALSE);
4469 }
4470 else
4471 ga_clear(&ga_cell);
4472 ga_text.ga_len = 0;
4473
4474 c = fgetc(fd);
4475 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004476 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004477 {
4478 int prev_len = ga_text.ga_len;
4479
Bram Moolenaar9271d052018-02-25 21:39:46 +01004480 if (c == '>')
4481 {
4482 if (cursor_pos->row != -1)
4483 dump_is_corrupt(&ga_text); /* duplicate cursor */
4484 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4485 cursor_pos->col = ga_cell.ga_len;
4486 }
4487
Bram Moolenaard96ff162018-02-18 22:13:29 +01004488 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4489 c = fgetc(fd);
4490 if (c != EOF)
4491 ga_append(&ga_text, c);
4492 for (;;)
4493 {
4494 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004495 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004496 || c == EOF || c == '\n')
4497 break;
4498 ga_append(&ga_text, c);
4499 }
4500
4501 /* save the character for repeating it */
4502 vim_free(prev_char);
4503 if (ga_text.ga_data != NULL)
4504 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4505 ga_text.ga_len - prev_len);
4506
Bram Moolenaar9271d052018-02-25 21:39:46 +01004507 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004508 {
4509 /* use all attributes from previous cell */
4510 }
4511 else if (c == '+' || c == '*')
4512 {
4513 int is_bg;
4514
4515 cell.width = c == '+' ? 1 : 2;
4516
4517 c = fgetc(fd);
4518 if (c == '&')
4519 {
4520 /* use same attr as previous cell */
4521 c = fgetc(fd);
4522 }
4523 else if (isdigit(c))
4524 {
4525 /* get the decimal attribute */
4526 attr = 0;
4527 while (isdigit(c))
4528 {
4529 attr = attr * 10 + (c - '0');
4530 c = fgetc(fd);
4531 }
4532 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004533
4534 /* is_bg == 0: fg, is_bg == 1: bg */
4535 for (is_bg = 0; is_bg <= 1; ++is_bg)
4536 {
4537 if (c == '&')
4538 {
4539 /* use same color as previous cell */
4540 c = fgetc(fd);
4541 }
4542 else if (c == '#')
4543 {
4544 int red, green, blue, index = 0;
4545
4546 c = fgetc(fd);
4547 red = hex2nr(c);
4548 c = fgetc(fd);
4549 red = (red << 4) + hex2nr(c);
4550 c = fgetc(fd);
4551 green = hex2nr(c);
4552 c = fgetc(fd);
4553 green = (green << 4) + hex2nr(c);
4554 c = fgetc(fd);
4555 blue = hex2nr(c);
4556 c = fgetc(fd);
4557 blue = (blue << 4) + hex2nr(c);
4558 c = fgetc(fd);
4559 if (!isdigit(c))
4560 dump_is_corrupt(&ga_text);
4561 while (isdigit(c))
4562 {
4563 index = index * 10 + (c - '0');
4564 c = fgetc(fd);
4565 }
4566
4567 if (is_bg)
4568 {
4569 cell.bg.red = red;
4570 cell.bg.green = green;
4571 cell.bg.blue = blue;
4572 cell.bg.ansi_index = index;
4573 }
4574 else
4575 {
4576 cell.fg.red = red;
4577 cell.fg.green = green;
4578 cell.fg.blue = blue;
4579 cell.fg.ansi_index = index;
4580 }
4581 }
4582 else
4583 dump_is_corrupt(&ga_text);
4584 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004585 }
4586 else
4587 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004588 }
4589 else
4590 dump_is_corrupt(&ga_text);
4591
4592 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004593 if (cell.width == 2)
4594 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004595 }
4596 else if (c == '@')
4597 {
4598 if (prev_char == NULL)
4599 dump_is_corrupt(&ga_text);
4600 else
4601 {
4602 int count = 0;
4603
4604 /* repeat previous character, get the count */
4605 for (;;)
4606 {
4607 c = fgetc(fd);
4608 if (!isdigit(c))
4609 break;
4610 count = count * 10 + (c - '0');
4611 }
4612
4613 while (count-- > 0)
4614 {
4615 ga_concat(&ga_text, prev_char);
4616 append_cell(&ga_cell, &cell);
4617 }
4618 }
4619 }
4620 else
4621 {
4622 dump_is_corrupt(&ga_text);
4623 c = fgetc(fd);
4624 }
4625 }
4626
4627 if (ga_text.ga_len > 0)
4628 {
4629 /* trailing characters after last NL */
4630 dump_is_corrupt(&ga_text);
4631 ga_append(&ga_text, NUL);
4632 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4633 ga_text.ga_len, FALSE);
4634 }
4635
4636 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004637 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004638 vim_free(prev_char);
4639
4640 return max_cells;
4641}
4642
4643/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004644 * Return an allocated string with at least "text_width" "=" characters and
4645 * "fname" inserted in the middle.
4646 */
4647 static char_u *
4648get_separator(int text_width, char_u *fname)
4649{
4650 int width = MAX(text_width, curwin->w_width);
4651 char_u *textline;
4652 int fname_size;
4653 char_u *p = fname;
4654 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004655 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004656
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004657 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004658 if (textline == NULL)
4659 return NULL;
4660
4661 fname_size = vim_strsize(fname);
4662 if (fname_size < width - 8)
4663 {
4664 /* enough room, don't use the full window width */
4665 width = MAX(text_width, fname_size + 8);
4666 }
4667 else if (fname_size > width - 8)
4668 {
4669 /* full name doesn't fit, use only the tail */
4670 p = gettail(fname);
4671 fname_size = vim_strsize(p);
4672 }
4673 /* skip characters until the name fits */
4674 while (fname_size > width - 8)
4675 {
4676 p += (*mb_ptr2len)(p);
4677 fname_size = vim_strsize(p);
4678 }
4679
4680 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4681 textline[i] = '=';
4682 textline[i++] = ' ';
4683
4684 STRCPY(textline + i, p);
4685 off = STRLEN(textline);
4686 textline[off] = ' ';
4687 for (i = 1; i < (width - fname_size) / 2; ++i)
4688 textline[off + i] = '=';
4689 textline[off + i] = NUL;
4690
4691 return textline;
4692}
4693
4694/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004695 * Common for "term_dumpdiff()" and "term_dumpload()".
4696 */
4697 static void
4698term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4699{
4700 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004701 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004702 char_u buf1[NUMBUFLEN];
4703 char_u buf2[NUMBUFLEN];
4704 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004705 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004706 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004707 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004708 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004709 char_u *textline = NULL;
4710
4711 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004712 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004713 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004714 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004715 if (fname1 == NULL || (do_diff && fname2 == NULL))
4716 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004717 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004718 return;
4719 }
4720 fd1 = mch_fopen((char *)fname1, READBIN);
4721 if (fd1 == NULL)
4722 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004723 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004724 return;
4725 }
4726 if (do_diff)
4727 {
4728 fd2 = mch_fopen((char *)fname2, READBIN);
4729 if (fd2 == NULL)
4730 {
4731 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004732 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004733 return;
4734 }
4735 }
4736
4737 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004738 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4739 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4740 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4741 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4742 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004743
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004744 if (opt.jo_term_name == NULL)
4745 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004746 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004747
Bram Moolenaar51e14382019-05-25 20:21:28 +02004748 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004749 if (fname_tofree != NULL)
4750 {
4751 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4752 opt.jo_term_name = fname_tofree;
4753 }
4754 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004755
Bram Moolenaar87abab92019-06-03 21:14:59 +02004756 if (opt.jo_bufnr_buf != NULL)
4757 {
4758 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4759
4760 // With "bufnr" argument: enter the window with this buffer and make it
4761 // empty.
4762 if (wp == NULL)
4763 semsg(_(e_invarg2), "bufnr");
4764 else
4765 {
4766 buf = curbuf;
4767 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4768 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02004769 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02004770 redraw_later(NOT_VALID);
4771 }
4772 }
4773 else
4774 // Create a new terminal window.
4775 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4776
Bram Moolenaard96ff162018-02-18 22:13:29 +01004777 if (buf != NULL && buf->b_term != NULL)
4778 {
4779 int i;
4780 linenr_T bot_lnum;
4781 linenr_T lnum;
4782 term_T *term = buf->b_term;
4783 int width;
4784 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004785 VTermPos cursor_pos1;
4786 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004787
Bram Moolenaar52acb112018-03-18 19:20:22 +01004788 init_default_colors(term);
4789
Bram Moolenaard96ff162018-02-18 22:13:29 +01004790 rettv->vval.v_number = buf->b_fnum;
4791
4792 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004793 width = read_dump_file(fd1, &cursor_pos1);
4794
4795 /* position the cursor */
4796 if (cursor_pos1.row >= 0)
4797 {
4798 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4799 coladvance(cursor_pos1.col);
4800 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004801
4802 /* Delete the empty line that was in the empty buffer. */
4803 ml_delete(1, FALSE);
4804
4805 /* For term_dumpload() we are done here. */
4806 if (!do_diff)
4807 goto theend;
4808
4809 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4810
Bram Moolenaar4a696342018-04-05 18:45:26 +02004811 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004812 if (textline == NULL)
4813 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004814 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4815 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4816 vim_free(textline);
4817
4818 textline = get_separator(width, fname2);
4819 if (textline == NULL)
4820 goto theend;
4821 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4822 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004823 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004824
4825 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004826 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004827 if (width2 > width)
4828 {
4829 vim_free(textline);
4830 textline = alloc(width2 + 1);
4831 if (textline == NULL)
4832 goto theend;
4833 width = width2;
4834 textline[width] = NUL;
4835 }
4836 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4837
4838 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4839 {
4840 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4841 {
4842 /* bottom part has fewer rows, fill with "-" */
4843 for (i = 0; i < width; ++i)
4844 textline[i] = '-';
4845 }
4846 else
4847 {
4848 char_u *line1;
4849 char_u *line2;
4850 char_u *p1;
4851 char_u *p2;
4852 int col;
4853 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4854 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4855 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4856 ->sb_cells;
4857
4858 /* Make a copy, getting the second line will invalidate it. */
4859 line1 = vim_strsave(ml_get(lnum));
4860 if (line1 == NULL)
4861 break;
4862 p1 = line1;
4863
4864 line2 = ml_get(lnum + bot_lnum);
4865 p2 = line2;
4866 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4867 {
4868 int len1 = utfc_ptr2len(p1);
4869 int len2 = utfc_ptr2len(p2);
4870
4871 textline[col] = ' ';
4872 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004873 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004874 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004875 else if (lnum == cursor_pos1.row + 1
4876 && col == cursor_pos1.col
4877 && (cursor_pos1.row != cursor_pos2.row
4878 || cursor_pos1.col != cursor_pos2.col))
4879 /* cursor in first but not in second */
4880 textline[col] = '>';
4881 else if (lnum == cursor_pos2.row + 1
4882 && col == cursor_pos2.col
4883 && (cursor_pos1.row != cursor_pos2.row
4884 || cursor_pos1.col != cursor_pos2.col))
4885 /* cursor in second but not in first */
4886 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004887 else if (cellattr1 != NULL && cellattr2 != NULL)
4888 {
4889 if ((cellattr1 + col)->width
4890 != (cellattr2 + col)->width)
4891 textline[col] = 'w';
4892 else if (!same_color(&(cellattr1 + col)->fg,
4893 &(cellattr2 + col)->fg))
4894 textline[col] = 'f';
4895 else if (!same_color(&(cellattr1 + col)->bg,
4896 &(cellattr2 + col)->bg))
4897 textline[col] = 'b';
4898 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4899 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4900 textline[col] = 'a';
4901 }
4902 p1 += len1;
4903 p2 += len2;
4904 /* TODO: handle different width */
4905 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004906
4907 while (col < width)
4908 {
4909 if (*p1 == NUL && *p2 == NUL)
4910 textline[col] = '?';
4911 else if (*p1 == NUL)
4912 {
4913 textline[col] = '+';
4914 p2 += utfc_ptr2len(p2);
4915 }
4916 else
4917 {
4918 textline[col] = '-';
4919 p1 += utfc_ptr2len(p1);
4920 }
4921 ++col;
4922 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004923
4924 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004925 }
4926 if (add_empty_scrollback(term, &term->tl_default_color,
4927 term->tl_top_diff_rows) == OK)
4928 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4929 ++bot_lnum;
4930 }
4931
4932 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4933 {
4934 /* bottom part has more rows, fill with "+" */
4935 for (i = 0; i < width; ++i)
4936 textline[i] = '+';
4937 if (add_empty_scrollback(term, &term->tl_default_color,
4938 term->tl_top_diff_rows) == OK)
4939 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4940 ++lnum;
4941 ++bot_lnum;
4942 }
4943
4944 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004945
4946 /* looks better without wrapping */
4947 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004948 }
4949
4950theend:
4951 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004952 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004953 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004954 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004955 fclose(fd2);
4956}
4957
4958/*
4959 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4960 * bottom files.
4961 * Return FAIL when this is not possible.
4962 */
4963 int
4964term_swap_diff()
4965{
4966 term_T *term = curbuf->b_term;
4967 linenr_T line_count;
4968 linenr_T top_rows;
4969 linenr_T bot_rows;
4970 linenr_T bot_start;
4971 linenr_T lnum;
4972 char_u *p;
4973 sb_line_T *sb_line;
4974
4975 if (term == NULL
4976 || !term_is_finished(curbuf)
4977 || term->tl_top_diff_rows == 0
4978 || term->tl_scrollback.ga_len == 0)
4979 return FAIL;
4980
4981 line_count = curbuf->b_ml.ml_line_count;
4982 top_rows = term->tl_top_diff_rows;
4983 bot_rows = term->tl_bot_diff_rows;
4984 bot_start = line_count - bot_rows;
4985 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4986
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004987 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01004988 for (lnum = 1; lnum <= top_rows; ++lnum)
4989 {
4990 p = vim_strsave(ml_get(1));
4991 if (p == NULL)
4992 return OK;
4993 ml_append(bot_start, p, 0, FALSE);
4994 ml_delete(1, FALSE);
4995 vim_free(p);
4996 }
4997
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004998 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01004999 for (lnum = 1; lnum <= bot_rows; ++lnum)
5000 {
5001 p = vim_strsave(ml_get(bot_start + lnum));
5002 if (p == NULL)
5003 return OK;
5004 ml_delete(bot_start + lnum, FALSE);
5005 ml_append(lnum - 1, p, 0, FALSE);
5006 vim_free(p);
5007 }
5008
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005009 // move top title to bottom
5010 p = vim_strsave(ml_get(bot_rows + 1));
5011 if (p == NULL)
5012 return OK;
5013 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5014 ml_delete(bot_rows + 1, FALSE);
5015 vim_free(p);
5016
5017 // move bottom title to top
5018 p = vim_strsave(ml_get(line_count - top_rows));
5019 if (p == NULL)
5020 return OK;
5021 ml_delete(line_count - top_rows, FALSE);
5022 ml_append(bot_rows, p, 0, FALSE);
5023 vim_free(p);
5024
Bram Moolenaard96ff162018-02-18 22:13:29 +01005025 if (top_rows == bot_rows)
5026 {
5027 /* rows counts are equal, can swap cell properties */
5028 for (lnum = 0; lnum < top_rows; ++lnum)
5029 {
5030 sb_line_T temp;
5031
5032 temp = *(sb_line + lnum);
5033 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5034 *(sb_line + bot_start + lnum) = temp;
5035 }
5036 }
5037 else
5038 {
5039 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005040 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005041
5042 /* need to copy cell properties into temp memory */
5043 if (temp != NULL)
5044 {
5045 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5046 mch_memmove(term->tl_scrollback.ga_data,
5047 temp + bot_start,
5048 sizeof(sb_line_T) * bot_rows);
5049 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5050 temp + top_rows,
5051 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5052 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5053 + line_count - top_rows,
5054 temp,
5055 sizeof(sb_line_T) * top_rows);
5056 vim_free(temp);
5057 }
5058 }
5059
5060 term->tl_top_diff_rows = bot_rows;
5061 term->tl_bot_diff_rows = top_rows;
5062
5063 update_screen(NOT_VALID);
5064 return OK;
5065}
5066
5067/*
5068 * "term_dumpdiff(filename, filename, options)" function
5069 */
5070 void
5071f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5072{
5073 term_load_dump(argvars, rettv, TRUE);
5074}
5075
5076/*
5077 * "term_dumpload(filename, options)" function
5078 */
5079 void
5080f_term_dumpload(typval_T *argvars, typval_T *rettv)
5081{
5082 term_load_dump(argvars, rettv, FALSE);
5083}
5084
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005085/*
5086 * "term_getaltscreen(buf)" function
5087 */
5088 void
5089f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5090{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005091 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005092
5093 if (buf == NULL)
5094 return;
5095 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5096}
5097
5098/*
5099 * "term_getattr(attr, name)" function
5100 */
5101 void
5102f_term_getattr(typval_T *argvars, typval_T *rettv)
5103{
5104 int attr;
5105 size_t i;
5106 char_u *name;
5107
5108 static struct {
5109 char *name;
5110 int attr;
5111 } attrs[] = {
5112 {"bold", HL_BOLD},
5113 {"italic", HL_ITALIC},
5114 {"underline", HL_UNDERLINE},
5115 {"strike", HL_STRIKETHROUGH},
5116 {"reverse", HL_INVERSE},
5117 };
5118
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005119 attr = tv_get_number(&argvars[0]);
5120 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005121 if (name == NULL)
5122 return;
5123
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005124 if (attr > HL_ALL)
5125 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005126 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5127 if (STRCMP(name, attrs[i].name) == 0)
5128 {
5129 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5130 break;
5131 }
5132}
5133
5134/*
5135 * "term_getcursor(buf)" function
5136 */
5137 void
5138f_term_getcursor(typval_T *argvars, typval_T *rettv)
5139{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005140 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005141 term_T *term;
5142 list_T *l;
5143 dict_T *d;
5144
5145 if (rettv_list_alloc(rettv) == FAIL)
5146 return;
5147 if (buf == NULL)
5148 return;
5149 term = buf->b_term;
5150
5151 l = rettv->vval.v_list;
5152 list_append_number(l, term->tl_cursor_pos.row + 1);
5153 list_append_number(l, term->tl_cursor_pos.col + 1);
5154
5155 d = dict_alloc();
5156 if (d != NULL)
5157 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005158 dict_add_number(d, "visible", term->tl_cursor_visible);
5159 dict_add_number(d, "blink", blink_state_is_inverted()
5160 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5161 dict_add_number(d, "shape", term->tl_cursor_shape);
5162 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005163 list_append_dict(l, d);
5164 }
5165}
5166
5167/*
5168 * "term_getjob(buf)" function
5169 */
5170 void
5171f_term_getjob(typval_T *argvars, typval_T *rettv)
5172{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005173 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005174
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005175 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005176 {
5177 rettv->v_type = VAR_SPECIAL;
5178 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005179 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005180 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005181
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005182 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005183 rettv->vval.v_job = buf->b_term->tl_job;
5184 if (rettv->vval.v_job != NULL)
5185 ++rettv->vval.v_job->jv_refcount;
5186}
5187
5188 static int
5189get_row_number(typval_T *tv, term_T *term)
5190{
5191 if (tv->v_type == VAR_STRING
5192 && tv->vval.v_string != NULL
5193 && STRCMP(tv->vval.v_string, ".") == 0)
5194 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005195 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005196}
5197
5198/*
5199 * "term_getline(buf, row)" function
5200 */
5201 void
5202f_term_getline(typval_T *argvars, typval_T *rettv)
5203{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005204 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005205 term_T *term;
5206 int row;
5207
5208 rettv->v_type = VAR_STRING;
5209 if (buf == NULL)
5210 return;
5211 term = buf->b_term;
5212 row = get_row_number(&argvars[1], term);
5213
5214 if (term->tl_vterm == NULL)
5215 {
5216 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5217
5218 /* vterm is finished, get the text from the buffer */
5219 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5220 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5221 }
5222 else
5223 {
5224 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5225 VTermRect rect;
5226 int len;
5227 char_u *p;
5228
5229 if (row < 0 || row >= term->tl_rows)
5230 return;
5231 len = term->tl_cols * MB_MAXBYTES + 1;
5232 p = alloc(len);
5233 if (p == NULL)
5234 return;
5235 rettv->vval.v_string = p;
5236
5237 rect.start_col = 0;
5238 rect.end_col = term->tl_cols;
5239 rect.start_row = row;
5240 rect.end_row = row + 1;
5241 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5242 }
5243}
5244
5245/*
5246 * "term_getscrolled(buf)" function
5247 */
5248 void
5249f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5250{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005251 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005252
5253 if (buf == NULL)
5254 return;
5255 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5256}
5257
5258/*
5259 * "term_getsize(buf)" function
5260 */
5261 void
5262f_term_getsize(typval_T *argvars, typval_T *rettv)
5263{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005264 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005265 list_T *l;
5266
5267 if (rettv_list_alloc(rettv) == FAIL)
5268 return;
5269 if (buf == NULL)
5270 return;
5271
5272 l = rettv->vval.v_list;
5273 list_append_number(l, buf->b_term->tl_rows);
5274 list_append_number(l, buf->b_term->tl_cols);
5275}
5276
5277/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005278 * "term_setsize(buf, rows, cols)" function
5279 */
5280 void
5281f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5282{
5283 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5284 term_T *term;
5285 varnumber_T rows, cols;
5286
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005287 if (buf == NULL)
5288 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005289 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005290 return;
5291 }
5292 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005293 return;
5294 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005295 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005296 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005297 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005298 cols = cols <= 0 ? term->tl_cols : cols;
5299 vterm_set_size(term->tl_vterm, rows, cols);
5300 /* handle_resize() will resize the windows */
5301
5302 /* Get and remember the size we ended up with. Update the pty. */
5303 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5304 term_report_winsize(term, term->tl_rows, term->tl_cols);
5305}
5306
5307/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005308 * "term_getstatus(buf)" function
5309 */
5310 void
5311f_term_getstatus(typval_T *argvars, typval_T *rettv)
5312{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005313 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005314 term_T *term;
5315 char_u val[100];
5316
5317 rettv->v_type = VAR_STRING;
5318 if (buf == NULL)
5319 return;
5320 term = buf->b_term;
5321
5322 if (term_job_running(term))
5323 STRCPY(val, "running");
5324 else
5325 STRCPY(val, "finished");
5326 if (term->tl_normal_mode)
5327 STRCAT(val, ",normal");
5328 rettv->vval.v_string = vim_strsave(val);
5329}
5330
5331/*
5332 * "term_gettitle(buf)" function
5333 */
5334 void
5335f_term_gettitle(typval_T *argvars, typval_T *rettv)
5336{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005337 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005338
5339 rettv->v_type = VAR_STRING;
5340 if (buf == NULL)
5341 return;
5342
5343 if (buf->b_term->tl_title != NULL)
5344 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5345}
5346
5347/*
5348 * "term_gettty(buf)" function
5349 */
5350 void
5351f_term_gettty(typval_T *argvars, typval_T *rettv)
5352{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005353 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005354 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005355 int num = 0;
5356
5357 rettv->v_type = VAR_STRING;
5358 if (buf == NULL)
5359 return;
5360 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005361 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005362
5363 switch (num)
5364 {
5365 case 0:
5366 if (buf->b_term->tl_job != NULL)
5367 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005368 break;
5369 case 1:
5370 if (buf->b_term->tl_job != NULL)
5371 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005372 break;
5373 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005374 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005375 return;
5376 }
5377 if (p != NULL)
5378 rettv->vval.v_string = vim_strsave(p);
5379}
5380
5381/*
5382 * "term_list()" function
5383 */
5384 void
5385f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5386{
5387 term_T *tp;
5388 list_T *l;
5389
5390 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5391 return;
5392
5393 l = rettv->vval.v_list;
5394 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5395 if (tp != NULL && tp->tl_buffer != NULL)
5396 if (list_append_number(l,
5397 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5398 return;
5399}
5400
5401/*
5402 * "term_scrape(buf, row)" function
5403 */
5404 void
5405f_term_scrape(typval_T *argvars, typval_T *rettv)
5406{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005407 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005408 VTermScreen *screen = NULL;
5409 VTermPos pos;
5410 list_T *l;
5411 term_T *term;
5412 char_u *p;
5413 sb_line_T *line;
5414
5415 if (rettv_list_alloc(rettv) == FAIL)
5416 return;
5417 if (buf == NULL)
5418 return;
5419 term = buf->b_term;
5420
5421 l = rettv->vval.v_list;
5422 pos.row = get_row_number(&argvars[1], term);
5423
5424 if (term->tl_vterm != NULL)
5425 {
5426 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005427 if (screen == NULL) // can't really happen
5428 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005429 p = NULL;
5430 line = NULL;
5431 }
5432 else
5433 {
5434 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5435
5436 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5437 return;
5438 p = ml_get_buf(buf, lnum + 1, FALSE);
5439 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5440 }
5441
5442 for (pos.col = 0; pos.col < term->tl_cols; )
5443 {
5444 dict_T *dcell;
5445 int width;
5446 VTermScreenCellAttrs attrs;
5447 VTermColor fg, bg;
5448 char_u rgb[8];
5449 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5450 int off = 0;
5451 int i;
5452
5453 if (screen == NULL)
5454 {
5455 cellattr_T *cellattr;
5456 int len;
5457
5458 /* vterm has finished, get the cell from scrollback */
5459 if (pos.col >= line->sb_cols)
5460 break;
5461 cellattr = line->sb_cells + pos.col;
5462 width = cellattr->width;
5463 attrs = cellattr->attrs;
5464 fg = cellattr->fg;
5465 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005466 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005467 mch_memmove(mbs, p, len);
5468 mbs[len] = NUL;
5469 p += len;
5470 }
5471 else
5472 {
5473 VTermScreenCell cell;
5474 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5475 break;
5476 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5477 {
5478 if (cell.chars[i] == 0)
5479 break;
5480 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5481 }
5482 mbs[off] = NUL;
5483 width = cell.width;
5484 attrs = cell.attrs;
5485 fg = cell.fg;
5486 bg = cell.bg;
5487 }
5488 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005489 if (dcell == NULL)
5490 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005491 list_append_dict(l, dcell);
5492
Bram Moolenaare0be1672018-07-08 16:50:37 +02005493 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005494
5495 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5496 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005497 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005498 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5499 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005500 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005501
Bram Moolenaare0be1672018-07-08 16:50:37 +02005502 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5503 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005504
5505 ++pos.col;
5506 if (width == 2)
5507 ++pos.col;
5508 }
5509}
5510
5511/*
5512 * "term_sendkeys(buf, keys)" function
5513 */
5514 void
5515f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5516{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005517 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005518 char_u *msg;
5519 term_T *term;
5520
5521 rettv->v_type = VAR_UNKNOWN;
5522 if (buf == NULL)
5523 return;
5524
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005525 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005526 if (msg == NULL)
5527 return;
5528 term = buf->b_term;
5529 if (term->tl_vterm == NULL)
5530 return;
5531
5532 while (*msg != NUL)
5533 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005534 int c;
5535
5536 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5537 {
5538 c = TO_SPECIAL(msg[1], msg[2]);
5539 msg += 3;
5540 }
5541 else
5542 {
5543 c = PTR2CHAR(msg);
5544 msg += MB_CPTR2LEN(msg);
5545 }
5546 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005547 }
5548}
5549
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005550#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5551/*
5552 * "term_getansicolors(buf)" function
5553 */
5554 void
5555f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5556{
5557 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5558 term_T *term;
5559 VTermState *state;
5560 VTermColor color;
5561 char_u hexbuf[10];
5562 int index;
5563 list_T *list;
5564
5565 if (rettv_list_alloc(rettv) == FAIL)
5566 return;
5567
5568 if (buf == NULL)
5569 return;
5570 term = buf->b_term;
5571 if (term->tl_vterm == NULL)
5572 return;
5573
5574 list = rettv->vval.v_list;
5575 state = vterm_obtain_state(term->tl_vterm);
5576 for (index = 0; index < 16; index++)
5577 {
5578 vterm_state_get_palette_color(state, index, &color);
5579 sprintf((char *)hexbuf, "#%02x%02x%02x",
5580 color.red, color.green, color.blue);
5581 if (list_append_string(list, hexbuf, 7) == FAIL)
5582 return;
5583 }
5584}
5585
5586/*
5587 * "term_setansicolors(buf, list)" function
5588 */
5589 void
5590f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5591{
5592 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5593 term_T *term;
5594
5595 if (buf == NULL)
5596 return;
5597 term = buf->b_term;
5598 if (term->tl_vterm == NULL)
5599 return;
5600
5601 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5602 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005603 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005604 return;
5605 }
5606
5607 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005608 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005609}
5610#endif
5611
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005612/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005613 * "term_setapi(buf, api)" function
5614 */
5615 void
5616f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5617{
5618 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5619 term_T *term;
5620 char_u *api;
5621
5622 if (buf == NULL)
5623 return;
5624 term = buf->b_term;
5625 vim_free(term->tl_api);
5626 api = tv_get_string_chk(&argvars[1]);
5627 if (api != NULL)
5628 term->tl_api = vim_strsave(api);
5629 else
5630 term->tl_api = NULL;
5631}
5632
5633/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005634 * "term_setrestore(buf, command)" function
5635 */
5636 void
5637f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5638{
5639#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005640 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005641 term_T *term;
5642 char_u *cmd;
5643
5644 if (buf == NULL)
5645 return;
5646 term = buf->b_term;
5647 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005648 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005649 if (cmd != NULL)
5650 term->tl_command = vim_strsave(cmd);
5651 else
5652 term->tl_command = NULL;
5653#endif
5654}
5655
5656/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005657 * "term_setkill(buf, how)" function
5658 */
5659 void
5660f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5661{
5662 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5663 term_T *term;
5664 char_u *how;
5665
5666 if (buf == NULL)
5667 return;
5668 term = buf->b_term;
5669 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005670 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005671 if (how != NULL)
5672 term->tl_kill = vim_strsave(how);
5673 else
5674 term->tl_kill = NULL;
5675}
5676
5677/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005678 * "term_start(command, options)" function
5679 */
5680 void
5681f_term_start(typval_T *argvars, typval_T *rettv)
5682{
5683 jobopt_T opt;
5684 buf_T *buf;
5685
5686 init_job_options(&opt);
5687 if (argvars[1].v_type != VAR_UNKNOWN
5688 && get_job_options(&argvars[1], &opt,
5689 JO_TIMEOUT_ALL + JO_STOPONEXIT
5690 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5691 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5692 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5693 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005694 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005695 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005696 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005697 return;
5698
Bram Moolenaar13568252018-03-16 20:46:58 +01005699 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005700
5701 if (buf != NULL && buf->b_term != NULL)
5702 rettv->vval.v_number = buf->b_fnum;
5703}
5704
5705/*
5706 * "term_wait" function
5707 */
5708 void
5709f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5710{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005711 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005712
5713 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005714 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005715 if (buf->b_term->tl_job == NULL)
5716 {
5717 ch_log(NULL, "term_wait(): no job to wait for");
5718 return;
5719 }
5720 if (buf->b_term->tl_job->jv_channel == NULL)
5721 /* channel is closed, nothing to do */
5722 return;
5723
5724 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005725 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005726 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5727 {
5728 /* The job is dead, keep reading channel I/O until the channel is
5729 * closed. buf->b_term may become NULL if the terminal was closed while
5730 * waiting. */
5731 ch_log(NULL, "term_wait(): waiting for channel to close");
5732 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5733 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005734 term_flush_messages();
5735
Bram Moolenaard45aa552018-05-21 22:50:29 +02005736 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005737 if (!buf_valid(buf))
5738 /* If the terminal is closed when the channel is closed the
5739 * buffer disappears. */
5740 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005741 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005742
5743 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005744 }
5745 else
5746 {
5747 long wait = 10L;
5748
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005749 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005750
5751 /* Wait for some time for any channel I/O. */
5752 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005753 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005754 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005755
5756 /* Flushing messages on channels is hopefully sufficient.
5757 * TODO: is there a better way? */
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005758 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005759 }
5760}
5761
5762/*
5763 * Called when a channel has sent all the lines to a terminal.
5764 * Send a CTRL-D to mark the end of the text.
5765 */
5766 void
5767term_send_eof(channel_T *ch)
5768{
5769 term_T *term;
5770
5771 for (term = first_term; term != NULL; term = term->tl_next)
5772 if (term->tl_job == ch->ch_job)
5773 {
5774 if (term->tl_eof_chars != NULL)
5775 {
5776 channel_send(ch, PART_IN, term->tl_eof_chars,
5777 (int)STRLEN(term->tl_eof_chars), NULL);
5778 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5779 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005780# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005781 else
5782 /* Default: CTRL-D */
5783 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5784# endif
5785 }
5786}
5787
Bram Moolenaar113e1072019-01-20 15:30:40 +01005788#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005789 job_T *
5790term_getjob(term_T *term)
5791{
5792 return term != NULL ? term->tl_job : NULL;
5793}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005794#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005795
Bram Moolenaar4f974752019-02-17 17:44:42 +01005796# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005797
5798/**************************************
5799 * 2. MS-Windows implementation.
5800 */
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005801#ifdef PROTO
5802typedef int COORD;
5803typedef int DWORD;
5804typedef int HANDLE;
5805typedef int *DWORD_PTR;
5806typedef int HPCON;
5807typedef int HRESULT;
5808typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005809typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005810typedef int PSIZE_T;
5811typedef int PVOID;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005812typedef int WINAPI;
5813#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005814
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005815HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5816HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5817HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005818BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5819BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5820void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005821
5822 static int
5823dyn_conpty_init(int verbose)
5824{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005825 static HMODULE hKerneldll = NULL;
5826 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005827 static struct
5828 {
5829 char *name;
5830 FARPROC *ptr;
5831 } conpty_entry[] =
5832 {
5833 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5834 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5835 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5836 {"InitializeProcThreadAttributeList",
5837 (FARPROC*)&pInitializeProcThreadAttributeList},
5838 {"UpdateProcThreadAttribute",
5839 (FARPROC*)&pUpdateProcThreadAttribute},
5840 {"DeleteProcThreadAttributeList",
5841 (FARPROC*)&pDeleteProcThreadAttributeList},
5842 {NULL, NULL}
5843 };
5844
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005845 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005846 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005847 if (verbose)
5848 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005849 return FAIL;
5850 }
5851
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005852 // No need to initialize twice.
5853 if (hKerneldll)
5854 return OK;
5855
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005856 hKerneldll = vimLoadLib("kernel32.dll");
5857 for (i = 0; conpty_entry[i].name != NULL
5858 && conpty_entry[i].ptr != NULL; ++i)
5859 {
5860 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5861 conpty_entry[i].name)) == NULL)
5862 {
5863 if (verbose)
5864 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005865 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005866 return FAIL;
5867 }
5868 }
5869
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005870 return OK;
5871}
5872
5873 static int
5874conpty_term_and_job_init(
5875 term_T *term,
5876 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005877 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005878 jobopt_T *opt,
5879 jobopt_T *orig_opt)
5880{
5881 WCHAR *cmd_wchar = NULL;
5882 WCHAR *cmd_wchar_copy = NULL;
5883 WCHAR *cwd_wchar = NULL;
5884 WCHAR *env_wchar = NULL;
5885 channel_T *channel = NULL;
5886 job_T *job = NULL;
5887 HANDLE jo = NULL;
5888 garray_T ga_cmd, ga_env;
5889 char_u *cmd = NULL;
5890 HRESULT hr;
5891 COORD consize;
5892 SIZE_T breq;
5893 PROCESS_INFORMATION proc_info;
5894 HANDLE i_theirs = NULL;
5895 HANDLE o_theirs = NULL;
5896 HANDLE i_ours = NULL;
5897 HANDLE o_ours = NULL;
5898
5899 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5900 ga_init2(&ga_env, (int)sizeof(char*), 20);
5901
5902 if (argvar->v_type == VAR_STRING)
5903 {
5904 cmd = argvar->vval.v_string;
5905 }
5906 else if (argvar->v_type == VAR_LIST)
5907 {
5908 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5909 goto failed;
5910 cmd = ga_cmd.ga_data;
5911 }
5912 if (cmd == NULL || *cmd == NUL)
5913 {
5914 emsg(_(e_invarg));
5915 goto failed;
5916 }
5917
5918 term->tl_arg0_cmd = vim_strsave(cmd);
5919
5920 cmd_wchar = enc_to_utf16(cmd, NULL);
5921
5922 if (cmd_wchar != NULL)
5923 {
5924 /* Request by CreateProcessW */
5925 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005926 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005927 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5928 }
5929
5930 ga_clear(&ga_cmd);
5931 if (cmd_wchar == NULL)
5932 goto failed;
5933 if (opt->jo_cwd != NULL)
5934 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5935
5936 win32_build_env(opt->jo_env, &ga_env, TRUE);
5937 env_wchar = ga_env.ga_data;
5938
5939 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5940 goto failed;
5941 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5942 goto failed;
5943
5944 consize.X = term->tl_cols;
5945 consize.Y = term->tl_rows;
5946 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
5947 &term->tl_conpty);
5948 if (FAILED(hr))
5949 goto failed;
5950
5951 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
5952
5953 /* Set up pipe inheritance safely: Vista or later. */
5954 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005955 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005956 if (!term->tl_siex.lpAttributeList)
5957 goto failed;
5958 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
5959 0, &breq))
5960 goto failed;
5961 if (!pUpdateProcThreadAttribute(
5962 term->tl_siex.lpAttributeList, 0,
5963 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
5964 sizeof(HPCON), NULL, NULL))
5965 goto failed;
5966
5967 channel = add_channel();
5968 if (channel == NULL)
5969 goto failed;
5970
5971 job = job_alloc();
5972 if (job == NULL)
5973 goto failed;
5974 if (argvar->v_type == VAR_STRING)
5975 {
5976 int argc;
5977
5978 build_argv_from_string(cmd, &job->jv_argv, &argc);
5979 }
5980 else
5981 {
5982 int argc;
5983
5984 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5985 }
5986
5987 if (opt->jo_set & JO_IN_BUF)
5988 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5989
5990 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
5991 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
5992 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
5993 | CREATE_DEFAULT_ERROR_MODE,
5994 env_wchar, cwd_wchar,
5995 &term->tl_siex.StartupInfo, &proc_info))
5996 goto failed;
5997
5998 CloseHandle(i_theirs);
5999 CloseHandle(o_theirs);
6000
6001 channel_set_pipes(channel,
6002 (sock_T)i_ours,
6003 (sock_T)o_ours,
6004 (sock_T)o_ours);
6005
6006 /* Write lines with CR instead of NL. */
6007 channel->ch_write_text_mode = TRUE;
6008
6009 /* Use to explicitly delete anonymous pipe handle. */
6010 channel->ch_anonymous_pipe = TRUE;
6011
6012 jo = CreateJobObject(NULL, NULL);
6013 if (jo == NULL)
6014 goto failed;
6015
6016 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6017 {
6018 /* Failed, switch the way to terminate process with TerminateProcess. */
6019 CloseHandle(jo);
6020 jo = NULL;
6021 }
6022
6023 ResumeThread(proc_info.hThread);
6024 CloseHandle(proc_info.hThread);
6025
6026 vim_free(cmd_wchar);
6027 vim_free(cmd_wchar_copy);
6028 vim_free(cwd_wchar);
6029 vim_free(env_wchar);
6030
6031 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6032 goto failed;
6033
6034#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6035 if (opt->jo_set2 & JO2_ANSI_COLORS)
6036 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6037 else
6038 init_vterm_ansi_colors(term->tl_vterm);
6039#endif
6040
6041 channel_set_job(channel, job, opt);
6042 job_set_options(job, opt);
6043
6044 job->jv_channel = channel;
6045 job->jv_proc_info = proc_info;
6046 job->jv_job_object = jo;
6047 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006048 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006049 ++job->jv_refcount;
6050 term->tl_job = job;
6051
6052 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6053 * open the file here and handle it in. opt->jo_io was changed in
6054 * setup_job_options(), use the original flags here. */
6055 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6056 {
6057 char_u *fname = opt->jo_io_name[PART_OUT];
6058
6059 ch_log(channel, "Opening output file %s", fname);
6060 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6061 if (term->tl_out_fd == NULL)
6062 semsg(_(e_notopen), fname);
6063 }
6064
6065 return OK;
6066
6067failed:
6068 ga_clear(&ga_cmd);
6069 ga_clear(&ga_env);
6070 vim_free(cmd_wchar);
6071 vim_free(cmd_wchar_copy);
6072 vim_free(cwd_wchar);
6073 if (channel != NULL)
6074 channel_clear(channel);
6075 if (job != NULL)
6076 {
6077 job->jv_channel = NULL;
6078 job_cleanup(job);
6079 }
6080 term->tl_job = NULL;
6081 if (jo != NULL)
6082 CloseHandle(jo);
6083
6084 if (term->tl_siex.lpAttributeList != NULL)
6085 {
6086 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6087 vim_free(term->tl_siex.lpAttributeList);
6088 }
6089 term->tl_siex.lpAttributeList = NULL;
6090 if (o_theirs != NULL)
6091 CloseHandle(o_theirs);
6092 if (o_ours != NULL)
6093 CloseHandle(o_ours);
6094 if (i_ours != NULL)
6095 CloseHandle(i_ours);
6096 if (i_theirs != NULL)
6097 CloseHandle(i_theirs);
6098 if (term->tl_conpty != NULL)
6099 pClosePseudoConsole(term->tl_conpty);
6100 term->tl_conpty = NULL;
6101 return FAIL;
6102}
6103
6104 static void
6105conpty_term_report_winsize(term_T *term, int rows, int cols)
6106{
6107 COORD consize;
6108
6109 consize.X = cols;
6110 consize.Y = rows;
6111 pResizePseudoConsole(term->tl_conpty, consize);
6112}
6113
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006114 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006115term_free_conpty(term_T *term)
6116{
6117 if (term->tl_siex.lpAttributeList != NULL)
6118 {
6119 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6120 vim_free(term->tl_siex.lpAttributeList);
6121 }
6122 term->tl_siex.lpAttributeList = NULL;
6123 if (term->tl_conpty != NULL)
6124 pClosePseudoConsole(term->tl_conpty);
6125 term->tl_conpty = NULL;
6126}
6127
6128 int
6129use_conpty(void)
6130{
6131 return has_conpty;
6132}
6133
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006134# ifndef PROTO
6135
6136#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6137#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006138#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006139
6140void* (*winpty_config_new)(UINT64, void*);
6141void* (*winpty_open)(void*, void*);
6142void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6143BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6144void (*winpty_config_set_mouse_mode)(void*, int);
6145void (*winpty_config_set_initial_size)(void*, int, int);
6146LPCWSTR (*winpty_conin_name)(void*);
6147LPCWSTR (*winpty_conout_name)(void*);
6148LPCWSTR (*winpty_conerr_name)(void*);
6149void (*winpty_free)(void*);
6150void (*winpty_config_free)(void*);
6151void (*winpty_spawn_config_free)(void*);
6152void (*winpty_error_free)(void*);
6153LPCWSTR (*winpty_error_msg)(void*);
6154BOOL (*winpty_set_size)(void*, int, int, void*);
6155HANDLE (*winpty_agent_process)(void*);
6156
6157#define WINPTY_DLL "winpty.dll"
6158
6159static HINSTANCE hWinPtyDLL = NULL;
6160# endif
6161
6162 static int
6163dyn_winpty_init(int verbose)
6164{
6165 int i;
6166 static struct
6167 {
6168 char *name;
6169 FARPROC *ptr;
6170 } winpty_entry[] =
6171 {
6172 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6173 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6174 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6175 {"winpty_config_set_mouse_mode",
6176 (FARPROC*)&winpty_config_set_mouse_mode},
6177 {"winpty_config_set_initial_size",
6178 (FARPROC*)&winpty_config_set_initial_size},
6179 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6180 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6181 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6182 {"winpty_free", (FARPROC*)&winpty_free},
6183 {"winpty_open", (FARPROC*)&winpty_open},
6184 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6185 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6186 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6187 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6188 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6189 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6190 {NULL, NULL}
6191 };
6192
6193 /* No need to initialize twice. */
6194 if (hWinPtyDLL)
6195 return OK;
6196 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6197 * winpty.dll. */
6198 if (*p_winptydll != NUL)
6199 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6200 if (!hWinPtyDLL)
6201 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6202 if (!hWinPtyDLL)
6203 {
6204 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006205 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006206 : (char_u *)WINPTY_DLL);
6207 return FAIL;
6208 }
6209 for (i = 0; winpty_entry[i].name != NULL
6210 && winpty_entry[i].ptr != NULL; ++i)
6211 {
6212 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6213 winpty_entry[i].name)) == NULL)
6214 {
6215 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006216 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006217 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006218 return FAIL;
6219 }
6220 }
6221
6222 return OK;
6223}
6224
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006225 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006226winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006227 term_T *term,
6228 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006229 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006230 jobopt_T *opt,
6231 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006232{
6233 WCHAR *cmd_wchar = NULL;
6234 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006235 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006236 channel_T *channel = NULL;
6237 job_T *job = NULL;
6238 DWORD error;
6239 HANDLE jo = NULL;
6240 HANDLE child_process_handle;
6241 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006242 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006243 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006244 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006245 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006246
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006247 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6248 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006249
6250 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006251 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006252 cmd = argvar->vval.v_string;
6253 }
6254 else if (argvar->v_type == VAR_LIST)
6255 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006256 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006257 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006258 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006259 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006260 if (cmd == NULL || *cmd == NUL)
6261 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006262 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006263 goto failed;
6264 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006265
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006266 term->tl_arg0_cmd = vim_strsave(cmd);
6267
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006268 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006269 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006270 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006271 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006272 if (opt->jo_cwd != NULL)
6273 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006274
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006275 win32_build_env(opt->jo_env, &ga_env, TRUE);
6276 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006277
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006278 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6279 if (term->tl_winpty_config == NULL)
6280 goto failed;
6281
6282 winpty_config_set_mouse_mode(term->tl_winpty_config,
6283 WINPTY_MOUSE_MODE_FORCE);
6284 winpty_config_set_initial_size(term->tl_winpty_config,
6285 term->tl_cols, term->tl_rows);
6286 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6287 if (term->tl_winpty == NULL)
6288 goto failed;
6289
6290 spawn_config = winpty_spawn_config_new(
6291 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6292 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6293 NULL,
6294 cmd_wchar,
6295 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006296 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006297 &winpty_err);
6298 if (spawn_config == NULL)
6299 goto failed;
6300
6301 channel = add_channel();
6302 if (channel == NULL)
6303 goto failed;
6304
6305 job = job_alloc();
6306 if (job == NULL)
6307 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006308 if (argvar->v_type == VAR_STRING)
6309 {
6310 int argc;
6311
6312 build_argv_from_string(cmd, &job->jv_argv, &argc);
6313 }
6314 else
6315 {
6316 int argc;
6317
6318 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6319 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006320
6321 if (opt->jo_set & JO_IN_BUF)
6322 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6323
6324 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6325 &child_thread_handle, &error, &winpty_err))
6326 goto failed;
6327
6328 channel_set_pipes(channel,
6329 (sock_T)CreateFileW(
6330 winpty_conin_name(term->tl_winpty),
6331 GENERIC_WRITE, 0, NULL,
6332 OPEN_EXISTING, 0, NULL),
6333 (sock_T)CreateFileW(
6334 winpty_conout_name(term->tl_winpty),
6335 GENERIC_READ, 0, NULL,
6336 OPEN_EXISTING, 0, NULL),
6337 (sock_T)CreateFileW(
6338 winpty_conerr_name(term->tl_winpty),
6339 GENERIC_READ, 0, NULL,
6340 OPEN_EXISTING, 0, NULL));
6341
6342 /* Write lines with CR instead of NL. */
6343 channel->ch_write_text_mode = TRUE;
6344
6345 jo = CreateJobObject(NULL, NULL);
6346 if (jo == NULL)
6347 goto failed;
6348
6349 if (!AssignProcessToJobObject(jo, child_process_handle))
6350 {
6351 /* Failed, switch the way to terminate process with TerminateProcess. */
6352 CloseHandle(jo);
6353 jo = NULL;
6354 }
6355
6356 winpty_spawn_config_free(spawn_config);
6357 vim_free(cmd_wchar);
6358 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006359 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006360
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006361 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6362 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006363
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006364#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6365 if (opt->jo_set2 & JO2_ANSI_COLORS)
6366 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6367 else
6368 init_vterm_ansi_colors(term->tl_vterm);
6369#endif
6370
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006371 channel_set_job(channel, job, opt);
6372 job_set_options(job, opt);
6373
6374 job->jv_channel = channel;
6375 job->jv_proc_info.hProcess = child_process_handle;
6376 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6377 job->jv_job_object = jo;
6378 job->jv_status = JOB_STARTED;
6379 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006380 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006381 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006382 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006383 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006384 ++job->jv_refcount;
6385 term->tl_job = job;
6386
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006387 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6388 * open the file here and handle it in. opt->jo_io was changed in
6389 * setup_job_options(), use the original flags here. */
6390 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6391 {
6392 char_u *fname = opt->jo_io_name[PART_OUT];
6393
6394 ch_log(channel, "Opening output file %s", fname);
6395 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6396 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006397 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006398 }
6399
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006400 return OK;
6401
6402failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006403 ga_clear(&ga_cmd);
6404 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006405 vim_free(cmd_wchar);
6406 vim_free(cwd_wchar);
6407 if (spawn_config != NULL)
6408 winpty_spawn_config_free(spawn_config);
6409 if (channel != NULL)
6410 channel_clear(channel);
6411 if (job != NULL)
6412 {
6413 job->jv_channel = NULL;
6414 job_cleanup(job);
6415 }
6416 term->tl_job = NULL;
6417 if (jo != NULL)
6418 CloseHandle(jo);
6419 if (term->tl_winpty != NULL)
6420 winpty_free(term->tl_winpty);
6421 term->tl_winpty = NULL;
6422 if (term->tl_winpty_config != NULL)
6423 winpty_config_free(term->tl_winpty_config);
6424 term->tl_winpty_config = NULL;
6425 if (winpty_err != NULL)
6426 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006427 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006428 (short_u *)winpty_error_msg(winpty_err), NULL);
6429
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006430 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006431 winpty_error_free(winpty_err);
6432 }
6433 return FAIL;
6434}
6435
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006436/*
6437 * Create a new terminal of "rows" by "cols" cells.
6438 * Store a reference in "term".
6439 * Return OK or FAIL.
6440 */
6441 static int
6442term_and_job_init(
6443 term_T *term,
6444 typval_T *argvar,
6445 char **argv UNUSED,
6446 jobopt_T *opt,
6447 jobopt_T *orig_opt)
6448{
6449 int use_winpty = FALSE;
6450 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006451 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006452
6453 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6454 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6455
6456 if (!has_winpty && !has_conpty)
6457 // If neither is available give the errors for winpty, since when
6458 // conpty is not available it can't be installed either.
6459 return dyn_winpty_init(TRUE);
6460
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006461 if (opt->jo_tty_type != NUL)
6462 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006463
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006464 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006465 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006466 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006467 use_conpty = TRUE;
6468 else if (has_winpty)
6469 use_winpty = TRUE;
6470 // else: error
6471 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006472 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006473 {
6474 if (has_winpty)
6475 use_winpty = TRUE;
6476 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006477 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006478 {
6479 if (has_conpty)
6480 use_conpty = TRUE;
6481 else
6482 return dyn_conpty_init(TRUE);
6483 }
6484
6485 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006486 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006487
6488 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006489 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006490
6491 // error
6492 return dyn_winpty_init(TRUE);
6493}
6494
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006495 static int
6496create_pty_only(term_T *term, jobopt_T *options)
6497{
6498 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6499 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6500 char in_name[80], out_name[80];
6501 channel_T *channel = NULL;
6502
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006503 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6504 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006505
6506 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6507 GetCurrentProcessId(),
6508 curbuf->b_fnum);
6509 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6510 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6511 PIPE_UNLIMITED_INSTANCES,
6512 0, 0, NMPWAIT_NOWAIT, NULL);
6513 if (hPipeIn == INVALID_HANDLE_VALUE)
6514 goto failed;
6515
6516 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6517 GetCurrentProcessId(),
6518 curbuf->b_fnum);
6519 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6520 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6521 PIPE_UNLIMITED_INSTANCES,
6522 0, 0, 0, NULL);
6523 if (hPipeOut == INVALID_HANDLE_VALUE)
6524 goto failed;
6525
6526 ConnectNamedPipe(hPipeIn, NULL);
6527 ConnectNamedPipe(hPipeOut, NULL);
6528
6529 term->tl_job = job_alloc();
6530 if (term->tl_job == NULL)
6531 goto failed;
6532 ++term->tl_job->jv_refcount;
6533
6534 /* behave like the job is already finished */
6535 term->tl_job->jv_status = JOB_FINISHED;
6536
6537 channel = add_channel();
6538 if (channel == NULL)
6539 goto failed;
6540 term->tl_job->jv_channel = channel;
6541 channel->ch_keep_open = TRUE;
6542 channel->ch_named_pipe = TRUE;
6543
6544 channel_set_pipes(channel,
6545 (sock_T)hPipeIn,
6546 (sock_T)hPipeOut,
6547 (sock_T)hPipeOut);
6548 channel_set_job(channel, term->tl_job, options);
6549 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6550 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6551
6552 return OK;
6553
6554failed:
6555 if (hPipeIn != NULL)
6556 CloseHandle(hPipeIn);
6557 if (hPipeOut != NULL)
6558 CloseHandle(hPipeOut);
6559 return FAIL;
6560}
6561
6562/*
6563 * Free the terminal emulator part of "term".
6564 */
6565 static void
6566term_free_vterm(term_T *term)
6567{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006568 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006569 if (term->tl_winpty != NULL)
6570 winpty_free(term->tl_winpty);
6571 term->tl_winpty = NULL;
6572 if (term->tl_winpty_config != NULL)
6573 winpty_config_free(term->tl_winpty_config);
6574 term->tl_winpty_config = NULL;
6575 if (term->tl_vterm != NULL)
6576 vterm_free(term->tl_vterm);
6577 term->tl_vterm = NULL;
6578}
6579
6580/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006581 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006582 */
6583 static void
6584term_report_winsize(term_T *term, int rows, int cols)
6585{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006586 if (term->tl_conpty)
6587 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006588 if (term->tl_winpty)
6589 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6590}
6591
6592 int
6593terminal_enabled(void)
6594{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006595 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006596}
6597
6598# else
6599
6600/**************************************
6601 * 3. Unix-like implementation.
6602 */
6603
6604/*
6605 * Create a new terminal of "rows" by "cols" cells.
6606 * Start job for "cmd".
6607 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006608 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006609 * Return OK or FAIL.
6610 */
6611 static int
6612term_and_job_init(
6613 term_T *term,
6614 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006615 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006616 jobopt_T *opt,
6617 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006618{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006619 term->tl_arg0_cmd = NULL;
6620
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006621 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6622 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006623
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006624#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6625 if (opt->jo_set2 & JO2_ANSI_COLORS)
6626 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6627 else
6628 init_vterm_ansi_colors(term->tl_vterm);
6629#endif
6630
Bram Moolenaar13568252018-03-16 20:46:58 +01006631 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006632 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006633 if (term->tl_job != NULL)
6634 ++term->tl_job->jv_refcount;
6635
6636 return term->tl_job != NULL
6637 && term->tl_job->jv_channel != NULL
6638 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6639}
6640
6641 static int
6642create_pty_only(term_T *term, jobopt_T *opt)
6643{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006644 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6645 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006646
6647 term->tl_job = job_alloc();
6648 if (term->tl_job == NULL)
6649 return FAIL;
6650 ++term->tl_job->jv_refcount;
6651
6652 /* behave like the job is already finished */
6653 term->tl_job->jv_status = JOB_FINISHED;
6654
6655 return mch_create_pty_channel(term->tl_job, opt);
6656}
6657
6658/*
6659 * Free the terminal emulator part of "term".
6660 */
6661 static void
6662term_free_vterm(term_T *term)
6663{
6664 if (term->tl_vterm != NULL)
6665 vterm_free(term->tl_vterm);
6666 term->tl_vterm = NULL;
6667}
6668
6669/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006670 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006671 */
6672 static void
6673term_report_winsize(term_T *term, int rows, int cols)
6674{
6675 /* Use an ioctl() to report the new window size to the job. */
6676 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6677 {
6678 int fd = -1;
6679 int part;
6680
6681 for (part = PART_OUT; part < PART_COUNT; ++part)
6682 {
6683 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006684 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006685 break;
6686 }
6687 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6688 mch_signal_job(term->tl_job, (char_u *)"winch");
6689 }
6690}
6691
6692# endif
6693
6694#endif /* FEAT_TERMINAL */