blob: d974c11322e17ea454b1176930ffa5ad342686da [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
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010054// This is VTermScreenCell without the characters, thus much smaller.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055typedef 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 Moolenaar0d6f5d92019-12-05 21:33:15 +010086// typedef term_T in structs.h
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020087struct 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)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010094 int tl_system; // when non-zero used for :!cmd output
95 int tl_toprow; // row with first line of system terminal
Bram Moolenaar13568252018-03-16 20:46:58 +010096#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010098 // Set when setting the size of a vterm, reset after redrawing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020099 int tl_vterm_size_changed;
100
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100101 int tl_normal_mode; // TRUE: Terminal-Normal mode
Bram Moolenaareea32af2021-11-21 14:51:13 +0000102 int tl_channel_closing;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200103 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200104 int tl_channel_recently_closed; // still need to handle tl_finish
105
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100106 int tl_finish;
107#define TL_FINISH_UNSET NUL
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100108#define TL_FINISH_CLOSE 'c' // ++close or :terminal without argument
109#define TL_FINISH_NOCLOSE 'n' // ++noclose
110#define TL_FINISH_OPEN 'o' // ++open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200111 char_u *tl_opencmd;
112 char_u *tl_eof_chars;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200113 char_u *tl_api; // prefix for terminal API function
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200114
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100115 char_u *tl_arg0_cmd; // To format the status bar
116
Bram Moolenaar4f974752019-02-17 17:44:42 +0100117#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200118 void *tl_winpty_config;
119 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200120
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100121 HPCON tl_conpty;
122 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
123
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200124 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200125#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100126#if defined(FEAT_SESSION)
127 char_u *tl_command;
128#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100129 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100131 // last known vterm size
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200132 int tl_rows;
133 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200134
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100135 char_u *tl_title; // NULL or allocated
136 char_u *tl_status_text; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200137
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100138 // Range of screen rows to update. Zero based.
139 int tl_dirty_row_start; // MAX_ROW if nothing dirty
140 int tl_dirty_row_end; // row below last one to update
141 int tl_dirty_snapshot; // text updated after making snapshot
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200142#ifdef FEAT_TIMERS
143 int tl_timer_set;
144 proftime_T tl_timer_due;
145#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100146 int tl_postponed_scroll; // to be scrolled up
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200148 garray_T tl_scrollback;
149 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100150 garray_T tl_scrollback_postponed;
151
Bram Moolenaar83d47902020-03-26 20:34:00 +0100152 char_u *tl_highlight_name; // replaces "Terminal"; allocated
153
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200154 cellattr_T tl_default_color;
155
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100156 linenr_T tl_top_diff_rows; // rows of top diff file or zero
157 linenr_T tl_bot_diff_rows; // rows of bottom diff file
Bram Moolenaard96ff162018-02-18 22:13:29 +0100158
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200159 VTermPos tl_cursor_pos;
160 int tl_cursor_visible;
161 int tl_cursor_blink;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100162 int tl_cursor_shape; // 1: block, 2: underline, 3: bar
163 char_u *tl_cursor_color; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200164
165 int tl_using_altscreen;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200166 garray_T tl_osc_buf; // incomplete OSC string
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167};
168
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100169#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
170#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200171
172/*
173 * List of all active terminals.
174 */
175static term_T *first_term = NULL;
176
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100177// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200178static term_T *in_terminal_loop = NULL;
179
Bram Moolenaar4f974752019-02-17 17:44:42 +0100180#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100181static BOOL has_winpty = FALSE;
182static BOOL has_conpty = FALSE;
183#endif
184
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100185#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200186#define KEY_BUF_LEN 200
187
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200188#define FOR_ALL_TERMS(term) \
189 for ((term) = first_term; (term) != NULL; (term) = (term)->tl_next)
190
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200191/*
192 * Functions with separate implementation for MS-Windows and Unix-like systems.
193 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200194static 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 +0200195static int create_pty_only(term_T *term, jobopt_T *opt);
196static void term_report_winsize(term_T *term, int rows, int cols);
197static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100198#ifdef FEAT_GUI
199static void update_system_term(term_T *term);
200#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200201
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100202static void handle_postponed_scrollback(term_T *term);
203
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100204// The character that we know (or assume) that the terminal expects for the
205// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200206static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200207
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100208// Store the last set and the desired cursor properties, so that we only update
209// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200210static char_u *last_set_cursor_color = NULL;
211static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100212static int last_set_cursor_shape = -1;
213static int desired_cursor_shape = -1;
214static int last_set_cursor_blink = -1;
215static int desired_cursor_blink = -1;
216
217
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100218///////////////////////////////////////
219// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200220
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200221 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200222cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
223{
224 if (lhs_color != NULL && rhs_color != NULL)
225 return STRCMP(lhs_color, rhs_color) == 0;
226 return lhs_color == NULL && rhs_color == NULL;
227}
228
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200229 static void
230cursor_color_copy(char_u **to_color, char_u *from_color)
231{
232 // Avoid a free & alloc if the value is already right.
233 if (cursor_color_equal(*to_color, from_color))
234 return;
235 vim_free(*to_color);
236 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
237}
238
239 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200240cursor_color_get(char_u *color)
241{
242 return (color == NULL) ? (char_u *)"" : color;
243}
244
245
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200246/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200247 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200248 * current window.
249 * Sets "rows" and/or "cols" to zero when it should follow the window size.
250 * Return TRUE if the size is the minimum size: "24*80".
251 */
252 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200253parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200254{
255 int minsize = FALSE;
256
257 *rows = 0;
258 *cols = 0;
259
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200260 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200261 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200262 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200263
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100264 // Syntax of value was already checked when it's set.
Bram Moolenaar498c2562018-04-15 23:45:15 +0200265 if (p == NULL)
266 {
267 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200268 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200269 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200270 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200271 *cols = atoi((char *)p + 1);
272 }
273 return minsize;
274}
275
276/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200277 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200278 */
279 static void
Bram Moolenaarb936b792020-09-04 18:34:09 +0200280set_term_and_win_size(term_T *term, jobopt_T *opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200281{
Bram Moolenaarb936b792020-09-04 18:34:09 +0200282 int rows, cols;
283 int minsize;
284
Bram Moolenaar13568252018-03-16 20:46:58 +0100285#ifdef FEAT_GUI
286 if (term->tl_system)
287 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100288 // Use the whole screen for the system command. However, it will start
289 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100290 term->tl_rows = Rows;
291 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200292 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100293 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100294#endif
Bram Moolenaarb936b792020-09-04 18:34:09 +0200295 term->tl_rows = curwin->w_height;
296 term->tl_cols = curwin->w_width;
297
298 minsize = parse_termwinsize(curwin, &rows, &cols);
299 if (minsize)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 {
Bram Moolenaarb936b792020-09-04 18:34:09 +0200301 if (term->tl_rows < rows)
302 term->tl_rows = rows;
303 if (term->tl_cols < cols)
304 term->tl_cols = cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200305 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200306 if ((opt->jo_set2 & JO2_TERM_ROWS))
307 term->tl_rows = opt->jo_term_rows;
308 else if (rows != 0)
309 term->tl_rows = rows;
310 if ((opt->jo_set2 & JO2_TERM_COLS))
311 term->tl_cols = opt->jo_term_cols;
312 else if (cols != 0)
313 term->tl_cols = cols;
314
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200315 if (!opt->jo_hidden)
Bram Moolenaarb936b792020-09-04 18:34:09 +0200316 {
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200317 if (term->tl_rows != curwin->w_height)
318 win_setheight_win(term->tl_rows, curwin);
319 if (term->tl_cols != curwin->w_width)
320 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaarb936b792020-09-04 18:34:09 +0200321
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200322 // Set 'winsize' now to avoid a resize at the next redraw.
323 if (!minsize && *curwin->w_p_tws != NUL)
324 {
325 char_u buf[100];
326
327 vim_snprintf((char *)buf, 100, "%dx%d",
328 term->tl_rows, term->tl_cols);
329 set_option_value((char_u *)"termwinsize", 0L, buf, OPT_LOCAL);
330 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200331 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200332}
333
334/*
335 * Initialize job options for a terminal job.
336 * Caller may overrule some of them.
337 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100338 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200339init_job_options(jobopt_T *opt)
340{
341 clear_job_options(opt);
342
343 opt->jo_mode = MODE_RAW;
344 opt->jo_out_mode = MODE_RAW;
345 opt->jo_err_mode = MODE_RAW;
346 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
347}
348
349/*
350 * Set job options mandatory for a terminal job.
351 */
352 static void
353setup_job_options(jobopt_T *opt, int rows, int cols)
354{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100355#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100356 // Win32: Redirecting the job output won't work, thus always connect stdout
357 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200358 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200359#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200360 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100361 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200362 opt->jo_io[PART_OUT] = JIO_BUFFER;
363 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
364 opt->jo_modifiable[PART_OUT] = 0;
365 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
366 }
367
Bram Moolenaar4f974752019-02-17 17:44:42 +0100368#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100369 // Win32: Redirecting the job output won't work, thus always connect stderr
370 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200371 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200372#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200373 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100374 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200375 opt->jo_io[PART_ERR] = JIO_BUFFER;
376 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
377 opt->jo_modifiable[PART_ERR] = 0;
378 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
379 }
380
381 opt->jo_pty = TRUE;
382 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
383 opt->jo_term_rows = rows;
384 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
385 opt->jo_term_cols = cols;
386}
387
388/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200389 * Flush messages on channels.
390 */
391 static void
392term_flush_messages()
393{
394 mch_check_messages();
395 parse_queued_messages();
396}
397
398/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100399 * Close a terminal buffer (and its window). Used when creating the terminal
400 * fails.
401 */
402 static void
403term_close_buffer(buf_T *buf, buf_T *old_curbuf)
404{
405 free_terminal(buf);
406 if (old_curbuf != NULL)
407 {
408 --curbuf->b_nwindows;
409 curbuf = old_curbuf;
410 curwin->w_buffer = curbuf;
411 ++curbuf->b_nwindows;
412 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100413 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100414
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100415 // Wiping out the buffer will also close the window and call
416 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100417 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
418}
419
420/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200421 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100422 * Use either "argvar" or "argv", the other must be NULL.
423 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
424 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200425 * Returns NULL when failed.
426 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100427 buf_T *
428term_start(
429 typval_T *argvar,
430 char **argv,
431 jobopt_T *opt,
432 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200433{
434 exarg_T split_ea;
435 win_T *old_curwin = curwin;
436 term_T *term;
437 buf_T *old_curbuf = NULL;
438 int res;
439 buf_T *newbuf;
Bram Moolenaare1004402020-10-24 20:49:43 +0200440 int vertical = opt->jo_vertical || (cmdmod.cmod_split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200441 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200442
443 if (check_restricted() || check_secure())
444 return NULL;
Bram Moolenaare5b44862021-05-30 13:54:03 +0200445#ifdef FEAT_CMDWIN
446 if (cmdwin_type != 0)
447 {
448 emsg(_(e_cannot_open_terminal_from_command_line_window));
449 return NULL;
450 }
451#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200452
453 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
454 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
455 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100456 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
457 || (argvar != NULL
458 && argvar->v_type == VAR_LIST
459 && argvar->vval.v_list != NULL
460 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200461 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000462 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200463 return NULL;
464 }
465
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200466 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200467 if (term == NULL)
468 return NULL;
469 term->tl_dirty_row_end = MAX_ROW;
470 term->tl_cursor_visible = TRUE;
471 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
472 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100473#ifdef FEAT_GUI
474 term->tl_system = (flags & TERM_START_SYSTEM);
475#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200476 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100477 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200478 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200479
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200480 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200481 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200482 if (opt->jo_curwin)
483 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100484 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100485 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200486 {
487 no_write_message();
488 vim_free(term);
489 return NULL;
490 }
491 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200492 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
493 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
494 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200495 {
496 vim_free(term);
497 return NULL;
498 }
499 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100500 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200501 {
502 buf_T *buf;
503
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100504 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100505 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200506 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
507 BLN_NEW | BLN_LISTED);
508 if (buf == NULL || ml_open(buf) == FAIL)
509 {
510 vim_free(term);
511 return NULL;
512 }
513 old_curbuf = curbuf;
514 --curbuf->b_nwindows;
515 curbuf = buf;
516 curwin->w_buffer = buf;
517 ++curbuf->b_nwindows;
518 }
519 else
520 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100521 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200522 split_ea.cmdidx = CMD_new;
523 split_ea.cmd = (char_u *)"new";
524 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100525 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200526 {
527 split_ea.line2 = opt->jo_term_rows;
528 split_ea.addr_count = 1;
529 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100530 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200531 {
532 split_ea.line2 = opt->jo_term_cols;
533 split_ea.addr_count = 1;
534 }
535
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100536 if (vertical)
Bram Moolenaare1004402020-10-24 20:49:43 +0200537 cmdmod.cmod_split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200538 ex_splitview(&split_ea);
539 if (curwin == old_curwin)
540 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100541 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200542 vim_free(term);
543 return NULL;
544 }
545 }
546 term->tl_buffer = curbuf;
547 curbuf->b_term = term;
548
549 if (!opt->jo_hidden)
550 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100551 // Only one size was taken care of with :new, do the other one. With
552 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100553 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200554 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100555 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200556 win_setwidth(opt->jo_term_cols);
557 }
558
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100559 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200560 term->tl_next = first_term;
561 first_term = term;
562
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100563 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
564
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200565 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100566 {
567 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100569 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100570 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100571 {
572 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100573 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100574 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200575 else
576 {
577 int i;
578 size_t len;
579 char_u *cmd, *p;
580
581 if (argvar->v_type == VAR_STRING)
582 {
583 cmd = argvar->vval.v_string;
584 if (cmd == NULL)
585 cmd = (char_u *)"";
586 else if (STRCMP(cmd, "NONE") == 0)
587 cmd = (char_u *)"pty";
588 }
589 else if (argvar->v_type != VAR_LIST
590 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100591 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100592 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200593 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
594 cmd = (char_u*)"";
595
596 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200597 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200598
599 for (i = 0; p != NULL; ++i)
600 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100601 // Prepend a ! to the command name to avoid the buffer name equals
602 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200603 if (i == 0)
604 vim_snprintf((char *)p, len, "!%s", cmd);
605 else
606 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
607 if (buflist_findname(p) == NULL)
608 {
609 vim_free(curbuf->b_ffname);
610 curbuf->b_ffname = p;
611 break;
612 }
613 }
614 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100615 vim_free(curbuf->b_sfname);
616 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200617 curbuf->b_fname = curbuf->b_ffname;
618
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100619 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
620
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200621 if (opt->jo_term_opencmd != NULL)
622 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
623
624 if (opt->jo_eof_chars != NULL)
625 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
626
627 set_string_option_direct((char_u *)"buftype", -1,
628 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200629 // Avoid that 'buftype' is reset when this buffer is entered.
630 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200631
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100632 // Mark the buffer as not modifiable. It can only be made modifiable after
633 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200634 curbuf->b_p_ma = FALSE;
635
Bram Moolenaarb936b792020-09-04 18:34:09 +0200636 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100637#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200638 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
639#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200640 setup_job_options(opt, term->tl_rows, term->tl_cols);
641
Bram Moolenaar13568252018-03-16 20:46:58 +0100642 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100643 return curbuf;
644
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100645#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100646 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100647 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100648 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100649 else if (argvar->v_type == VAR_STRING)
650 {
651 char_u *cmd = argvar->vval.v_string;
652
653 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
654 term->tl_command = vim_strsave(cmd);
655 }
656 else if (argvar->v_type == VAR_LIST
657 && argvar->vval.v_list != NULL
658 && argvar->vval.v_list->lv_len > 0)
659 {
660 garray_T ga;
661 listitem_T *item;
662
663 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200664 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100665 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100666 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100667 char_u *p;
668
669 if (s == NULL)
670 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100671 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100672 if (p == NULL)
673 break;
674 ga_concat(&ga, p);
675 vim_free(p);
676 ga_append(&ga, ' ');
677 }
678 if (item == NULL)
679 {
680 ga_append(&ga, NUL);
681 term->tl_command = ga.ga_data;
682 }
683 else
684 ga_clear(&ga);
685 }
686#endif
687
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100688 if (opt->jo_term_kill != NULL)
689 {
690 char_u *p = skiptowhite(opt->jo_term_kill);
691
692 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
693 }
694
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200695 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100696 {
697 char_u *p = skiptowhite(opt->jo_term_api);
698
699 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
700 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200701 else
702 term->tl_api = vim_strsave((char_u *)"Tapi_");
703
Bram Moolenaar83d47902020-03-26 20:34:00 +0100704 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
705 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
706
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100707 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100708 if (argv == NULL
709 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200710 && argvar->vval.v_string != NULL
711 && STRCMP(argvar->vval.v_string, "NONE") == 0)
712 res = create_pty_only(term, opt);
713 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200714 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200715
716 newbuf = curbuf;
717 if (res == OK)
718 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100719 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200720 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
721 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100722#ifdef FEAT_GUI
723 if (term->tl_system)
724 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100725 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100726 term->tl_toprow = msg_row + 1;
727 term->tl_dirty_row_end = 0;
728 }
729#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200730
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100731 // Make sure we don't get stuck on sending keys to the job, it leads to
732 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200733 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
734
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200735 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200736 {
737 --curbuf->b_nwindows;
738 curbuf = old_curbuf;
739 curwin->w_buffer = curbuf;
740 ++curbuf->b_nwindows;
741 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000742 else if (vgetc_busy
743#ifdef FEAT_TIMERS
744 || timer_busy
745#endif
746 || input_busy)
747 {
748 char_u ignore[4];
749
750 // When waiting for input need to return and possibly end up in
751 // terminal_loop() instead.
752 ignore[0] = K_SPECIAL;
753 ignore[1] = KS_EXTRA;
754 ignore[2] = KE_IGNORE;
755 ignore[3] = NUL;
756 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
757 typebuf_was_filled = TRUE;
758 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200759 }
760 else
761 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100762 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200763 return NULL;
764 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100765
Bram Moolenaar13568252018-03-16 20:46:58 +0100766 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200767 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
768 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200769 return newbuf;
770}
771
772/*
773 * ":terminal": open a terminal window and execute a job in it.
774 */
775 void
776ex_terminal(exarg_T *eap)
777{
778 typval_T argvar[2];
779 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100780 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200781 char_u *cmd;
782 char_u *tofree = NULL;
783
784 init_job_options(&opt);
785
786 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100787 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788 {
789 char_u *p, *ep;
790
791 cmd += 2;
792 p = skiptowhite(cmd);
793 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200794 if (ep != NULL)
795 {
796 if (ep < p)
797 p = ep;
798 else
799 ep = NULL;
800 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200801
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200802# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
803 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
804 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200805 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200806 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100807 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200808 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200809 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200810 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200811 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200812 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200813 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200814 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100815 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100816 else if (OPTARG_HAS("shell"))
817 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200818 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100819 {
820 opt.jo_set2 |= JO2_TERM_KILL;
821 opt.jo_term_kill = ep + 1;
822 p = skiptowhite(cmd);
823 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200824 else if (OPTARG_HAS("api"))
825 {
826 opt.jo_set2 |= JO2_TERM_API;
827 if (ep != NULL)
828 {
829 opt.jo_term_api = ep + 1;
830 p = skiptowhite(cmd);
831 }
832 else
833 opt.jo_term_api = NULL;
834 }
835 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200836 {
837 opt.jo_set2 |= JO2_TERM_ROWS;
838 opt.jo_term_rows = atoi((char *)ep + 1);
839 p = skiptowhite(cmd);
840 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200841 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200842 {
843 opt.jo_set2 |= JO2_TERM_COLS;
844 opt.jo_term_cols = atoi((char *)ep + 1);
845 p = skiptowhite(cmd);
846 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200847 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200848 {
849 char_u *buf = NULL;
850 char_u *keys;
851
Bram Moolenaar21109272020-01-30 16:27:20 +0100852 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200853 p = skiptowhite(cmd);
854 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200855 keys = replace_termcodes(ep + 1, &buf,
856 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200857 opt.jo_set2 |= JO2_EOF_CHARS;
858 opt.jo_eof_chars = vim_strsave(keys);
859 vim_free(buf);
860 *p = ' ';
861 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100862#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100863 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
864 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100865 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100866 int tty_type = NUL;
867
868 p = skiptowhite(cmd);
869 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
870 tty_type = 'w';
871 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
872 tty_type = 'c';
873 else
874 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000875 semsg(e_invalid_value_for_argument_str, "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100876 goto theend;
877 }
878 opt.jo_set2 |= JO2_TTY_TYPE;
879 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100880 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100881#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200882 else
883 {
884 if (*p)
885 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100886 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100887 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200888 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200889# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200890 cmd = skipwhite(p);
891 }
892 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100893 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100894 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200895 tofree = cmd = vim_strsave(p_sh);
896
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100897 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100898 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200899 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100900 }
901
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200902 if (eap->addr_count > 0)
903 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100904 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200905 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
906 opt.jo_io[PART_IN] = JIO_BUFFER;
907 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
908 opt.jo_in_top = eap->line1;
909 opt.jo_in_bot = eap->line2;
910 }
911
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100912 if (opt_shell && tofree == NULL)
913 {
914#ifdef UNIX
915 char **argv = NULL;
916 char_u *tofree1 = NULL;
917 char_u *tofree2 = NULL;
918
919 // :term ++shell command
920 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
921 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100922 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100923 vim_free(tofree1);
924 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100925 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100926#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100927# ifdef MSWIN
928 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
929 char_u *newcmd;
930
931 newcmd = alloc(cmdlen);
932 if (newcmd == NULL)
933 goto theend;
934 tofree = newcmd;
935 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
936 cmd = newcmd;
937# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000938 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100939 goto theend;
940# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100941#endif
942 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100943 argvar[0].v_type = VAR_STRING;
944 argvar[0].vval.v_string = cmd;
945 argvar[1].v_type = VAR_UNKNOWN;
946 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100947
948theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100949 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200950 vim_free(opt.jo_eof_chars);
951}
952
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100953#if defined(FEAT_SESSION) || defined(PROTO)
954/*
955 * Write a :terminal command to the session file to restore the terminal in
956 * window "wp".
957 * Return FAIL if writing fails.
958 */
959 int
Bram Moolenaar0e655112020-09-11 20:36:36 +0200960term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100961{
Bram Moolenaar0e655112020-09-11 20:36:36 +0200962 const int bufnr = wp->w_buffer->b_fnum;
963 term_T *term = wp->w_buffer->b_term;
964
Bram Moolenaarc2c82052020-09-11 22:10:22 +0200965 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +0200966 {
967 // There are multiple views into this terminal buffer. We don't want to
968 // create the terminal multiple times. If it's the first time, create,
969 // otherwise link to the first buffer.
970 char id_as_str[NUMBUFLEN];
971 hashitem_T *entry;
972
973 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
974
975 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
976 if (!HASHITEM_EMPTY(entry))
977 {
978 // we've already opened this terminal buffer
979 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
980 return FAIL;
981 return put_eol(fd);
982 }
983 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100984
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100985 // Create the terminal and run the command. This is not without
986 // risk, but let's assume the user only creates a session when this
987 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100988 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
989 term->tl_cols, term->tl_rows) < 0)
990 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100991#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100992 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
993 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100994#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100995 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
996 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +0200997 if (put_eol(fd) != OK)
998 return FAIL;
999
1000 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1001 return FAIL;
1002
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001003 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001004 {
1005 char *hash_key = alloc(NUMBUFLEN);
1006
1007 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
1008 hash_add(terminal_bufs, (char_u *)hash_key);
1009 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001010
1011 return put_eol(fd);
1012}
1013
1014/*
1015 * Return TRUE if "buf" has a terminal that should be restored.
1016 */
1017 int
1018term_should_restore(buf_T *buf)
1019{
1020 term_T *term = buf->b_term;
1021
1022 return term != NULL && (term->tl_command == NULL
1023 || STRCMP(term->tl_command, "NONE") != 0);
1024}
1025#endif
1026
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001027/*
1028 * Free the scrollback buffer for "term".
1029 */
1030 static void
1031free_scrollback(term_T *term)
1032{
1033 int i;
1034
1035 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1036 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1037 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001038 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1039 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1040 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001041}
1042
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001043
1044// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001045static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001046
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001047/*
1048 * Free a terminal and everything it refers to.
1049 * Kills the job if there is one.
1050 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001051 * The actual terminal structure is freed later in free_unused_terminals(),
1052 * because callbacks may wipe out a buffer while the terminal is still
1053 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001054 */
1055 void
1056free_terminal(buf_T *buf)
1057{
1058 term_T *term = buf->b_term;
1059 term_T *tp;
1060
1061 if (term == NULL)
1062 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001063
1064 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001065 if (first_term == term)
1066 first_term = term->tl_next;
1067 else
1068 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1069 if (tp->tl_next == term)
1070 {
1071 tp->tl_next = term->tl_next;
1072 break;
1073 }
1074
1075 if (term->tl_job != NULL)
1076 {
1077 if (term->tl_job->jv_status != JOB_ENDED
1078 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001079 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001080 job_stop(term->tl_job, NULL, "kill");
1081 job_unref(term->tl_job);
1082 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001083 term->tl_next = terminals_to_free;
1084 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001085
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001086 buf->b_term = NULL;
1087 if (in_terminal_loop == term)
1088 in_terminal_loop = NULL;
1089}
1090
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001091 void
1092free_unused_terminals()
1093{
1094 while (terminals_to_free != NULL)
1095 {
1096 term_T *term = terminals_to_free;
1097
1098 terminals_to_free = term->tl_next;
1099
1100 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001101 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001102
1103 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001104 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001105 vim_free(term->tl_title);
1106#ifdef FEAT_SESSION
1107 vim_free(term->tl_command);
1108#endif
1109 vim_free(term->tl_kill);
1110 vim_free(term->tl_status_text);
1111 vim_free(term->tl_opencmd);
1112 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001113 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001114#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001115 if (term->tl_out_fd != NULL)
1116 fclose(term->tl_out_fd);
1117#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001118 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001119 vim_free(term->tl_cursor_color);
1120 vim_free(term);
1121 }
1122}
1123
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001124/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001125 * Get the part that is connected to the tty. Normally this is PART_IN, but
1126 * when writing buffer lines to the job it can be another. This makes it
1127 * possible to do "1,5term vim -".
1128 */
1129 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001130get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001131{
1132#ifdef UNIX
1133 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1134 int i;
1135
1136 for (i = 0; i < 3; ++i)
1137 {
1138 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1139
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001140 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001141 return parts[i];
1142 }
1143#endif
1144 return PART_IN;
1145}
1146
1147/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001148 * Read any vterm output and send it on the channel.
1149 */
1150 static void
1151term_forward_output(term_T *term)
1152{
1153 VTerm *vterm = term->tl_vterm;
1154 char buf[KEY_BUF_LEN];
1155 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1156
1157 if (curlen > 0)
1158 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1159 (char_u *)buf, (int)curlen, NULL);
1160}
1161
1162/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001163 * Write job output "msg[len]" to the vterm.
1164 */
1165 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001166term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001167{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001168 char_u *msg = msg_arg;
1169 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001170 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001171 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001172 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1173
1174 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1175 // the end.
1176 if (len > limit)
1177 {
1178 char_u *p = msg + len - limit;
1179
1180 p -= (*mb_head_off)(msg, p);
1181 len -= p - msg;
1182 msg = p;
1183 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001184
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001185 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001186
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001187 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001188 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001189 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001190
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001191 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001192 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1193}
1194
1195 static void
1196update_cursor(term_T *term, int redraw)
1197{
1198 if (term->tl_normal_mode)
1199 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001200#ifdef FEAT_GUI
1201 if (term->tl_system)
1202 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1203 term->tl_cursor_pos.col);
1204 else
1205#endif
1206 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001207 if (redraw)
1208 {
1209 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1210 cursor_on();
1211 out_flush();
1212#ifdef FEAT_GUI
1213 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001214 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001215 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001216 gui_mch_flush();
1217 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001218#endif
1219 }
1220}
1221
1222/*
1223 * Invoked when "msg" output from a job was received. Write it to the terminal
1224 * of "buffer".
1225 */
1226 void
1227write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1228{
1229 size_t len = STRLEN(msg);
1230 term_T *term = buffer->b_term;
1231
Bram Moolenaar4f974752019-02-17 17:44:42 +01001232#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001233 // Win32: Cannot redirect output of the job, intercept it here and write to
1234 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001235 if (term->tl_out_fd != NULL)
1236 {
1237 ch_log(channel, "Writing %d bytes to output file", (int)len);
1238 fwrite(msg, len, 1, term->tl_out_fd);
1239 return;
1240 }
1241#endif
1242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001243 if (term->tl_vterm == NULL)
1244 {
1245 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1246 return;
1247 }
1248 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001249 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001250 term_write_job_output(term, msg, len);
1251
Bram Moolenaar13568252018-03-16 20:46:58 +01001252#ifdef FEAT_GUI
1253 if (term->tl_system)
1254 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001255 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001256 update_system_term(term);
1257 update_cursor(term, TRUE);
1258 }
1259 else
1260#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001261 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1262 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001263 if (!term->tl_normal_mode)
1264 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001265 // Don't use update_screen() when editing the command line, it gets
1266 // cleared.
1267 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001268 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001269 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001270 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001271 update_screen(VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001272 // update_screen() can be slow, check the terminal wasn't closed
1273 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001274 if (buffer == curbuf && curbuf->b_term != NULL)
1275 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001276 }
1277 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001278 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001279 }
1280}
1281
1282/*
1283 * Send a mouse position and click to the vterm
1284 */
1285 static int
1286term_send_mouse(VTerm *vterm, int button, int pressed)
1287{
1288 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001289 int row = mouse_row - W_WINROW(curwin);
1290 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001291
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001292#ifdef FEAT_PROP_POPUP
1293 if (popup_is_popup(curwin))
1294 {
1295 row -= popup_top_extra(curwin);
1296 col -= popup_left_extra(curwin);
1297 }
1298#endif
1299 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001300 if (button != 0)
1301 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001302 return TRUE;
1303}
1304
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001305static int enter_mouse_col = -1;
1306static int enter_mouse_row = -1;
1307
1308/*
1309 * Handle a mouse click, drag or release.
1310 * Return TRUE when a mouse event is sent to the terminal.
1311 */
1312 static int
1313term_mouse_click(VTerm *vterm, int key)
1314{
1315#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001316 // For modeless selection mouse drag and release events are ignored, unless
1317 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001318 static int ignore_drag_release = TRUE;
1319 VTermMouseState mouse_state;
1320
1321 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1322 if (mouse_state.flags == 0)
1323 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001324 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001325 switch (key)
1326 {
1327 case K_LEFTDRAG:
1328 case K_LEFTRELEASE:
1329 case K_RIGHTDRAG:
1330 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001331 // Ignore drag and release events when the button-down wasn't
1332 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001333 if (ignore_drag_release)
1334 {
1335 int save_mouse_col, save_mouse_row;
1336
1337 if (enter_mouse_col < 0)
1338 break;
1339
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001340 // mouse click in the window gave us focus, handle that
1341 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001342 save_mouse_col = mouse_col;
1343 save_mouse_row = mouse_row;
1344 mouse_col = enter_mouse_col;
1345 mouse_row = enter_mouse_row;
1346 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1347 mouse_col = save_mouse_col;
1348 mouse_row = save_mouse_row;
1349 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001350 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001351 case K_LEFTMOUSE:
1352 case K_RIGHTMOUSE:
1353 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1354 ignore_drag_release = TRUE;
1355 else
1356 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001357 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001358 if (clip_star.available)
1359 {
1360 int button, is_click, is_drag;
1361
1362 button = get_mouse_button(KEY2TERMCAP1(key),
1363 &is_click, &is_drag);
1364 if (mouse_model_popup() && button == MOUSE_LEFT
1365 && (mod_mask & MOD_MASK_SHIFT))
1366 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001367 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001368 button = MOUSE_RIGHT;
1369 mod_mask &= ~MOD_MASK_SHIFT;
1370 }
1371 clip_modeless(button, is_click, is_drag);
1372 }
1373 break;
1374
1375 case K_MIDDLEMOUSE:
1376 if (clip_star.available)
1377 insert_reg('*', TRUE);
1378 break;
1379 }
1380 enter_mouse_col = -1;
1381 return FALSE;
1382 }
1383#endif
1384 enter_mouse_col = -1;
1385
1386 switch (key)
1387 {
1388 case K_LEFTMOUSE:
1389 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1390 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1391 case K_LEFTRELEASE:
1392 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1393 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1394 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1395 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1396 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1397 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1398 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1399 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1400 }
1401 return TRUE;
1402}
1403
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001404/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001405 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1406 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001407 * Return the number of bytes in "buf".
1408 */
1409 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001410term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001411{
1412 VTerm *vterm = term->tl_vterm;
1413 VTermKey key = VTERM_KEY_NONE;
1414 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001415 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001416
1417 switch (c)
1418 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001419 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001420
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001421 // don't use VTERM_KEY_BACKSPACE, it always
1422 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001423 case K_BS: c = term_backspace_char; break;
1424
1425 case ESC: key = VTERM_KEY_ESCAPE; break;
1426 case K_DEL: key = VTERM_KEY_DEL; break;
1427 case K_DOWN: key = VTERM_KEY_DOWN; break;
1428 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1429 key = VTERM_KEY_DOWN; break;
1430 case K_END: key = VTERM_KEY_END; break;
1431 case K_S_END: mod = VTERM_MOD_SHIFT;
1432 key = VTERM_KEY_END; break;
1433 case K_C_END: mod = VTERM_MOD_CTRL;
1434 key = VTERM_KEY_END; break;
1435 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1436 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1437 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1438 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1439 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1440 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1441 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1442 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1443 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1444 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1445 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1446 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1447 case K_HOME: key = VTERM_KEY_HOME; break;
1448 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1449 key = VTERM_KEY_HOME; break;
1450 case K_C_HOME: mod = VTERM_MOD_CTRL;
1451 key = VTERM_KEY_HOME; break;
1452 case K_INS: key = VTERM_KEY_INS; break;
1453 case K_K0: key = VTERM_KEY_KP_0; break;
1454 case K_K1: key = VTERM_KEY_KP_1; break;
1455 case K_K2: key = VTERM_KEY_KP_2; break;
1456 case K_K3: key = VTERM_KEY_KP_3; break;
1457 case K_K4: key = VTERM_KEY_KP_4; break;
1458 case K_K5: key = VTERM_KEY_KP_5; break;
1459 case K_K6: key = VTERM_KEY_KP_6; break;
1460 case K_K7: key = VTERM_KEY_KP_7; break;
1461 case K_K8: key = VTERM_KEY_KP_8; break;
1462 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001463 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001464 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001465 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001466 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001467 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1468 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001469 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1470 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001471 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1472 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001473 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1474 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1475 case K_LEFT: key = VTERM_KEY_LEFT; break;
1476 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1477 key = VTERM_KEY_LEFT; break;
1478 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1479 key = VTERM_KEY_LEFT; break;
1480 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1481 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1482 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1483 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1484 key = VTERM_KEY_RIGHT; break;
1485 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1486 key = VTERM_KEY_RIGHT; break;
1487 case K_UP: key = VTERM_KEY_UP; break;
1488 case K_S_UP: mod = VTERM_MOD_SHIFT;
1489 key = VTERM_KEY_UP; break;
1490 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001491 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1492 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001493
Bram Moolenaara42ad572017-11-16 13:08:04 +01001494 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1495 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001496 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1497 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001498
1499 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001500 case K_LEFTMOUSE_NM:
1501 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001502 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001503 case K_LEFTRELEASE_NM:
1504 case K_MOUSEMOVE:
1505 case K_MIDDLEMOUSE:
1506 case K_MIDDLEDRAG:
1507 case K_MIDDLERELEASE:
1508 case K_RIGHTMOUSE:
1509 case K_RIGHTDRAG:
1510 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1511 return 0;
1512 other = TRUE;
1513 break;
1514
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001515 case K_X1MOUSE: /* TODO */ return 0;
1516 case K_X1DRAG: /* TODO */ return 0;
1517 case K_X1RELEASE: /* TODO */ return 0;
1518 case K_X2MOUSE: /* TODO */ return 0;
1519 case K_X2DRAG: /* TODO */ return 0;
1520 case K_X2RELEASE: /* TODO */ return 0;
1521
1522 case K_IGNORE: return 0;
1523 case K_NOP: return 0;
1524 case K_UNDO: return 0;
1525 case K_HELP: return 0;
1526 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1527 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1528 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1529 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1530 case K_SELECT: return 0;
1531#ifdef FEAT_GUI
1532 case K_VER_SCROLLBAR: return 0;
1533 case K_HOR_SCROLLBAR: return 0;
1534#endif
1535#ifdef FEAT_GUI_TABLINE
1536 case K_TABLINE: return 0;
1537 case K_TABMENU: return 0;
1538#endif
1539#ifdef FEAT_NETBEANS_INTG
1540 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1541#endif
1542#ifdef FEAT_DND
1543 case K_DROP: return 0;
1544#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001545 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001546 case K_PS: vterm_keyboard_start_paste(vterm);
1547 other = TRUE;
1548 break;
1549 case K_PE: vterm_keyboard_end_paste(vterm);
1550 other = TRUE;
1551 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001552 }
1553
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001554 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001555 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001556 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001557 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001558 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001559 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001560 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001561
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001562 /*
1563 * Convert special keys to vterm keys:
1564 * - Write keys to vterm: vterm_keyboard_key()
1565 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001566 */
1567 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001568 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001569 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001570 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001571 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001572 vterm_keyboard_unichar(vterm, c, mod);
1573
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001574 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001575 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1576}
1577
1578/*
1579 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001580 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001581 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001582 */
1583 static int
1584term_job_running_check(term_T *term, int check_job_status)
1585{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001586 // Also consider the job finished when the channel is closed, to avoid a
1587 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001588 if (term != NULL
1589 && term->tl_job != NULL
1590 && channel_is_open(term->tl_job->jv_channel))
1591 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001592 job_T *job = term->tl_job;
1593
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00001594 // Careful: Checking the job status may invoke callbacks, which close
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001595 // the buffer and terminate "term". However, "job" will not be freed
1596 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001597 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001598 job_status(job);
1599 return (job->jv_status == JOB_STARTED
1600 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001601 }
1602 return FALSE;
1603}
1604
1605/*
1606 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001607 */
1608 int
1609term_job_running(term_T *term)
1610{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001611 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001612}
1613
1614/*
1615 * Return TRUE if "term" has an active channel and used ":term NONE".
1616 */
1617 int
1618term_none_open(term_T *term)
1619{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001620 // Also consider the job finished when the channel is closed, to avoid a
1621 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001622 return term != NULL
1623 && term->tl_job != NULL
1624 && channel_is_open(term->tl_job->jv_channel)
1625 && term->tl_job->jv_channel->ch_keep_open;
1626}
1627
1628/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001629 * Used when exiting: kill the job in "buf" if so desired.
1630 * Return OK when the job finished.
1631 * Return FAIL when the job is still running.
1632 */
1633 int
1634term_try_stop_job(buf_T *buf)
1635{
1636 int count;
1637 char *how = (char *)buf->b_term->tl_kill;
1638
1639#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001640 if ((how == NULL || *how == NUL)
1641 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001642 {
1643 char_u buff[DIALOG_MSG_SIZE];
1644 int ret;
1645
Bram Moolenaar00806bc2020-11-05 19:36:38 +01001646 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001647 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1648 if (ret == VIM_YES)
1649 how = "kill";
1650 else if (ret == VIM_CANCEL)
1651 return FAIL;
1652 }
1653#endif
1654 if (how == NULL || *how == NUL)
1655 return FAIL;
1656
1657 job_stop(buf->b_term->tl_job, NULL, how);
1658
Bram Moolenaar9172d232019-01-29 23:06:54 +01001659 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001660 for (count = 0; count < 100; ++count)
1661 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001662 job_T *job;
1663
1664 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001665 if (!buf_valid(buf)
1666 || buf->b_term == NULL
1667 || buf->b_term->tl_job == NULL)
1668 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001669 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001670
Bram Moolenaar9172d232019-01-29 23:06:54 +01001671 // Call job_status() to update jv_status. It may cause the job to be
1672 // cleaned up but it won't be freed.
1673 job_status(job);
1674 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001675 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001676
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001677 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001678 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001679 }
1680 return FAIL;
1681}
1682
1683/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001684 * Add the last line of the scrollback buffer to the buffer in the window.
1685 */
1686 static void
1687add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1688{
1689 buf_T *buf = term->tl_buffer;
1690 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1691 linenr_T lnum = buf->b_ml.ml_line_count;
1692
Bram Moolenaar4f974752019-02-17 17:44:42 +01001693#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001694 if (!enc_utf8 && enc_codepage > 0)
1695 {
1696 WCHAR *ret = NULL;
1697 int length = 0;
1698
1699 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1700 &ret, &length);
1701 if (ret != NULL)
1702 {
1703 WideCharToMultiByte_alloc(enc_codepage, 0,
1704 ret, length, (char **)&text, &len, 0, 0);
1705 vim_free(ret);
1706 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1707 vim_free(text);
1708 }
1709 }
1710 else
1711#endif
1712 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1713 if (empty)
1714 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001715 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001716 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001717 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001718 curbuf = curwin->w_buffer;
1719 }
1720}
1721
1722 static void
1723cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1724{
1725 attr->width = cell->width;
1726 attr->attrs = cell->attrs;
1727 attr->fg = cell->fg;
1728 attr->bg = cell->bg;
1729}
1730
1731 static int
1732equal_celattr(cellattr_T *a, cellattr_T *b)
1733{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001734 // We only compare the RGB colors, ignoring the ANSI index and type.
1735 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001736 return a->fg.red == b->fg.red
1737 && a->fg.green == b->fg.green
1738 && a->fg.blue == b->fg.blue
1739 && a->bg.red == b->bg.red
1740 && a->bg.green == b->bg.green
1741 && a->bg.blue == b->bg.blue;
1742}
1743
Bram Moolenaard96ff162018-02-18 22:13:29 +01001744/*
1745 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1746 * line at this position. Otherwise at the end.
1747 */
1748 static int
1749add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1750{
1751 if (ga_grow(&term->tl_scrollback, 1) == OK)
1752 {
1753 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1754 + term->tl_scrollback.ga_len;
1755
1756 if (lnum > 0)
1757 {
1758 int i;
1759
1760 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1761 {
1762 *line = *(line - 1);
1763 --line;
1764 }
1765 }
1766 line->sb_cols = 0;
1767 line->sb_cells = NULL;
1768 line->sb_fill_attr = *fill_attr;
1769 ++term->tl_scrollback.ga_len;
1770 return OK;
1771 }
1772 return FALSE;
1773}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001774
1775/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001776 * Remove the terminal contents from the scrollback and the buffer.
1777 * Used before adding a new scrollback line or updating the buffer for lines
1778 * displayed in the terminal.
1779 */
1780 static void
1781cleanup_scrollback(term_T *term)
1782{
1783 sb_line_T *line;
1784 garray_T *gap;
1785
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001786 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001787 gap = &term->tl_scrollback;
1788 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1789 && gap->ga_len > 0)
1790 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001791 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001792 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1793 vim_free(line->sb_cells);
1794 --gap->ga_len;
1795 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001796 curbuf = curwin->w_buffer;
1797 if (curbuf == term->tl_buffer)
1798 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001799}
1800
1801/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001802 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001803 */
1804 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001805update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001806{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001807 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001808 int len;
1809 int lines_skipped = 0;
1810 VTermPos pos;
1811 VTermScreenCell cell;
1812 cellattr_T fill_attr, new_fill_attr;
1813 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001814
1815 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1816 "Adding terminal window snapshot to buffer");
1817
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001818 // First remove the lines that were appended before, they might be
1819 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001820 cleanup_scrollback(term);
1821
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001822 screen = vterm_obtain_screen(term->tl_vterm);
1823 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1825 {
1826 len = 0;
1827 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1828 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1829 && cell.chars[0] != NUL)
1830 {
1831 len = pos.col + 1;
1832 new_fill_attr = term->tl_default_color;
1833 }
1834 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001835 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001836 cell2cellattr(&cell, &new_fill_attr);
1837
1838 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1839 ++lines_skipped;
1840 else
1841 {
1842 while (lines_skipped > 0)
1843 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001844 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001845 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001846 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001847 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001848 }
1849
1850 if (len == 0)
1851 p = NULL;
1852 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001853 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001854 if ((p != NULL || len == 0)
1855 && ga_grow(&term->tl_scrollback, 1) == OK)
1856 {
1857 garray_T ga;
1858 int width;
1859 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1860 + term->tl_scrollback.ga_len;
1861
1862 ga_init2(&ga, 1, 100);
1863 for (pos.col = 0; pos.col < len; pos.col += width)
1864 {
1865 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1866 {
1867 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02001868 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001869 if (ga_grow(&ga, 1) == OK)
1870 ga.ga_len += utf_char2bytes(' ',
1871 (char_u *)ga.ga_data + ga.ga_len);
1872 }
1873 else
1874 {
1875 width = cell.width;
1876
1877 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01001878 if (width == 2)
1879 // second cell of double-width character has the
1880 // same attributes.
1881 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001882
Bram Moolenaara79fd562018-12-20 20:47:32 +01001883 // Each character can be up to 6 bytes.
1884 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001885 {
1886 int i;
1887 int c;
1888
1889 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1890 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1891 (char_u *)ga.ga_data + ga.ga_len);
1892 }
1893 }
1894 }
1895 line->sb_cols = len;
1896 line->sb_cells = p;
1897 line->sb_fill_attr = new_fill_attr;
1898 fill_attr = new_fill_attr;
1899 ++term->tl_scrollback.ga_len;
1900
1901 if (ga_grow(&ga, 1) == FAIL)
1902 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1903 else
1904 {
1905 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1906 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1907 }
1908 ga_clear(&ga);
1909 }
1910 else
1911 vim_free(p);
1912 }
1913 }
1914
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001915 // Add trailing empty lines.
1916 for (pos.row = term->tl_scrollback.ga_len;
1917 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1918 ++pos.row)
1919 {
1920 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1921 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1922 }
1923
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001924 term->tl_dirty_snapshot = FALSE;
1925#ifdef FEAT_TIMERS
1926 term->tl_timer_set = FALSE;
1927#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001928}
1929
1930/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001931 * Loop over all windows in the current tab, and also curwin, which is not
1932 * encountered when using a terminal in a popup window.
1933 * Return TRUE if "*wp" was set to the next window.
1934 */
1935 static int
1936for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1937{
1938 if (*wp == NULL)
1939 *wp = firstwin;
1940 else if ((*wp)->w_next != NULL)
1941 *wp = (*wp)->w_next;
1942 else if (!*did_curwin)
1943 *wp = curwin;
1944 else
1945 return FALSE;
1946 if (*wp == curwin)
1947 *did_curwin = TRUE;
1948 return TRUE;
1949}
1950
1951/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001952 * If needed, add the current lines of the terminal to scrollback and to the
1953 * buffer. Called after the job has ended and when switching to
1954 * Terminal-Normal mode.
1955 * When "redraw" is TRUE redraw the windows that show the terminal.
1956 */
1957 static void
1958may_move_terminal_to_buffer(term_T *term, int redraw)
1959{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001960 if (term->tl_vterm == NULL)
1961 return;
1962
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001963 // Update the snapshot only if something changes or the buffer does not
1964 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001965 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1966 <= term->tl_scrollback_scrolled)
1967 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001968
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001969 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001970 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1971 &term->tl_default_color.fg, &term->tl_default_color.bg);
1972
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001973 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001974 {
1975 win_T *wp = NULL;
1976 int did_curwin = FALSE;
1977
1978 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001979 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001980 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001981 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001982 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1983 wp->w_cursor.col = 0;
1984 wp->w_valid = 0;
1985 if (wp->w_cursor.lnum >= wp->w_height)
1986 {
1987 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001988
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001989 if (wp->w_topline < min_topline)
1990 wp->w_topline = min_topline;
1991 }
1992 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001994 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001995 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001996}
1997
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001998#if defined(FEAT_TIMERS) || defined(PROTO)
1999/*
2000 * Check if any terminal timer expired. If so, copy text from the terminal to
2001 * the buffer.
2002 * Return the time until the next timer will expire.
2003 */
2004 int
2005term_check_timers(int next_due_arg, proftime_T *now)
2006{
2007 term_T *term;
2008 int next_due = next_due_arg;
2009
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002010 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002011 {
2012 if (term->tl_timer_set && !term->tl_normal_mode)
2013 {
2014 long this_due = proftime_time_left(&term->tl_timer_due, now);
2015
2016 if (this_due <= 1)
2017 {
2018 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002019 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002020 }
2021 else if (next_due == -1 || next_due > this_due)
2022 next_due = this_due;
2023 }
2024 }
2025
2026 return next_due;
2027}
2028#endif
2029
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002030/*
2031 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2032 * otherwise end it.
2033 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002034 static void
2035set_terminal_mode(term_T *term, int normal_mode)
2036{
2037 term->tl_normal_mode = normal_mode;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002038 trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002039 if (!normal_mode)
2040 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002041 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002042 if (term->tl_buffer == curbuf)
2043 maketitle();
2044}
2045
2046/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002047 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002048 * Move the vterm contents into the scrollback buffer and free the vterm.
2049 */
2050 static void
2051cleanup_vterm(term_T *term)
2052{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002053 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002054 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002055 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002056 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002057}
2058
2059/*
2060 * Switch from Terminal-Job mode to Terminal-Normal mode.
2061 * Suspends updating the terminal window.
2062 */
2063 static void
2064term_enter_normal_mode(void)
2065{
2066 term_T *term = curbuf->b_term;
2067
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002068 set_terminal_mode(term, TRUE);
2069
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002070 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002071 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002072
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002073 // Move the window cursor to the position of the cursor in the
2074 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002075 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2076 + term->tl_cursor_pos.row + 1;
2077 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002078 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2079 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002080 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002081
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002082 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002083 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2084}
2085
2086/*
2087 * Returns TRUE if the current window contains a terminal and we are in
2088 * Terminal-Normal mode.
2089 */
2090 int
2091term_in_normal_mode(void)
2092{
2093 term_T *term = curbuf->b_term;
2094
2095 return term != NULL && term->tl_normal_mode;
2096}
2097
2098/*
2099 * Switch from Terminal-Normal mode to Terminal-Job mode.
2100 * Restores updating the terminal window.
2101 */
2102 void
2103term_enter_job_mode()
2104{
2105 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002106
2107 set_terminal_mode(term, FALSE);
2108
2109 if (term->tl_channel_closed)
2110 cleanup_vterm(term);
2111 redraw_buf_and_status_later(curbuf, NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002112#ifdef FEAT_PROP_POPUP
2113 if (WIN_IS_POPUP(curwin))
Bram Moolenaard5bc32d2020-03-22 19:25:50 +01002114 redraw_later(NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002115#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002116}
2117
2118/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002119 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002120 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002121 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002122 */
2123 static int
2124term_vgetc()
2125{
2126 int c;
2127 int save_State = State;
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002128 int modify_other_keys = curbuf->b_term->tl_vterm == NULL ? FALSE
2129 : vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002130
2131 State = TERMINAL;
2132 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002133#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002134 ctrl_break_was_pressed = FALSE;
2135#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002136 if (modify_other_keys)
2137 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002138 c = vgetc();
2139 got_int = FALSE;
2140 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002141 if (modify_other_keys)
2142 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002143 return c;
2144}
2145
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002146static int mouse_was_outside = FALSE;
2147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002148/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002149 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002150 * Return FAIL when the key needs to be handled in Normal mode.
2151 * Return OK when the key was dropped or sent to the terminal.
2152 */
2153 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002154send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002155{
2156 char msg[KEY_BUF_LEN];
2157 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002158 int dragging_outside = FALSE;
2159
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002160 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002161 switch (c)
2162 {
2163 case NUL:
2164 case K_ZERO:
2165 if (typed)
2166 stuffcharReadbuff(c);
2167 return FAIL;
2168
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002169 case K_TABLINE:
2170 stuffcharReadbuff(c);
2171 return FAIL;
2172
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002173 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002174 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175 return FAIL;
2176
2177 case K_LEFTDRAG:
2178 case K_MIDDLEDRAG:
2179 case K_RIGHTDRAG:
2180 case K_X1DRAG:
2181 case K_X2DRAG:
2182 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002183 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002184 case K_LEFTMOUSE:
2185 case K_LEFTMOUSE_NM:
2186 case K_LEFTRELEASE:
2187 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002188 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002189 case K_MIDDLEMOUSE:
2190 case K_MIDDLERELEASE:
2191 case K_RIGHTMOUSE:
2192 case K_RIGHTRELEASE:
2193 case K_X1MOUSE:
2194 case K_X1RELEASE:
2195 case K_X2MOUSE:
2196 case K_X2RELEASE:
2197
2198 case K_MOUSEUP:
2199 case K_MOUSEDOWN:
2200 case K_MOUSELEFT:
2201 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002202 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002203 int row = mouse_row;
2204 int col = mouse_col;
2205
2206#ifdef FEAT_PROP_POPUP
2207 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002208 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002209 row -= popup_top_extra(curwin);
2210 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002211 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002212#endif
2213 if (row < W_WINROW(curwin)
2214 || row >= (W_WINROW(curwin) + curwin->w_height)
2215 || col < curwin->w_wincol
2216 || col >= W_ENDCOL(curwin)
2217 || dragging_outside)
2218 {
2219 // click or scroll outside the current window or on status
2220 // line or vertical separator
2221 if (typed)
2222 {
2223 stuffcharReadbuff(c);
2224 mouse_was_outside = TRUE;
2225 }
2226 return FAIL;
2227 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002228 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002229 break;
2230
2231 case K_COMMAND:
2232 return do_cmdline(NULL, getcmdkeycmd, NULL, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002233 }
2234 if (typed)
2235 mouse_was_outside = FALSE;
2236
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002237 // Convert the typed key to a sequence of bytes for the job.
2238 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002239 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002240 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002241 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2242 (char_u *)msg, (int)len, NULL);
2243
2244 return OK;
2245}
2246
2247 static void
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002248position_cursor(win_T *wp, VTermPos *pos)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002249{
2250 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2251 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002252#ifdef FEAT_PROP_POPUP
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002253 if (popup_is_popup(wp))
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002254 {
Bram Moolenaarf5452692020-11-28 21:56:06 +01002255 wp->w_wrow += popup_top_extra(wp);
2256 wp->w_wcol += popup_left_extra(wp);
Bram Moolenaar6a076442020-11-15 20:32:58 +01002257 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002258 }
Bram Moolenaar6a076442020-11-15 20:32:58 +01002259 else
2260 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002261#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2263}
2264
2265/*
2266 * Handle CTRL-W "": send register contents to the job.
2267 */
2268 static void
2269term_paste_register(int prev_c UNUSED)
2270{
2271 int c;
2272 list_T *l;
2273 listitem_T *item;
2274 long reglen = 0;
2275 int type;
2276
2277#ifdef FEAT_CMDL_INFO
2278 if (add_to_showcmd(prev_c))
2279 if (add_to_showcmd('"'))
2280 out_flush();
2281#endif
2282 c = term_vgetc();
2283#ifdef FEAT_CMDL_INFO
2284 clear_showcmd();
2285#endif
2286 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002287 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002288 return;
2289
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002290 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002291 if (c == '=' && get_expr_register() != '=')
2292 return;
2293 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002294 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002295 return;
2296
2297 l = (list_T *)get_reg_contents(c, GREG_LIST);
2298 if (l != NULL)
2299 {
2300 type = get_reg_type(c, &reglen);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002301 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002302 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002303 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002304#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002305 char_u *tmp = s;
2306
2307 if (!enc_utf8 && enc_codepage > 0)
2308 {
2309 WCHAR *ret = NULL;
2310 int length = 0;
2311
2312 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2313 (int)STRLEN(s), &ret, &length);
2314 if (ret != NULL)
2315 {
2316 WideCharToMultiByte_alloc(CP_UTF8, 0,
2317 ret, length, (char **)&s, &length, 0, 0);
2318 vim_free(ret);
2319 }
2320 }
2321#endif
2322 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2323 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002324#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002325 if (tmp != s)
2326 vim_free(s);
2327#endif
2328
2329 if (item->li_next != NULL || type == MLINE)
2330 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2331 (char_u *)"\r", 1, NULL);
2332 }
2333 list_free(l);
2334 }
2335}
2336
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002337/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002338 * Return TRUE when waiting for a character in the terminal, the cursor of the
2339 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002340 */
2341 int
2342terminal_is_active()
2343{
2344 return in_terminal_loop != NULL;
2345}
2346
Bram Moolenaar83d47902020-03-26 20:34:00 +01002347/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002348 * Return the highight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002349 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002350 static int
2351term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002352{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002353 char_u *name;
2354
2355 if (wp != NULL && *wp->w_p_wcr != NUL)
2356 name = wp->w_p_wcr;
2357 else if (term->tl_highlight_name != NULL)
2358 name = term->tl_highlight_name;
2359 else
2360 name = (char_u*)"Terminal";
2361
2362 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002363}
2364
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002365#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002366 cursorentry_T *
2367term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2368{
2369 term_T *term = in_terminal_loop;
2370 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002371 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002372 guicolor_T term_fg = INVALCOLOR;
2373 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002374
Bram Moolenaara80faa82020-04-12 19:37:17 +02002375 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002376 entry.shape = entry.mshape =
2377 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2378 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2379 SHAPE_BLOCK;
2380 entry.percentage = 20;
2381 if (term->tl_cursor_blink)
2382 {
2383 entry.blinkwait = 700;
2384 entry.blinkon = 400;
2385 entry.blinkoff = 250;
2386 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002387
Bram Moolenaar83d47902020-03-26 20:34:00 +01002388 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002389 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002390 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002391 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002392 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002393 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002394 else
2395 *fg = gui.back_pixel;
2396
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002397 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002398 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002399 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002400 *bg = term_fg;
2401 else
2402 *bg = gui.norm_pixel;
2403 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002404 else
2405 *bg = color_name2handle(term->tl_cursor_color);
2406 entry.name = "n";
2407 entry.used_for = SHAPE_CURSOR;
2408
2409 return &entry;
2410}
2411#endif
2412
Bram Moolenaard317b382018-02-08 22:33:31 +01002413 static void
2414may_output_cursor_props(void)
2415{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002416 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002417 || last_set_cursor_shape != desired_cursor_shape
2418 || last_set_cursor_blink != desired_cursor_blink)
2419 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002420 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002421 last_set_cursor_shape = desired_cursor_shape;
2422 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002423 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002424 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002425 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002426 ui_cursor_shape_forced(TRUE);
2427 else
2428 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2429 }
2430}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002431
Bram Moolenaard317b382018-02-08 22:33:31 +01002432/*
2433 * Set the cursor color and shape, if not last set to these.
2434 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002435 static void
2436may_set_cursor_props(term_T *term)
2437{
2438#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002439 // For the GUI the cursor properties are obtained with
2440 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002441 if (gui.in_use)
2442 return;
2443#endif
2444 if (in_terminal_loop == term)
2445 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002446 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002447 desired_cursor_shape = term->tl_cursor_shape;
2448 desired_cursor_blink = term->tl_cursor_blink;
2449 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002450 }
2451}
2452
Bram Moolenaard317b382018-02-08 22:33:31 +01002453/*
2454 * Reset the desired cursor properties and restore them when needed.
2455 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002456 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002457prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002458{
2459#ifdef FEAT_GUI
2460 if (gui.in_use)
2461 return;
2462#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002463 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002464 desired_cursor_shape = -1;
2465 desired_cursor_blink = -1;
2466 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002467}
2468
2469/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002470 * Returns TRUE if the current window contains a terminal and we are sending
2471 * keys to the job.
2472 * If "check_job_status" is TRUE update the job status.
2473 */
2474 static int
2475term_use_loop_check(int check_job_status)
2476{
2477 term_T *term = curbuf->b_term;
2478
2479 return term != NULL
2480 && !term->tl_normal_mode
2481 && term->tl_vterm != NULL
2482 && term_job_running_check(term, check_job_status);
2483}
2484
2485/*
2486 * Returns TRUE if the current window contains a terminal and we are sending
2487 * keys to the job.
2488 */
2489 int
2490term_use_loop(void)
2491{
2492 return term_use_loop_check(FALSE);
2493}
2494
2495/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002496 * Called when entering a window with the mouse. If this is a terminal window
2497 * we may want to change state.
2498 */
2499 void
2500term_win_entered()
2501{
2502 term_T *term = curbuf->b_term;
2503
2504 if (term != NULL)
2505 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002506 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002507 {
2508 reset_VIsual_and_resel();
2509 if (State & INSERT)
2510 stop_insert_mode = TRUE;
2511 }
2512 mouse_was_outside = FALSE;
2513 enter_mouse_col = mouse_col;
2514 enter_mouse_row = mouse_row;
2515 }
2516}
2517
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002518 void
2519term_focus_change(int in_focus)
2520{
2521 term_T *term = curbuf->b_term;
2522
2523 if (term != NULL && term->tl_vterm != NULL)
2524 {
2525 VTermState *state = vterm_obtain_state(term->tl_vterm);
2526
2527 if (in_focus)
2528 vterm_state_focus_in(state);
2529 else
2530 vterm_state_focus_out(state);
2531 term_forward_output(term);
2532 }
2533}
2534
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002535/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002536 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2537 * Return the Ctrl-key value in that case.
2538 */
2539 static int
2540raw_c_to_ctrl(int c)
2541{
2542 if ((mod_mask & MOD_MASK_CTRL)
2543 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2544 return c & 0x1f;
2545 return c;
2546}
2547
2548/*
2549 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2550 * May set "mod_mask".
2551 */
2552 static int
2553ctrl_to_raw_c(int c)
2554{
2555 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2556 {
2557 mod_mask |= MOD_MASK_CTRL;
2558 return c + '@';
2559 }
2560 return c;
2561}
2562
2563/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002564 * Wait for input and send it to the job.
2565 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2566 * when there is no more typahead.
2567 * Return when the start of a CTRL-W command is typed or anything else that
2568 * should be handled as a Normal mode command.
2569 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2570 * the terminal was closed.
2571 */
2572 int
2573terminal_loop(int blocking)
2574{
2575 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002576 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002577 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002578 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002579#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002580 int tty_fd = curbuf->b_term->tl_job->jv_channel
2581 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002582#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002583 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002584
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002585 // Remember the terminal we are sending keys to. However, the terminal
2586 // might be closed while waiting for a character, e.g. typing "exit" in a
2587 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2588 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002589 in_terminal_loop = curbuf->b_term;
2590
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002591 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002592 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002593 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002594 if (termwinkey == Ctrl_W)
2595 termwinkey = 0;
2596 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002597 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002598 may_set_cursor_props(curbuf->b_term);
2599
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002600 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002601 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002602#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002603 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002604#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002605 // TODO: skip screen update when handling a sequence of keys.
2606 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002607 while (must_redraw != 0)
2608 if (update_screen(0) == FAIL)
2609 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002610 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002611 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002612 break;
2613
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002614 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002615 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002616
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002617 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002618 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002619 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002620 // Job finished while waiting for a character. Push back the
2621 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002622 if (raw_c != K_IGNORE)
2623 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002624 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002625 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002626 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002627 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002628 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002629
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002630#ifdef UNIX
2631 /*
2632 * The shell or another program may change the tty settings. Getting
2633 * them for every typed character is a bit of overhead, but it's needed
2634 * for the first character typed, e.g. when Vim starts in a shell.
2635 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002636 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002637 {
2638 ttyinfo_T info;
2639
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002640 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002641 if (get_tty_info(tty_fd, &info) == OK)
2642 term_backspace_char = info.backspace;
2643 }
2644#endif
2645
Bram Moolenaar4f974752019-02-17 17:44:42 +01002646#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002647 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2648 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002649 if (ctrl_break_was_pressed)
2650 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2651#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002652 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2653 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002654 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002655#ifdef FEAT_GUI
2656 && !curbuf->b_term->tl_system
2657#endif
2658 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002659 {
2660 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002661 int prev_raw_c = raw_c;
2662 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002663
2664#ifdef FEAT_CMDL_INFO
2665 if (add_to_showcmd(c))
2666 out_flush();
2667#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002668 raw_c = term_vgetc();
2669 c = raw_c_to_ctrl(raw_c);
2670
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002671#ifdef FEAT_CMDL_INFO
2672 clear_showcmd();
2673#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002674 if (!term_use_loop_check(TRUE)
2675 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002676 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002677 break;
2678
2679 if (prev_c == Ctrl_BSL)
2680 {
2681 if (c == Ctrl_N)
2682 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002683 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002684 term_enter_normal_mode();
2685 ret = FAIL;
2686 goto theend;
2687 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002688 // Send both keys to the terminal, first one here, second one
2689 // below.
2690 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2691 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002692 }
2693 else if (c == Ctrl_C)
2694 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002695 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002696 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2697 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002698 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002699 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002700 // "CTRL-W .": send CTRL-W to the job
2701 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002702 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002703 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002704 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002705 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002706 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002707 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002708 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002709 else if (c == 'N')
2710 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002711 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002712 term_enter_normal_mode();
2713 ret = FAIL;
2714 goto theend;
2715 }
2716 else if (c == '"')
2717 {
2718 term_paste_register(prev_c);
2719 continue;
2720 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002721 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002722 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002723 // space for CTRL-W, modifier, multi-byte char and NUL
2724 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002725
2726 // Put the command into the typeahead buffer, when using the
2727 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2728 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002729 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002730 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002731 ret = OK;
2732 goto theend;
2733 }
2734 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002735# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002736 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002737 {
2738 WCHAR wc;
2739 char_u mb[3];
2740
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002741 mb[0] = (unsigned)raw_c >> 8;
2742 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002743 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002744 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002745 }
2746# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002747 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002748 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002749 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002750 // We are sure to come back here, don't reset the cursor color
2751 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002752 restore_cursor = FALSE;
2753
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002754 ret = OK;
2755 goto theend;
2756 }
2757 }
2758 ret = FAIL;
2759
2760theend:
2761 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002762 if (restore_cursor)
2763 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002764
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002765 // Move a snapshot of the screen contents to the buffer, so that completion
2766 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002767 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2768 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002769
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002770 return ret;
2771}
2772
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002773 static void
2774may_toggle_cursor(term_T *term)
2775{
2776 if (in_terminal_loop == term)
2777 {
2778 if (term->tl_cursor_visible)
2779 cursor_on();
2780 else
2781 cursor_off();
2782 }
2783}
2784
2785/*
2786 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002787 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002788 */
2789 static int
2790color2index(VTermColor *color, int fg, int *boldp)
2791{
2792 int red = color->red;
2793 int blue = color->blue;
2794 int green = color->green;
2795
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002796 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002797 return 0;
2798 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002799 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002800 // The first 16 colors and default: use the ANSI index.
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002801 switch (color->index + 1)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002802 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002803 case 0: return 0;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002804 case 1: return lookup_color( 0, fg, boldp) + 1; // black
2805 case 2: return lookup_color( 4, fg, boldp) + 1; // dark red
2806 case 3: return lookup_color( 2, fg, boldp) + 1; // dark green
Bram Moolenaare2978022020-04-26 14:47:44 +02002807 case 4: return lookup_color( 7, fg, boldp) + 1; // dark yellow
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002808 case 5: return lookup_color( 1, fg, boldp) + 1; // dark blue
2809 case 6: return lookup_color( 5, fg, boldp) + 1; // dark magenta
2810 case 7: return lookup_color( 3, fg, boldp) + 1; // dark cyan
2811 case 8: return lookup_color( 8, fg, boldp) + 1; // light grey
2812 case 9: return lookup_color(12, fg, boldp) + 1; // dark grey
2813 case 10: return lookup_color(20, fg, boldp) + 1; // red
2814 case 11: return lookup_color(16, fg, boldp) + 1; // green
2815 case 12: return lookup_color(24, fg, boldp) + 1; // yellow
2816 case 13: return lookup_color(14, fg, boldp) + 1; // blue
2817 case 14: return lookup_color(22, fg, boldp) + 1; // magenta
2818 case 15: return lookup_color(18, fg, boldp) + 1; // cyan
2819 case 16: return lookup_color(26, fg, boldp) + 1; // white
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002820 }
2821 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002822
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002823 if (t_colors >= 256)
2824 {
2825 if (red == blue && red == green)
2826 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002827 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002828 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002829 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2830 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2831 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002832 int i;
2833
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002834 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002835 return 17; // 00/00/00
2836 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002837 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002838 for (i = 0; i < 23; ++i)
2839 if (red < cutoff[i])
2840 return i + 233;
2841 return 256;
2842 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002843 {
2844 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2845 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002846
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002847 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002848 for (ri = 0; ri < 5; ++ri)
2849 if (red < cutoff[ri])
2850 break;
2851 for (gi = 0; gi < 5; ++gi)
2852 if (green < cutoff[gi])
2853 break;
2854 for (bi = 0; bi < 5; ++bi)
2855 if (blue < cutoff[bi])
2856 break;
2857 return 17 + ri * 36 + gi * 6 + bi;
2858 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002859 }
2860 return 0;
2861}
2862
2863/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002864 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002865 */
2866 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002867vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002868{
2869 int attr = 0;
2870
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002871 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002872 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002873 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002874 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002875 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002876 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002877 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002878 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002879 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002881 return attr;
2882}
2883
2884/*
2885 * Store Vterm attributes in "cell" from highlight flags.
2886 */
2887 static void
2888hl2vtermAttr(int attr, cellattr_T *cell)
2889{
Bram Moolenaara80faa82020-04-12 19:37:17 +02002890 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002891 if (attr & HL_BOLD)
2892 cell->attrs.bold = 1;
2893 if (attr & HL_UNDERLINE)
2894 cell->attrs.underline = 1;
2895 if (attr & HL_ITALIC)
2896 cell->attrs.italic = 1;
2897 if (attr & HL_STRIKETHROUGH)
2898 cell->attrs.strike = 1;
2899 if (attr & HL_INVERSE)
2900 cell->attrs.reverse = 1;
2901}
2902
2903/*
2904 * Convert the attributes of a vterm cell into an attribute index.
2905 */
2906 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002907cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01002908 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002909 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002910 VTermScreenCellAttrs *cellattrs,
2911 VTermColor *cellfg,
2912 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002913{
2914 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002915 VTermColor *fg = cellfg;
2916 VTermColor *bg = cellbg;
2917 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
2918 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
2919
2920 if (is_default_fg || is_default_bg)
2921 {
2922 if (wp != NULL && *wp->w_p_wcr != NUL)
2923 {
2924 if (is_default_fg)
2925 fg = &wp->w_term_wincolor.fg;
2926 if (is_default_bg)
2927 bg = &wp->w_term_wincolor.bg;
2928 }
2929 else
2930 {
2931 if (is_default_fg)
2932 fg = &term->tl_default_color.fg;
2933 if (is_default_bg)
2934 bg = &term->tl_default_color.bg;
2935 }
2936 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002937
2938#ifdef FEAT_GUI
2939 if (gui.in_use)
2940 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002941 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
2942 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
2943 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002944 }
2945 else
2946#endif
2947#ifdef FEAT_TERMGUICOLORS
2948 if (p_tgc)
2949 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002950 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
2951 ? INVALCOLOR
2952 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
2953 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
2954 ? INVALCOLOR
2955 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
2956 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002957 }
2958 else
2959#endif
2960 {
2961 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002962 int ctermfg = color2index(fg, TRUE, &bold);
2963 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002964
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002965 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002966 if (bold == TRUE)
2967 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002968
2969 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002970 }
2971 return 0;
2972}
2973
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002974 static void
2975set_dirty_snapshot(term_T *term)
2976{
2977 term->tl_dirty_snapshot = TRUE;
2978#ifdef FEAT_TIMERS
2979 if (!term->tl_normal_mode)
2980 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002981 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002982 profile_setlimit(100L, &term->tl_timer_due);
2983 term->tl_timer_set = TRUE;
2984 }
2985#endif
2986}
2987
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002988 static int
2989handle_damage(VTermRect rect, void *user)
2990{
2991 term_T *term = (term_T *)user;
2992
2993 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2994 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002995 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002996 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002997 return 1;
2998}
2999
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003000 static void
3001term_scroll_up(term_T *term, int start_row, int count)
3002{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003003 win_T *wp = NULL;
3004 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003005 VTermColor fg, bg;
3006 VTermScreenCellAttrs attr;
3007 int clear_attr;
3008
Bram Moolenaara80faa82020-04-12 19:37:17 +02003009 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003010
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003011 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003012 {
3013 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003014 {
3015 // Set the color to clear lines with.
3016 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3017 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003018 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003019 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003020 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003021 }
3022}
3023
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003024 static int
3025handle_moverect(VTermRect dest, VTermRect src, void *user)
3026{
3027 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003028 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003029
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003030 // Scrolling up is done much more efficiently by deleting lines instead of
3031 // redrawing the text. But avoid doing this multiple times, postpone until
3032 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003033 if (dest.start_col == src.start_col
3034 && dest.end_col == src.end_col
3035 && dest.start_row < src.start_row)
3036 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003037 if (dest.start_row == 0)
3038 term->tl_postponed_scroll += count;
3039 else
3040 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003041 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003042
3043 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3044 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003045 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003046
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003047 // Note sure if the scrolling will work correctly, let's do a complete
3048 // redraw later.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003049 redraw_buf_later(term->tl_buffer, NOT_VALID);
3050 return 1;
3051}
3052
3053 static int
3054handle_movecursor(
3055 VTermPos pos,
3056 VTermPos oldpos UNUSED,
3057 int visible,
3058 void *user)
3059{
3060 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003061 win_T *wp = NULL;
3062 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003063
3064 term->tl_cursor_pos = pos;
3065 term->tl_cursor_visible = visible;
3066
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003067 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003068 {
3069 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003070 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003071 }
3072 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003073 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003074
3075 return 1;
3076}
3077
3078 static int
3079handle_settermprop(
3080 VTermProp prop,
3081 VTermValue *value,
3082 void *user)
3083{
3084 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003085 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003086
3087 switch (prop)
3088 {
3089 case VTERM_PROP_TITLE:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003090 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003091 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003092 if (strval == NULL)
3093 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003094 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003095 // a blank title isn't useful, make it empty, so that "running" is
3096 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003097 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003098 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003099 // Same as blank
3100 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003101 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003102 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3103 term->tl_title = NULL;
3104 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003105 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003106 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003107#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003108 else if (!enc_utf8 && enc_codepage > 0)
3109 {
3110 WCHAR *ret = NULL;
3111 int length = 0;
3112
3113 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003114 (char*)value->string.str,
3115 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003116 if (ret != NULL)
3117 {
3118 WideCharToMultiByte_alloc(enc_codepage, 0,
3119 ret, length, (char**)&term->tl_title,
3120 &length, 0, 0);
3121 vim_free(ret);
3122 }
3123 }
3124#endif
3125 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003126 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003127 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003128 strval = NULL;
3129 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003130 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003131 if (term == curbuf->b_term)
3132 maketitle();
3133 break;
3134
3135 case VTERM_PROP_CURSORVISIBLE:
3136 term->tl_cursor_visible = value->boolean;
3137 may_toggle_cursor(term);
3138 out_flush();
3139 break;
3140
3141 case VTERM_PROP_CURSORBLINK:
3142 term->tl_cursor_blink = value->boolean;
3143 may_set_cursor_props(term);
3144 break;
3145
3146 case VTERM_PROP_CURSORSHAPE:
3147 term->tl_cursor_shape = value->number;
3148 may_set_cursor_props(term);
3149 break;
3150
3151 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003152 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003153 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003154 if (strval == NULL)
3155 break;
3156 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003157 may_set_cursor_props(term);
3158 break;
3159
3160 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003161 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003162 term->tl_using_altscreen = value->boolean;
3163 break;
3164
3165 default:
3166 break;
3167 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003168 vim_free(strval);
3169
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003170 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003171 return 1;
3172}
3173
3174/*
3175 * The job running in the terminal resized the terminal.
3176 */
3177 static int
3178handle_resize(int rows, int cols, void *user)
3179{
3180 term_T *term = (term_T *)user;
3181 win_T *wp;
3182
3183 term->tl_rows = rows;
3184 term->tl_cols = cols;
3185 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003186 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003187 term->tl_vterm_size_changed = FALSE;
3188 else
3189 {
3190 FOR_ALL_WINDOWS(wp)
3191 {
3192 if (wp->w_buffer == term->tl_buffer)
3193 {
3194 win_setheight_win(rows, wp);
3195 win_setwidth_win(cols, wp);
3196 }
3197 }
3198 redraw_buf_later(term->tl_buffer, NOT_VALID);
3199 }
3200 return 1;
3201}
3202
3203/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003204 * If the number of lines that are stored goes over 'termscrollback' then
3205 * delete the first 10%.
3206 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3207 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003208 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003209 static void
3210limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003211{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003212 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003213 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003214 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003215 int i;
3216
3217 curbuf = term->tl_buffer;
3218 for (i = 0; i < todo; ++i)
3219 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003220 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3221 if (update_buffer)
Bram Moolenaarca70c072020-05-30 20:30:46 +02003222 ml_delete(1);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003223 }
3224 curbuf = curwin->w_buffer;
3225
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003226 gap->ga_len -= todo;
3227 mch_memmove(gap->ga_data,
3228 (sb_line_T *)gap->ga_data + todo,
3229 sizeof(sb_line_T) * gap->ga_len);
3230 if (update_buffer)
3231 term->tl_scrollback_scrolled -= todo;
3232 }
3233}
3234
3235/*
3236 * Handle a line that is pushed off the top of the screen.
3237 */
3238 static int
3239handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3240{
3241 term_T *term = (term_T *)user;
3242 garray_T *gap;
3243 int update_buffer;
3244
3245 if (term->tl_normal_mode)
3246 {
3247 // In Terminal-Normal mode the user interacts with the buffer, thus we
3248 // must not change it. Postpone adding the scrollback lines.
3249 gap = &term->tl_scrollback_postponed;
3250 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003251 }
3252 else
3253 {
3254 // First remove the lines that were appended before, the pushed line
3255 // goes above it.
3256 cleanup_scrollback(term);
3257 gap = &term->tl_scrollback;
3258 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003259 }
3260
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003261 limit_scrollback(term, gap, update_buffer);
3262
3263 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003264 {
3265 cellattr_T *p = NULL;
3266 int len = 0;
3267 int i;
3268 int c;
3269 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003270 int text_len;
3271 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003272 sb_line_T *line;
3273 garray_T ga;
3274 cellattr_T fill_attr = term->tl_default_color;
3275
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003276 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003277 for (i = 0; i < cols; ++i)
3278 if (cells[i].chars[0] != 0)
3279 len = i + 1;
3280 else
3281 cell2cellattr(&cells[i], &fill_attr);
3282
3283 ga_init2(&ga, 1, 100);
3284 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003285 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003286 if (p != NULL)
3287 {
3288 for (col = 0; col < len; col += cells[col].width)
3289 {
3290 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3291 {
3292 ga.ga_len = 0;
3293 break;
3294 }
3295 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3296 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3297 (char_u *)ga.ga_data + ga.ga_len);
3298 cell2cellattr(&cells[col], &p[col]);
3299 }
3300 }
3301 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003302 {
3303 if (update_buffer)
3304 text = (char_u *)"";
3305 else
3306 text = vim_strsave((char_u *)"");
3307 text_len = 0;
3308 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003309 else
3310 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003311 text = ga.ga_data;
3312 text_len = ga.ga_len;
3313 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003314 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003315 if (update_buffer)
3316 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003317
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003318 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003319 line->sb_cols = len;
3320 line->sb_cells = p;
3321 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003322 if (update_buffer)
3323 {
3324 line->sb_text = NULL;
3325 ++term->tl_scrollback_scrolled;
3326 ga_clear(&ga); // free the text
3327 }
3328 else
3329 {
3330 line->sb_text = text;
3331 ga_init(&ga); // text is kept in tl_scrollback_postponed
3332 }
3333 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003334 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003335 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003336}
3337
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003338/*
3339 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3340 * received and stored in tl_scrollback_postponed.
3341 */
3342 static void
3343handle_postponed_scrollback(term_T *term)
3344{
3345 int i;
3346
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003347 if (term->tl_scrollback_postponed.ga_len == 0)
3348 return;
3349 ch_log(NULL, "Moving postponed scrollback to scrollback");
3350
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003351 // First remove the lines that were appended before, the pushed lines go
3352 // above it.
3353 cleanup_scrollback(term);
3354
3355 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3356 {
3357 char_u *text;
3358 sb_line_T *pp_line;
3359 sb_line_T *line;
3360
3361 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3362 break;
3363 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3364
3365 text = pp_line->sb_text;
3366 if (text == NULL)
3367 text = (char_u *)"";
3368 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3369 vim_free(pp_line->sb_text);
3370
3371 line = (sb_line_T *)term->tl_scrollback.ga_data
3372 + term->tl_scrollback.ga_len;
3373 line->sb_cols = pp_line->sb_cols;
3374 line->sb_cells = pp_line->sb_cells;
3375 line->sb_fill_attr = pp_line->sb_fill_attr;
3376 line->sb_text = NULL;
3377 ++term->tl_scrollback_scrolled;
3378 ++term->tl_scrollback.ga_len;
3379 }
3380
3381 ga_clear(&term->tl_scrollback_postponed);
3382 limit_scrollback(term, &term->tl_scrollback, TRUE);
3383}
3384
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003385static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003386 handle_damage, // damage
3387 handle_moverect, // moverect
3388 handle_movecursor, // movecursor
3389 handle_settermprop, // settermprop
3390 NULL, // bell
3391 handle_resize, // resize
3392 handle_pushline, // sb_pushline
3393 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003394};
3395
3396/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003397 * Do the work after the channel of a terminal was closed.
3398 * Must be called only when updating_screen is FALSE.
3399 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3400 */
3401 static int
3402term_after_channel_closed(term_T *term)
3403{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003404 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003405 if (!term->tl_normal_mode)
3406 {
3407 int fnum = term->tl_buffer->b_fnum;
3408
3409 cleanup_vterm(term);
3410
3411 if (term->tl_finish == TL_FINISH_CLOSE)
3412 {
3413 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003414 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003415#ifdef FEAT_PROP_POPUP
3416 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003417
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003418 // If this was a terminal in a popup window, go back to the
3419 // previous window.
3420 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3421 {
3422 pwin = curwin;
3423 if (win_valid(prevwin))
3424 win_enter(prevwin, FALSE);
3425 }
3426 else
3427#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003428 // If this is the last normal window: exit Vim.
3429 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3430 {
3431 exarg_T ea;
3432
Bram Moolenaara80faa82020-04-12 19:37:17 +02003433 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003434 ex_quit(&ea);
3435 return TRUE;
3436 }
3437
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003438 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003439 ch_log(NULL, "terminal job finished, closing window");
3440 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003441 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003442 if (curwin == aucmd_win)
3443 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003444 if (do_set_w_closing)
3445 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003446 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003447 if (do_set_w_closing)
3448 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003449 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003450#ifdef FEAT_PROP_POPUP
3451 if (pwin != NULL)
3452 popup_close_with_retval(pwin, 0);
3453#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003454 return TRUE;
3455 }
3456 if (term->tl_finish == TL_FINISH_OPEN
3457 && term->tl_buffer->b_nwindows == 0)
3458 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003459 char *cmd = term->tl_opencmd == NULL
3460 ? "botright sbuf %d"
3461 : (char *)term->tl_opencmd;
3462 size_t len = strlen(cmd) + 50;
3463 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003464
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003465 if (buf != NULL)
3466 {
3467 ch_log(NULL, "terminal job finished, opening window");
3468 vim_snprintf(buf, len, cmd, fnum);
3469 do_cmdline_cmd((char_u *)buf);
3470 vim_free(buf);
3471 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003472 }
3473 else
3474 ch_log(NULL, "terminal job finished");
3475 }
3476
3477 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3478 return FALSE;
3479}
3480
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003481#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3482/*
3483 * If the current window is a terminal in a popup window and the job has
3484 * finished, close the popup window and to back to the previous window.
3485 * Otherwise return FAIL.
3486 */
3487 int
3488may_close_term_popup(void)
3489{
3490 if (popup_is_popup(curwin) && curbuf->b_term != NULL
3491 && !term_job_running(curbuf->b_term))
3492 {
3493 win_T *pwin = curwin;
3494
3495 if (win_valid(prevwin))
3496 win_enter(prevwin, FALSE);
3497 popup_close_with_retval(pwin, 0);
3498 return OK;
3499 }
3500 return FAIL;
3501}
3502#endif
3503
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003504/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003505 * Called when a channel is going to be closed, before invoking the close
3506 * callback.
3507 */
3508 void
3509term_channel_closing(channel_T *ch)
3510{
3511 term_T *term;
3512
3513 for (term = first_term; term != NULL; term = term->tl_next)
3514 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3515 term->tl_channel_closing = TRUE;
3516}
3517
3518/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003519 * Called when a channel has been closed.
3520 * If this was a channel for a terminal window then finish it up.
3521 */
3522 void
3523term_channel_closed(channel_T *ch)
3524{
3525 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003526 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003527 int did_one = FALSE;
3528
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003529 for (term = first_term; term != NULL; term = next_term)
3530 {
3531 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003532 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003533 {
3534 term->tl_channel_closed = TRUE;
3535 did_one = TRUE;
3536
Bram Moolenaard23a8232018-02-10 18:45:26 +01003537 VIM_CLEAR(term->tl_title);
3538 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003539#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003540 if (term->tl_out_fd != NULL)
3541 {
3542 fclose(term->tl_out_fd);
3543 term->tl_out_fd = NULL;
3544 }
3545#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003546
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003547 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003548 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003549 // Cannot open or close windows now. Can happen when
3550 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003551 term->tl_channel_recently_closed = TRUE;
3552 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003553 }
3554
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003555 if (term_after_channel_closed(term))
3556 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003557 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003558 }
3559
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003560 if (did_one)
3561 {
3562 redraw_statuslines();
3563
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003564 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003565 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003566 typebuf_was_filled = TRUE;
3567
3568 term = curbuf->b_term;
3569 if (term != NULL)
3570 {
3571 if (term->tl_job == ch->ch_job)
3572 maketitle();
3573 update_cursor(term, term->tl_cursor_visible);
3574 }
3575 }
3576}
3577
3578/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003579 * To be called after resetting updating_screen: handle any terminal where the
3580 * channel was closed.
3581 */
3582 void
3583term_check_channel_closed_recently()
3584{
3585 term_T *term;
3586 term_T *next_term;
3587
3588 for (term = first_term; term != NULL; term = next_term)
3589 {
3590 next_term = term->tl_next;
3591 if (term->tl_channel_recently_closed)
3592 {
3593 term->tl_channel_recently_closed = FALSE;
3594 if (term_after_channel_closed(term))
3595 // start over, the list may have changed
3596 next_term = first_term;
3597 }
3598 }
3599}
3600
3601/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003602 * Fill one screen line from a line of the terminal.
3603 * Advances "pos" to past the last column.
3604 */
3605 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003606term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003607 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003608 win_T *wp,
3609 VTermScreen *screen,
3610 VTermPos *pos,
3611 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003612{
3613 int off = screen_get_current_line_off();
3614
3615 for (pos->col = 0; pos->col < max_col; )
3616 {
3617 VTermScreenCell cell;
3618 int c;
3619
3620 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003621 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003622
3623 c = cell.chars[0];
3624 if (c == NUL)
3625 {
3626 ScreenLines[off] = ' ';
3627 if (enc_utf8)
3628 ScreenLinesUC[off] = NUL;
3629 }
3630 else
3631 {
3632 if (enc_utf8)
3633 {
3634 int i;
3635
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003636 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003637 for (i = 0; i < Screen_mco
3638 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3639 {
3640 ScreenLinesC[i][off] = cell.chars[i + 1];
3641 if (cell.chars[i + 1] == 0)
3642 break;
3643 }
3644 if (c >= 0x80 || (Screen_mco > 0
3645 && ScreenLinesC[0][off] != 0))
3646 {
3647 ScreenLines[off] = ' ';
3648 ScreenLinesUC[off] = c;
3649 }
3650 else
3651 {
3652 ScreenLines[off] = c;
3653 ScreenLinesUC[off] = NUL;
3654 }
3655 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003656#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003657 else if (has_mbyte && c >= 0x80)
3658 {
3659 char_u mb[MB_MAXBYTES+1];
3660 WCHAR wc = c;
3661
3662 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3663 (char*)mb, 2, 0, 0) > 1)
3664 {
3665 ScreenLines[off] = mb[0];
3666 ScreenLines[off + 1] = mb[1];
3667 cell.width = mb_ptr2cells(mb);
3668 }
3669 else
3670 ScreenLines[off] = c;
3671 }
3672#endif
3673 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003674 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003675 ScreenLines[off] = c;
3676 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003677 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3678 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003679
3680 ++pos->col;
3681 ++off;
3682 if (cell.width == 2)
3683 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003684 // don't set the second byte to NUL for a DBCS encoding, it
3685 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003686 if (enc_utf8)
3687 {
3688 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003689 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003690 }
3691 else if (!has_mbyte)
3692 {
3693 // Can't show a double-width character with a single-byte
3694 // 'encoding', just use a space.
3695 ScreenLines[off] = ' ';
3696 ScreenAttrs[off] = ScreenAttrs[off - 1];
3697 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003698
3699 ++pos->col;
3700 ++off;
3701 }
3702 }
3703}
3704
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003705#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003706 static void
3707update_system_term(term_T *term)
3708{
3709 VTermPos pos;
3710 VTermScreen *screen;
3711
3712 if (term->tl_vterm == NULL)
3713 return;
3714 screen = vterm_obtain_screen(term->tl_vterm);
3715
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003716 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003717 while (term->tl_toprow > 0
3718 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3719 {
3720 int save_p_more = p_more;
3721
3722 p_more = FALSE;
3723 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003724 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003725 p_more = save_p_more;
3726 --term->tl_toprow;
3727 }
3728
3729 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3730 && pos.row < Rows; ++pos.row)
3731 {
3732 if (pos.row < term->tl_rows)
3733 {
3734 int max_col = MIN(Columns, term->tl_cols);
3735
Bram Moolenaar83d47902020-03-26 20:34:00 +01003736 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003737 }
3738 else
3739 pos.col = 0;
3740
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003741 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003742 }
3743
3744 term->tl_dirty_row_start = MAX_ROW;
3745 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003746}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003747#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003748
3749/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003750 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3751 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003752 * Terminal-Normal mode.
3753 */
3754 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003755term_do_update_window(win_T *wp)
3756{
3757 term_T *term = wp->w_buffer->b_term;
3758
3759 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3760}
3761
3762/*
3763 * Called to update a window that contains an active terminal.
3764 */
3765 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003766term_update_window(win_T *wp)
3767{
3768 term_T *term = wp->w_buffer->b_term;
3769 VTerm *vterm;
3770 VTermScreen *screen;
3771 VTermState *state;
3772 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003773 int rows, cols;
3774 int newrows, newcols;
3775 int minsize;
3776 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003777
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003778 vterm = term->tl_vterm;
3779 screen = vterm_obtain_screen(vterm);
3780 state = vterm_obtain_state(vterm);
3781
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003782 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3783 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003784 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003785 {
3786 term->tl_dirty_row_start = 0;
3787 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003788
3789 if (term->tl_postponed_scroll > 0
3790 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003791 // Scrolling is usually faster than redrawing, when there are only
3792 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003793 term_scroll_up(term, 0, term->tl_postponed_scroll);
3794 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003795 }
3796
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003797 /*
3798 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003799 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003800 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003801 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003802
Bram Moolenaar498c2562018-04-15 23:45:15 +02003803 newrows = 99999;
3804 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003805 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003806 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003807 // Always use curwin, it may be a popup window.
3808 win_T *wwp = twp == NULL ? curwin : twp;
3809
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003810 // When more than one window shows the same terminal, use the
3811 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003812 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003813 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003814 newrows = MIN(newrows, wwp->w_height);
3815 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003816 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003817 if (twp == NULL)
3818 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003819 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003820 if (newrows == 99999 || newcols == 99999)
3821 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003822 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3823 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3824
Bram Moolenaareba13e42021-02-23 17:47:23 +01003825 // If no cell is visible there is no point in resizing. Also, vterm can't
3826 // handle a zero height.
3827 if (newrows == 0 || newcols == 0)
3828 return;
3829
Bram Moolenaar498c2562018-04-15 23:45:15 +02003830 if (term->tl_rows != newrows || term->tl_cols != newcols)
3831 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003832 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003833 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003834 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003835 newrows);
3836 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003837
3838 // Updating the terminal size will cause the snapshot to be cleared.
3839 // When not in terminal_loop() we need to restore it.
3840 if (term != in_terminal_loop)
3841 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003842 }
3843
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003844 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003845 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003846 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003847
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003848 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3849 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003850 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003851 if (pos.row < term->tl_rows)
3852 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003853 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003854
Bram Moolenaar83d47902020-03-26 20:34:00 +01003855 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003856 }
3857 else
3858 pos.col = 0;
3859
Bram Moolenaarf118d482018-03-13 13:14:00 +01003860 screen_line(wp->w_winrow + pos.row
3861#ifdef FEAT_MENU
3862 + winbar_height(wp)
3863#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003864 , wp->w_wincol, pos.col, wp->w_width,
3865#ifdef FEAT_PROP_POPUP
3866 popup_is_popup(wp) ? SLF_POPUP :
3867#endif
3868 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003869 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00003870}
3871
3872/*
3873 * Called after updating all windows: may reset dirty rows.
3874 */
3875 void
3876term_did_update_window(win_T *wp)
3877{
3878 term_T *term = wp->w_buffer->b_term;
3879
3880 if (term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode
3881 && wp->w_redr_type == 0)
3882 {
3883 term->tl_dirty_row_start = MAX_ROW;
3884 term->tl_dirty_row_end = 0;
3885 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003886}
3887
3888/*
3889 * Return TRUE if "wp" is a terminal window where the job has finished.
3890 */
3891 int
3892term_is_finished(buf_T *buf)
3893{
3894 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3895}
3896
3897/*
3898 * Return TRUE if "wp" is a terminal window where the job has finished or we
3899 * are in Terminal-Normal mode, thus we show the buffer contents.
3900 */
3901 int
3902term_show_buffer(buf_T *buf)
3903{
3904 term_T *term = buf->b_term;
3905
3906 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3907}
3908
3909/*
3910 * The current buffer is going to be changed. If there is terminal
3911 * highlighting remove it now.
3912 */
3913 void
3914term_change_in_curbuf(void)
3915{
3916 term_T *term = curbuf->b_term;
3917
3918 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3919 {
3920 free_scrollback(term);
3921 redraw_buf_later(term->tl_buffer, NOT_VALID);
3922
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003923 // The buffer is now like a normal buffer, it cannot be easily
3924 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003925 set_string_option_direct((char_u *)"buftype", -1,
3926 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3927 }
3928}
3929
3930/*
3931 * Get the screen attribute for a position in the buffer.
3932 * Use a negative "col" to get the filler background color.
3933 */
3934 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003935term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003936{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003937 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003938 term_T *term = buf->b_term;
3939 sb_line_T *line;
3940 cellattr_T *cellattr;
3941
3942 if (lnum > term->tl_scrollback.ga_len)
3943 cellattr = &term->tl_default_color;
3944 else
3945 {
3946 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3947 if (col < 0 || col >= line->sb_cols)
3948 cellattr = &line->sb_fill_attr;
3949 else
3950 cellattr = line->sb_cells + col;
3951 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003952 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003953}
3954
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003955/*
3956 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003957 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003958 */
3959 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003960cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003961{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003962 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
3963 if (rgb->index == 0)
3964 rgb->type = VTERM_COLOR_RGB;
3965 else
3966 {
3967 rgb->type = VTERM_COLOR_INDEXED;
3968 --rgb->index;
3969 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003970}
3971
3972/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003973 * Initialize vterm color from the synID.
3974 * Returns TRUE if color is set to "fg" and "bg".
3975 * Otherwise returns FALSE.
3976 */
3977 static int
3978get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
3979{
3980#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3981 // Use the actual color for the GUI and when 'termguicolors' is set.
3982 if (0
3983# ifdef FEAT_GUI
3984 || gui.in_use
3985# endif
3986# ifdef FEAT_TERMGUICOLORS
3987 || p_tgc
3988# ifdef FEAT_VTP
3989 // Finally get INVALCOLOR on this execution path
3990 || (!p_tgc && t_colors >= 256)
3991# endif
3992# endif
3993 )
3994 {
3995 guicolor_T fg_rgb = INVALCOLOR;
3996 guicolor_T bg_rgb = INVALCOLOR;
3997
3998 if (id > 0)
3999 syn_id2colors(id, &fg_rgb, &bg_rgb);
4000
4001 if (fg_rgb != INVALCOLOR)
4002 {
4003 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4004 fg->red = (unsigned)(rgb >> 16);
4005 fg->green = (unsigned)(rgb >> 8) & 255;
4006 fg->blue = (unsigned)rgb & 255;
4007 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4008 }
4009 else
4010 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4011
4012 if (bg_rgb != INVALCOLOR)
4013 {
4014 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4015 bg->red = (unsigned)(rgb >> 16);
4016 bg->green = (unsigned)(rgb >> 8) & 255;
4017 bg->blue = (unsigned)rgb & 255;
4018 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4019 }
4020 else
4021 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4022
4023 return TRUE;
4024 }
4025 else
4026#endif
4027 if (t_colors >= 16)
4028 {
4029 int cterm_fg = -1;
4030 int cterm_bg = -1;
4031
4032 if (id > 0)
4033 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4034
4035 if (cterm_fg >= 0)
4036 {
4037 cterm_color2vterm(cterm_fg, fg);
4038 fg->type |= VTERM_COLOR_DEFAULT_FG;
4039 }
4040 else
4041 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4042
4043 if (cterm_bg >= 0)
4044 {
4045 cterm_color2vterm(cterm_bg, bg);
4046 bg->type |= VTERM_COLOR_DEFAULT_BG;
4047 }
4048 else
4049 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4050
4051 return TRUE;
4052 }
4053
4054 return FALSE;
4055}
4056
4057 void
4058term_reset_wincolor(win_T *wp)
4059{
4060 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4061 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4062}
4063
4064/*
4065 * Cache the color of 'wincolor'.
4066 */
4067 void
4068term_update_wincolor(win_T *wp)
4069{
4070 int id = 0;
4071
4072 if (*wp->w_p_wcr != NUL)
4073 id = syn_name2id(wp->w_p_wcr);
4074 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4075 &wp->w_term_wincolor.bg))
4076 term_reset_wincolor(wp);
4077}
4078
4079/*
4080 * Called when option 'termguicolors' was set,
4081 * or when any highlight is changed.
4082 */
4083 void
4084term_update_wincolor_all()
4085{
4086 win_T *wp = NULL;
4087 int did_curwin = FALSE;
4088
4089 while (for_all_windows_and_curwin(&wp, &did_curwin))
4090 term_update_wincolor(wp);
4091}
4092
4093/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004094 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004095 */
4096 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004097init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004098{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004099 VTermColor *fg, *bg;
4100 int fgval, bgval;
4101 int id;
4102
Bram Moolenaara80faa82020-04-12 19:37:17 +02004103 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004104 term->tl_default_color.width = 1;
4105 fg = &term->tl_default_color.fg;
4106 bg = &term->tl_default_color.bg;
4107
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004108 // Vterm uses a default black background. Set it to white when
4109 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004110 if (*p_bg == 'l')
4111 {
4112 fgval = 0;
4113 bgval = 255;
4114 }
4115 else
4116 {
4117 fgval = 255;
4118 bgval = 0;
4119 }
4120 fg->red = fg->green = fg->blue = fgval;
4121 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004122 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4123 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004124
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004125 // The highlight group overrules the defaults.
4126 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004127
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004128 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004129 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004130#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004131 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004132#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004133
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004134 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004135 if (cterm_normal_fg_color > 0)
4136 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004137 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004138# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4139# ifdef VIMDLL
4140 if (!gui.in_use)
4141# endif
4142 {
4143 tmp = fg->red;
4144 fg->red = fg->blue;
4145 fg->blue = tmp;
4146 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004147# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004148 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004149# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004150 else
4151 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004152# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004153
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004154 if (cterm_normal_bg_color > 0)
4155 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004156 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004157# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4158# ifdef VIMDLL
4159 if (!gui.in_use)
4160# endif
4161 {
4162 tmp = fg->red;
4163 fg->red = fg->blue;
4164 fg->blue = tmp;
4165 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004166# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004167 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004168# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004169 else
4170 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004171# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004172 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004173}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004174
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004175#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4176/*
4177 * Set the 16 ANSI colors from array of RGB values
4178 */
4179 static void
4180set_vterm_palette(VTerm *vterm, long_u *rgb)
4181{
4182 int index = 0;
4183 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004184
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004185 for (; index < 16; index++)
4186 {
4187 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004188
Millyb771b6b2021-11-23 12:07:25 +00004189 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004190 color.red = (unsigned)(rgb[index] >> 16);
4191 color.green = (unsigned)(rgb[index] >> 8) & 255;
4192 color.blue = (unsigned)rgb[index] & 255;
4193 vterm_state_set_palette_color(state, index, &color);
4194 }
4195}
4196
4197/*
4198 * Set the ANSI color palette from a list of colors
4199 */
4200 static int
4201set_ansi_colors_list(VTerm *vterm, list_T *list)
4202{
4203 int n = 0;
4204 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004205 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004206
Bram Moolenaarb0992022020-01-30 14:55:42 +01004207 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004208 {
4209 char_u *color_name;
4210 guicolor_T guicolor;
4211
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004212 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004213 if (color_name == NULL)
4214 return FAIL;
4215
4216 guicolor = GUI_GET_COLOR(color_name);
4217 if (guicolor == INVALCOLOR)
4218 return FAIL;
4219
4220 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4221 }
4222
4223 if (n != 16 || li != NULL)
4224 return FAIL;
4225
4226 set_vterm_palette(vterm, rgb);
4227
4228 return OK;
4229}
4230
4231/*
4232 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4233 */
4234 static void
4235init_vterm_ansi_colors(VTerm *vterm)
4236{
4237 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4238
4239 if (var != NULL
4240 && (var->di_tv.v_type != VAR_LIST
4241 || var->di_tv.vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +01004242 || var->di_tv.vval.v_list->lv_first == &range_list_item
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004243 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004244 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004245}
4246#endif
4247
Bram Moolenaar52acb112018-03-18 19:20:22 +01004248/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004249 * Handles a "drop" command from the job in the terminal.
4250 * "item" is the file name, "item->li_next" may have options.
4251 */
4252 static void
4253handle_drop_command(listitem_T *item)
4254{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004255 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004256 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004257 int bufnr;
4258 win_T *wp;
4259 tabpage_T *tp;
4260 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004261 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004262
4263 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4264 FOR_ALL_TAB_WINDOWS(tp, wp)
4265 {
4266 if (wp->w_buffer->b_fnum == bufnr)
4267 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004268 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004269 goto_tabpage_win(tp, wp);
4270 return;
4271 }
4272 }
4273
Bram Moolenaara80faa82020-04-12 19:37:17 +02004274 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004275
4276 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4277 && opt_item->li_tv.vval.v_dict != NULL)
4278 {
4279 dict_T *dict = opt_item->li_tv.vval.v_dict;
4280 char_u *p;
4281
Bram Moolenaar8f667172018-12-14 15:38:31 +01004282 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004283 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004284 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004285 if (p != NULL)
4286 {
4287 if (check_ff_value(p) == FAIL)
4288 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4289 else
4290 ea.force_ff = *p;
4291 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01004292 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004293 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004294 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004295 if (p != NULL)
4296 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004297 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004298 if (ea.cmd != NULL)
4299 {
4300 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4301 ea.force_enc = 11;
4302 tofree = ea.cmd;
4303 }
4304 }
4305
Bram Moolenaar8f667172018-12-14 15:38:31 +01004306 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004307 if (p != NULL)
4308 get_bad_opt(p, &ea);
4309
4310 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
4311 ea.force_bin = FORCE_BIN;
4312 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
4313 ea.force_bin = FORCE_BIN;
4314 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
4315 ea.force_bin = FORCE_NOBIN;
4316 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
4317 ea.force_bin = FORCE_NOBIN;
4318 }
4319
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004320 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004321 if (ea.cmd == NULL)
4322 ea.cmd = (char_u *)"split";
4323 ea.arg = fname;
4324 ea.cmdidx = CMD_split;
4325 ex_splitview(&ea);
4326
4327 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004328}
4329
4330/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004331 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4332 */
4333 static int
4334is_permitted_term_api(char_u *func, char_u *pat)
4335{
4336 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4337}
4338
4339/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004340 * Handles a function call from the job running in a terminal.
4341 * "item" is the function name, "item->li_next" has the arguments.
4342 */
4343 static void
4344handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4345{
4346 char_u *func;
4347 typval_T argvars[2];
4348 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004349 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004350
4351 if (item->li_next == NULL)
4352 {
4353 ch_log(channel, "Missing function arguments for call");
4354 return;
4355 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004356 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004357
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004358 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004359 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004360 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004361 return;
4362 }
4363
4364 argvars[0].v_type = VAR_NUMBER;
4365 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4366 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004367 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004368 funcexe.fe_firstline = 1L;
4369 funcexe.fe_lastline = 1L;
4370 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004371 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004372 {
4373 clear_tv(&rettv);
4374 ch_log(channel, "Function %s called", func);
4375 }
4376 else
4377 ch_log(channel, "Calling function %s failed", func);
4378}
4379
4380/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004381 * URL decoding (also know as Percent-encoding).
4382 *
4383 * Note this function currently is only used for decoding shell's
4384 * OSC 7 escape sequence which we can assume all bytes are valid
4385 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4386 * encoding bytes like 0xfe, 0xff.
4387 */
4388 static size_t
4389url_decode(const char *src, const size_t len, char_u *dst)
4390{
4391 size_t i = 0, j = 0;
4392
4393 while (i < len)
4394 {
4395 if (src[i] == '%' && i + 2 < len)
4396 {
4397 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4398 j++;
4399 i += 3;
4400 }
4401 else
4402 {
4403 dst[j] = src[i];
4404 i++;
4405 j++;
4406 }
4407 }
4408 dst[j] = '\0';
4409 return j;
4410}
4411
4412/*
4413 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4414 *
4415 * The OSC 7 sequence has the format of
4416 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4417 * and what VTerm provides via VTermStringFragment is
4418 * "file://HOSTNAME/CURRENT/DIR"
4419 */
4420 static void
4421sync_shell_dir(VTermStringFragment *frag)
4422{
4423 int offset = 7; // len of "file://" is 7
4424 char *pos = (char *)frag->str + offset;
4425 char_u *new_dir;
4426
4427 // remove HOSTNAME to get PWD
Bram Moolenaar918b0892021-05-08 20:09:24 +02004428 while (*pos != '/' && offset < (int)frag->len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004429 {
4430 offset += 1;
4431 pos += 1;
4432 }
4433
Bram Moolenaar918b0892021-05-08 20:09:24 +02004434 if (offset >= (int)frag->len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004435 {
4436 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
4437 frag->str);
4438 return;
4439 }
4440
4441 new_dir = alloc(frag->len - offset + 1);
4442 url_decode(pos, frag->len-offset, new_dir);
4443 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4444 vim_free(new_dir);
4445}
4446
4447/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004448 * Called by libvterm when it cannot recognize an OSC sequence.
4449 * We recognize a terminal API command.
4450 */
4451 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004452parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004453{
4454 term_T *term = (term_T *)user;
4455 js_read_T reader;
4456 typval_T tv;
4457 channel_T *channel = term->tl_job == NULL ? NULL
4458 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004459 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004460
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004461 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
4462 if (p_asd && command == 7)
4463 {
4464 sync_shell_dir(&frag);
4465 return 1;
4466 }
4467
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004468 if (command != 51)
4469 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004470
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004471 // Concatenate what was received until the final piece is found.
4472 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4473 {
4474 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004475 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004476 }
4477 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004478 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004479 if (!frag.final)
4480 return 1;
4481
4482 ((char *)gap->ga_data)[gap->ga_len] = 0;
4483 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004484 reader.js_fill = NULL;
4485 reader.js_used = 0;
4486 if (json_decode(&reader, &tv, 0) == OK
4487 && tv.v_type == VAR_LIST
4488 && tv.vval.v_list != NULL)
4489 {
4490 listitem_T *item = tv.vval.v_list->lv_first;
4491
4492 if (item == NULL)
4493 ch_log(channel, "Missing command");
4494 else
4495 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004496 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004497
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004498 // Make sure an invoked command doesn't delete the buffer (and the
4499 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004500 ++term->tl_buffer->b_locked;
4501
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004502 item = item->li_next;
4503 if (item == NULL)
4504 ch_log(channel, "Missing argument for %s", cmd);
4505 else if (STRCMP(cmd, "drop") == 0)
4506 handle_drop_command(item);
4507 else if (STRCMP(cmd, "call") == 0)
4508 handle_call_command(term, channel, item);
4509 else
4510 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004511 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004512 }
4513 }
4514 else
4515 ch_log(channel, "Invalid JSON received");
4516
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004517 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004518 clear_tv(&tv);
4519 return 1;
4520}
4521
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004522/*
4523 * Called by libvterm when it cannot recognize a CSI sequence.
4524 * We recognize the window position report.
4525 */
4526 static int
4527parse_csi(
4528 const char *leader UNUSED,
4529 const long args[],
4530 int argcount,
4531 const char *intermed UNUSED,
4532 char command,
4533 void *user)
4534{
4535 term_T *term = (term_T *)user;
4536 char buf[100];
4537 int len;
4538 int x = 0;
4539 int y = 0;
4540 win_T *wp;
4541
4542 // We recognize only CSI 13 t
4543 if (command != 't' || argcount != 1 || args[0] != 13)
4544 return 0; // not handled
4545
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004546 // When getting the window position is not possible or it fails it results
4547 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004548#if defined(FEAT_GUI) \
4549 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4550 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004551 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004552#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004553
4554 FOR_ALL_WINDOWS(wp)
4555 if (wp->w_buffer == term->tl_buffer)
4556 break;
4557 if (wp != NULL)
4558 {
4559#ifdef FEAT_GUI
4560 if (gui.in_use)
4561 {
4562 x += wp->w_wincol * gui.char_width;
4563 y += W_WINROW(wp) * gui.char_height;
4564 }
4565 else
4566#endif
4567 {
4568 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004569 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004570 x += wp->w_wincol * 7;
4571 y += W_WINROW(wp) * 10;
4572 }
4573 }
4574
4575 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4576 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4577 (char_u *)buf, len, NULL);
4578 return 1;
4579}
4580
Bram Moolenaard8637282020-05-20 18:41:41 +02004581static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004582 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004583 parse_csi, // csi
4584 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004585 NULL, // dcs
4586 NULL, // apc
4587 NULL, // pm
4588 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004589};
4590
4591/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004592 * Use Vim's allocation functions for vterm so profiling works.
4593 */
4594 static void *
4595vterm_malloc(size_t size, void *data UNUSED)
4596{
Bram Moolenaar88137392021-11-12 16:01:15 +00004597 // make sure that the length is not zero
4598 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004599}
4600
4601 static void
4602vterm_memfree(void *ptr, void *data UNUSED)
4603{
4604 vim_free(ptr);
4605}
4606
4607static VTermAllocatorFunctions vterm_allocator = {
4608 &vterm_malloc,
4609 &vterm_memfree
4610};
4611
4612/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004613 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004614 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004615 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004616 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004617create_vterm(term_T *term, int rows, int cols)
4618{
4619 VTerm *vterm;
4620 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004621 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004622 VTermValue value;
4623
Bram Moolenaar756ef112018-04-10 12:04:27 +02004624 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004625 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004626 if (vterm == NULL)
4627 return FAIL;
4628
4629 // Allocate screen and state here, so we can bail out if that fails.
4630 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004631 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004632 if (state == NULL || screen == NULL)
4633 {
4634 vterm_free(vterm);
4635 return FAIL;
4636 }
4637
Bram Moolenaar52acb112018-03-18 19:20:22 +01004638 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004639 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004640 vterm_set_utf8(vterm, 1);
4641
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004642 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004643
4644 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004645 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004646 &term->tl_default_color.fg,
4647 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004648
Bram Moolenaar9e587872019-05-13 20:27:23 +02004649 if (t_colors < 16)
4650 // Less than 16 colors: assume that bold means using a bright color for
4651 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004652 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4653
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004654 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004655 vterm_screen_reset(screen, 1 /* hard */);
4656
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004657 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004658 vterm_screen_enable_altscreen(screen, 1);
4659
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004660 // For unix do not use a blinking cursor. In an xterm this causes the
4661 // cursor to blink if it's blinking in the xterm.
4662 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004663#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004664 if (GetCaretBlinkTime() == INFINITE)
4665 value.boolean = 0;
4666 else
4667 value.boolean = 1;
4668#else
4669 value.boolean = 0;
4670#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004671 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004672 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004673
4674 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004675}
4676
4677/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004678 * Called when option 'background' or 'termguicolors' was set,
4679 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02004680 */
4681 void
4682term_update_colors_all(void)
4683{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004684 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02004685
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004686 FOR_ALL_TERMS(term)
4687 {
4688 if (term->tl_vterm == NULL)
4689 continue;
4690 init_default_colors(term);
4691 vterm_state_set_default_colors(
4692 vterm_obtain_state(term->tl_vterm),
4693 &term->tl_default_color.fg,
4694 &term->tl_default_color.bg);
4695 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004696}
4697
4698/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004699 * Return the text to show for the buffer name and status.
4700 */
4701 char_u *
4702term_get_status_text(term_T *term)
4703{
4704 if (term->tl_status_text == NULL)
4705 {
4706 char_u *txt;
4707 size_t len;
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004708 char_u *fname;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004709
4710 if (term->tl_normal_mode)
4711 {
4712 if (term_job_running(term))
4713 txt = (char_u *)_("Terminal");
4714 else
4715 txt = (char_u *)_("Terminal-finished");
4716 }
4717 else if (term->tl_title != NULL)
4718 txt = term->tl_title;
4719 else if (term_none_open(term))
4720 txt = (char_u *)_("active");
4721 else if (term_job_running(term))
4722 txt = (char_u *)_("running");
4723 else
4724 txt = (char_u *)_("finished");
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004725 fname = buf_get_fname(term->tl_buffer);
4726 len = 9 + STRLEN(fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004727 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004728 if (term->tl_status_text != NULL)
4729 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004730 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004731 }
4732 return term->tl_status_text;
4733}
4734
4735/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00004736 * Clear the cached value of the status text.
4737 */
4738 void
4739term_clear_status_text(term_T *term)
4740{
4741 VIM_CLEAR(term->tl_status_text);
4742}
4743
4744/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004745 * Mark references in jobs of terminals.
4746 */
4747 int
4748set_ref_in_term(int copyID)
4749{
4750 int abort = FALSE;
4751 term_T *term;
4752 typval_T tv;
4753
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004754 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004755 if (term->tl_job != NULL)
4756 {
4757 tv.v_type = VAR_JOB;
4758 tv.vval.v_job = term->tl_job;
4759 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4760 }
4761 return abort;
4762}
4763
4764/*
4765 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004766 * Returns NULL when the buffer is not for a terminal window and logs a message
4767 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004768 */
4769 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004770term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004771{
4772 buf_T *buf;
4773
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004774 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004775 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004776 --emsg_off;
4777 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004778 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01004779 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004780 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004781 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004782 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004783 return buf;
4784}
4785
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004786 static void
4787clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004788{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004789 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004790 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4791 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004792}
4793
4794 static void
4795dump_term_color(FILE *fd, VTermColor *color)
4796{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004797 int index;
4798
4799 if (VTERM_COLOR_IS_INDEXED(color))
4800 index = color->index + 1;
4801 else if (color->type == 0)
4802 // use RGB values
4803 index = 255;
4804 else
4805 // default color
4806 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004807 fprintf(fd, "%02x%02x%02x%d",
4808 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004809 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004810}
4811
4812/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004813 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004814 *
4815 * Each screen cell in full is:
4816 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4817 * {characters} is a space for an empty cell
4818 * For a double-width character "+" is changed to "*" and the next cell is
4819 * skipped.
4820 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4821 * when "&" use the same as the previous cell.
4822 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4823 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4824 * {color-idx} is a number from 0 to 255
4825 *
4826 * Screen cell with same width, attributes and color as the previous one:
4827 * |{characters}
4828 *
4829 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4830 *
4831 * Repeating the previous screen cell:
4832 * @{count}
4833 */
4834 void
4835f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4836{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02004837 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004838 term_T *term;
4839 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004840 int max_height = 0;
4841 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004842 stat_T st;
4843 FILE *fd;
4844 VTermPos pos;
4845 VTermScreen *screen;
4846 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004847 VTermState *state;
4848 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004849
4850 if (check_restricted() || check_secure())
4851 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02004852
4853 if (in_vim9script()
4854 && (check_for_buffer_arg(argvars, 0) == FAIL
4855 || check_for_string_arg(argvars, 1) == FAIL
4856 || check_for_opt_dict_arg(argvars, 2) == FAIL))
4857 return;
4858
4859 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004860 if (buf == NULL)
4861 return;
4862 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004863 if (term->tl_vterm == NULL)
4864 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004865 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004866 return;
4867 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004868
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004869 if (argvars[2].v_type != VAR_UNKNOWN)
4870 {
4871 dict_T *d;
4872
4873 if (argvars[2].v_type != VAR_DICT)
4874 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00004875 emsg(_(e_dictionary_required));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004876 return;
4877 }
4878 d = argvars[2].vval.v_dict;
4879 if (d != NULL)
4880 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004881 max_height = dict_get_number(d, (char_u *)"rows");
4882 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004883 }
4884 }
4885
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004886 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004887 if (fname == NULL)
4888 return;
4889 if (mch_stat((char *)fname, &st) >= 0)
4890 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004891 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004892 return;
4893 }
4894
Bram Moolenaard96ff162018-02-18 22:13:29 +01004895 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4896 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00004897 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004898 return;
4899 }
4900
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004901 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004902
4903 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004904 state = vterm_obtain_state(term->tl_vterm);
4905 vterm_state_get_cursorpos(state, &cursor_pos);
4906
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004907 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4908 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004909 {
4910 int repeat = 0;
4911
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004912 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4913 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004914 {
4915 VTermScreenCell cell;
4916 int same_attr;
4917 int same_chars = TRUE;
4918 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004919 int is_cursor_pos = (pos.col == cursor_pos.col
4920 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004921
4922 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004923 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004924
4925 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4926 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004927 int c = cell.chars[i];
4928 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02004929 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01004930
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004931 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01004932 if (i == 0)
4933 {
4934 c = (c == NUL) ? ' ' : c;
4935 pc = (pc == NUL) ? ' ' : pc;
4936 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004937 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004938 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02004939 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004940 break;
4941 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004942 same_attr = vtermAttr2hl(&cell.attrs)
4943 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004944 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
4945 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004946 if (same_chars && cell.width == prev_cell.width && same_attr
4947 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004948 {
4949 ++repeat;
4950 }
4951 else
4952 {
4953 if (repeat > 0)
4954 {
4955 fprintf(fd, "@%d", repeat);
4956 repeat = 0;
4957 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004958 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004959
4960 if (cell.chars[0] == NUL)
4961 fputs(" ", fd);
4962 else
4963 {
4964 char_u charbuf[10];
4965 int len;
4966
4967 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4968 && cell.chars[i] != NUL; ++i)
4969 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004970 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004971 fwrite(charbuf, len, 1, fd);
4972 }
4973 }
4974
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004975 // When only the characters differ we don't write anything, the
4976 // following "|", "@" or NL will indicate using the same
4977 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004978 if (cell.width != prev_cell.width || !same_attr)
4979 {
4980 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004981 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004982 else
4983 fputs("+", fd);
4984
4985 if (same_attr)
4986 {
4987 fputs("&", fd);
4988 }
4989 else
4990 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004991 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004992 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01004993 fputs("&", fd);
4994 else
4995 {
4996 fputs("#", fd);
4997 dump_term_color(fd, &cell.fg);
4998 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004999 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005000 fputs("&", fd);
5001 else
5002 {
5003 fputs("#", fd);
5004 dump_term_color(fd, &cell.bg);
5005 }
5006 }
5007 }
5008
5009 prev_cell = cell;
5010 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005011
5012 if (cell.width == 2)
5013 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005014 }
5015 if (repeat > 0)
5016 fprintf(fd, "@%d", repeat);
5017 fputs("\n", fd);
5018 }
5019
5020 fclose(fd);
5021}
5022
5023/*
5024 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5025 */
5026 static void
5027dump_is_corrupt(garray_T *gap)
5028{
5029 ga_concat(gap, (char_u *)"CORRUPT");
5030}
5031
5032 static void
5033append_cell(garray_T *gap, cellattr_T *cell)
5034{
5035 if (ga_grow(gap, 1) == OK)
5036 {
5037 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5038 ++gap->ga_len;
5039 }
5040}
5041
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005042 static void
5043clear_cellattr(cellattr_T *cell)
5044{
5045 CLEAR_FIELD(*cell);
5046 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5047 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5048}
5049
Bram Moolenaard96ff162018-02-18 22:13:29 +01005050/*
5051 * Read the dump file from "fd" and append lines to the current buffer.
5052 * Return the cell width of the longest line.
5053 */
5054 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005055read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005056{
5057 int c;
5058 garray_T ga_text;
5059 garray_T ga_cell;
5060 char_u *prev_char = NULL;
5061 int attr = 0;
5062 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005063 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005064 term_T *term = curbuf->b_term;
5065 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005066 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005067
5068 ga_init2(&ga_text, 1, 90);
5069 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005070 clear_cellattr(&cell);
5071 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005072 cursor_pos->row = -1;
5073 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005074
5075 c = fgetc(fd);
5076 for (;;)
5077 {
5078 if (c == EOF)
5079 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005080 if (c == '\r')
5081 {
5082 // DOS line endings? Ignore.
5083 c = fgetc(fd);
5084 }
5085 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005086 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005087 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005088 if (ga_text.ga_data == NULL)
5089 dump_is_corrupt(&ga_text);
5090 if (ga_grow(&term->tl_scrollback, 1) == OK)
5091 {
5092 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5093 + term->tl_scrollback.ga_len;
5094
5095 if (max_cells < ga_cell.ga_len)
5096 max_cells = ga_cell.ga_len;
5097 line->sb_cols = ga_cell.ga_len;
5098 line->sb_cells = ga_cell.ga_data;
5099 line->sb_fill_attr = term->tl_default_color;
5100 ++term->tl_scrollback.ga_len;
5101 ga_init(&ga_cell);
5102
5103 ga_append(&ga_text, NUL);
5104 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5105 ga_text.ga_len, FALSE);
5106 }
5107 else
5108 ga_clear(&ga_cell);
5109 ga_text.ga_len = 0;
5110
5111 c = fgetc(fd);
5112 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005113 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005114 {
5115 int prev_len = ga_text.ga_len;
5116
Bram Moolenaar9271d052018-02-25 21:39:46 +01005117 if (c == '>')
5118 {
5119 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005120 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005121 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5122 cursor_pos->col = ga_cell.ga_len;
5123 }
5124
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005125 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005126 c = fgetc(fd);
5127 if (c != EOF)
5128 ga_append(&ga_text, c);
5129 for (;;)
5130 {
5131 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005132 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005133 || c == EOF || c == '\n')
5134 break;
5135 ga_append(&ga_text, c);
5136 }
5137
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005138 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005139 vim_free(prev_char);
5140 if (ga_text.ga_data != NULL)
5141 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5142 ga_text.ga_len - prev_len);
5143
Bram Moolenaar9271d052018-02-25 21:39:46 +01005144 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005145 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005146 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005147 }
5148 else if (c == '+' || c == '*')
5149 {
5150 int is_bg;
5151
5152 cell.width = c == '+' ? 1 : 2;
5153
5154 c = fgetc(fd);
5155 if (c == '&')
5156 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005157 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005158 c = fgetc(fd);
5159 }
5160 else if (isdigit(c))
5161 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005162 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005163 attr = 0;
5164 while (isdigit(c))
5165 {
5166 attr = attr * 10 + (c - '0');
5167 c = fgetc(fd);
5168 }
5169 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005170
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005171 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005172 for (is_bg = 0; is_bg <= 1; ++is_bg)
5173 {
5174 if (c == '&')
5175 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005176 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005177 c = fgetc(fd);
5178 }
5179 else if (c == '#')
5180 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005181 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005182
5183 c = fgetc(fd);
5184 red = hex2nr(c);
5185 c = fgetc(fd);
5186 red = (red << 4) + hex2nr(c);
5187 c = fgetc(fd);
5188 green = hex2nr(c);
5189 c = fgetc(fd);
5190 green = (green << 4) + hex2nr(c);
5191 c = fgetc(fd);
5192 blue = hex2nr(c);
5193 c = fgetc(fd);
5194 blue = (blue << 4) + hex2nr(c);
5195 c = fgetc(fd);
5196 if (!isdigit(c))
5197 dump_is_corrupt(&ga_text);
5198 while (isdigit(c))
5199 {
5200 index = index * 10 + (c - '0');
5201 c = fgetc(fd);
5202 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005203 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005204 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005205 type = VTERM_COLOR_RGB;
5206 if (index == 0)
5207 {
5208 if (is_bg)
5209 type |= VTERM_COLOR_DEFAULT_BG;
5210 else
5211 type |= VTERM_COLOR_DEFAULT_FG;
5212 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005213 }
5214 else
5215 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005216 type = VTERM_COLOR_INDEXED;
5217 index -= 1;
5218 }
5219 if (is_bg)
5220 {
5221 cell.bg.type = type;
5222 cell.bg.red = red;
5223 cell.bg.green = green;
5224 cell.bg.blue = blue;
5225 cell.bg.index = index;
5226 }
5227 else
5228 {
5229 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005230 cell.fg.red = red;
5231 cell.fg.green = green;
5232 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005233 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005234 }
5235 }
5236 else
5237 dump_is_corrupt(&ga_text);
5238 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005239 }
5240 else
5241 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005242 }
5243 else
5244 dump_is_corrupt(&ga_text);
5245
5246 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005247 if (cell.width == 2)
5248 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005249 }
5250 else if (c == '@')
5251 {
5252 if (prev_char == NULL)
5253 dump_is_corrupt(&ga_text);
5254 else
5255 {
5256 int count = 0;
5257
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005258 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005259 for (;;)
5260 {
5261 c = fgetc(fd);
5262 if (!isdigit(c))
5263 break;
5264 count = count * 10 + (c - '0');
5265 }
5266
5267 while (count-- > 0)
5268 {
5269 ga_concat(&ga_text, prev_char);
5270 append_cell(&ga_cell, &cell);
5271 }
5272 }
5273 }
5274 else
5275 {
5276 dump_is_corrupt(&ga_text);
5277 c = fgetc(fd);
5278 }
5279 }
5280
5281 if (ga_text.ga_len > 0)
5282 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005283 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005284 dump_is_corrupt(&ga_text);
5285 ga_append(&ga_text, NUL);
5286 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5287 ga_text.ga_len, FALSE);
5288 }
5289
5290 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005291 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005292 vim_free(prev_char);
5293
5294 return max_cells;
5295}
5296
5297/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005298 * Return an allocated string with at least "text_width" "=" characters and
5299 * "fname" inserted in the middle.
5300 */
5301 static char_u *
5302get_separator(int text_width, char_u *fname)
5303{
5304 int width = MAX(text_width, curwin->w_width);
5305 char_u *textline;
5306 int fname_size;
5307 char_u *p = fname;
5308 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005309 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005310
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005311 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005312 if (textline == NULL)
5313 return NULL;
5314
5315 fname_size = vim_strsize(fname);
5316 if (fname_size < width - 8)
5317 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005318 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005319 width = MAX(text_width, fname_size + 8);
5320 }
5321 else if (fname_size > width - 8)
5322 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005323 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005324 p = gettail(fname);
5325 fname_size = vim_strsize(p);
5326 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005327 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005328 while (fname_size > width - 8)
5329 {
5330 p += (*mb_ptr2len)(p);
5331 fname_size = vim_strsize(p);
5332 }
5333
5334 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5335 textline[i] = '=';
5336 textline[i++] = ' ';
5337
5338 STRCPY(textline + i, p);
5339 off = STRLEN(textline);
5340 textline[off] = ' ';
5341 for (i = 1; i < (width - fname_size) / 2; ++i)
5342 textline[off + i] = '=';
5343 textline[off + i] = NUL;
5344
5345 return textline;
5346}
5347
5348/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005349 * Common for "term_dumpdiff()" and "term_dumpload()".
5350 */
5351 static void
5352term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5353{
5354 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005355 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005356 char_u buf1[NUMBUFLEN];
5357 char_u buf2[NUMBUFLEN];
5358 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005359 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005360 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005361 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005362 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005363 char_u *textline = NULL;
5364
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005365 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005366 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005367 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005368 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005369 if (fname1 == NULL || (do_diff && fname2 == NULL))
5370 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005371 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005372 return;
5373 }
5374 fd1 = mch_fopen((char *)fname1, READBIN);
5375 if (fd1 == NULL)
5376 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005377 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005378 return;
5379 }
5380 if (do_diff)
5381 {
5382 fd2 = mch_fopen((char *)fname2, READBIN);
5383 if (fd2 == NULL)
5384 {
5385 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005386 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005387 return;
5388 }
5389 }
5390
5391 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005392 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5393 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5394 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5395 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5396 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005397
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005398 if (opt.jo_term_name == NULL)
5399 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005400 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005401
Bram Moolenaar51e14382019-05-25 20:21:28 +02005402 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005403 if (fname_tofree != NULL)
5404 {
5405 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5406 opt.jo_term_name = fname_tofree;
5407 }
5408 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005409
Bram Moolenaar87abab92019-06-03 21:14:59 +02005410 if (opt.jo_bufnr_buf != NULL)
5411 {
5412 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5413
5414 // With "bufnr" argument: enter the window with this buffer and make it
5415 // empty.
5416 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005417 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005418 else
5419 {
5420 buf = curbuf;
5421 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005422 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005423 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005424 redraw_later(NOT_VALID);
5425 }
5426 }
5427 else
5428 // Create a new terminal window.
5429 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5430
Bram Moolenaard96ff162018-02-18 22:13:29 +01005431 if (buf != NULL && buf->b_term != NULL)
5432 {
5433 int i;
5434 linenr_T bot_lnum;
5435 linenr_T lnum;
5436 term_T *term = buf->b_term;
5437 int width;
5438 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005439 VTermPos cursor_pos1;
5440 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005441
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005442 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005443
Bram Moolenaard96ff162018-02-18 22:13:29 +01005444 rettv->vval.v_number = buf->b_fnum;
5445
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005446 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005447 width = read_dump_file(fd1, &cursor_pos1);
5448
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005449 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005450 if (cursor_pos1.row >= 0)
5451 {
5452 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5453 coladvance(cursor_pos1.col);
5454 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005455
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005456 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005457 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005458
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005459 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005460 if (!do_diff)
5461 goto theend;
5462
5463 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5464
Bram Moolenaar4a696342018-04-05 18:45:26 +02005465 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005466 if (textline == NULL)
5467 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005468 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5469 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5470 vim_free(textline);
5471
5472 textline = get_separator(width, fname2);
5473 if (textline == NULL)
5474 goto theend;
5475 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5476 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005477 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005478
5479 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005480 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005481 if (width2 > width)
5482 {
5483 vim_free(textline);
5484 textline = alloc(width2 + 1);
5485 if (textline == NULL)
5486 goto theend;
5487 width = width2;
5488 textline[width] = NUL;
5489 }
5490 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5491
5492 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5493 {
5494 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5495 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005496 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005497 for (i = 0; i < width; ++i)
5498 textline[i] = '-';
5499 }
5500 else
5501 {
5502 char_u *line1;
5503 char_u *line2;
5504 char_u *p1;
5505 char_u *p2;
5506 int col;
5507 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5508 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5509 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5510 ->sb_cells;
5511
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005512 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005513 line1 = vim_strsave(ml_get(lnum));
5514 if (line1 == NULL)
5515 break;
5516 p1 = line1;
5517
5518 line2 = ml_get(lnum + bot_lnum);
5519 p2 = line2;
5520 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5521 {
5522 int len1 = utfc_ptr2len(p1);
5523 int len2 = utfc_ptr2len(p2);
5524
5525 textline[col] = ' ';
5526 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005527 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005528 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005529 else if (lnum == cursor_pos1.row + 1
5530 && col == cursor_pos1.col
5531 && (cursor_pos1.row != cursor_pos2.row
5532 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005533 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005534 textline[col] = '>';
5535 else if (lnum == cursor_pos2.row + 1
5536 && col == cursor_pos2.col
5537 && (cursor_pos1.row != cursor_pos2.row
5538 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005539 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005540 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005541 else if (cellattr1 != NULL && cellattr2 != NULL)
5542 {
5543 if ((cellattr1 + col)->width
5544 != (cellattr2 + col)->width)
5545 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005546 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005547 &(cellattr2 + col)->fg))
5548 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005549 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005550 &(cellattr2 + col)->bg))
5551 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005552 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5553 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005554 textline[col] = 'a';
5555 }
5556 p1 += len1;
5557 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005558 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005559 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005560
5561 while (col < width)
5562 {
5563 if (*p1 == NUL && *p2 == NUL)
5564 textline[col] = '?';
5565 else if (*p1 == NUL)
5566 {
5567 textline[col] = '+';
5568 p2 += utfc_ptr2len(p2);
5569 }
5570 else
5571 {
5572 textline[col] = '-';
5573 p1 += utfc_ptr2len(p1);
5574 }
5575 ++col;
5576 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005577
5578 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005579 }
5580 if (add_empty_scrollback(term, &term->tl_default_color,
5581 term->tl_top_diff_rows) == OK)
5582 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5583 ++bot_lnum;
5584 }
5585
5586 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5587 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005588 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005589 for (i = 0; i < width; ++i)
5590 textline[i] = '+';
5591 if (add_empty_scrollback(term, &term->tl_default_color,
5592 term->tl_top_diff_rows) == OK)
5593 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5594 ++lnum;
5595 ++bot_lnum;
5596 }
5597
5598 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005599
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005600 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005601 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005602 }
5603
5604theend:
5605 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005606 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005607 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005608 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005609 fclose(fd2);
5610}
5611
5612/*
5613 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5614 * bottom files.
5615 * Return FAIL when this is not possible.
5616 */
5617 int
5618term_swap_diff()
5619{
5620 term_T *term = curbuf->b_term;
5621 linenr_T line_count;
5622 linenr_T top_rows;
5623 linenr_T bot_rows;
5624 linenr_T bot_start;
5625 linenr_T lnum;
5626 char_u *p;
5627 sb_line_T *sb_line;
5628
5629 if (term == NULL
5630 || !term_is_finished(curbuf)
5631 || term->tl_top_diff_rows == 0
5632 || term->tl_scrollback.ga_len == 0)
5633 return FAIL;
5634
5635 line_count = curbuf->b_ml.ml_line_count;
5636 top_rows = term->tl_top_diff_rows;
5637 bot_rows = term->tl_bot_diff_rows;
5638 bot_start = line_count - bot_rows;
5639 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5640
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005641 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005642 for (lnum = 1; lnum <= top_rows; ++lnum)
5643 {
5644 p = vim_strsave(ml_get(1));
5645 if (p == NULL)
5646 return OK;
5647 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005648 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005649 vim_free(p);
5650 }
5651
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005652 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005653 for (lnum = 1; lnum <= bot_rows; ++lnum)
5654 {
5655 p = vim_strsave(ml_get(bot_start + lnum));
5656 if (p == NULL)
5657 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005658 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005659 ml_append(lnum - 1, p, 0, FALSE);
5660 vim_free(p);
5661 }
5662
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005663 // move top title to bottom
5664 p = vim_strsave(ml_get(bot_rows + 1));
5665 if (p == NULL)
5666 return OK;
5667 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005668 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005669 vim_free(p);
5670
5671 // move bottom title to top
5672 p = vim_strsave(ml_get(line_count - top_rows));
5673 if (p == NULL)
5674 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005675 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005676 ml_append(bot_rows, p, 0, FALSE);
5677 vim_free(p);
5678
Bram Moolenaard96ff162018-02-18 22:13:29 +01005679 if (top_rows == bot_rows)
5680 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005681 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005682 for (lnum = 0; lnum < top_rows; ++lnum)
5683 {
5684 sb_line_T temp;
5685
5686 temp = *(sb_line + lnum);
5687 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5688 *(sb_line + bot_start + lnum) = temp;
5689 }
5690 }
5691 else
5692 {
5693 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005694 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005695
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005696 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005697 if (temp != NULL)
5698 {
5699 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5700 mch_memmove(term->tl_scrollback.ga_data,
5701 temp + bot_start,
5702 sizeof(sb_line_T) * bot_rows);
5703 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5704 temp + top_rows,
5705 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5706 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5707 + line_count - top_rows,
5708 temp,
5709 sizeof(sb_line_T) * top_rows);
5710 vim_free(temp);
5711 }
5712 }
5713
5714 term->tl_top_diff_rows = bot_rows;
5715 term->tl_bot_diff_rows = top_rows;
5716
5717 update_screen(NOT_VALID);
5718 return OK;
5719}
5720
5721/*
5722 * "term_dumpdiff(filename, filename, options)" function
5723 */
5724 void
5725f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5726{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005727 if (in_vim9script()
5728 && (check_for_string_arg(argvars, 0) == FAIL
5729 || check_for_string_arg(argvars, 1) == FAIL
5730 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5731 return;
5732
Bram Moolenaard96ff162018-02-18 22:13:29 +01005733 term_load_dump(argvars, rettv, TRUE);
5734}
5735
5736/*
5737 * "term_dumpload(filename, options)" function
5738 */
5739 void
5740f_term_dumpload(typval_T *argvars, typval_T *rettv)
5741{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005742 if (in_vim9script()
5743 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02005744 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005745 return;
5746
Bram Moolenaard96ff162018-02-18 22:13:29 +01005747 term_load_dump(argvars, rettv, FALSE);
5748}
5749
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005750/*
5751 * "term_getaltscreen(buf)" function
5752 */
5753 void
5754f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5755{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005756 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005757
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005758 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5759 return;
5760
5761 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005762 if (buf == NULL)
5763 return;
5764 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5765}
5766
5767/*
5768 * "term_getattr(attr, name)" function
5769 */
5770 void
5771f_term_getattr(typval_T *argvars, typval_T *rettv)
5772{
5773 int attr;
5774 size_t i;
5775 char_u *name;
5776
5777 static struct {
5778 char *name;
5779 int attr;
5780 } attrs[] = {
5781 {"bold", HL_BOLD},
5782 {"italic", HL_ITALIC},
5783 {"underline", HL_UNDERLINE},
5784 {"strike", HL_STRIKETHROUGH},
5785 {"reverse", HL_INVERSE},
5786 };
5787
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02005788 if (in_vim9script()
5789 && (check_for_number_arg(argvars, 0) == FAIL
5790 || check_for_string_arg(argvars, 1) == FAIL))
5791 return;
5792
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005793 attr = tv_get_number(&argvars[0]);
5794 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005795 if (name == NULL)
5796 return;
5797
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005798 if (attr > HL_ALL)
5799 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02005800 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005801 if (STRCMP(name, attrs[i].name) == 0)
5802 {
5803 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5804 break;
5805 }
5806}
5807
5808/*
5809 * "term_getcursor(buf)" function
5810 */
5811 void
5812f_term_getcursor(typval_T *argvars, typval_T *rettv)
5813{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005814 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005815 term_T *term;
5816 list_T *l;
5817 dict_T *d;
5818
5819 if (rettv_list_alloc(rettv) == FAIL)
5820 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005821
5822 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5823 return;
5824
5825 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005826 if (buf == NULL)
5827 return;
5828 term = buf->b_term;
5829
5830 l = rettv->vval.v_list;
5831 list_append_number(l, term->tl_cursor_pos.row + 1);
5832 list_append_number(l, term->tl_cursor_pos.col + 1);
5833
5834 d = dict_alloc();
5835 if (d != NULL)
5836 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005837 dict_add_number(d, "visible", term->tl_cursor_visible);
5838 dict_add_number(d, "blink", blink_state_is_inverted()
5839 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5840 dict_add_number(d, "shape", term->tl_cursor_shape);
5841 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005842 list_append_dict(l, d);
5843 }
5844}
5845
5846/*
5847 * "term_getjob(buf)" function
5848 */
5849 void
5850f_term_getjob(typval_T *argvars, typval_T *rettv)
5851{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005852 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005853
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005854 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5855 return;
5856
5857 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005858 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005859 {
5860 rettv->v_type = VAR_SPECIAL;
5861 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005862 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005863 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005864
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005865 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005866 rettv->vval.v_job = buf->b_term->tl_job;
5867 if (rettv->vval.v_job != NULL)
5868 ++rettv->vval.v_job->jv_refcount;
5869}
5870
5871 static int
5872get_row_number(typval_T *tv, term_T *term)
5873{
5874 if (tv->v_type == VAR_STRING
5875 && tv->vval.v_string != NULL
5876 && STRCMP(tv->vval.v_string, ".") == 0)
5877 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005878 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005879}
5880
5881/*
5882 * "term_getline(buf, row)" function
5883 */
5884 void
5885f_term_getline(typval_T *argvars, typval_T *rettv)
5886{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02005887 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005888 term_T *term;
5889 int row;
5890
5891 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02005892
5893 if (in_vim9script()
5894 && (check_for_buffer_arg(argvars, 0) == FAIL
5895 || check_for_lnum_arg(argvars, 1) == FAIL))
5896 return;
5897
5898 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005899 if (buf == NULL)
5900 return;
5901 term = buf->b_term;
5902 row = get_row_number(&argvars[1], term);
5903
5904 if (term->tl_vterm == NULL)
5905 {
5906 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5907
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005908 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005909 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5910 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5911 }
5912 else
5913 {
5914 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5915 VTermRect rect;
5916 int len;
5917 char_u *p;
5918
5919 if (row < 0 || row >= term->tl_rows)
5920 return;
5921 len = term->tl_cols * MB_MAXBYTES + 1;
5922 p = alloc(len);
5923 if (p == NULL)
5924 return;
5925 rettv->vval.v_string = p;
5926
5927 rect.start_col = 0;
5928 rect.end_col = term->tl_cols;
5929 rect.start_row = row;
5930 rect.end_row = row + 1;
5931 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5932 }
5933}
5934
5935/*
5936 * "term_getscrolled(buf)" function
5937 */
5938 void
5939f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5940{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005941 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005942
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005943 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5944 return;
5945
5946 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005947 if (buf == NULL)
5948 return;
5949 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5950}
5951
5952/*
5953 * "term_getsize(buf)" function
5954 */
5955 void
5956f_term_getsize(typval_T *argvars, typval_T *rettv)
5957{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005958 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005959 list_T *l;
5960
5961 if (rettv_list_alloc(rettv) == FAIL)
5962 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005963
5964 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5965 return;
5966
5967 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005968 if (buf == NULL)
5969 return;
5970
5971 l = rettv->vval.v_list;
5972 list_append_number(l, buf->b_term->tl_rows);
5973 list_append_number(l, buf->b_term->tl_cols);
5974}
5975
5976/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005977 * "term_setsize(buf, rows, cols)" function
5978 */
5979 void
5980f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5981{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02005982 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02005983 term_T *term;
5984 varnumber_T rows, cols;
5985
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02005986 if (in_vim9script()
5987 && (check_for_buffer_arg(argvars, 0) == FAIL
5988 || check_for_number_arg(argvars, 1) == FAIL
5989 || check_for_number_arg(argvars, 2) == FAIL))
5990 return;
5991
5992 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005993 if (buf == NULL)
5994 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005995 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005996 return;
5997 }
5998 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005999 return;
6000 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006001 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006002 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006003 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006004 cols = cols <= 0 ? term->tl_cols : cols;
6005 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006006 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006007
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006008 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006009 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6010 term_report_winsize(term, term->tl_rows, term->tl_cols);
6011}
6012
6013/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006014 * "term_getstatus(buf)" function
6015 */
6016 void
6017f_term_getstatus(typval_T *argvars, typval_T *rettv)
6018{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006019 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006020 term_T *term;
6021 char_u val[100];
6022
6023 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006024
6025 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6026 return;
6027
6028 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006029 if (buf == NULL)
6030 return;
6031 term = buf->b_term;
6032
6033 if (term_job_running(term))
6034 STRCPY(val, "running");
6035 else
6036 STRCPY(val, "finished");
6037 if (term->tl_normal_mode)
6038 STRCAT(val, ",normal");
6039 rettv->vval.v_string = vim_strsave(val);
6040}
6041
6042/*
6043 * "term_gettitle(buf)" function
6044 */
6045 void
6046f_term_gettitle(typval_T *argvars, typval_T *rettv)
6047{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006048 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006049
6050 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006051
6052 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6053 return;
6054
6055 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006056 if (buf == NULL)
6057 return;
6058
6059 if (buf->b_term->tl_title != NULL)
6060 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6061}
6062
6063/*
6064 * "term_gettty(buf)" function
6065 */
6066 void
6067f_term_gettty(typval_T *argvars, typval_T *rettv)
6068{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006069 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006070 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006071 int num = 0;
6072
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006073 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006074 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006075 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6076 return;
6077
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006078 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006079 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006080 if (buf == NULL)
6081 return;
6082 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006083 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006084
6085 switch (num)
6086 {
6087 case 0:
6088 if (buf->b_term->tl_job != NULL)
6089 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006090 break;
6091 case 1:
6092 if (buf->b_term->tl_job != NULL)
6093 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006094 break;
6095 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006096 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006097 return;
6098 }
6099 if (p != NULL)
6100 rettv->vval.v_string = vim_strsave(p);
6101}
6102
6103/*
6104 * "term_list()" function
6105 */
6106 void
6107f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6108{
6109 term_T *tp;
6110 list_T *l;
6111
6112 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6113 return;
6114
6115 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006116 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006117 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006118 if (list_append_number(l,
6119 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6120 return;
6121}
6122
6123/*
6124 * "term_scrape(buf, row)" function
6125 */
6126 void
6127f_term_scrape(typval_T *argvars, typval_T *rettv)
6128{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006129 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006130 VTermScreen *screen = NULL;
6131 VTermPos pos;
6132 list_T *l;
6133 term_T *term;
6134 char_u *p;
6135 sb_line_T *line;
6136
6137 if (rettv_list_alloc(rettv) == FAIL)
6138 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006139
6140 if (in_vim9script()
6141 && (check_for_buffer_arg(argvars, 0) == FAIL
6142 || check_for_lnum_arg(argvars, 1) == FAIL))
6143 return;
6144
6145 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006146 if (buf == NULL)
6147 return;
6148 term = buf->b_term;
6149
6150 l = rettv->vval.v_list;
6151 pos.row = get_row_number(&argvars[1], term);
6152
6153 if (term->tl_vterm != NULL)
6154 {
6155 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006156 if (screen == NULL) // can't really happen
6157 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006158 p = NULL;
6159 line = NULL;
6160 }
6161 else
6162 {
6163 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6164
6165 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6166 return;
6167 p = ml_get_buf(buf, lnum + 1, FALSE);
6168 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6169 }
6170
6171 for (pos.col = 0; pos.col < term->tl_cols; )
6172 {
6173 dict_T *dcell;
6174 int width;
6175 VTermScreenCellAttrs attrs;
6176 VTermColor fg, bg;
6177 char_u rgb[8];
6178 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6179 int off = 0;
6180 int i;
6181
6182 if (screen == NULL)
6183 {
6184 cellattr_T *cellattr;
6185 int len;
6186
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006187 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006188 if (pos.col >= line->sb_cols)
6189 break;
6190 cellattr = line->sb_cells + pos.col;
6191 width = cellattr->width;
6192 attrs = cellattr->attrs;
6193 fg = cellattr->fg;
6194 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006195 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006196 mch_memmove(mbs, p, len);
6197 mbs[len] = NUL;
6198 p += len;
6199 }
6200 else
6201 {
6202 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006203
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006204 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6205 break;
6206 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6207 {
6208 if (cell.chars[i] == 0)
6209 break;
6210 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6211 }
6212 mbs[off] = NUL;
6213 width = cell.width;
6214 attrs = cell.attrs;
6215 fg = cell.fg;
6216 bg = cell.bg;
6217 }
6218 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006219 if (dcell == NULL)
6220 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006221 list_append_dict(l, dcell);
6222
Bram Moolenaare0be1672018-07-08 16:50:37 +02006223 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006224
6225 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6226 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006227 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006228 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6229 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006230 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006231
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006232 dict_add_number(dcell, "attr",
6233 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006234 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006235
6236 ++pos.col;
6237 if (width == 2)
6238 ++pos.col;
6239 }
6240}
6241
6242/*
6243 * "term_sendkeys(buf, keys)" function
6244 */
6245 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006246f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006247{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006248 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006249 char_u *msg;
6250 term_T *term;
6251
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006252 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006253 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006254 || check_for_string_arg(argvars, 1) == FAIL))
6255 return;
6256
6257 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006258 if (buf == NULL)
6259 return;
6260
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006261 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006262 if (msg == NULL)
6263 return;
6264 term = buf->b_term;
6265 if (term->tl_vterm == NULL)
6266 return;
6267
6268 while (*msg != NUL)
6269 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006270 int c;
6271
6272 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6273 {
6274 c = TO_SPECIAL(msg[1], msg[2]);
6275 msg += 3;
6276 }
6277 else
6278 {
6279 c = PTR2CHAR(msg);
6280 msg += MB_CPTR2LEN(msg);
6281 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006282 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006283 }
6284}
6285
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006286#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6287/*
6288 * "term_getansicolors(buf)" function
6289 */
6290 void
6291f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6292{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006293 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006294 term_T *term;
6295 VTermState *state;
6296 VTermColor color;
6297 char_u hexbuf[10];
6298 int index;
6299 list_T *list;
6300
6301 if (rettv_list_alloc(rettv) == FAIL)
6302 return;
6303
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006304 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6305 return;
6306
6307 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006308 if (buf == NULL)
6309 return;
6310 term = buf->b_term;
6311 if (term->tl_vterm == NULL)
6312 return;
6313
6314 list = rettv->vval.v_list;
6315 state = vterm_obtain_state(term->tl_vterm);
6316 for (index = 0; index < 16; index++)
6317 {
6318 vterm_state_get_palette_color(state, index, &color);
6319 sprintf((char *)hexbuf, "#%02x%02x%02x",
6320 color.red, color.green, color.blue);
6321 if (list_append_string(list, hexbuf, 7) == FAIL)
6322 return;
6323 }
6324}
6325
6326/*
6327 * "term_setansicolors(buf, list)" function
6328 */
6329 void
6330f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6331{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006332 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006333 term_T *term;
6334
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006335 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006336 && (check_for_buffer_arg(argvars, 0) == FAIL
6337 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006338 return;
6339
6340 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006341 if (buf == NULL)
6342 return;
6343 term = buf->b_term;
6344 if (term->tl_vterm == NULL)
6345 return;
6346
6347 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
6348 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006349 emsg(_(e_list_required));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006350 return;
6351 }
6352
6353 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006354 emsg(_(e_invalid_argument));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006355}
6356#endif
6357
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006358/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006359 * "term_setapi(buf, api)" function
6360 */
6361 void
6362f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6363{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006364 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006365 term_T *term;
6366 char_u *api;
6367
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006368 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006369 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006370 || check_for_string_arg(argvars, 1) == FAIL))
6371 return;
6372
6373 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006374 if (buf == NULL)
6375 return;
6376 term = buf->b_term;
6377 vim_free(term->tl_api);
6378 api = tv_get_string_chk(&argvars[1]);
6379 if (api != NULL)
6380 term->tl_api = vim_strsave(api);
6381 else
6382 term->tl_api = NULL;
6383}
6384
6385/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006386 * "term_setrestore(buf, command)" function
6387 */
6388 void
6389f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6390{
6391#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006392 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006393 term_T *term;
6394 char_u *cmd;
6395
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006396 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006397 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006398 || check_for_string_arg(argvars, 1) == FAIL))
6399 return;
6400
6401 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006402 if (buf == NULL)
6403 return;
6404 term = buf->b_term;
6405 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006406 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006407 if (cmd != NULL)
6408 term->tl_command = vim_strsave(cmd);
6409 else
6410 term->tl_command = NULL;
6411#endif
6412}
6413
6414/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006415 * "term_setkill(buf, how)" function
6416 */
6417 void
6418f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6419{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006420 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006421 term_T *term;
6422 char_u *how;
6423
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006424 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006425 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006426 || check_for_string_arg(argvars, 1) == FAIL))
6427 return;
6428
6429 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006430 if (buf == NULL)
6431 return;
6432 term = buf->b_term;
6433 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006434 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006435 if (how != NULL)
6436 term->tl_kill = vim_strsave(how);
6437 else
6438 term->tl_kill = NULL;
6439}
6440
6441/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006442 * "term_start(command, options)" function
6443 */
6444 void
6445f_term_start(typval_T *argvars, typval_T *rettv)
6446{
6447 jobopt_T opt;
6448 buf_T *buf;
6449
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006450 if (in_vim9script()
6451 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6452 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6453 return;
6454
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006455 init_job_options(&opt);
6456 if (argvars[1].v_type != VAR_UNKNOWN
6457 && get_job_options(&argvars[1], &opt,
6458 JO_TIMEOUT_ALL + JO_STOPONEXIT
6459 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6460 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6461 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6462 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006463 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006464 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006465 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006466 return;
6467
Bram Moolenaar13568252018-03-16 20:46:58 +01006468 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006469
6470 if (buf != NULL && buf->b_term != NULL)
6471 rettv->vval.v_number = buf->b_fnum;
6472}
6473
6474/*
6475 * "term_wait" function
6476 */
6477 void
6478f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6479{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006480 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006481
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006482 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006483 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006484 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006485 return;
6486
6487 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006488 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006489 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006490 if (buf->b_term->tl_job == NULL)
6491 {
6492 ch_log(NULL, "term_wait(): no job to wait for");
6493 return;
6494 }
6495 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006496 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006497 return;
6498
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006499 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006500 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006501 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6502 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006503 // The job is dead, keep reading channel I/O until the channel is
6504 // closed. buf->b_term may become NULL if the terminal was closed while
6505 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006506 ch_log(NULL, "term_wait(): waiting for channel to close");
6507 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6508 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006509 term_flush_messages();
6510
Bram Moolenaard45aa552018-05-21 22:50:29 +02006511 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006512 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006513 // If the terminal is closed when the channel is closed the
6514 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006515 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006516 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6517 // came here from a close callback, only wait one time
6518 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006519 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006520
6521 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006522 }
6523 else
6524 {
6525 long wait = 10L;
6526
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006527 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006528
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006529 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006530 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006531 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006532 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006533
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006534 // Flushing messages on channels is hopefully sufficient.
6535 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006536 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006537 }
6538}
6539
6540/*
6541 * Called when a channel has sent all the lines to a terminal.
6542 * Send a CTRL-D to mark the end of the text.
6543 */
6544 void
6545term_send_eof(channel_T *ch)
6546{
6547 term_T *term;
6548
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006549 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006550 if (term->tl_job == ch->ch_job)
6551 {
6552 if (term->tl_eof_chars != NULL)
6553 {
6554 channel_send(ch, PART_IN, term->tl_eof_chars,
6555 (int)STRLEN(term->tl_eof_chars), NULL);
6556 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6557 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006558# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006559 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006560 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006561 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6562# endif
6563 }
6564}
6565
Bram Moolenaar113e1072019-01-20 15:30:40 +01006566#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006567 job_T *
6568term_getjob(term_T *term)
6569{
6570 return term != NULL ? term->tl_job : NULL;
6571}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006572#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006573
Bram Moolenaar4f974752019-02-17 17:44:42 +01006574# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006575
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006576///////////////////////////////////////
6577// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006578#ifdef PROTO
6579typedef int COORD;
6580typedef int DWORD;
6581typedef int HANDLE;
6582typedef int *DWORD_PTR;
6583typedef int HPCON;
6584typedef int HRESULT;
6585typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006586typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006587typedef int PSIZE_T;
6588typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006589typedef int BOOL;
6590# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006591#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006592
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006593HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6594HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6595HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006596BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6597BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6598void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006599
6600 static int
6601dyn_conpty_init(int verbose)
6602{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006603 static HMODULE hKerneldll = NULL;
6604 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006605 static struct
6606 {
6607 char *name;
6608 FARPROC *ptr;
6609 } conpty_entry[] =
6610 {
6611 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6612 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6613 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6614 {"InitializeProcThreadAttributeList",
6615 (FARPROC*)&pInitializeProcThreadAttributeList},
6616 {"UpdateProcThreadAttribute",
6617 (FARPROC*)&pUpdateProcThreadAttribute},
6618 {"DeleteProcThreadAttributeList",
6619 (FARPROC*)&pDeleteProcThreadAttributeList},
6620 {NULL, NULL}
6621 };
6622
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006623 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006624 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006625 if (verbose)
6626 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006627 return FAIL;
6628 }
6629
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006630 // No need to initialize twice.
6631 if (hKerneldll)
6632 return OK;
6633
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006634 hKerneldll = vimLoadLib("kernel32.dll");
6635 for (i = 0; conpty_entry[i].name != NULL
6636 && conpty_entry[i].ptr != NULL; ++i)
6637 {
6638 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6639 conpty_entry[i].name)) == NULL)
6640 {
6641 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006642 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006643 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006644 return FAIL;
6645 }
6646 }
6647
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006648 return OK;
6649}
6650
6651 static int
6652conpty_term_and_job_init(
6653 term_T *term,
6654 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006655 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006656 jobopt_T *opt,
6657 jobopt_T *orig_opt)
6658{
6659 WCHAR *cmd_wchar = NULL;
6660 WCHAR *cmd_wchar_copy = NULL;
6661 WCHAR *cwd_wchar = NULL;
6662 WCHAR *env_wchar = NULL;
6663 channel_T *channel = NULL;
6664 job_T *job = NULL;
6665 HANDLE jo = NULL;
6666 garray_T ga_cmd, ga_env;
6667 char_u *cmd = NULL;
6668 HRESULT hr;
6669 COORD consize;
6670 SIZE_T breq;
6671 PROCESS_INFORMATION proc_info;
6672 HANDLE i_theirs = NULL;
6673 HANDLE o_theirs = NULL;
6674 HANDLE i_ours = NULL;
6675 HANDLE o_ours = NULL;
6676
6677 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6678 ga_init2(&ga_env, (int)sizeof(char*), 20);
6679
6680 if (argvar->v_type == VAR_STRING)
6681 {
6682 cmd = argvar->vval.v_string;
6683 }
6684 else if (argvar->v_type == VAR_LIST)
6685 {
6686 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6687 goto failed;
6688 cmd = ga_cmd.ga_data;
6689 }
6690 if (cmd == NULL || *cmd == NUL)
6691 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006692 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006693 goto failed;
6694 }
6695
6696 term->tl_arg0_cmd = vim_strsave(cmd);
6697
6698 cmd_wchar = enc_to_utf16(cmd, NULL);
6699
6700 if (cmd_wchar != NULL)
6701 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006702 // Request by CreateProcessW
6703 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006704 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006705 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6706 }
6707
6708 ga_clear(&ga_cmd);
6709 if (cmd_wchar == NULL)
6710 goto failed;
6711 if (opt->jo_cwd != NULL)
6712 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6713
6714 win32_build_env(opt->jo_env, &ga_env, TRUE);
6715 env_wchar = ga_env.ga_data;
6716
6717 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6718 goto failed;
6719 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6720 goto failed;
6721
6722 consize.X = term->tl_cols;
6723 consize.Y = term->tl_rows;
6724 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6725 &term->tl_conpty);
6726 if (FAILED(hr))
6727 goto failed;
6728
6729 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6730
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006731 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006732 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006733 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006734 if (!term->tl_siex.lpAttributeList)
6735 goto failed;
6736 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6737 0, &breq))
6738 goto failed;
6739 if (!pUpdateProcThreadAttribute(
6740 term->tl_siex.lpAttributeList, 0,
6741 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6742 sizeof(HPCON), NULL, NULL))
6743 goto failed;
6744
6745 channel = add_channel();
6746 if (channel == NULL)
6747 goto failed;
6748
6749 job = job_alloc();
6750 if (job == NULL)
6751 goto failed;
6752 if (argvar->v_type == VAR_STRING)
6753 {
6754 int argc;
6755
6756 build_argv_from_string(cmd, &job->jv_argv, &argc);
6757 }
6758 else
6759 {
6760 int argc;
6761
6762 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6763 }
6764
6765 if (opt->jo_set & JO_IN_BUF)
6766 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6767
6768 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6769 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02006770 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006771 env_wchar, cwd_wchar,
6772 &term->tl_siex.StartupInfo, &proc_info))
6773 goto failed;
6774
6775 CloseHandle(i_theirs);
6776 CloseHandle(o_theirs);
6777
6778 channel_set_pipes(channel,
6779 (sock_T)i_ours,
6780 (sock_T)o_ours,
6781 (sock_T)o_ours);
6782
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006783 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006784 channel->ch_write_text_mode = TRUE;
6785
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006786 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006787 channel->ch_anonymous_pipe = TRUE;
6788
6789 jo = CreateJobObject(NULL, NULL);
6790 if (jo == NULL)
6791 goto failed;
6792
6793 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6794 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006795 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006796 CloseHandle(jo);
6797 jo = NULL;
6798 }
6799
6800 ResumeThread(proc_info.hThread);
6801 CloseHandle(proc_info.hThread);
6802
6803 vim_free(cmd_wchar);
6804 vim_free(cmd_wchar_copy);
6805 vim_free(cwd_wchar);
6806 vim_free(env_wchar);
6807
6808 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6809 goto failed;
6810
6811#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6812 if (opt->jo_set2 & JO2_ANSI_COLORS)
6813 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6814 else
6815 init_vterm_ansi_colors(term->tl_vterm);
6816#endif
6817
6818 channel_set_job(channel, job, opt);
6819 job_set_options(job, opt);
6820
6821 job->jv_channel = channel;
6822 job->jv_proc_info = proc_info;
6823 job->jv_job_object = jo;
6824 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006825 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006826 ++job->jv_refcount;
6827 term->tl_job = job;
6828
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006829 // Redirecting stdout and stderr doesn't work at the job level. Instead
6830 // open the file here and handle it in. opt->jo_io was changed in
6831 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006832 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6833 {
6834 char_u *fname = opt->jo_io_name[PART_OUT];
6835
6836 ch_log(channel, "Opening output file %s", fname);
6837 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6838 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006839 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006840 }
6841
6842 return OK;
6843
6844failed:
6845 ga_clear(&ga_cmd);
6846 ga_clear(&ga_env);
6847 vim_free(cmd_wchar);
6848 vim_free(cmd_wchar_copy);
6849 vim_free(cwd_wchar);
6850 if (channel != NULL)
6851 channel_clear(channel);
6852 if (job != NULL)
6853 {
6854 job->jv_channel = NULL;
6855 job_cleanup(job);
6856 }
6857 term->tl_job = NULL;
6858 if (jo != NULL)
6859 CloseHandle(jo);
6860
6861 if (term->tl_siex.lpAttributeList != NULL)
6862 {
6863 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6864 vim_free(term->tl_siex.lpAttributeList);
6865 }
6866 term->tl_siex.lpAttributeList = NULL;
6867 if (o_theirs != NULL)
6868 CloseHandle(o_theirs);
6869 if (o_ours != NULL)
6870 CloseHandle(o_ours);
6871 if (i_ours != NULL)
6872 CloseHandle(i_ours);
6873 if (i_theirs != NULL)
6874 CloseHandle(i_theirs);
6875 if (term->tl_conpty != NULL)
6876 pClosePseudoConsole(term->tl_conpty);
6877 term->tl_conpty = NULL;
6878 return FAIL;
6879}
6880
6881 static void
6882conpty_term_report_winsize(term_T *term, int rows, int cols)
6883{
6884 COORD consize;
6885
6886 consize.X = cols;
6887 consize.Y = rows;
6888 pResizePseudoConsole(term->tl_conpty, consize);
6889}
6890
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006891 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006892term_free_conpty(term_T *term)
6893{
6894 if (term->tl_siex.lpAttributeList != NULL)
6895 {
6896 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6897 vim_free(term->tl_siex.lpAttributeList);
6898 }
6899 term->tl_siex.lpAttributeList = NULL;
6900 if (term->tl_conpty != NULL)
6901 pClosePseudoConsole(term->tl_conpty);
6902 term->tl_conpty = NULL;
6903}
6904
6905 int
6906use_conpty(void)
6907{
6908 return has_conpty;
6909}
6910
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006911# ifndef PROTO
6912
6913#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6914#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006915#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006916
6917void* (*winpty_config_new)(UINT64, void*);
6918void* (*winpty_open)(void*, void*);
6919void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6920BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6921void (*winpty_config_set_mouse_mode)(void*, int);
6922void (*winpty_config_set_initial_size)(void*, int, int);
6923LPCWSTR (*winpty_conin_name)(void*);
6924LPCWSTR (*winpty_conout_name)(void*);
6925LPCWSTR (*winpty_conerr_name)(void*);
6926void (*winpty_free)(void*);
6927void (*winpty_config_free)(void*);
6928void (*winpty_spawn_config_free)(void*);
6929void (*winpty_error_free)(void*);
6930LPCWSTR (*winpty_error_msg)(void*);
6931BOOL (*winpty_set_size)(void*, int, int, void*);
6932HANDLE (*winpty_agent_process)(void*);
6933
6934#define WINPTY_DLL "winpty.dll"
6935
6936static HINSTANCE hWinPtyDLL = NULL;
6937# endif
6938
6939 static int
6940dyn_winpty_init(int verbose)
6941{
6942 int i;
6943 static struct
6944 {
6945 char *name;
6946 FARPROC *ptr;
6947 } winpty_entry[] =
6948 {
6949 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6950 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6951 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6952 {"winpty_config_set_mouse_mode",
6953 (FARPROC*)&winpty_config_set_mouse_mode},
6954 {"winpty_config_set_initial_size",
6955 (FARPROC*)&winpty_config_set_initial_size},
6956 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6957 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6958 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6959 {"winpty_free", (FARPROC*)&winpty_free},
6960 {"winpty_open", (FARPROC*)&winpty_open},
6961 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6962 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6963 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6964 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6965 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6966 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6967 {NULL, NULL}
6968 };
6969
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006970 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006971 if (hWinPtyDLL)
6972 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006973 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6974 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006975 if (*p_winptydll != NUL)
6976 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6977 if (!hWinPtyDLL)
6978 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6979 if (!hWinPtyDLL)
6980 {
6981 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006982 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02006983 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
6984 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006985 return FAIL;
6986 }
6987 for (i = 0; winpty_entry[i].name != NULL
6988 && winpty_entry[i].ptr != NULL; ++i)
6989 {
6990 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6991 winpty_entry[i].name)) == NULL)
6992 {
6993 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006994 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006995 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006996 return FAIL;
6997 }
6998 }
6999
7000 return OK;
7001}
7002
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007003 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007004winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007005 term_T *term,
7006 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007007 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007008 jobopt_T *opt,
7009 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007010{
7011 WCHAR *cmd_wchar = NULL;
7012 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007013 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007014 channel_T *channel = NULL;
7015 job_T *job = NULL;
7016 DWORD error;
7017 HANDLE jo = NULL;
7018 HANDLE child_process_handle;
7019 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007020 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007021 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007022 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007023 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007024
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007025 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
7026 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007027
7028 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007029 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007030 cmd = argvar->vval.v_string;
7031 }
7032 else if (argvar->v_type == VAR_LIST)
7033 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007034 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007035 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007036 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007037 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007038 if (cmd == NULL || *cmd == NUL)
7039 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007040 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007041 goto failed;
7042 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007043
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007044 term->tl_arg0_cmd = vim_strsave(cmd);
7045
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007046 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007047 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007048 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007049 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007050 if (opt->jo_cwd != NULL)
7051 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007052
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007053 win32_build_env(opt->jo_env, &ga_env, TRUE);
7054 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007055
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007056 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7057 if (term->tl_winpty_config == NULL)
7058 goto failed;
7059
7060 winpty_config_set_mouse_mode(term->tl_winpty_config,
7061 WINPTY_MOUSE_MODE_FORCE);
7062 winpty_config_set_initial_size(term->tl_winpty_config,
7063 term->tl_cols, term->tl_rows);
7064 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7065 if (term->tl_winpty == NULL)
7066 goto failed;
7067
7068 spawn_config = winpty_spawn_config_new(
7069 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7070 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7071 NULL,
7072 cmd_wchar,
7073 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007074 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007075 &winpty_err);
7076 if (spawn_config == NULL)
7077 goto failed;
7078
7079 channel = add_channel();
7080 if (channel == NULL)
7081 goto failed;
7082
7083 job = job_alloc();
7084 if (job == NULL)
7085 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007086 if (argvar->v_type == VAR_STRING)
7087 {
7088 int argc;
7089
7090 build_argv_from_string(cmd, &job->jv_argv, &argc);
7091 }
7092 else
7093 {
7094 int argc;
7095
7096 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7097 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007098
7099 if (opt->jo_set & JO_IN_BUF)
7100 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7101
7102 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7103 &child_thread_handle, &error, &winpty_err))
7104 goto failed;
7105
7106 channel_set_pipes(channel,
7107 (sock_T)CreateFileW(
7108 winpty_conin_name(term->tl_winpty),
7109 GENERIC_WRITE, 0, NULL,
7110 OPEN_EXISTING, 0, NULL),
7111 (sock_T)CreateFileW(
7112 winpty_conout_name(term->tl_winpty),
7113 GENERIC_READ, 0, NULL,
7114 OPEN_EXISTING, 0, NULL),
7115 (sock_T)CreateFileW(
7116 winpty_conerr_name(term->tl_winpty),
7117 GENERIC_READ, 0, NULL,
7118 OPEN_EXISTING, 0, NULL));
7119
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007120 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007121 channel->ch_write_text_mode = TRUE;
7122
7123 jo = CreateJobObject(NULL, NULL);
7124 if (jo == NULL)
7125 goto failed;
7126
7127 if (!AssignProcessToJobObject(jo, child_process_handle))
7128 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007129 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007130 CloseHandle(jo);
7131 jo = NULL;
7132 }
7133
7134 winpty_spawn_config_free(spawn_config);
7135 vim_free(cmd_wchar);
7136 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007137 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007138
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007139 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7140 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007141
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007142#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
7143 if (opt->jo_set2 & JO2_ANSI_COLORS)
7144 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
7145 else
7146 init_vterm_ansi_colors(term->tl_vterm);
7147#endif
7148
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007149 channel_set_job(channel, job, opt);
7150 job_set_options(job, opt);
7151
7152 job->jv_channel = channel;
7153 job->jv_proc_info.hProcess = child_process_handle;
7154 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7155 job->jv_job_object = jo;
7156 job->jv_status = JOB_STARTED;
7157 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007158 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007159 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007160 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007161 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007162 ++job->jv_refcount;
7163 term->tl_job = job;
7164
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007165 // Redirecting stdout and stderr doesn't work at the job level. Instead
7166 // open the file here and handle it in. opt->jo_io was changed in
7167 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007168 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7169 {
7170 char_u *fname = opt->jo_io_name[PART_OUT];
7171
7172 ch_log(channel, "Opening output file %s", fname);
7173 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7174 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007175 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007176 }
7177
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007178 return OK;
7179
7180failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007181 ga_clear(&ga_cmd);
7182 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007183 vim_free(cmd_wchar);
7184 vim_free(cwd_wchar);
7185 if (spawn_config != NULL)
7186 winpty_spawn_config_free(spawn_config);
7187 if (channel != NULL)
7188 channel_clear(channel);
7189 if (job != NULL)
7190 {
7191 job->jv_channel = NULL;
7192 job_cleanup(job);
7193 }
7194 term->tl_job = NULL;
7195 if (jo != NULL)
7196 CloseHandle(jo);
7197 if (term->tl_winpty != NULL)
7198 winpty_free(term->tl_winpty);
7199 term->tl_winpty = NULL;
7200 if (term->tl_winpty_config != NULL)
7201 winpty_config_free(term->tl_winpty_config);
7202 term->tl_winpty_config = NULL;
7203 if (winpty_err != NULL)
7204 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007205 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007206 (short_u *)winpty_error_msg(winpty_err), NULL);
7207
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007208 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007209 winpty_error_free(winpty_err);
7210 }
7211 return FAIL;
7212}
7213
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007214/*
7215 * Create a new terminal of "rows" by "cols" cells.
7216 * Store a reference in "term".
7217 * Return OK or FAIL.
7218 */
7219 static int
7220term_and_job_init(
7221 term_T *term,
7222 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007223 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007224 jobopt_T *opt,
7225 jobopt_T *orig_opt)
7226{
7227 int use_winpty = FALSE;
7228 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007229 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007230
7231 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7232 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7233
7234 if (!has_winpty && !has_conpty)
7235 // If neither is available give the errors for winpty, since when
7236 // conpty is not available it can't be installed either.
7237 return dyn_winpty_init(TRUE);
7238
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007239 if (opt->jo_tty_type != NUL)
7240 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007241
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007242 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007243 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007244 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007245 use_conpty = TRUE;
7246 else if (has_winpty)
7247 use_winpty = TRUE;
7248 // else: error
7249 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007250 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007251 {
7252 if (has_winpty)
7253 use_winpty = TRUE;
7254 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007255 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007256 {
7257 if (has_conpty)
7258 use_conpty = TRUE;
7259 else
7260 return dyn_conpty_init(TRUE);
7261 }
7262
7263 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007264 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007265
7266 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007267 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007268
7269 // error
7270 return dyn_winpty_init(TRUE);
7271}
7272
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007273 static int
7274create_pty_only(term_T *term, jobopt_T *options)
7275{
7276 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7277 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7278 char in_name[80], out_name[80];
7279 channel_T *channel = NULL;
7280
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007281 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7282 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007283
7284 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7285 GetCurrentProcessId(),
7286 curbuf->b_fnum);
7287 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7288 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7289 PIPE_UNLIMITED_INSTANCES,
7290 0, 0, NMPWAIT_NOWAIT, NULL);
7291 if (hPipeIn == INVALID_HANDLE_VALUE)
7292 goto failed;
7293
7294 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7295 GetCurrentProcessId(),
7296 curbuf->b_fnum);
7297 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7298 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7299 PIPE_UNLIMITED_INSTANCES,
7300 0, 0, 0, NULL);
7301 if (hPipeOut == INVALID_HANDLE_VALUE)
7302 goto failed;
7303
7304 ConnectNamedPipe(hPipeIn, NULL);
7305 ConnectNamedPipe(hPipeOut, NULL);
7306
7307 term->tl_job = job_alloc();
7308 if (term->tl_job == NULL)
7309 goto failed;
7310 ++term->tl_job->jv_refcount;
7311
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007312 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007313 term->tl_job->jv_status = JOB_FINISHED;
7314
7315 channel = add_channel();
7316 if (channel == NULL)
7317 goto failed;
7318 term->tl_job->jv_channel = channel;
7319 channel->ch_keep_open = TRUE;
7320 channel->ch_named_pipe = TRUE;
7321
7322 channel_set_pipes(channel,
7323 (sock_T)hPipeIn,
7324 (sock_T)hPipeOut,
7325 (sock_T)hPipeOut);
7326 channel_set_job(channel, term->tl_job, options);
7327 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7328 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7329
7330 return OK;
7331
7332failed:
7333 if (hPipeIn != NULL)
7334 CloseHandle(hPipeIn);
7335 if (hPipeOut != NULL)
7336 CloseHandle(hPipeOut);
7337 return FAIL;
7338}
7339
7340/*
7341 * Free the terminal emulator part of "term".
7342 */
7343 static void
7344term_free_vterm(term_T *term)
7345{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007346 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007347 if (term->tl_winpty != NULL)
7348 winpty_free(term->tl_winpty);
7349 term->tl_winpty = NULL;
7350 if (term->tl_winpty_config != NULL)
7351 winpty_config_free(term->tl_winpty_config);
7352 term->tl_winpty_config = NULL;
7353 if (term->tl_vterm != NULL)
7354 vterm_free(term->tl_vterm);
7355 term->tl_vterm = NULL;
7356}
7357
7358/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007359 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007360 */
7361 static void
7362term_report_winsize(term_T *term, int rows, int cols)
7363{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007364 if (term->tl_conpty)
7365 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007366 if (term->tl_winpty)
7367 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7368}
7369
7370 int
7371terminal_enabled(void)
7372{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007373 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007374}
7375
7376# else
7377
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007378///////////////////////////////////////
7379// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007380
7381/*
7382 * Create a new terminal of "rows" by "cols" cells.
7383 * Start job for "cmd".
7384 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007385 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007386 * Return OK or FAIL.
7387 */
7388 static int
7389term_and_job_init(
7390 term_T *term,
7391 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007392 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007393 jobopt_T *opt,
7394 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007395{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007396 term->tl_arg0_cmd = NULL;
7397
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007398 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7399 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007400
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007401#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
7402 if (opt->jo_set2 & JO2_ANSI_COLORS)
7403 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
7404 else
7405 init_vterm_ansi_colors(term->tl_vterm);
7406#endif
7407
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007408 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007409 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007410 if (term->tl_job != NULL)
7411 ++term->tl_job->jv_refcount;
7412
7413 return term->tl_job != NULL
7414 && term->tl_job->jv_channel != NULL
7415 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7416}
7417
7418 static int
7419create_pty_only(term_T *term, jobopt_T *opt)
7420{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007421 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7422 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007423
7424 term->tl_job = job_alloc();
7425 if (term->tl_job == NULL)
7426 return FAIL;
7427 ++term->tl_job->jv_refcount;
7428
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007429 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007430 term->tl_job->jv_status = JOB_FINISHED;
7431
7432 return mch_create_pty_channel(term->tl_job, opt);
7433}
7434
7435/*
7436 * Free the terminal emulator part of "term".
7437 */
7438 static void
7439term_free_vterm(term_T *term)
7440{
7441 if (term->tl_vterm != NULL)
7442 vterm_free(term->tl_vterm);
7443 term->tl_vterm = NULL;
7444}
7445
7446/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007447 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007448 */
7449 static void
7450term_report_winsize(term_T *term, int rows, int cols)
7451{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007452 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007453 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
7454 {
7455 int fd = -1;
7456 int part;
7457
7458 for (part = PART_OUT; part < PART_COUNT; ++part)
7459 {
7460 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01007461 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007462 break;
7463 }
7464 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7465 mch_signal_job(term->tl_job, (char_u *)"winch");
7466 }
7467}
7468
7469# endif
7470
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007471#endif // FEAT_TERMINAL