blob: a951870057257f4ebe6b017d43646e82fc9a6b40 [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
LemonBoyb2b3acb2022-05-20 10:10:34 +0100165 long_u *tl_palette; // array of 16 colors specified by term_start, can
166 // be NULL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167 int tl_using_altscreen;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200168 garray_T tl_osc_buf; // incomplete OSC string
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200169};
170
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100171#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
172#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200173
174/*
175 * List of all active terminals.
176 */
177static term_T *first_term = NULL;
178
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100179// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200180static term_T *in_terminal_loop = NULL;
181
Bram Moolenaar4f974752019-02-17 17:44:42 +0100182#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100183static BOOL has_winpty = FALSE;
184static BOOL has_conpty = FALSE;
185#endif
186
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100187#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188#define KEY_BUF_LEN 200
189
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200190#define FOR_ALL_TERMS(term) \
191 for ((term) = first_term; (term) != NULL; (term) = (term)->tl_next)
192
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193/*
194 * Functions with separate implementation for MS-Windows and Unix-like systems.
195 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200196static 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 +0200197static int create_pty_only(term_T *term, jobopt_T *opt);
198static void term_report_winsize(term_T *term, int rows, int cols);
199static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100200#ifdef FEAT_GUI
201static void update_system_term(term_T *term);
202#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200203
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100204static void handle_postponed_scrollback(term_T *term);
205
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100206// The character that we know (or assume) that the terminal expects for the
207// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200208static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200209
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100210// Store the last set and the desired cursor properties, so that we only update
211// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200212static char_u *last_set_cursor_color = NULL;
213static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100214static int last_set_cursor_shape = -1;
215static int desired_cursor_shape = -1;
216static int last_set_cursor_blink = -1;
217static int desired_cursor_blink = -1;
218
219
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100220///////////////////////////////////////
221// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200222
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200223 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200224cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
225{
226 if (lhs_color != NULL && rhs_color != NULL)
227 return STRCMP(lhs_color, rhs_color) == 0;
228 return lhs_color == NULL && rhs_color == NULL;
229}
230
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200231 static void
232cursor_color_copy(char_u **to_color, char_u *from_color)
233{
234 // Avoid a free & alloc if the value is already right.
235 if (cursor_color_equal(*to_color, from_color))
236 return;
237 vim_free(*to_color);
238 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
239}
240
241 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200242cursor_color_get(char_u *color)
243{
244 return (color == NULL) ? (char_u *)"" : color;
245}
246
247
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200248/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200249 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200250 * current window.
251 * Sets "rows" and/or "cols" to zero when it should follow the window size.
252 * Return TRUE if the size is the minimum size: "24*80".
253 */
254 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200255parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200256{
257 int minsize = FALSE;
258
259 *rows = 0;
260 *cols = 0;
261
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200262 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200263 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200264 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200265
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100266 // Syntax of value was already checked when it's set.
Bram Moolenaar498c2562018-04-15 23:45:15 +0200267 if (p == NULL)
268 {
269 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200270 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200271 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200272 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200273 *cols = atoi((char *)p + 1);
274 }
275 return minsize;
276}
277
278/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200279 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200280 */
281 static void
Bram Moolenaarb936b792020-09-04 18:34:09 +0200282set_term_and_win_size(term_T *term, jobopt_T *opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200283{
Bram Moolenaarb936b792020-09-04 18:34:09 +0200284 int rows, cols;
285 int minsize;
286
Bram Moolenaar13568252018-03-16 20:46:58 +0100287#ifdef FEAT_GUI
288 if (term->tl_system)
289 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100290 // Use the whole screen for the system command. However, it will start
291 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100292 term->tl_rows = Rows;
293 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200294 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100295 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100296#endif
Bram Moolenaarb936b792020-09-04 18:34:09 +0200297 term->tl_rows = curwin->w_height;
298 term->tl_cols = curwin->w_width;
299
300 minsize = parse_termwinsize(curwin, &rows, &cols);
301 if (minsize)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200302 {
Bram Moolenaarb936b792020-09-04 18:34:09 +0200303 if (term->tl_rows < rows)
304 term->tl_rows = rows;
305 if (term->tl_cols < cols)
306 term->tl_cols = cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200307 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200308 if ((opt->jo_set2 & JO2_TERM_ROWS))
309 term->tl_rows = opt->jo_term_rows;
310 else if (rows != 0)
311 term->tl_rows = rows;
312 if ((opt->jo_set2 & JO2_TERM_COLS))
313 term->tl_cols = opt->jo_term_cols;
314 else if (cols != 0)
315 term->tl_cols = cols;
316
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200317 if (!opt->jo_hidden)
Bram Moolenaarb936b792020-09-04 18:34:09 +0200318 {
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200319 if (term->tl_rows != curwin->w_height)
320 win_setheight_win(term->tl_rows, curwin);
321 if (term->tl_cols != curwin->w_width)
322 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaarb936b792020-09-04 18:34:09 +0200323
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200324 // Set 'winsize' now to avoid a resize at the next redraw.
325 if (!minsize && *curwin->w_p_tws != NUL)
326 {
327 char_u buf[100];
328
329 vim_snprintf((char *)buf, 100, "%dx%d",
330 term->tl_rows, term->tl_cols);
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100331 set_option_value_give_err((char_u *)"termwinsize",
332 0L, buf, OPT_LOCAL);
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200333 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200334 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200335}
336
337/*
338 * Initialize job options for a terminal job.
339 * Caller may overrule some of them.
340 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100341 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200342init_job_options(jobopt_T *opt)
343{
344 clear_job_options(opt);
345
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100346 opt->jo_mode = CH_MODE_RAW;
347 opt->jo_out_mode = CH_MODE_RAW;
348 opt->jo_err_mode = CH_MODE_RAW;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200349 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
350}
351
352/*
353 * Set job options mandatory for a terminal job.
354 */
355 static void
356setup_job_options(jobopt_T *opt, int rows, int cols)
357{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100358#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100359 // Win32: Redirecting the job output won't work, thus always connect stdout
360 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200361 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200362#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200363 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100364 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200365 opt->jo_io[PART_OUT] = JIO_BUFFER;
366 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
367 opt->jo_modifiable[PART_OUT] = 0;
368 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
369 }
370
Bram Moolenaar4f974752019-02-17 17:44:42 +0100371#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100372 // Win32: Redirecting the job output won't work, thus always connect stderr
373 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200374 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200375#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200376 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100377 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200378 opt->jo_io[PART_ERR] = JIO_BUFFER;
379 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
380 opt->jo_modifiable[PART_ERR] = 0;
381 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
382 }
383
384 opt->jo_pty = TRUE;
385 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
386 opt->jo_term_rows = rows;
387 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
388 opt->jo_term_cols = cols;
389}
390
391/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200392 * Flush messages on channels.
393 */
394 static void
395term_flush_messages()
396{
397 mch_check_messages();
398 parse_queued_messages();
399}
400
401/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100402 * Close a terminal buffer (and its window). Used when creating the terminal
403 * fails.
404 */
405 static void
406term_close_buffer(buf_T *buf, buf_T *old_curbuf)
407{
408 free_terminal(buf);
409 if (old_curbuf != NULL)
410 {
411 --curbuf->b_nwindows;
412 curbuf = old_curbuf;
413 curwin->w_buffer = curbuf;
414 ++curbuf->b_nwindows;
415 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100416 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100417
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100418 // Wiping out the buffer will also close the window and call
419 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100420 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
421}
422
423/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200424 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100425 * Use either "argvar" or "argv", the other must be NULL.
426 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
427 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 * Returns NULL when failed.
429 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100430 buf_T *
431term_start(
432 typval_T *argvar,
433 char **argv,
434 jobopt_T *opt,
435 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200436{
437 exarg_T split_ea;
438 win_T *old_curwin = curwin;
439 term_T *term;
440 buf_T *old_curbuf = NULL;
441 int res;
442 buf_T *newbuf;
Bram Moolenaare1004402020-10-24 20:49:43 +0200443 int vertical = opt->jo_vertical || (cmdmod.cmod_split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200444 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200445
446 if (check_restricted() || check_secure())
447 return NULL;
Bram Moolenaare5b44862021-05-30 13:54:03 +0200448#ifdef FEAT_CMDWIN
449 if (cmdwin_type != 0)
450 {
451 emsg(_(e_cannot_open_terminal_from_command_line_window));
452 return NULL;
453 }
454#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200455
456 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
457 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
458 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100459 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
460 || (argvar != NULL
461 && argvar->v_type == VAR_LIST
462 && argvar->vval.v_list != NULL
463 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200464 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000465 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200466 return NULL;
467 }
468
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200469 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200470 if (term == NULL)
471 return NULL;
472 term->tl_dirty_row_end = MAX_ROW;
473 term->tl_cursor_visible = TRUE;
474 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
475 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100476#ifdef FEAT_GUI
477 term->tl_system = (flags & TERM_START_SYSTEM);
478#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200479 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100480 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200481 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200482
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200483 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200484 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200485 if (opt->jo_curwin)
486 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100487 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100488 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200489 {
490 no_write_message();
491 vim_free(term);
492 return NULL;
493 }
494 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200495 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
496 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
497 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200498 {
499 vim_free(term);
500 return NULL;
501 }
502 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100503 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200504 {
505 buf_T *buf;
506
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100507 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100508 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200509 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
510 BLN_NEW | BLN_LISTED);
511 if (buf == NULL || ml_open(buf) == FAIL)
512 {
513 vim_free(term);
514 return NULL;
515 }
516 old_curbuf = curbuf;
517 --curbuf->b_nwindows;
518 curbuf = buf;
519 curwin->w_buffer = buf;
520 ++curbuf->b_nwindows;
521 }
522 else
523 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100524 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200525 split_ea.cmdidx = CMD_new;
526 split_ea.cmd = (char_u *)"new";
527 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100528 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200529 {
530 split_ea.line2 = opt->jo_term_rows;
531 split_ea.addr_count = 1;
532 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100533 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200534 {
535 split_ea.line2 = opt->jo_term_cols;
536 split_ea.addr_count = 1;
537 }
538
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100539 if (vertical)
Bram Moolenaare1004402020-10-24 20:49:43 +0200540 cmdmod.cmod_split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200541 ex_splitview(&split_ea);
542 if (curwin == old_curwin)
543 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100544 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200545 vim_free(term);
546 return NULL;
547 }
548 }
549 term->tl_buffer = curbuf;
550 curbuf->b_term = term;
551
552 if (!opt->jo_hidden)
553 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100554 // Only one size was taken care of with :new, do the other one. With
555 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100556 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200557 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100558 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200559 win_setwidth(opt->jo_term_cols);
560 }
561
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100562 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200563 term->tl_next = first_term;
564 first_term = term;
565
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100566 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
567
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100569 {
570 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200571 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100572 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100573 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100574 {
575 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100576 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100577 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200578 else
579 {
580 int i;
581 size_t len;
582 char_u *cmd, *p;
583
584 if (argvar->v_type == VAR_STRING)
585 {
586 cmd = argvar->vval.v_string;
587 if (cmd == NULL)
588 cmd = (char_u *)"";
589 else if (STRCMP(cmd, "NONE") == 0)
590 cmd = (char_u *)"pty";
591 }
592 else if (argvar->v_type != VAR_LIST
593 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100594 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100595 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200596 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
597 cmd = (char_u*)"";
598
599 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200600 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200601
602 for (i = 0; p != NULL; ++i)
603 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100604 // Prepend a ! to the command name to avoid the buffer name equals
605 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200606 if (i == 0)
607 vim_snprintf((char *)p, len, "!%s", cmd);
608 else
609 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
610 if (buflist_findname(p) == NULL)
611 {
612 vim_free(curbuf->b_ffname);
613 curbuf->b_ffname = p;
614 break;
615 }
616 }
617 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100618 vim_free(curbuf->b_sfname);
619 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200620 curbuf->b_fname = curbuf->b_ffname;
621
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100622 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
623
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200624 if (opt->jo_term_opencmd != NULL)
625 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
626
627 if (opt->jo_eof_chars != NULL)
628 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
629
630 set_string_option_direct((char_u *)"buftype", -1,
631 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200632 // Avoid that 'buftype' is reset when this buffer is entered.
633 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200634
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100635 // Mark the buffer as not modifiable. It can only be made modifiable after
636 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200637 curbuf->b_p_ma = FALSE;
638
Bram Moolenaarb936b792020-09-04 18:34:09 +0200639 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100640#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200641 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
642#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200643 setup_job_options(opt, term->tl_rows, term->tl_cols);
644
Bram Moolenaar13568252018-03-16 20:46:58 +0100645 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100646 return curbuf;
647
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100648#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100649 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100650 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100651 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100652 else if (argvar->v_type == VAR_STRING)
653 {
654 char_u *cmd = argvar->vval.v_string;
655
656 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
657 term->tl_command = vim_strsave(cmd);
658 }
659 else if (argvar->v_type == VAR_LIST
660 && argvar->vval.v_list != NULL
661 && argvar->vval.v_list->lv_len > 0)
662 {
663 garray_T ga;
664 listitem_T *item;
665
666 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200667 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100668 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100669 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100670 char_u *p;
671
672 if (s == NULL)
673 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100674 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100675 if (p == NULL)
676 break;
677 ga_concat(&ga, p);
678 vim_free(p);
679 ga_append(&ga, ' ');
680 }
681 if (item == NULL)
682 {
683 ga_append(&ga, NUL);
684 term->tl_command = ga.ga_data;
685 }
686 else
687 ga_clear(&ga);
688 }
689#endif
690
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100691 if (opt->jo_term_kill != NULL)
692 {
693 char_u *p = skiptowhite(opt->jo_term_kill);
694
695 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
696 }
697
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200698 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100699 {
700 char_u *p = skiptowhite(opt->jo_term_api);
701
702 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
703 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200704 else
705 term->tl_api = vim_strsave((char_u *)"Tapi_");
706
Bram Moolenaar83d47902020-03-26 20:34:00 +0100707 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
708 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
709
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100710#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100711 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
712 if (opt->jo_set2 & JO2_ANSI_COLORS)
713 {
714 term->tl_palette = ALLOC_MULT(long_u, 16);
715 if (term->tl_palette == NULL)
716 {
717 vim_free(term);
718 return NULL;
719 }
720 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
721 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100722#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100723
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100724 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100725 if (argv == NULL
726 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200727 && argvar->vval.v_string != NULL
728 && STRCMP(argvar->vval.v_string, "NONE") == 0)
729 res = create_pty_only(term, opt);
730 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200731 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200732
733 newbuf = curbuf;
734 if (res == OK)
735 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100736 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200737 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
738 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100739#ifdef FEAT_GUI
740 if (term->tl_system)
741 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100742 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100743 term->tl_toprow = msg_row + 1;
744 term->tl_dirty_row_end = 0;
745 }
746#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200747
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100748 // Make sure we don't get stuck on sending keys to the job, it leads to
749 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200750 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
751
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200752 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200753 {
754 --curbuf->b_nwindows;
755 curbuf = old_curbuf;
756 curwin->w_buffer = curbuf;
757 ++curbuf->b_nwindows;
758 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000759 else if (vgetc_busy
760#ifdef FEAT_TIMERS
761 || timer_busy
762#endif
763 || input_busy)
764 {
765 char_u ignore[4];
766
767 // When waiting for input need to return and possibly end up in
768 // terminal_loop() instead.
769 ignore[0] = K_SPECIAL;
770 ignore[1] = KS_EXTRA;
771 ignore[2] = KE_IGNORE;
772 ignore[3] = NUL;
773 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
774 typebuf_was_filled = TRUE;
775 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200776 }
777 else
778 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100779 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200780 return NULL;
781 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100782
Bram Moolenaar13568252018-03-16 20:46:58 +0100783 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200784 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
785 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200786 return newbuf;
787}
788
789/*
790 * ":terminal": open a terminal window and execute a job in it.
791 */
792 void
793ex_terminal(exarg_T *eap)
794{
795 typval_T argvar[2];
796 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100797 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200798 char_u *cmd;
799 char_u *tofree = NULL;
800
801 init_job_options(&opt);
802
803 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100804 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200805 {
806 char_u *p, *ep;
807
808 cmd += 2;
809 p = skiptowhite(cmd);
810 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200811 if (ep != NULL)
812 {
813 if (ep < p)
814 p = ep;
815 else
816 ep = NULL;
817 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200818
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200819# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
820 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
821 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200822 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200823 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100824 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200825 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200826 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200827 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200828 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200829 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200830 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200831 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100832 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100833 else if (OPTARG_HAS("shell"))
834 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200835 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100836 {
837 opt.jo_set2 |= JO2_TERM_KILL;
838 opt.jo_term_kill = ep + 1;
839 p = skiptowhite(cmd);
840 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200841 else if (OPTARG_HAS("api"))
842 {
843 opt.jo_set2 |= JO2_TERM_API;
844 if (ep != NULL)
845 {
846 opt.jo_term_api = ep + 1;
847 p = skiptowhite(cmd);
848 }
849 else
850 opt.jo_term_api = NULL;
851 }
852 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200853 {
854 opt.jo_set2 |= JO2_TERM_ROWS;
855 opt.jo_term_rows = atoi((char *)ep + 1);
856 p = skiptowhite(cmd);
857 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200858 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200859 {
860 opt.jo_set2 |= JO2_TERM_COLS;
861 opt.jo_term_cols = atoi((char *)ep + 1);
862 p = skiptowhite(cmd);
863 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200864 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200865 {
866 char_u *buf = NULL;
867 char_u *keys;
868
Bram Moolenaar21109272020-01-30 16:27:20 +0100869 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200870 p = skiptowhite(cmd);
871 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200872 keys = replace_termcodes(ep + 1, &buf,
873 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200874 opt.jo_set2 |= JO2_EOF_CHARS;
875 opt.jo_eof_chars = vim_strsave(keys);
876 vim_free(buf);
877 *p = ' ';
878 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100879#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100880 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
881 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100882 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100883 int tty_type = NUL;
884
885 p = skiptowhite(cmd);
886 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
887 tty_type = 'w';
888 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
889 tty_type = 'c';
890 else
891 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000892 semsg(e_invalid_value_for_argument_str, "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100893 goto theend;
894 }
895 opt.jo_set2 |= JO2_TTY_TYPE;
896 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100897 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100898#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200899 else
900 {
901 if (*p)
902 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000903 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100904 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200905 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200906# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200907 cmd = skipwhite(p);
908 }
909 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100910 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100911 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200912 tofree = cmd = vim_strsave(p_sh);
913
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100914 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100915 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200916 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100917 }
918
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200919 if (eap->addr_count > 0)
920 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100921 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200922 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
923 opt.jo_io[PART_IN] = JIO_BUFFER;
924 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
925 opt.jo_in_top = eap->line1;
926 opt.jo_in_bot = eap->line2;
927 }
928
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100929 if (opt_shell && tofree == NULL)
930 {
931#ifdef UNIX
932 char **argv = NULL;
933 char_u *tofree1 = NULL;
934 char_u *tofree2 = NULL;
935
936 // :term ++shell command
937 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
938 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100939 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100940 vim_free(tofree1);
941 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100942 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100943#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100944# ifdef MSWIN
945 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
946 char_u *newcmd;
947
948 newcmd = alloc(cmdlen);
949 if (newcmd == NULL)
950 goto theend;
951 tofree = newcmd;
952 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
953 cmd = newcmd;
954# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000955 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100956 goto theend;
957# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100958#endif
959 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100960 argvar[0].v_type = VAR_STRING;
961 argvar[0].vval.v_string = cmd;
962 argvar[1].v_type = VAR_UNKNOWN;
963 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100964
965theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100966 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200967 vim_free(opt.jo_eof_chars);
968}
969
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100970#if defined(FEAT_SESSION) || defined(PROTO)
971/*
972 * Write a :terminal command to the session file to restore the terminal in
973 * window "wp".
974 * Return FAIL if writing fails.
975 */
976 int
Bram Moolenaar0e655112020-09-11 20:36:36 +0200977term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100978{
Bram Moolenaar0e655112020-09-11 20:36:36 +0200979 const int bufnr = wp->w_buffer->b_fnum;
980 term_T *term = wp->w_buffer->b_term;
981
Bram Moolenaarc2c82052020-09-11 22:10:22 +0200982 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +0200983 {
984 // There are multiple views into this terminal buffer. We don't want to
985 // create the terminal multiple times. If it's the first time, create,
986 // otherwise link to the first buffer.
987 char id_as_str[NUMBUFLEN];
988 hashitem_T *entry;
989
990 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
991
992 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
993 if (!HASHITEM_EMPTY(entry))
994 {
995 // we've already opened this terminal buffer
996 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
997 return FAIL;
998 return put_eol(fd);
999 }
1000 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001001
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001002 // Create the terminal and run the command. This is not without
1003 // risk, but let's assume the user only creates a session when this
1004 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001005 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1006 term->tl_cols, term->tl_rows) < 0)
1007 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001008#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001009 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1010 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001011#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001012 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1013 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001014 if (put_eol(fd) != OK)
1015 return FAIL;
1016
1017 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1018 return FAIL;
1019
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001020 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001021 {
1022 char *hash_key = alloc(NUMBUFLEN);
1023
1024 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
1025 hash_add(terminal_bufs, (char_u *)hash_key);
1026 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001027
1028 return put_eol(fd);
1029}
1030
1031/*
1032 * Return TRUE if "buf" has a terminal that should be restored.
1033 */
1034 int
1035term_should_restore(buf_T *buf)
1036{
1037 term_T *term = buf->b_term;
1038
1039 return term != NULL && (term->tl_command == NULL
1040 || STRCMP(term->tl_command, "NONE") != 0);
1041}
1042#endif
1043
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001044/*
1045 * Free the scrollback buffer for "term".
1046 */
1047 static void
1048free_scrollback(term_T *term)
1049{
1050 int i;
1051
1052 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1053 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1054 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001055 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1056 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1057 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001058}
1059
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001060
1061// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001062static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001063
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001064/*
1065 * Free a terminal and everything it refers to.
1066 * Kills the job if there is one.
1067 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001068 * The actual terminal structure is freed later in free_unused_terminals(),
1069 * because callbacks may wipe out a buffer while the terminal is still
1070 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001071 */
1072 void
1073free_terminal(buf_T *buf)
1074{
1075 term_T *term = buf->b_term;
1076 term_T *tp;
1077
1078 if (term == NULL)
1079 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001080
1081 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001082 if (first_term == term)
1083 first_term = term->tl_next;
1084 else
1085 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1086 if (tp->tl_next == term)
1087 {
1088 tp->tl_next = term->tl_next;
1089 break;
1090 }
1091
1092 if (term->tl_job != NULL)
1093 {
1094 if (term->tl_job->jv_status != JOB_ENDED
1095 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001096 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001097 job_stop(term->tl_job, NULL, "kill");
1098 job_unref(term->tl_job);
1099 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001100 term->tl_next = terminals_to_free;
1101 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001102
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001103 buf->b_term = NULL;
1104 if (in_terminal_loop == term)
1105 in_terminal_loop = NULL;
1106}
1107
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001108 void
1109free_unused_terminals()
1110{
1111 while (terminals_to_free != NULL)
1112 {
1113 term_T *term = terminals_to_free;
1114
1115 terminals_to_free = term->tl_next;
1116
1117 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001118 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001119
1120 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001121 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001122 vim_free(term->tl_title);
1123#ifdef FEAT_SESSION
1124 vim_free(term->tl_command);
1125#endif
1126 vim_free(term->tl_kill);
1127 vim_free(term->tl_status_text);
1128 vim_free(term->tl_opencmd);
1129 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001130 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001131#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001132 if (term->tl_out_fd != NULL)
1133 fclose(term->tl_out_fd);
1134#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001135 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001136 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001137 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001138 vim_free(term);
1139 }
1140}
1141
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001142/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001143 * Get the part that is connected to the tty. Normally this is PART_IN, but
1144 * when writing buffer lines to the job it can be another. This makes it
1145 * possible to do "1,5term vim -".
1146 */
1147 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001148get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001149{
1150#ifdef UNIX
1151 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1152 int i;
1153
1154 for (i = 0; i < 3; ++i)
1155 {
1156 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1157
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001158 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001159 return parts[i];
1160 }
1161#endif
1162 return PART_IN;
1163}
1164
1165/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001166 * Read any vterm output and send it on the channel.
1167 */
1168 static void
1169term_forward_output(term_T *term)
1170{
1171 VTerm *vterm = term->tl_vterm;
1172 char buf[KEY_BUF_LEN];
1173 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1174
1175 if (curlen > 0)
1176 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1177 (char_u *)buf, (int)curlen, NULL);
1178}
1179
1180/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001181 * Write job output "msg[len]" to the vterm.
1182 */
1183 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001184term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001185{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001186 char_u *msg = msg_arg;
1187 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001188 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001189 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001190 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1191
1192 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1193 // the end.
1194 if (len > limit)
1195 {
1196 char_u *p = msg + len - limit;
1197
1198 p -= (*mb_head_off)(msg, p);
1199 len -= p - msg;
1200 msg = p;
1201 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001202
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001203 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001204
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001205 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001206 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001207 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001208
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001209 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001210 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1211}
1212
1213 static void
1214update_cursor(term_T *term, int redraw)
1215{
1216 if (term->tl_normal_mode)
1217 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001218#ifdef FEAT_GUI
1219 if (term->tl_system)
1220 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1221 term->tl_cursor_pos.col);
1222 else
1223#endif
1224 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001225 if (redraw)
1226 {
1227 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1228 cursor_on();
1229 out_flush();
1230#ifdef FEAT_GUI
1231 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001232 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001233 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001234 gui_mch_flush();
1235 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001236#endif
1237 }
1238}
1239
1240/*
1241 * Invoked when "msg" output from a job was received. Write it to the terminal
1242 * of "buffer".
1243 */
1244 void
1245write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1246{
1247 size_t len = STRLEN(msg);
1248 term_T *term = buffer->b_term;
1249
Bram Moolenaar4f974752019-02-17 17:44:42 +01001250#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001251 // Win32: Cannot redirect output of the job, intercept it here and write to
1252 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001253 if (term->tl_out_fd != NULL)
1254 {
1255 ch_log(channel, "Writing %d bytes to output file", (int)len);
1256 fwrite(msg, len, 1, term->tl_out_fd);
1257 return;
1258 }
1259#endif
1260
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001261 if (term->tl_vterm == NULL)
1262 {
1263 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1264 return;
1265 }
1266 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001267 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001268 term_write_job_output(term, msg, len);
1269
Bram Moolenaar13568252018-03-16 20:46:58 +01001270#ifdef FEAT_GUI
1271 if (term->tl_system)
1272 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001273 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001274 update_system_term(term);
1275 update_cursor(term, TRUE);
1276 }
1277 else
1278#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001279 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1280 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001281 if (!term->tl_normal_mode)
1282 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001283 // Don't use update_screen() when editing the command line, it gets
1284 // cleared.
1285 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001286 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001287 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001288 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001289 update_screen(UPD_VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001290 // update_screen() can be slow, check the terminal wasn't closed
1291 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001292 if (buffer == curbuf && curbuf->b_term != NULL)
1293 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001294 }
1295 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001296 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001297 }
1298}
1299
1300/*
1301 * Send a mouse position and click to the vterm
1302 */
1303 static int
1304term_send_mouse(VTerm *vterm, int button, int pressed)
1305{
1306 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001307 int row = mouse_row - W_WINROW(curwin);
1308 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001309
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001310#ifdef FEAT_PROP_POPUP
1311 if (popup_is_popup(curwin))
1312 {
1313 row -= popup_top_extra(curwin);
1314 col -= popup_left_extra(curwin);
1315 }
1316#endif
1317 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001318 if (button != 0)
1319 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001320 return TRUE;
1321}
1322
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001323static int enter_mouse_col = -1;
1324static int enter_mouse_row = -1;
1325
1326/*
1327 * Handle a mouse click, drag or release.
1328 * Return TRUE when a mouse event is sent to the terminal.
1329 */
1330 static int
1331term_mouse_click(VTerm *vterm, int key)
1332{
1333#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001334 // For modeless selection mouse drag and release events are ignored, unless
1335 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001336 static int ignore_drag_release = TRUE;
1337 VTermMouseState mouse_state;
1338
1339 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1340 if (mouse_state.flags == 0)
1341 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001342 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001343 switch (key)
1344 {
1345 case K_LEFTDRAG:
1346 case K_LEFTRELEASE:
1347 case K_RIGHTDRAG:
1348 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001349 // Ignore drag and release events when the button-down wasn't
1350 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001351 if (ignore_drag_release)
1352 {
1353 int save_mouse_col, save_mouse_row;
1354
1355 if (enter_mouse_col < 0)
1356 break;
1357
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001358 // mouse click in the window gave us focus, handle that
1359 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001360 save_mouse_col = mouse_col;
1361 save_mouse_row = mouse_row;
1362 mouse_col = enter_mouse_col;
1363 mouse_row = enter_mouse_row;
1364 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1365 mouse_col = save_mouse_col;
1366 mouse_row = save_mouse_row;
1367 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001368 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001369 case K_LEFTMOUSE:
1370 case K_RIGHTMOUSE:
1371 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1372 ignore_drag_release = TRUE;
1373 else
1374 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001375 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001376 if (clip_star.available)
1377 {
1378 int button, is_click, is_drag;
1379
1380 button = get_mouse_button(KEY2TERMCAP1(key),
1381 &is_click, &is_drag);
1382 if (mouse_model_popup() && button == MOUSE_LEFT
1383 && (mod_mask & MOD_MASK_SHIFT))
1384 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001385 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001386 button = MOUSE_RIGHT;
1387 mod_mask &= ~MOD_MASK_SHIFT;
1388 }
1389 clip_modeless(button, is_click, is_drag);
1390 }
1391 break;
1392
1393 case K_MIDDLEMOUSE:
1394 if (clip_star.available)
1395 insert_reg('*', TRUE);
1396 break;
1397 }
1398 enter_mouse_col = -1;
1399 return FALSE;
1400 }
1401#endif
1402 enter_mouse_col = -1;
1403
1404 switch (key)
1405 {
1406 case K_LEFTMOUSE:
1407 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1408 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1409 case K_LEFTRELEASE:
1410 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1411 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1412 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1413 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1414 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1415 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1416 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1417 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1418 }
1419 return TRUE;
1420}
1421
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001422/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001423 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1424 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001425 * Return the number of bytes in "buf".
1426 */
1427 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001428term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001429{
1430 VTerm *vterm = term->tl_vterm;
1431 VTermKey key = VTERM_KEY_NONE;
1432 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001433 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001434
1435 switch (c)
1436 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001437 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001438
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001439 // don't use VTERM_KEY_BACKSPACE, it always
1440 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001441 case K_BS: c = term_backspace_char; break;
1442
1443 case ESC: key = VTERM_KEY_ESCAPE; break;
1444 case K_DEL: key = VTERM_KEY_DEL; break;
1445 case K_DOWN: key = VTERM_KEY_DOWN; break;
1446 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1447 key = VTERM_KEY_DOWN; break;
1448 case K_END: key = VTERM_KEY_END; break;
1449 case K_S_END: mod = VTERM_MOD_SHIFT;
1450 key = VTERM_KEY_END; break;
1451 case K_C_END: mod = VTERM_MOD_CTRL;
1452 key = VTERM_KEY_END; break;
1453 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1454 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1455 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1456 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1457 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1458 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1459 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1460 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1461 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1462 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1463 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1464 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1465 case K_HOME: key = VTERM_KEY_HOME; break;
1466 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1467 key = VTERM_KEY_HOME; break;
1468 case K_C_HOME: mod = VTERM_MOD_CTRL;
1469 key = VTERM_KEY_HOME; break;
1470 case K_INS: key = VTERM_KEY_INS; break;
1471 case K_K0: key = VTERM_KEY_KP_0; break;
1472 case K_K1: key = VTERM_KEY_KP_1; break;
1473 case K_K2: key = VTERM_KEY_KP_2; break;
1474 case K_K3: key = VTERM_KEY_KP_3; break;
1475 case K_K4: key = VTERM_KEY_KP_4; break;
1476 case K_K5: key = VTERM_KEY_KP_5; break;
1477 case K_K6: key = VTERM_KEY_KP_6; break;
1478 case K_K7: key = VTERM_KEY_KP_7; break;
1479 case K_K8: key = VTERM_KEY_KP_8; break;
1480 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001481 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001482 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001483 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001484 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001485 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1486 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001487 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1488 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001489 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1490 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001491 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1492 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1493 case K_LEFT: key = VTERM_KEY_LEFT; break;
1494 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1495 key = VTERM_KEY_LEFT; break;
1496 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1497 key = VTERM_KEY_LEFT; break;
1498 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1499 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1500 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1501 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1502 key = VTERM_KEY_RIGHT; break;
1503 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1504 key = VTERM_KEY_RIGHT; break;
1505 case K_UP: key = VTERM_KEY_UP; break;
1506 case K_S_UP: mod = VTERM_MOD_SHIFT;
1507 key = VTERM_KEY_UP; break;
1508 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001509 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1510 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001511
Bram Moolenaara42ad572017-11-16 13:08:04 +01001512 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1513 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001514 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1515 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001516
1517 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001518 case K_LEFTMOUSE_NM:
1519 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001520 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001521 case K_LEFTRELEASE_NM:
1522 case K_MOUSEMOVE:
1523 case K_MIDDLEMOUSE:
1524 case K_MIDDLEDRAG:
1525 case K_MIDDLERELEASE:
1526 case K_RIGHTMOUSE:
1527 case K_RIGHTDRAG:
1528 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1529 return 0;
1530 other = TRUE;
1531 break;
1532
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001533 case K_X1MOUSE: /* TODO */ return 0;
1534 case K_X1DRAG: /* TODO */ return 0;
1535 case K_X1RELEASE: /* TODO */ return 0;
1536 case K_X2MOUSE: /* TODO */ return 0;
1537 case K_X2DRAG: /* TODO */ return 0;
1538 case K_X2RELEASE: /* TODO */ return 0;
1539
1540 case K_IGNORE: return 0;
1541 case K_NOP: return 0;
1542 case K_UNDO: return 0;
1543 case K_HELP: return 0;
1544 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1545 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1546 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1547 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1548 case K_SELECT: return 0;
1549#ifdef FEAT_GUI
1550 case K_VER_SCROLLBAR: return 0;
1551 case K_HOR_SCROLLBAR: return 0;
1552#endif
1553#ifdef FEAT_GUI_TABLINE
1554 case K_TABLINE: return 0;
1555 case K_TABMENU: return 0;
1556#endif
1557#ifdef FEAT_NETBEANS_INTG
1558 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1559#endif
1560#ifdef FEAT_DND
1561 case K_DROP: return 0;
1562#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001563 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001564 case K_PS: vterm_keyboard_start_paste(vterm);
1565 other = TRUE;
1566 break;
1567 case K_PE: vterm_keyboard_end_paste(vterm);
1568 other = TRUE;
1569 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001570 }
1571
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001572 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001573 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001574 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001575 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001576 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001577 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001578 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001579
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001580 /*
1581 * Convert special keys to vterm keys:
1582 * - Write keys to vterm: vterm_keyboard_key()
1583 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001584 */
1585 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001586 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001587 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001588 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001589 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001590 vterm_keyboard_unichar(vterm, c, mod);
1591
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001592 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001593 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1594}
1595
1596/*
1597 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001598 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001599 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001600 */
1601 static int
1602term_job_running_check(term_T *term, int check_job_status)
1603{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001604 // Also consider the job finished when the channel is closed, to avoid a
1605 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001606 if (term != NULL
1607 && term->tl_job != NULL
1608 && channel_is_open(term->tl_job->jv_channel))
1609 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001610 job_T *job = term->tl_job;
1611
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00001612 // Careful: Checking the job status may invoke callbacks, which close
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001613 // the buffer and terminate "term". However, "job" will not be freed
1614 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001615 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001616 job_status(job);
1617 return (job->jv_status == JOB_STARTED
1618 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001619 }
1620 return FALSE;
1621}
1622
1623/*
1624 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001625 */
1626 int
1627term_job_running(term_T *term)
1628{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001629 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001630}
1631
1632/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001633 * Return TRUE if the job for "term" is still running, ignoring the job was
1634 * "NONE".
1635 */
1636 int
1637term_job_running_not_none(term_T *term)
1638{
1639 return term_job_running(term) && !term_none_open(term);
1640}
1641
1642/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001643 * Return TRUE if "term" has an active channel and used ":term NONE".
1644 */
1645 int
1646term_none_open(term_T *term)
1647{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001648 // Also consider the job finished when the channel is closed, to avoid a
1649 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001650 return term != NULL
1651 && term->tl_job != NULL
1652 && channel_is_open(term->tl_job->jv_channel)
1653 && term->tl_job->jv_channel->ch_keep_open;
1654}
1655
1656/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001657 * Used when exiting: kill the job in "buf" if so desired.
1658 * Return OK when the job finished.
1659 * Return FAIL when the job is still running.
1660 */
1661 int
1662term_try_stop_job(buf_T *buf)
1663{
1664 int count;
1665 char *how = (char *)buf->b_term->tl_kill;
1666
1667#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001668 if ((how == NULL || *how == NUL)
1669 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001670 {
1671 char_u buff[DIALOG_MSG_SIZE];
1672 int ret;
1673
Bram Moolenaar00806bc2020-11-05 19:36:38 +01001674 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001675 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1676 if (ret == VIM_YES)
1677 how = "kill";
1678 else if (ret == VIM_CANCEL)
1679 return FAIL;
1680 }
1681#endif
1682 if (how == NULL || *how == NUL)
1683 return FAIL;
1684
1685 job_stop(buf->b_term->tl_job, NULL, how);
1686
Bram Moolenaar9172d232019-01-29 23:06:54 +01001687 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001688 for (count = 0; count < 100; ++count)
1689 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001690 job_T *job;
1691
1692 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001693 if (!buf_valid(buf)
1694 || buf->b_term == NULL
1695 || buf->b_term->tl_job == NULL)
1696 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001697 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001698
Bram Moolenaar9172d232019-01-29 23:06:54 +01001699 // Call job_status() to update jv_status. It may cause the job to be
1700 // cleaned up but it won't be freed.
1701 job_status(job);
1702 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001703 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001704
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001705 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001706 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001707 }
1708 return FAIL;
1709}
1710
1711/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001712 * Add the last line of the scrollback buffer to the buffer in the window.
1713 */
1714 static void
1715add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1716{
1717 buf_T *buf = term->tl_buffer;
1718 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1719 linenr_T lnum = buf->b_ml.ml_line_count;
1720
Bram Moolenaar4f974752019-02-17 17:44:42 +01001721#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001722 if (!enc_utf8 && enc_codepage > 0)
1723 {
1724 WCHAR *ret = NULL;
1725 int length = 0;
1726
1727 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1728 &ret, &length);
1729 if (ret != NULL)
1730 {
1731 WideCharToMultiByte_alloc(enc_codepage, 0,
1732 ret, length, (char **)&text, &len, 0, 0);
1733 vim_free(ret);
1734 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1735 vim_free(text);
1736 }
1737 }
1738 else
1739#endif
1740 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1741 if (empty)
1742 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001743 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001744 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001745 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001746 curbuf = curwin->w_buffer;
1747 }
1748}
1749
1750 static void
1751cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1752{
1753 attr->width = cell->width;
1754 attr->attrs = cell->attrs;
1755 attr->fg = cell->fg;
1756 attr->bg = cell->bg;
1757}
1758
1759 static int
1760equal_celattr(cellattr_T *a, cellattr_T *b)
1761{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001762 // We only compare the RGB colors, ignoring the ANSI index and type.
1763 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001764 return a->fg.red == b->fg.red
1765 && a->fg.green == b->fg.green
1766 && a->fg.blue == b->fg.blue
1767 && a->bg.red == b->bg.red
1768 && a->bg.green == b->bg.green
1769 && a->bg.blue == b->bg.blue;
1770}
1771
Bram Moolenaard96ff162018-02-18 22:13:29 +01001772/*
1773 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1774 * line at this position. Otherwise at the end.
1775 */
1776 static int
1777add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1778{
1779 if (ga_grow(&term->tl_scrollback, 1) == OK)
1780 {
1781 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1782 + term->tl_scrollback.ga_len;
1783
1784 if (lnum > 0)
1785 {
1786 int i;
1787
1788 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1789 {
1790 *line = *(line - 1);
1791 --line;
1792 }
1793 }
1794 line->sb_cols = 0;
1795 line->sb_cells = NULL;
1796 line->sb_fill_attr = *fill_attr;
1797 ++term->tl_scrollback.ga_len;
1798 return OK;
1799 }
1800 return FALSE;
1801}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001802
1803/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001804 * Remove the terminal contents from the scrollback and the buffer.
1805 * Used before adding a new scrollback line or updating the buffer for lines
1806 * displayed in the terminal.
1807 */
1808 static void
1809cleanup_scrollback(term_T *term)
1810{
1811 sb_line_T *line;
1812 garray_T *gap;
1813
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001814 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001815 gap = &term->tl_scrollback;
1816 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1817 && gap->ga_len > 0)
1818 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001819 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001820 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1821 vim_free(line->sb_cells);
1822 --gap->ga_len;
1823 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001824 curbuf = curwin->w_buffer;
1825 if (curbuf == term->tl_buffer)
1826 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001827}
1828
1829/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001830 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001831 */
1832 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001833update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001834{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001835 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001836 int len;
1837 int lines_skipped = 0;
1838 VTermPos pos;
1839 VTermScreenCell cell;
1840 cellattr_T fill_attr, new_fill_attr;
1841 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001842
1843 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1844 "Adding terminal window snapshot to buffer");
1845
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001846 // First remove the lines that were appended before, they might be
1847 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001848 cleanup_scrollback(term);
1849
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001850 screen = vterm_obtain_screen(term->tl_vterm);
1851 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001852 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1853 {
1854 len = 0;
1855 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1856 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1857 && cell.chars[0] != NUL)
1858 {
1859 len = pos.col + 1;
1860 new_fill_attr = term->tl_default_color;
1861 }
1862 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001863 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001864 cell2cellattr(&cell, &new_fill_attr);
1865
1866 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1867 ++lines_skipped;
1868 else
1869 {
1870 while (lines_skipped > 0)
1871 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001872 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001873 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001874 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001876 }
1877
1878 if (len == 0)
1879 p = NULL;
1880 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001881 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001882 if ((p != NULL || len == 0)
1883 && ga_grow(&term->tl_scrollback, 1) == OK)
1884 {
1885 garray_T ga;
1886 int width;
1887 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1888 + term->tl_scrollback.ga_len;
1889
1890 ga_init2(&ga, 1, 100);
1891 for (pos.col = 0; pos.col < len; pos.col += width)
1892 {
1893 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1894 {
1895 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02001896 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897 if (ga_grow(&ga, 1) == OK)
1898 ga.ga_len += utf_char2bytes(' ',
1899 (char_u *)ga.ga_data + ga.ga_len);
1900 }
1901 else
1902 {
1903 width = cell.width;
1904
1905 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01001906 if (width == 2)
1907 // second cell of double-width character has the
1908 // same attributes.
1909 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001910
Bram Moolenaara79fd562018-12-20 20:47:32 +01001911 // Each character can be up to 6 bytes.
1912 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913 {
1914 int i;
1915 int c;
1916
1917 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1918 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1919 (char_u *)ga.ga_data + ga.ga_len);
1920 }
1921 }
1922 }
1923 line->sb_cols = len;
1924 line->sb_cells = p;
1925 line->sb_fill_attr = new_fill_attr;
1926 fill_attr = new_fill_attr;
1927 ++term->tl_scrollback.ga_len;
1928
1929 if (ga_grow(&ga, 1) == FAIL)
1930 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1931 else
1932 {
1933 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1934 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1935 }
1936 ga_clear(&ga);
1937 }
1938 else
1939 vim_free(p);
1940 }
1941 }
1942
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001943 // Add trailing empty lines.
1944 for (pos.row = term->tl_scrollback.ga_len;
1945 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1946 ++pos.row)
1947 {
1948 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1949 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1950 }
1951
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001952 term->tl_dirty_snapshot = FALSE;
1953#ifdef FEAT_TIMERS
1954 term->tl_timer_set = FALSE;
1955#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001956}
1957
1958/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001959 * Loop over all windows in the current tab, and also curwin, which is not
1960 * encountered when using a terminal in a popup window.
1961 * Return TRUE if "*wp" was set to the next window.
1962 */
1963 static int
1964for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1965{
1966 if (*wp == NULL)
1967 *wp = firstwin;
1968 else if ((*wp)->w_next != NULL)
1969 *wp = (*wp)->w_next;
1970 else if (!*did_curwin)
1971 *wp = curwin;
1972 else
1973 return FALSE;
1974 if (*wp == curwin)
1975 *did_curwin = TRUE;
1976 return TRUE;
1977}
1978
1979/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001980 * If needed, add the current lines of the terminal to scrollback and to the
1981 * buffer. Called after the job has ended and when switching to
1982 * Terminal-Normal mode.
1983 * When "redraw" is TRUE redraw the windows that show the terminal.
1984 */
1985 static void
1986may_move_terminal_to_buffer(term_T *term, int redraw)
1987{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001988 if (term->tl_vterm == NULL)
1989 return;
1990
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001991 // Update the snapshot only if something changes or the buffer does not
1992 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001993 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1994 <= term->tl_scrollback_scrolled)
1995 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001996
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001997 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001998 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1999 &term->tl_default_color.fg, &term->tl_default_color.bg);
2000
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002001 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002002 {
2003 win_T *wp = NULL;
2004 int did_curwin = FALSE;
2005
2006 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002007 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002008 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002009 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002010 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2011 wp->w_cursor.col = 0;
2012 wp->w_valid = 0;
2013 if (wp->w_cursor.lnum >= wp->w_height)
2014 {
2015 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002017 if (wp->w_topline < min_topline)
2018 wp->w_topline = min_topline;
2019 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002020 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002021 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002023 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002024}
2025
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002026#if defined(FEAT_TIMERS) || defined(PROTO)
2027/*
2028 * Check if any terminal timer expired. If so, copy text from the terminal to
2029 * the buffer.
2030 * Return the time until the next timer will expire.
2031 */
2032 int
2033term_check_timers(int next_due_arg, proftime_T *now)
2034{
2035 term_T *term;
2036 int next_due = next_due_arg;
2037
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002038 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002039 {
2040 if (term->tl_timer_set && !term->tl_normal_mode)
2041 {
2042 long this_due = proftime_time_left(&term->tl_timer_due, now);
2043
2044 if (this_due <= 1)
2045 {
2046 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002047 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002048 }
2049 else if (next_due == -1 || next_due > this_due)
2050 next_due = this_due;
2051 }
2052 }
2053
2054 return next_due;
2055}
2056#endif
2057
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002058/*
2059 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2060 * otherwise end it.
2061 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002062 static void
2063set_terminal_mode(term_T *term, int normal_mode)
2064{
2065 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002066 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002067 if (!normal_mode)
2068 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002069 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002070 if (term->tl_buffer == curbuf)
2071 maketitle();
2072}
2073
2074/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002075 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002076 * Move the vterm contents into the scrollback buffer and free the vterm.
2077 */
2078 static void
2079cleanup_vterm(term_T *term)
2080{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002081 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002082 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002083 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002084 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002085}
2086
2087/*
2088 * Switch from Terminal-Job mode to Terminal-Normal mode.
2089 * Suspends updating the terminal window.
2090 */
2091 static void
2092term_enter_normal_mode(void)
2093{
2094 term_T *term = curbuf->b_term;
2095
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002096 set_terminal_mode(term, TRUE);
2097
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002098 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002099 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002100
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002101 // Move the window cursor to the position of the cursor in the
2102 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002103 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2104 + term->tl_cursor_pos.row + 1;
2105 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002106 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2107 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002108 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002109
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002110 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002111 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2112}
2113
2114/*
2115 * Returns TRUE if the current window contains a terminal and we are in
2116 * Terminal-Normal mode.
2117 */
2118 int
2119term_in_normal_mode(void)
2120{
2121 term_T *term = curbuf->b_term;
2122
2123 return term != NULL && term->tl_normal_mode;
2124}
2125
2126/*
2127 * Switch from Terminal-Normal mode to Terminal-Job mode.
2128 * Restores updating the terminal window.
2129 */
2130 void
2131term_enter_job_mode()
2132{
2133 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002134
2135 set_terminal_mode(term, FALSE);
2136
2137 if (term->tl_channel_closed)
2138 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002139 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002140#ifdef FEAT_PROP_POPUP
2141 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002142 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002143#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002144}
2145
2146/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002147 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002148 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002149 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002150 */
2151 static int
2152term_vgetc()
2153{
2154 int c;
2155 int save_State = State;
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002156 int modify_other_keys = curbuf->b_term->tl_vterm == NULL ? FALSE
2157 : vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002158
Bram Moolenaar24959102022-05-07 20:01:16 +01002159 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002160 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002161#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002162 ctrl_break_was_pressed = FALSE;
2163#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002164 if (modify_other_keys)
2165 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166 c = vgetc();
2167 got_int = FALSE;
2168 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002169 if (modify_other_keys)
2170 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002171 return c;
2172}
2173
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002174static int mouse_was_outside = FALSE;
2175
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002176/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002177 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002178 * Return FAIL when the key needs to be handled in Normal mode.
2179 * Return OK when the key was dropped or sent to the terminal.
2180 */
2181 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002182send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002183{
2184 char msg[KEY_BUF_LEN];
2185 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002186 int dragging_outside = FALSE;
2187
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002188 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002189 switch (c)
2190 {
2191 case NUL:
2192 case K_ZERO:
2193 if (typed)
2194 stuffcharReadbuff(c);
2195 return FAIL;
2196
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002197 case K_TABLINE:
2198 stuffcharReadbuff(c);
2199 return FAIL;
2200
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002201 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002202 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002203 return FAIL;
2204
2205 case K_LEFTDRAG:
2206 case K_MIDDLEDRAG:
2207 case K_RIGHTDRAG:
2208 case K_X1DRAG:
2209 case K_X2DRAG:
2210 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002211 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002212 case K_LEFTMOUSE:
2213 case K_LEFTMOUSE_NM:
2214 case K_LEFTRELEASE:
2215 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002216 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002217 case K_MIDDLEMOUSE:
2218 case K_MIDDLERELEASE:
2219 case K_RIGHTMOUSE:
2220 case K_RIGHTRELEASE:
2221 case K_X1MOUSE:
2222 case K_X1RELEASE:
2223 case K_X2MOUSE:
2224 case K_X2RELEASE:
2225
2226 case K_MOUSEUP:
2227 case K_MOUSEDOWN:
2228 case K_MOUSELEFT:
2229 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002230 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002231 int row = mouse_row;
2232 int col = mouse_col;
2233
2234#ifdef FEAT_PROP_POPUP
2235 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002237 row -= popup_top_extra(curwin);
2238 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002239 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002240#endif
2241 if (row < W_WINROW(curwin)
2242 || row >= (W_WINROW(curwin) + curwin->w_height)
2243 || col < curwin->w_wincol
2244 || col >= W_ENDCOL(curwin)
2245 || dragging_outside)
2246 {
2247 // click or scroll outside the current window or on status
2248 // line or vertical separator
2249 if (typed)
2250 {
2251 stuffcharReadbuff(c);
2252 mouse_was_outside = TRUE;
2253 }
2254 return FAIL;
2255 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002256 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002257 break;
2258
2259 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002260 case K_SCRIPT_COMMAND:
2261 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262 }
2263 if (typed)
2264 mouse_was_outside = FALSE;
2265
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002266 // Convert the typed key to a sequence of bytes for the job.
2267 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002268 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002269 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002270 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2271 (char_u *)msg, (int)len, NULL);
2272
2273 return OK;
2274}
2275
2276 static void
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002277position_cursor(win_T *wp, VTermPos *pos)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002278{
2279 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2280 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002281#ifdef FEAT_PROP_POPUP
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002282 if (popup_is_popup(wp))
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002283 {
Bram Moolenaarf5452692020-11-28 21:56:06 +01002284 wp->w_wrow += popup_top_extra(wp);
2285 wp->w_wcol += popup_left_extra(wp);
Bram Moolenaar6a076442020-11-15 20:32:58 +01002286 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002287 }
Bram Moolenaar6a076442020-11-15 20:32:58 +01002288 else
2289 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002290#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002291 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2292}
2293
2294/*
2295 * Handle CTRL-W "": send register contents to the job.
2296 */
2297 static void
2298term_paste_register(int prev_c UNUSED)
2299{
2300 int c;
2301 list_T *l;
2302 listitem_T *item;
2303 long reglen = 0;
2304 int type;
2305
2306#ifdef FEAT_CMDL_INFO
2307 if (add_to_showcmd(prev_c))
2308 if (add_to_showcmd('"'))
2309 out_flush();
2310#endif
2311 c = term_vgetc();
2312#ifdef FEAT_CMDL_INFO
2313 clear_showcmd();
2314#endif
2315 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002316 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002317 return;
2318
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002319 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002320 if (c == '=' && get_expr_register() != '=')
2321 return;
2322 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002323 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002324 return;
2325
2326 l = (list_T *)get_reg_contents(c, GREG_LIST);
2327 if (l != NULL)
2328 {
2329 type = get_reg_type(c, &reglen);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002330 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002331 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002332 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002333#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002334 char_u *tmp = s;
2335
2336 if (!enc_utf8 && enc_codepage > 0)
2337 {
2338 WCHAR *ret = NULL;
2339 int length = 0;
2340
2341 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2342 (int)STRLEN(s), &ret, &length);
2343 if (ret != NULL)
2344 {
2345 WideCharToMultiByte_alloc(CP_UTF8, 0,
2346 ret, length, (char **)&s, &length, 0, 0);
2347 vim_free(ret);
2348 }
2349 }
2350#endif
2351 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2352 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002353#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002354 if (tmp != s)
2355 vim_free(s);
2356#endif
2357
2358 if (item->li_next != NULL || type == MLINE)
2359 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2360 (char_u *)"\r", 1, NULL);
2361 }
2362 list_free(l);
2363 }
2364}
2365
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002366/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002367 * Return TRUE when waiting for a character in the terminal, the cursor of the
2368 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002369 */
2370 int
2371terminal_is_active()
2372{
2373 return in_terminal_loop != NULL;
2374}
2375
Bram Moolenaar83d47902020-03-26 20:34:00 +01002376/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002377 * Return the highight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002378 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002379 static int
2380term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002381{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002382 char_u *name;
2383
2384 if (wp != NULL && *wp->w_p_wcr != NUL)
2385 name = wp->w_p_wcr;
2386 else if (term->tl_highlight_name != NULL)
2387 name = term->tl_highlight_name;
2388 else
2389 name = (char_u*)"Terminal";
2390
2391 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002392}
2393
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002394#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002395 cursorentry_T *
2396term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2397{
2398 term_T *term = in_terminal_loop;
2399 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002400 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002401 guicolor_T term_fg = INVALCOLOR;
2402 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002403
Bram Moolenaara80faa82020-04-12 19:37:17 +02002404 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002405 entry.shape = entry.mshape =
2406 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2407 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2408 SHAPE_BLOCK;
2409 entry.percentage = 20;
2410 if (term->tl_cursor_blink)
2411 {
2412 entry.blinkwait = 700;
2413 entry.blinkon = 400;
2414 entry.blinkoff = 250;
2415 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002416
Bram Moolenaar83d47902020-03-26 20:34:00 +01002417 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002418 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002419 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002420 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002421 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002422 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002423 else
2424 *fg = gui.back_pixel;
2425
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002426 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002427 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002428 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002429 *bg = term_fg;
2430 else
2431 *bg = gui.norm_pixel;
2432 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002433 else
2434 *bg = color_name2handle(term->tl_cursor_color);
2435 entry.name = "n";
2436 entry.used_for = SHAPE_CURSOR;
2437
2438 return &entry;
2439}
2440#endif
2441
Bram Moolenaard317b382018-02-08 22:33:31 +01002442 static void
2443may_output_cursor_props(void)
2444{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002445 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002446 || last_set_cursor_shape != desired_cursor_shape
2447 || last_set_cursor_blink != desired_cursor_blink)
2448 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002449 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002450 last_set_cursor_shape = desired_cursor_shape;
2451 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002452 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002453 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002454 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002455 ui_cursor_shape_forced(TRUE);
2456 else
2457 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2458 }
2459}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002460
Bram Moolenaard317b382018-02-08 22:33:31 +01002461/*
2462 * Set the cursor color and shape, if not last set to these.
2463 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002464 static void
2465may_set_cursor_props(term_T *term)
2466{
2467#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002468 // For the GUI the cursor properties are obtained with
2469 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002470 if (gui.in_use)
2471 return;
2472#endif
2473 if (in_terminal_loop == term)
2474 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002475 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002476 desired_cursor_shape = term->tl_cursor_shape;
2477 desired_cursor_blink = term->tl_cursor_blink;
2478 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002479 }
2480}
2481
Bram Moolenaard317b382018-02-08 22:33:31 +01002482/*
2483 * Reset the desired cursor properties and restore them when needed.
2484 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002485 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002486prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002487{
2488#ifdef FEAT_GUI
2489 if (gui.in_use)
2490 return;
2491#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002492 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002493 desired_cursor_shape = -1;
2494 desired_cursor_blink = -1;
2495 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002496}
2497
2498/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002499 * Returns TRUE if the current window contains a terminal and we are sending
2500 * keys to the job.
2501 * If "check_job_status" is TRUE update the job status.
2502 */
2503 static int
2504term_use_loop_check(int check_job_status)
2505{
2506 term_T *term = curbuf->b_term;
2507
2508 return term != NULL
2509 && !term->tl_normal_mode
2510 && term->tl_vterm != NULL
2511 && term_job_running_check(term, check_job_status);
2512}
2513
2514/*
2515 * Returns TRUE if the current window contains a terminal and we are sending
2516 * keys to the job.
2517 */
2518 int
2519term_use_loop(void)
2520{
2521 return term_use_loop_check(FALSE);
2522}
2523
2524/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002525 * Called when entering a window with the mouse. If this is a terminal window
2526 * we may want to change state.
2527 */
2528 void
2529term_win_entered()
2530{
2531 term_T *term = curbuf->b_term;
2532
2533 if (term != NULL)
2534 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002535 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002536 {
2537 reset_VIsual_and_resel();
Bram Moolenaar24959102022-05-07 20:01:16 +01002538 if (State & MODE_INSERT)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002539 stop_insert_mode = TRUE;
2540 }
2541 mouse_was_outside = FALSE;
2542 enter_mouse_col = mouse_col;
2543 enter_mouse_row = mouse_row;
2544 }
2545}
2546
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002547 void
2548term_focus_change(int in_focus)
2549{
2550 term_T *term = curbuf->b_term;
2551
2552 if (term != NULL && term->tl_vterm != NULL)
2553 {
2554 VTermState *state = vterm_obtain_state(term->tl_vterm);
2555
2556 if (in_focus)
2557 vterm_state_focus_in(state);
2558 else
2559 vterm_state_focus_out(state);
2560 term_forward_output(term);
2561 }
2562}
2563
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002564/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002565 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2566 * Return the Ctrl-key value in that case.
2567 */
2568 static int
2569raw_c_to_ctrl(int c)
2570{
2571 if ((mod_mask & MOD_MASK_CTRL)
2572 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2573 return c & 0x1f;
2574 return c;
2575}
2576
2577/*
2578 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2579 * May set "mod_mask".
2580 */
2581 static int
2582ctrl_to_raw_c(int c)
2583{
2584 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2585 {
2586 mod_mask |= MOD_MASK_CTRL;
2587 return c + '@';
2588 }
2589 return c;
2590}
2591
2592/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 * Wait for input and send it to the job.
2594 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2595 * when there is no more typahead.
2596 * Return when the start of a CTRL-W command is typed or anything else that
2597 * should be handled as a Normal mode command.
2598 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2599 * the terminal was closed.
2600 */
2601 int
2602terminal_loop(int blocking)
2603{
2604 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002605 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002606 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002607 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002608#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002609 int tty_fd = curbuf->b_term->tl_job->jv_channel
2610 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002611#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002612 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002613
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002614 // Remember the terminal we are sending keys to. However, the terminal
2615 // might be closed while waiting for a character, e.g. typing "exit" in a
2616 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2617 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002618 in_terminal_loop = curbuf->b_term;
2619
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002620 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002621 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002622 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002623 if (termwinkey == Ctrl_W)
2624 termwinkey = 0;
2625 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002626 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002627 may_set_cursor_props(curbuf->b_term);
2628
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002629 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002630 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002631#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002632 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002633#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002634 // TODO: skip screen update when handling a sequence of keys.
2635 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002636 while (must_redraw != 0)
2637 if (update_screen(0) == FAIL)
2638 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002639 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002640 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002641 break;
2642
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002643 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002644 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002645
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002646 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002647 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002648 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002649 // Job finished while waiting for a character. Push back the
2650 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002651 if (raw_c != K_IGNORE)
2652 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002653 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002654 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002655 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002656 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002657 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002658
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002659#ifdef UNIX
2660 /*
2661 * The shell or another program may change the tty settings. Getting
2662 * them for every typed character is a bit of overhead, but it's needed
2663 * for the first character typed, e.g. when Vim starts in a shell.
2664 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002665 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002666 {
2667 ttyinfo_T info;
2668
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002669 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002670 if (get_tty_info(tty_fd, &info) == OK)
2671 term_backspace_char = info.backspace;
2672 }
2673#endif
2674
Bram Moolenaar4f974752019-02-17 17:44:42 +01002675#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002676 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2677 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002678 if (ctrl_break_was_pressed)
2679 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2680#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002681 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2682 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002683 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002684#ifdef FEAT_GUI
2685 && !curbuf->b_term->tl_system
2686#endif
2687 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002688 {
2689 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002690 int prev_raw_c = raw_c;
2691 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002692
2693#ifdef FEAT_CMDL_INFO
2694 if (add_to_showcmd(c))
2695 out_flush();
2696#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002697 raw_c = term_vgetc();
2698 c = raw_c_to_ctrl(raw_c);
2699
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002700#ifdef FEAT_CMDL_INFO
2701 clear_showcmd();
2702#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002703 if (!term_use_loop_check(TRUE)
2704 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002705 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002706 break;
2707
2708 if (prev_c == Ctrl_BSL)
2709 {
2710 if (c == Ctrl_N)
2711 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002712 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002713 term_enter_normal_mode();
2714 ret = FAIL;
2715 goto theend;
2716 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002717 // Send both keys to the terminal, first one here, second one
2718 // below.
2719 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2720 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002721 }
2722 else if (c == Ctrl_C)
2723 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002724 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002725 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2726 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002727 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002728 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002729 // "CTRL-W .": send CTRL-W to the job
2730 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002731 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002732 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002733 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002734 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002735 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002736 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002737 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002738 else if (c == 'N')
2739 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002740 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002741 term_enter_normal_mode();
2742 ret = FAIL;
2743 goto theend;
2744 }
2745 else if (c == '"')
2746 {
2747 term_paste_register(prev_c);
2748 continue;
2749 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002750 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002751 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002752 // space for CTRL-W, modifier, multi-byte char and NUL
2753 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002754
2755 // Put the command into the typeahead buffer, when using the
2756 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2757 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002758 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002759 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002760 ret = OK;
2761 goto theend;
2762 }
2763 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002764# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002765 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002766 {
2767 WCHAR wc;
2768 char_u mb[3];
2769
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002770 mb[0] = (unsigned)raw_c >> 8;
2771 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002772 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002773 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002774 }
2775# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002776 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002777 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002778 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002779 // We are sure to come back here, don't reset the cursor color
2780 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002781 restore_cursor = FALSE;
2782
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002783 ret = OK;
2784 goto theend;
2785 }
2786 }
2787 ret = FAIL;
2788
2789theend:
2790 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002791 if (restore_cursor)
2792 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002793
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002794 // Move a snapshot of the screen contents to the buffer, so that completion
2795 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002796 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2797 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002798
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002799 return ret;
2800}
2801
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002802 static void
2803may_toggle_cursor(term_T *term)
2804{
2805 if (in_terminal_loop == term)
2806 {
2807 if (term->tl_cursor_visible)
2808 cursor_on();
2809 else
2810 cursor_off();
2811 }
2812}
2813
2814/*
2815 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002816 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002817 */
2818 static int
2819color2index(VTermColor *color, int fg, int *boldp)
2820{
2821 int red = color->red;
2822 int blue = color->blue;
2823 int green = color->green;
2824
LemonBoyb2b3acb2022-05-20 10:10:34 +01002825 *boldp = FALSE;
2826
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002827 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002828 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01002829
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002830 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002831 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01002832 // Use the color as-is if possible, give up otherwise.
2833 if (color->index < t_colors)
2834 return color->index + 1;
2835 // 8-color terminals can actually display twice as many colors by
2836 // setting the high-intensity/bold bit.
2837 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002838 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01002839 *boldp = TRUE;
2840 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002841 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01002842 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002843 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002844
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002845 if (t_colors >= 256)
2846 {
2847 if (red == blue && red == green)
2848 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002849 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002850 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002851 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2852 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2853 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002854 int i;
2855
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002856 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002857 return 17; // 00/00/00
2858 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002859 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002860 for (i = 0; i < 23; ++i)
2861 if (red < cutoff[i])
2862 return i + 233;
2863 return 256;
2864 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002865 {
2866 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2867 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002868
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002869 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002870 for (ri = 0; ri < 5; ++ri)
2871 if (red < cutoff[ri])
2872 break;
2873 for (gi = 0; gi < 5; ++gi)
2874 if (green < cutoff[gi])
2875 break;
2876 for (bi = 0; bi < 5; ++bi)
2877 if (blue < cutoff[bi])
2878 break;
2879 return 17 + ri * 36 + gi * 6 + bi;
2880 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002881 }
2882 return 0;
2883}
2884
2885/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002886 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002887 */
2888 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002889vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002890{
2891 int attr = 0;
2892
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002893 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002894 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002895 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002896 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002897 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002898 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002899 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002900 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002901 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002902 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002903 return attr;
2904}
2905
2906/*
2907 * Store Vterm attributes in "cell" from highlight flags.
2908 */
2909 static void
2910hl2vtermAttr(int attr, cellattr_T *cell)
2911{
Bram Moolenaara80faa82020-04-12 19:37:17 +02002912 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002913 if (attr & HL_BOLD)
2914 cell->attrs.bold = 1;
2915 if (attr & HL_UNDERLINE)
2916 cell->attrs.underline = 1;
2917 if (attr & HL_ITALIC)
2918 cell->attrs.italic = 1;
2919 if (attr & HL_STRIKETHROUGH)
2920 cell->attrs.strike = 1;
2921 if (attr & HL_INVERSE)
2922 cell->attrs.reverse = 1;
2923}
2924
2925/*
2926 * Convert the attributes of a vterm cell into an attribute index.
2927 */
2928 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002929cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01002930 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002931 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002932 VTermScreenCellAttrs *cellattrs,
2933 VTermColor *cellfg,
2934 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002935{
2936 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002937 VTermColor *fg = cellfg;
2938 VTermColor *bg = cellbg;
2939 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
2940 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
2941
2942 if (is_default_fg || is_default_bg)
2943 {
2944 if (wp != NULL && *wp->w_p_wcr != NUL)
2945 {
2946 if (is_default_fg)
2947 fg = &wp->w_term_wincolor.fg;
2948 if (is_default_bg)
2949 bg = &wp->w_term_wincolor.bg;
2950 }
2951 else
2952 {
2953 if (is_default_fg)
2954 fg = &term->tl_default_color.fg;
2955 if (is_default_bg)
2956 bg = &term->tl_default_color.bg;
2957 }
2958 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002959
2960#ifdef FEAT_GUI
2961 if (gui.in_use)
2962 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002963 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
2964 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
2965 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002966 }
2967 else
2968#endif
2969#ifdef FEAT_TERMGUICOLORS
2970 if (p_tgc)
2971 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002972 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
2973 ? INVALCOLOR
2974 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
2975 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
2976 ? INVALCOLOR
2977 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
2978 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002979 }
2980 else
2981#endif
2982 {
2983 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002984 int ctermfg = color2index(fg, TRUE, &bold);
2985 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002986
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002987 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002988 if (bold == TRUE)
2989 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002990
2991 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002992 }
2993 return 0;
2994}
2995
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002996 static void
2997set_dirty_snapshot(term_T *term)
2998{
2999 term->tl_dirty_snapshot = TRUE;
3000#ifdef FEAT_TIMERS
3001 if (!term->tl_normal_mode)
3002 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003003 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003004 profile_setlimit(100L, &term->tl_timer_due);
3005 term->tl_timer_set = TRUE;
3006 }
3007#endif
3008}
3009
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003010 static int
3011handle_damage(VTermRect rect, void *user)
3012{
3013 term_T *term = (term_T *)user;
3014
3015 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3016 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003017 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003018 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003019 return 1;
3020}
3021
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003022 static void
3023term_scroll_up(term_T *term, int start_row, int count)
3024{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003025 win_T *wp = NULL;
3026 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003027 VTermColor fg, bg;
3028 VTermScreenCellAttrs attr;
3029 int clear_attr;
3030
Bram Moolenaara80faa82020-04-12 19:37:17 +02003031 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003032
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003033 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003034 {
3035 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003036 {
3037 // Set the color to clear lines with.
3038 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3039 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003040 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003041 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003042 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003043 }
3044}
3045
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003046 static int
3047handle_moverect(VTermRect dest, VTermRect src, void *user)
3048{
3049 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003050 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003051
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003052 // Scrolling up is done much more efficiently by deleting lines instead of
3053 // redrawing the text. But avoid doing this multiple times, postpone until
3054 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003055 if (dest.start_col == src.start_col
3056 && dest.end_col == src.end_col
3057 && dest.start_row < src.start_row)
3058 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003059 if (dest.start_row == 0)
3060 term->tl_postponed_scroll += count;
3061 else
3062 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003063 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003064
3065 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3066 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003067 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003068
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003069 // Note sure if the scrolling will work correctly, let's do a complete
3070 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003071 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003072 return 1;
3073}
3074
3075 static int
3076handle_movecursor(
3077 VTermPos pos,
3078 VTermPos oldpos UNUSED,
3079 int visible,
3080 void *user)
3081{
3082 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003083 win_T *wp = NULL;
3084 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003085
3086 term->tl_cursor_pos = pos;
3087 term->tl_cursor_visible = visible;
3088
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003089 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003090 {
3091 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003092 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003093 }
3094 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003096
3097 return 1;
3098}
3099
3100 static int
3101handle_settermprop(
3102 VTermProp prop,
3103 VTermValue *value,
3104 void *user)
3105{
3106 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003107 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003108
3109 switch (prop)
3110 {
3111 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003112 if (disable_vterm_title_for_testing)
3113 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003114 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003115 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003116 if (strval == NULL)
3117 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003118 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003119 // a blank title isn't useful, make it empty, so that "running" is
3120 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003121 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003122 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003123 // Same as blank
3124 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003125 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003126 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3127 term->tl_title = NULL;
3128 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003129 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003130 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003131#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003132 else if (!enc_utf8 && enc_codepage > 0)
3133 {
3134 WCHAR *ret = NULL;
3135 int length = 0;
3136
3137 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003138 (char*)value->string.str,
3139 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003140 if (ret != NULL)
3141 {
3142 WideCharToMultiByte_alloc(enc_codepage, 0,
3143 ret, length, (char**)&term->tl_title,
3144 &length, 0, 0);
3145 vim_free(ret);
3146 }
3147 }
3148#endif
3149 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003150 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003151 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003152 strval = NULL;
3153 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003154 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003155 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003156 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003157 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003158 curwin->w_redr_status = TRUE;
3159 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003160 break;
3161
3162 case VTERM_PROP_CURSORVISIBLE:
3163 term->tl_cursor_visible = value->boolean;
3164 may_toggle_cursor(term);
3165 out_flush();
3166 break;
3167
3168 case VTERM_PROP_CURSORBLINK:
3169 term->tl_cursor_blink = value->boolean;
3170 may_set_cursor_props(term);
3171 break;
3172
3173 case VTERM_PROP_CURSORSHAPE:
3174 term->tl_cursor_shape = value->number;
3175 may_set_cursor_props(term);
3176 break;
3177
3178 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003179 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003180 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003181 if (strval == NULL)
3182 break;
3183 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003184 may_set_cursor_props(term);
3185 break;
3186
3187 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003188 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003189 term->tl_using_altscreen = value->boolean;
3190 break;
3191
3192 default:
3193 break;
3194 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003195 vim_free(strval);
3196
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003197 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003198 return 1;
3199}
3200
3201/*
3202 * The job running in the terminal resized the terminal.
3203 */
3204 static int
3205handle_resize(int rows, int cols, void *user)
3206{
3207 term_T *term = (term_T *)user;
3208 win_T *wp;
3209
3210 term->tl_rows = rows;
3211 term->tl_cols = cols;
3212 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003213 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003214 term->tl_vterm_size_changed = FALSE;
3215 else
3216 {
3217 FOR_ALL_WINDOWS(wp)
3218 {
3219 if (wp->w_buffer == term->tl_buffer)
3220 {
3221 win_setheight_win(rows, wp);
3222 win_setwidth_win(cols, wp);
3223 }
3224 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003225 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003226 }
3227 return 1;
3228}
3229
3230/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003231 * If the number of lines that are stored goes over 'termscrollback' then
3232 * delete the first 10%.
3233 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3234 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003235 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003236 static void
3237limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003238{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003239 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003240 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003241 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003242 int i;
3243
3244 curbuf = term->tl_buffer;
3245 for (i = 0; i < todo; ++i)
3246 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003247 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3248 if (update_buffer)
Bram Moolenaarca70c072020-05-30 20:30:46 +02003249 ml_delete(1);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003250 }
3251 curbuf = curwin->w_buffer;
3252
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003253 gap->ga_len -= todo;
3254 mch_memmove(gap->ga_data,
3255 (sb_line_T *)gap->ga_data + todo,
3256 sizeof(sb_line_T) * gap->ga_len);
3257 if (update_buffer)
3258 term->tl_scrollback_scrolled -= todo;
3259 }
3260}
3261
3262/*
3263 * Handle a line that is pushed off the top of the screen.
3264 */
3265 static int
3266handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3267{
3268 term_T *term = (term_T *)user;
3269 garray_T *gap;
3270 int update_buffer;
3271
3272 if (term->tl_normal_mode)
3273 {
3274 // In Terminal-Normal mode the user interacts with the buffer, thus we
3275 // must not change it. Postpone adding the scrollback lines.
3276 gap = &term->tl_scrollback_postponed;
3277 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003278 }
3279 else
3280 {
3281 // First remove the lines that were appended before, the pushed line
3282 // goes above it.
3283 cleanup_scrollback(term);
3284 gap = &term->tl_scrollback;
3285 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003286 }
3287
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003288 limit_scrollback(term, gap, update_buffer);
3289
3290 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003291 {
3292 cellattr_T *p = NULL;
3293 int len = 0;
3294 int i;
3295 int c;
3296 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003297 int text_len;
3298 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003299 sb_line_T *line;
3300 garray_T ga;
3301 cellattr_T fill_attr = term->tl_default_color;
3302
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003303 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003304 for (i = 0; i < cols; ++i)
3305 if (cells[i].chars[0] != 0)
3306 len = i + 1;
3307 else
3308 cell2cellattr(&cells[i], &fill_attr);
3309
3310 ga_init2(&ga, 1, 100);
3311 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003312 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003313 if (p != NULL)
3314 {
3315 for (col = 0; col < len; col += cells[col].width)
3316 {
3317 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3318 {
3319 ga.ga_len = 0;
3320 break;
3321 }
3322 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3323 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3324 (char_u *)ga.ga_data + ga.ga_len);
3325 cell2cellattr(&cells[col], &p[col]);
3326 }
3327 }
3328 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003329 {
3330 if (update_buffer)
3331 text = (char_u *)"";
3332 else
3333 text = vim_strsave((char_u *)"");
3334 text_len = 0;
3335 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003336 else
3337 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003338 text = ga.ga_data;
3339 text_len = ga.ga_len;
3340 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003341 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003342 if (update_buffer)
3343 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003344
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003345 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003346 line->sb_cols = len;
3347 line->sb_cells = p;
3348 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003349 if (update_buffer)
3350 {
3351 line->sb_text = NULL;
3352 ++term->tl_scrollback_scrolled;
3353 ga_clear(&ga); // free the text
3354 }
3355 else
3356 {
3357 line->sb_text = text;
3358 ga_init(&ga); // text is kept in tl_scrollback_postponed
3359 }
3360 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003361 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003362 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003363}
3364
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003365/*
3366 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3367 * received and stored in tl_scrollback_postponed.
3368 */
3369 static void
3370handle_postponed_scrollback(term_T *term)
3371{
3372 int i;
3373
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003374 if (term->tl_scrollback_postponed.ga_len == 0)
3375 return;
3376 ch_log(NULL, "Moving postponed scrollback to scrollback");
3377
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003378 // First remove the lines that were appended before, the pushed lines go
3379 // above it.
3380 cleanup_scrollback(term);
3381
3382 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3383 {
3384 char_u *text;
3385 sb_line_T *pp_line;
3386 sb_line_T *line;
3387
3388 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3389 break;
3390 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3391
3392 text = pp_line->sb_text;
3393 if (text == NULL)
3394 text = (char_u *)"";
3395 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3396 vim_free(pp_line->sb_text);
3397
3398 line = (sb_line_T *)term->tl_scrollback.ga_data
3399 + term->tl_scrollback.ga_len;
3400 line->sb_cols = pp_line->sb_cols;
3401 line->sb_cells = pp_line->sb_cells;
3402 line->sb_fill_attr = pp_line->sb_fill_attr;
3403 line->sb_text = NULL;
3404 ++term->tl_scrollback_scrolled;
3405 ++term->tl_scrollback.ga_len;
3406 }
3407
3408 ga_clear(&term->tl_scrollback_postponed);
3409 limit_scrollback(term, &term->tl_scrollback, TRUE);
3410}
3411
LemonBoy77771d32022-04-13 11:47:25 +01003412/*
3413 * Called when the terminal wants to ring the system bell.
3414 */
3415 static int
3416handle_bell(void *user UNUSED)
3417{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003418 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003419 return 0;
3420}
3421
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003422static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003423 handle_damage, // damage
3424 handle_moverect, // moverect
3425 handle_movecursor, // movecursor
3426 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003427 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003428 handle_resize, // resize
3429 handle_pushline, // sb_pushline
3430 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003431};
3432
3433/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003434 * Do the work after the channel of a terminal was closed.
3435 * Must be called only when updating_screen is FALSE.
3436 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3437 */
3438 static int
3439term_after_channel_closed(term_T *term)
3440{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003441 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003442 if (!term->tl_normal_mode)
3443 {
3444 int fnum = term->tl_buffer->b_fnum;
3445
3446 cleanup_vterm(term);
3447
3448 if (term->tl_finish == TL_FINISH_CLOSE)
3449 {
3450 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003451 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003452#ifdef FEAT_PROP_POPUP
3453 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003454
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003455 // If this was a terminal in a popup window, go back to the
3456 // previous window.
3457 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3458 {
3459 pwin = curwin;
3460 if (win_valid(prevwin))
3461 win_enter(prevwin, FALSE);
3462 }
3463 else
3464#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003465 // If this is the last normal window: exit Vim.
3466 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3467 {
3468 exarg_T ea;
3469
Bram Moolenaara80faa82020-04-12 19:37:17 +02003470 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003471 ex_quit(&ea);
3472 return TRUE;
3473 }
3474
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003475 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003476 ch_log(NULL, "terminal job finished, closing window");
3477 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003478 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003479 if (curwin == aucmd_win)
3480 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003481 if (do_set_w_closing)
3482 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003483 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003484 if (do_set_w_closing)
3485 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003486 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003487#ifdef FEAT_PROP_POPUP
3488 if (pwin != NULL)
3489 popup_close_with_retval(pwin, 0);
3490#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003491 return TRUE;
3492 }
3493 if (term->tl_finish == TL_FINISH_OPEN
3494 && term->tl_buffer->b_nwindows == 0)
3495 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003496 char *cmd = term->tl_opencmd == NULL
3497 ? "botright sbuf %d"
3498 : (char *)term->tl_opencmd;
3499 size_t len = strlen(cmd) + 50;
3500 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003501
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003502 if (buf != NULL)
3503 {
3504 ch_log(NULL, "terminal job finished, opening window");
3505 vim_snprintf(buf, len, cmd, fnum);
3506 do_cmdline_cmd((char_u *)buf);
3507 vim_free(buf);
3508 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003509 }
3510 else
3511 ch_log(NULL, "terminal job finished");
3512 }
3513
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003514 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003515 return FALSE;
3516}
3517
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003518#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3519/*
3520 * If the current window is a terminal in a popup window and the job has
3521 * finished, close the popup window and to back to the previous window.
3522 * Otherwise return FAIL.
3523 */
3524 int
3525may_close_term_popup(void)
3526{
3527 if (popup_is_popup(curwin) && curbuf->b_term != NULL
Bram Moolenaar9e636b92022-05-29 22:37:05 +01003528 && !term_job_running_not_none(curbuf->b_term))
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003529 {
3530 win_T *pwin = curwin;
3531
3532 if (win_valid(prevwin))
3533 win_enter(prevwin, FALSE);
3534 popup_close_with_retval(pwin, 0);
3535 return OK;
3536 }
3537 return FAIL;
3538}
3539#endif
3540
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003541/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003542 * Called when a channel is going to be closed, before invoking the close
3543 * callback.
3544 */
3545 void
3546term_channel_closing(channel_T *ch)
3547{
3548 term_T *term;
3549
3550 for (term = first_term; term != NULL; term = term->tl_next)
3551 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3552 term->tl_channel_closing = TRUE;
3553}
3554
3555/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003556 * Called when a channel has been closed.
3557 * If this was a channel for a terminal window then finish it up.
3558 */
3559 void
3560term_channel_closed(channel_T *ch)
3561{
3562 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003563 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003564 int did_one = FALSE;
3565
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003566 for (term = first_term; term != NULL; term = next_term)
3567 {
3568 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003569 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003570 {
3571 term->tl_channel_closed = TRUE;
3572 did_one = TRUE;
3573
Bram Moolenaard23a8232018-02-10 18:45:26 +01003574 VIM_CLEAR(term->tl_title);
3575 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003576#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003577 if (term->tl_out_fd != NULL)
3578 {
3579 fclose(term->tl_out_fd);
3580 term->tl_out_fd = NULL;
3581 }
3582#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003583
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003584 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003585 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003586 // Cannot open or close windows now. Can happen when
3587 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003588 term->tl_channel_recently_closed = TRUE;
3589 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003590 }
3591
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003592 if (term_after_channel_closed(term))
3593 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003594 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003595 }
3596
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003597 if (did_one)
3598 {
3599 redraw_statuslines();
3600
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003601 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003602 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003603 typebuf_was_filled = TRUE;
3604
3605 term = curbuf->b_term;
3606 if (term != NULL)
3607 {
3608 if (term->tl_job == ch->ch_job)
3609 maketitle();
3610 update_cursor(term, term->tl_cursor_visible);
3611 }
3612 }
3613}
3614
3615/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003616 * To be called after resetting updating_screen: handle any terminal where the
3617 * channel was closed.
3618 */
3619 void
3620term_check_channel_closed_recently()
3621{
3622 term_T *term;
3623 term_T *next_term;
3624
3625 for (term = first_term; term != NULL; term = next_term)
3626 {
3627 next_term = term->tl_next;
3628 if (term->tl_channel_recently_closed)
3629 {
3630 term->tl_channel_recently_closed = FALSE;
3631 if (term_after_channel_closed(term))
3632 // start over, the list may have changed
3633 next_term = first_term;
3634 }
3635 }
3636}
3637
3638/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003639 * Fill one screen line from a line of the terminal.
3640 * Advances "pos" to past the last column.
3641 */
3642 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003643term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003644 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003645 win_T *wp,
3646 VTermScreen *screen,
3647 VTermPos *pos,
3648 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003649{
3650 int off = screen_get_current_line_off();
3651
3652 for (pos->col = 0; pos->col < max_col; )
3653 {
3654 VTermScreenCell cell;
3655 int c;
3656
3657 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003658 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003659
3660 c = cell.chars[0];
3661 if (c == NUL)
3662 {
3663 ScreenLines[off] = ' ';
3664 if (enc_utf8)
3665 ScreenLinesUC[off] = NUL;
3666 }
3667 else
3668 {
3669 if (enc_utf8)
3670 {
3671 int i;
3672
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003673 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003674 for (i = 0; i < Screen_mco
3675 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3676 {
3677 ScreenLinesC[i][off] = cell.chars[i + 1];
3678 if (cell.chars[i + 1] == 0)
3679 break;
3680 }
3681 if (c >= 0x80 || (Screen_mco > 0
3682 && ScreenLinesC[0][off] != 0))
3683 {
3684 ScreenLines[off] = ' ';
3685 ScreenLinesUC[off] = c;
3686 }
3687 else
3688 {
3689 ScreenLines[off] = c;
3690 ScreenLinesUC[off] = NUL;
3691 }
3692 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003693#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003694 else if (has_mbyte && c >= 0x80)
3695 {
3696 char_u mb[MB_MAXBYTES+1];
3697 WCHAR wc = c;
3698
3699 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3700 (char*)mb, 2, 0, 0) > 1)
3701 {
3702 ScreenLines[off] = mb[0];
3703 ScreenLines[off + 1] = mb[1];
3704 cell.width = mb_ptr2cells(mb);
3705 }
3706 else
3707 ScreenLines[off] = c;
3708 }
3709#endif
3710 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003711 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003712 ScreenLines[off] = c;
3713 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003714 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3715 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003716
3717 ++pos->col;
3718 ++off;
3719 if (cell.width == 2)
3720 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003721 // don't set the second byte to NUL for a DBCS encoding, it
3722 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003723 if (enc_utf8)
3724 {
3725 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003726 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003727 }
3728 else if (!has_mbyte)
3729 {
3730 // Can't show a double-width character with a single-byte
3731 // 'encoding', just use a space.
3732 ScreenLines[off] = ' ';
3733 ScreenAttrs[off] = ScreenAttrs[off - 1];
3734 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003735
3736 ++pos->col;
3737 ++off;
3738 }
3739 }
3740}
3741
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003742#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003743 static void
3744update_system_term(term_T *term)
3745{
3746 VTermPos pos;
3747 VTermScreen *screen;
3748
3749 if (term->tl_vterm == NULL)
3750 return;
3751 screen = vterm_obtain_screen(term->tl_vterm);
3752
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003753 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003754 while (term->tl_toprow > 0
3755 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3756 {
3757 int save_p_more = p_more;
3758
3759 p_more = FALSE;
3760 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003761 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003762 p_more = save_p_more;
3763 --term->tl_toprow;
3764 }
3765
3766 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3767 && pos.row < Rows; ++pos.row)
3768 {
3769 if (pos.row < term->tl_rows)
3770 {
3771 int max_col = MIN(Columns, term->tl_cols);
3772
Bram Moolenaar83d47902020-03-26 20:34:00 +01003773 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003774 }
3775 else
3776 pos.col = 0;
3777
Bram Moolenaar510f0372022-07-04 17:46:22 +01003778 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003779 }
3780
3781 term->tl_dirty_row_start = MAX_ROW;
3782 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003783}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003784#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003785
3786/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003787 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3788 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003789 * Terminal-Normal mode.
3790 */
3791 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003792term_do_update_window(win_T *wp)
3793{
3794 term_T *term = wp->w_buffer->b_term;
3795
3796 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3797}
3798
3799/*
3800 * Called to update a window that contains an active terminal.
3801 */
3802 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003803term_update_window(win_T *wp)
3804{
3805 term_T *term = wp->w_buffer->b_term;
3806 VTerm *vterm;
3807 VTermScreen *screen;
3808 VTermState *state;
3809 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003810 int rows, cols;
3811 int newrows, newcols;
3812 int minsize;
3813 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003814
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003815 vterm = term->tl_vterm;
3816 screen = vterm_obtain_screen(vterm);
3817 state = vterm_obtain_state(vterm);
3818
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003819 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
3820 // With UPD_SOME_VALID only redraw what was marked dirty.
3821 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003822 {
3823 term->tl_dirty_row_start = 0;
3824 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003825
3826 if (term->tl_postponed_scroll > 0
3827 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003828 // Scrolling is usually faster than redrawing, when there are only
3829 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003830 term_scroll_up(term, 0, term->tl_postponed_scroll);
3831 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003832 }
3833
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003834 /*
3835 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003836 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003837 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003838 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003839
Bram Moolenaar498c2562018-04-15 23:45:15 +02003840 newrows = 99999;
3841 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003842 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003843 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003844 // Always use curwin, it may be a popup window.
3845 win_T *wwp = twp == NULL ? curwin : twp;
3846
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003847 // When more than one window shows the same terminal, use the
3848 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003849 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003850 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003851 newrows = MIN(newrows, wwp->w_height);
3852 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003853 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003854 if (twp == NULL)
3855 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003856 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003857 if (newrows == 99999 || newcols == 99999)
3858 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003859 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3860 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3861
Bram Moolenaareba13e42021-02-23 17:47:23 +01003862 // If no cell is visible there is no point in resizing. Also, vterm can't
3863 // handle a zero height.
3864 if (newrows == 0 || newcols == 0)
3865 return;
3866
Bram Moolenaar498c2562018-04-15 23:45:15 +02003867 if (term->tl_rows != newrows || term->tl_cols != newcols)
3868 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003869 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003870 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003871 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003872 newrows);
3873 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003874
3875 // Updating the terminal size will cause the snapshot to be cleared.
3876 // When not in terminal_loop() we need to restore it.
3877 if (term != in_terminal_loop)
3878 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003879 }
3880
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003881 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003882 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003883 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003884
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003885 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3886 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003887 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003888 if (pos.row < term->tl_rows)
3889 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003890 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003891
Bram Moolenaar83d47902020-03-26 20:34:00 +01003892 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003893 }
3894 else
3895 pos.col = 0;
3896
Bram Moolenaar510f0372022-07-04 17:46:22 +01003897 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01003898#ifdef FEAT_MENU
3899 + winbar_height(wp)
3900#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003901 , wp->w_wincol, pos.col, wp->w_width,
3902#ifdef FEAT_PROP_POPUP
3903 popup_is_popup(wp) ? SLF_POPUP :
3904#endif
3905 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003906 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00003907}
3908
3909/*
3910 * Called after updating all windows: may reset dirty rows.
3911 */
3912 void
3913term_did_update_window(win_T *wp)
3914{
3915 term_T *term = wp->w_buffer->b_term;
3916
3917 if (term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode
3918 && wp->w_redr_type == 0)
3919 {
3920 term->tl_dirty_row_start = MAX_ROW;
3921 term->tl_dirty_row_end = 0;
3922 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003923}
3924
3925/*
3926 * Return TRUE if "wp" is a terminal window where the job has finished.
3927 */
3928 int
3929term_is_finished(buf_T *buf)
3930{
3931 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3932}
3933
3934/*
3935 * Return TRUE if "wp" is a terminal window where the job has finished or we
3936 * are in Terminal-Normal mode, thus we show the buffer contents.
3937 */
3938 int
3939term_show_buffer(buf_T *buf)
3940{
3941 term_T *term = buf->b_term;
3942
3943 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3944}
3945
3946/*
3947 * The current buffer is going to be changed. If there is terminal
3948 * highlighting remove it now.
3949 */
3950 void
3951term_change_in_curbuf(void)
3952{
3953 term_T *term = curbuf->b_term;
3954
3955 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3956 {
3957 free_scrollback(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003958 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003959
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003960 // The buffer is now like a normal buffer, it cannot be easily
3961 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003962 set_string_option_direct((char_u *)"buftype", -1,
3963 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3964 }
3965}
3966
3967/*
3968 * Get the screen attribute for a position in the buffer.
3969 * Use a negative "col" to get the filler background color.
3970 */
3971 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003972term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003973{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003974 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003975 term_T *term = buf->b_term;
3976 sb_line_T *line;
3977 cellattr_T *cellattr;
3978
3979 if (lnum > term->tl_scrollback.ga_len)
3980 cellattr = &term->tl_default_color;
3981 else
3982 {
3983 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3984 if (col < 0 || col >= line->sb_cols)
3985 cellattr = &line->sb_fill_attr;
3986 else
3987 cellattr = line->sb_cells + col;
3988 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003989 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003990}
3991
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003992/*
3993 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003994 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003995 */
3996 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003997cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003998{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003999 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4000 if (rgb->index == 0)
4001 rgb->type = VTERM_COLOR_RGB;
4002 else
4003 {
4004 rgb->type = VTERM_COLOR_INDEXED;
4005 --rgb->index;
4006 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004007}
4008
4009/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004010 * Initialize vterm color from the synID.
4011 * Returns TRUE if color is set to "fg" and "bg".
4012 * Otherwise returns FALSE.
4013 */
4014 static int
4015get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4016{
4017#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4018 // Use the actual color for the GUI and when 'termguicolors' is set.
4019 if (0
4020# ifdef FEAT_GUI
4021 || gui.in_use
4022# endif
4023# ifdef FEAT_TERMGUICOLORS
4024 || p_tgc
4025# ifdef FEAT_VTP
4026 // Finally get INVALCOLOR on this execution path
4027 || (!p_tgc && t_colors >= 256)
4028# endif
4029# endif
4030 )
4031 {
4032 guicolor_T fg_rgb = INVALCOLOR;
4033 guicolor_T bg_rgb = INVALCOLOR;
4034
4035 if (id > 0)
4036 syn_id2colors(id, &fg_rgb, &bg_rgb);
4037
4038 if (fg_rgb != INVALCOLOR)
4039 {
4040 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4041 fg->red = (unsigned)(rgb >> 16);
4042 fg->green = (unsigned)(rgb >> 8) & 255;
4043 fg->blue = (unsigned)rgb & 255;
4044 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4045 }
4046 else
4047 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4048
4049 if (bg_rgb != INVALCOLOR)
4050 {
4051 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4052 bg->red = (unsigned)(rgb >> 16);
4053 bg->green = (unsigned)(rgb >> 8) & 255;
4054 bg->blue = (unsigned)rgb & 255;
4055 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4056 }
4057 else
4058 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4059
4060 return TRUE;
4061 }
4062 else
4063#endif
4064 if (t_colors >= 16)
4065 {
4066 int cterm_fg = -1;
4067 int cterm_bg = -1;
4068
4069 if (id > 0)
4070 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4071
4072 if (cterm_fg >= 0)
4073 {
4074 cterm_color2vterm(cterm_fg, fg);
4075 fg->type |= VTERM_COLOR_DEFAULT_FG;
4076 }
4077 else
4078 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4079
4080 if (cterm_bg >= 0)
4081 {
4082 cterm_color2vterm(cterm_bg, bg);
4083 bg->type |= VTERM_COLOR_DEFAULT_BG;
4084 }
4085 else
4086 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4087
4088 return TRUE;
4089 }
4090
4091 return FALSE;
4092}
4093
4094 void
4095term_reset_wincolor(win_T *wp)
4096{
4097 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4098 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4099}
4100
4101/*
4102 * Cache the color of 'wincolor'.
4103 */
4104 void
4105term_update_wincolor(win_T *wp)
4106{
4107 int id = 0;
4108
4109 if (*wp->w_p_wcr != NUL)
4110 id = syn_name2id(wp->w_p_wcr);
4111 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4112 &wp->w_term_wincolor.bg))
4113 term_reset_wincolor(wp);
4114}
4115
4116/*
4117 * Called when option 'termguicolors' was set,
4118 * or when any highlight is changed.
4119 */
4120 void
4121term_update_wincolor_all()
4122{
4123 win_T *wp = NULL;
4124 int did_curwin = FALSE;
4125
4126 while (for_all_windows_and_curwin(&wp, &did_curwin))
4127 term_update_wincolor(wp);
4128}
4129
4130/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004131 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004132 */
4133 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004134init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004135{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004136 VTermColor *fg, *bg;
4137 int fgval, bgval;
4138 int id;
4139
Bram Moolenaara80faa82020-04-12 19:37:17 +02004140 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004141 term->tl_default_color.width = 1;
4142 fg = &term->tl_default_color.fg;
4143 bg = &term->tl_default_color.bg;
4144
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004145 // Vterm uses a default black background. Set it to white when
4146 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004147 if (*p_bg == 'l')
4148 {
4149 fgval = 0;
4150 bgval = 255;
4151 }
4152 else
4153 {
4154 fgval = 255;
4155 bgval = 0;
4156 }
4157 fg->red = fg->green = fg->blue = fgval;
4158 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004159 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4160 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004161
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004162 // The highlight group overrules the defaults.
4163 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004164
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004165 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004166 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004167#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004168 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004169#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004170
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004171 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004172 if (cterm_normal_fg_color > 0)
4173 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004174 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004175# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4176# ifdef VIMDLL
4177 if (!gui.in_use)
4178# endif
4179 {
4180 tmp = fg->red;
4181 fg->red = fg->blue;
4182 fg->blue = tmp;
4183 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004184# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004185 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004186# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004187 else
4188 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004189# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004190
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004191 if (cterm_normal_bg_color > 0)
4192 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004193 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004194# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4195# ifdef VIMDLL
4196 if (!gui.in_use)
4197# endif
4198 {
4199 tmp = fg->red;
4200 fg->red = fg->blue;
4201 fg->blue = tmp;
4202 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004203# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004204 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004205# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004206 else
4207 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004208# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004209 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004210}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004211
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004212#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4213/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004214 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4215 * "ansi_colors" argument in term_start()) shall be applied.
4216 */
4217 static int
4218term_use_palette()
4219{
4220 if (0
4221#ifdef FEAT_GUI
4222 || gui.in_use
4223#endif
4224#ifdef FEAT_TERMGUICOLORS
4225 || p_tgc
4226#endif
4227 )
4228 return TRUE;
4229 return FALSE;
4230}
4231
4232/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004233 * Set the 16 ANSI colors from array of RGB values
4234 */
4235 static void
4236set_vterm_palette(VTerm *vterm, long_u *rgb)
4237{
4238 int index = 0;
4239 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004240
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004241 for (; index < 16; index++)
4242 {
4243 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004244
Millyb771b6b2021-11-23 12:07:25 +00004245 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004246 color.red = (unsigned)(rgb[index] >> 16);
4247 color.green = (unsigned)(rgb[index] >> 8) & 255;
4248 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004249 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004250 vterm_state_set_palette_color(state, index, &color);
4251 }
4252}
4253
4254/*
4255 * Set the ANSI color palette from a list of colors
4256 */
4257 static int
4258set_ansi_colors_list(VTerm *vterm, list_T *list)
4259{
4260 int n = 0;
4261 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004262 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004263
Bram Moolenaarb0992022020-01-30 14:55:42 +01004264 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004265 {
4266 char_u *color_name;
4267 guicolor_T guicolor;
4268
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004269 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004270 if (color_name == NULL)
4271 return FAIL;
4272
4273 guicolor = GUI_GET_COLOR(color_name);
4274 if (guicolor == INVALCOLOR)
4275 return FAIL;
4276
4277 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4278 }
4279
4280 if (n != 16 || li != NULL)
4281 return FAIL;
4282
4283 set_vterm_palette(vterm, rgb);
4284
4285 return OK;
4286}
4287
4288/*
4289 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4290 */
4291 static void
4292init_vterm_ansi_colors(VTerm *vterm)
4293{
4294 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4295
LemonBoyb2b3acb2022-05-20 10:10:34 +01004296 if (var == NULL)
4297 return;
4298
4299 if (var->di_tv.v_type != VAR_LIST
4300 || var->di_tv.vval.v_list == NULL
4301 || var->di_tv.vval.v_list->lv_first == &range_list_item
4302 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004303 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004304}
4305#endif
4306
Bram Moolenaar52acb112018-03-18 19:20:22 +01004307/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004308 * Handles a "drop" command from the job in the terminal.
4309 * "item" is the file name, "item->li_next" may have options.
4310 */
4311 static void
4312handle_drop_command(listitem_T *item)
4313{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004314 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004315 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004316 int bufnr;
4317 win_T *wp;
4318 tabpage_T *tp;
4319 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004320 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004321
4322 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4323 FOR_ALL_TAB_WINDOWS(tp, wp)
4324 {
4325 if (wp->w_buffer->b_fnum == bufnr)
4326 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004327 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004328 goto_tabpage_win(tp, wp);
4329 return;
4330 }
4331 }
4332
Bram Moolenaara80faa82020-04-12 19:37:17 +02004333 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004334
4335 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4336 && opt_item->li_tv.vval.v_dict != NULL)
4337 {
4338 dict_T *dict = opt_item->li_tv.vval.v_dict;
4339 char_u *p;
4340
Bram Moolenaard61efa52022-07-23 09:52:04 +01004341 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004342 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004343 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004344 if (p != NULL)
4345 {
4346 if (check_ff_value(p) == FAIL)
4347 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4348 else
4349 ea.force_ff = *p;
4350 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004351 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004352 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004353 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004354 if (p != NULL)
4355 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004356 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004357 if (ea.cmd != NULL)
4358 {
4359 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4360 ea.force_enc = 11;
4361 tofree = ea.cmd;
4362 }
4363 }
4364
Bram Moolenaard61efa52022-07-23 09:52:04 +01004365 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004366 if (p != NULL)
4367 get_bad_opt(p, &ea);
4368
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004369 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004370 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004371 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004372 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004373 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004374 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004375 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004376 ea.force_bin = FORCE_NOBIN;
4377 }
4378
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004379 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004380 if (ea.cmd == NULL)
4381 ea.cmd = (char_u *)"split";
4382 ea.arg = fname;
4383 ea.cmdidx = CMD_split;
4384 ex_splitview(&ea);
4385
4386 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004387}
4388
4389/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004390 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4391 */
4392 static int
4393is_permitted_term_api(char_u *func, char_u *pat)
4394{
4395 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4396}
4397
4398/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004399 * Handles a function call from the job running in a terminal.
4400 * "item" is the function name, "item->li_next" has the arguments.
4401 */
4402 static void
4403handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4404{
4405 char_u *func;
4406 typval_T argvars[2];
4407 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004408 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004409
4410 if (item->li_next == NULL)
4411 {
4412 ch_log(channel, "Missing function arguments for call");
4413 return;
4414 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004415 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004416
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004417 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004418 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004419 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004420 return;
4421 }
4422
4423 argvars[0].v_type = VAR_NUMBER;
4424 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4425 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004426 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004427 funcexe.fe_firstline = 1L;
4428 funcexe.fe_lastline = 1L;
4429 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004430 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004431 {
4432 clear_tv(&rettv);
4433 ch_log(channel, "Function %s called", func);
4434 }
4435 else
4436 ch_log(channel, "Calling function %s failed", func);
4437}
4438
4439/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004440 * URL decoding (also know as Percent-encoding).
4441 *
4442 * Note this function currently is only used for decoding shell's
4443 * OSC 7 escape sequence which we can assume all bytes are valid
4444 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4445 * encoding bytes like 0xfe, 0xff.
4446 */
4447 static size_t
4448url_decode(const char *src, const size_t len, char_u *dst)
4449{
4450 size_t i = 0, j = 0;
4451
4452 while (i < len)
4453 {
4454 if (src[i] == '%' && i + 2 < len)
4455 {
4456 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4457 j++;
4458 i += 3;
4459 }
4460 else
4461 {
4462 dst[j] = src[i];
4463 i++;
4464 j++;
4465 }
4466 }
4467 dst[j] = '\0';
4468 return j;
4469}
4470
4471/*
4472 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4473 *
4474 * The OSC 7 sequence has the format of
4475 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4476 * and what VTerm provides via VTermStringFragment is
4477 * "file://HOSTNAME/CURRENT/DIR"
4478 */
4479 static void
4480sync_shell_dir(VTermStringFragment *frag)
4481{
4482 int offset = 7; // len of "file://" is 7
4483 char *pos = (char *)frag->str + offset;
4484 char_u *new_dir;
4485
4486 // remove HOSTNAME to get PWD
Bram Moolenaar918b0892021-05-08 20:09:24 +02004487 while (*pos != '/' && offset < (int)frag->len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004488 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004489 offset += 1;
4490 pos += 1;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004491 }
4492
Bram Moolenaar918b0892021-05-08 20:09:24 +02004493 if (offset >= (int)frag->len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004494 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004495 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004496 frag->str);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004497 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004498 }
4499
4500 new_dir = alloc(frag->len - offset + 1);
4501 url_decode(pos, frag->len-offset, new_dir);
4502 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4503 vim_free(new_dir);
4504}
4505
4506/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004507 * Called by libvterm when it cannot recognize an OSC sequence.
4508 * We recognize a terminal API command.
4509 */
4510 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004511parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004512{
4513 term_T *term = (term_T *)user;
4514 js_read_T reader;
4515 typval_T tv;
4516 channel_T *channel = term->tl_job == NULL ? NULL
4517 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004518 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004519
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004520 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
4521 if (p_asd && command == 7)
4522 {
4523 sync_shell_dir(&frag);
4524 return 1;
4525 }
4526
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004527 if (command != 51)
4528 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004529
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004530 // Concatenate what was received until the final piece is found.
4531 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4532 {
4533 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004534 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004535 }
4536 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004537 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004538 if (!frag.final)
4539 return 1;
4540
4541 ((char *)gap->ga_data)[gap->ga_len] = 0;
4542 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004543 reader.js_fill = NULL;
4544 reader.js_used = 0;
4545 if (json_decode(&reader, &tv, 0) == OK
4546 && tv.v_type == VAR_LIST
4547 && tv.vval.v_list != NULL)
4548 {
4549 listitem_T *item = tv.vval.v_list->lv_first;
4550
4551 if (item == NULL)
4552 ch_log(channel, "Missing command");
4553 else
4554 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004555 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004556
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004557 // Make sure an invoked command doesn't delete the buffer (and the
4558 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004559 ++term->tl_buffer->b_locked;
4560
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004561 item = item->li_next;
4562 if (item == NULL)
4563 ch_log(channel, "Missing argument for %s", cmd);
4564 else if (STRCMP(cmd, "drop") == 0)
4565 handle_drop_command(item);
4566 else if (STRCMP(cmd, "call") == 0)
4567 handle_call_command(term, channel, item);
4568 else
4569 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004570 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004571 }
4572 }
4573 else
4574 ch_log(channel, "Invalid JSON received");
4575
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004576 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004577 clear_tv(&tv);
4578 return 1;
4579}
4580
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004581/*
4582 * Called by libvterm when it cannot recognize a CSI sequence.
4583 * We recognize the window position report.
4584 */
4585 static int
4586parse_csi(
4587 const char *leader UNUSED,
4588 const long args[],
4589 int argcount,
4590 const char *intermed UNUSED,
4591 char command,
4592 void *user)
4593{
4594 term_T *term = (term_T *)user;
4595 char buf[100];
4596 int len;
4597 int x = 0;
4598 int y = 0;
4599 win_T *wp;
4600
4601 // We recognize only CSI 13 t
4602 if (command != 't' || argcount != 1 || args[0] != 13)
4603 return 0; // not handled
4604
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004605 // When getting the window position is not possible or it fails it results
4606 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004607#if defined(FEAT_GUI) \
4608 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4609 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004610 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004611#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004612
4613 FOR_ALL_WINDOWS(wp)
4614 if (wp->w_buffer == term->tl_buffer)
4615 break;
4616 if (wp != NULL)
4617 {
4618#ifdef FEAT_GUI
4619 if (gui.in_use)
4620 {
4621 x += wp->w_wincol * gui.char_width;
4622 y += W_WINROW(wp) * gui.char_height;
4623 }
4624 else
4625#endif
4626 {
4627 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004628 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004629 x += wp->w_wincol * 7;
4630 y += W_WINROW(wp) * 10;
4631 }
4632 }
4633
4634 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4635 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4636 (char_u *)buf, len, NULL);
4637 return 1;
4638}
4639
Bram Moolenaard8637282020-05-20 18:41:41 +02004640static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004641 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004642 parse_csi, // csi
4643 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004644 NULL, // dcs
4645 NULL, // apc
4646 NULL, // pm
4647 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004648};
4649
4650/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004651 * Use Vim's allocation functions for vterm so profiling works.
4652 */
4653 static void *
4654vterm_malloc(size_t size, void *data UNUSED)
4655{
Bram Moolenaar88137392021-11-12 16:01:15 +00004656 // make sure that the length is not zero
4657 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004658}
4659
4660 static void
4661vterm_memfree(void *ptr, void *data UNUSED)
4662{
4663 vim_free(ptr);
4664}
4665
4666static VTermAllocatorFunctions vterm_allocator = {
4667 &vterm_malloc,
4668 &vterm_memfree
4669};
4670
4671/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004672 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004673 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004674 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004675 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004676create_vterm(term_T *term, int rows, int cols)
4677{
4678 VTerm *vterm;
4679 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004680 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004681 VTermValue value;
4682
Bram Moolenaar756ef112018-04-10 12:04:27 +02004683 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004684 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004685 if (vterm == NULL)
4686 return FAIL;
4687
4688 // Allocate screen and state here, so we can bail out if that fails.
4689 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004690 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004691 if (state == NULL || screen == NULL)
4692 {
4693 vterm_free(vterm);
4694 return FAIL;
4695 }
4696
Bram Moolenaar52acb112018-03-18 19:20:22 +01004697 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004698 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004699 vterm_set_utf8(vterm, 1);
4700
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004701 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004702
4703 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004704 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004705 &term->tl_default_color.fg,
4706 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004707
Bram Moolenaar9e587872019-05-13 20:27:23 +02004708 if (t_colors < 16)
4709 // Less than 16 colors: assume that bold means using a bright color for
4710 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004711 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4712
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004713 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004714 vterm_screen_reset(screen, 1 /* hard */);
4715
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004716 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004717 vterm_screen_enable_altscreen(screen, 1);
4718
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004719 // For unix do not use a blinking cursor. In an xterm this causes the
4720 // cursor to blink if it's blinking in the xterm.
4721 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004722#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004723 if (GetCaretBlinkTime() == INFINITE)
4724 value.boolean = 0;
4725 else
4726 value.boolean = 1;
4727#else
4728 value.boolean = 0;
4729#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004730 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004731 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004732
4733 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004734}
4735
4736/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004737 * Reset the terminal palette to its default value.
4738 */
4739 static void
4740term_reset_palette(VTerm *vterm)
4741{
4742 VTermState *state = vterm_obtain_state(vterm);
4743 int index;
4744
4745 for (index = 0; index < 16; index++)
4746 {
4747 VTermColor color;
4748
4749 color.type = VTERM_COLOR_INDEXED;
4750 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4751 &color.index);
4752 // The first valid index starts at 1.
4753 color.index -= 1;
4754
4755 vterm_state_set_palette_color(state, index, &color);
4756 }
4757}
4758
4759 static void
4760term_update_palette(term_T *term)
4761{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004762#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004763 if (term_use_palette()
4764 && (term->tl_palette != NULL
4765 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004766 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004767 {
4768 if (term->tl_palette != NULL)
4769 set_vterm_palette(term->tl_vterm, term->tl_palette);
4770 else
4771 init_vterm_ansi_colors(term->tl_vterm);
4772 }
4773 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004774#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004775 term_reset_palette(term->tl_vterm);
4776}
4777
4778/*
4779 * Called when option 'termguicolors' is changed.
4780 */
4781 void
4782term_update_palette_all()
4783{
4784 term_T *term;
4785
4786 FOR_ALL_TERMS(term)
4787 {
4788 if (term->tl_vterm == NULL)
4789 continue;
4790 term_update_palette(term);
4791 }
4792}
4793
4794/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004795 * Called when option 'background' or 'termguicolors' was set,
4796 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02004797 */
4798 void
4799term_update_colors_all(void)
4800{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004801 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02004802
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004803 FOR_ALL_TERMS(term)
4804 {
4805 if (term->tl_vterm == NULL)
4806 continue;
4807 init_default_colors(term);
4808 vterm_state_set_default_colors(
4809 vterm_obtain_state(term->tl_vterm),
4810 &term->tl_default_color.fg,
4811 &term->tl_default_color.bg);
4812 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004813}
4814
4815/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004816 * Return the text to show for the buffer name and status.
4817 */
4818 char_u *
4819term_get_status_text(term_T *term)
4820{
4821 if (term->tl_status_text == NULL)
4822 {
4823 char_u *txt;
4824 size_t len;
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004825 char_u *fname;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004826
4827 if (term->tl_normal_mode)
4828 {
4829 if (term_job_running(term))
4830 txt = (char_u *)_("Terminal");
4831 else
4832 txt = (char_u *)_("Terminal-finished");
4833 }
4834 else if (term->tl_title != NULL)
4835 txt = term->tl_title;
4836 else if (term_none_open(term))
4837 txt = (char_u *)_("active");
4838 else if (term_job_running(term))
4839 txt = (char_u *)_("running");
4840 else
4841 txt = (char_u *)_("finished");
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004842 fname = buf_get_fname(term->tl_buffer);
4843 len = 9 + STRLEN(fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004844 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004845 if (term->tl_status_text != NULL)
4846 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004847 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004848 }
4849 return term->tl_status_text;
4850}
4851
4852/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00004853 * Clear the cached value of the status text.
4854 */
4855 void
4856term_clear_status_text(term_T *term)
4857{
4858 VIM_CLEAR(term->tl_status_text);
4859}
4860
4861/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004862 * Mark references in jobs of terminals.
4863 */
4864 int
4865set_ref_in_term(int copyID)
4866{
4867 int abort = FALSE;
4868 term_T *term;
4869 typval_T tv;
4870
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004871 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004872 if (term->tl_job != NULL)
4873 {
4874 tv.v_type = VAR_JOB;
4875 tv.vval.v_job = term->tl_job;
4876 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4877 }
4878 return abort;
4879}
4880
4881/*
4882 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004883 * Returns NULL when the buffer is not for a terminal window and logs a message
4884 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004885 */
4886 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004887term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004888{
4889 buf_T *buf;
4890
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004891 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004892 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004893 --emsg_off;
4894 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004895 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01004896 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004897 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004898 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004899 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004900 return buf;
4901}
4902
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004903 static void
4904clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004905{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004906 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004907 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4908 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004909}
4910
4911 static void
4912dump_term_color(FILE *fd, VTermColor *color)
4913{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004914 int index;
4915
4916 if (VTERM_COLOR_IS_INDEXED(color))
4917 index = color->index + 1;
4918 else if (color->type == 0)
4919 // use RGB values
4920 index = 255;
4921 else
4922 // default color
4923 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004924 fprintf(fd, "%02x%02x%02x%d",
4925 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004926 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004927}
4928
4929/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004930 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004931 *
4932 * Each screen cell in full is:
4933 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4934 * {characters} is a space for an empty cell
4935 * For a double-width character "+" is changed to "*" and the next cell is
4936 * skipped.
4937 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4938 * when "&" use the same as the previous cell.
4939 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4940 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4941 * {color-idx} is a number from 0 to 255
4942 *
4943 * Screen cell with same width, attributes and color as the previous one:
4944 * |{characters}
4945 *
4946 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4947 *
4948 * Repeating the previous screen cell:
4949 * @{count}
4950 */
4951 void
4952f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4953{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02004954 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004955 term_T *term;
4956 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004957 int max_height = 0;
4958 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004959 stat_T st;
4960 FILE *fd;
4961 VTermPos pos;
4962 VTermScreen *screen;
4963 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004964 VTermState *state;
4965 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004966
4967 if (check_restricted() || check_secure())
4968 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02004969
4970 if (in_vim9script()
4971 && (check_for_buffer_arg(argvars, 0) == FAIL
4972 || check_for_string_arg(argvars, 1) == FAIL
4973 || check_for_opt_dict_arg(argvars, 2) == FAIL))
4974 return;
4975
4976 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004977 if (buf == NULL)
4978 return;
4979 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004980 if (term->tl_vterm == NULL)
4981 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00004982 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004983 return;
4984 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004985
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004986 if (argvars[2].v_type != VAR_UNKNOWN)
4987 {
4988 dict_T *d;
4989
4990 if (argvars[2].v_type != VAR_DICT)
4991 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00004992 emsg(_(e_dictionary_required));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004993 return;
4994 }
4995 d = argvars[2].vval.v_dict;
4996 if (d != NULL)
4997 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01004998 max_height = dict_get_number(d, "rows");
4999 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005000 }
5001 }
5002
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005003 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005004 if (fname == NULL)
5005 return;
5006 if (mch_stat((char *)fname, &st) >= 0)
5007 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005008 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005009 return;
5010 }
5011
Bram Moolenaard96ff162018-02-18 22:13:29 +01005012 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5013 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005014 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005015 return;
5016 }
5017
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005018 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005019
5020 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005021 state = vterm_obtain_state(term->tl_vterm);
5022 vterm_state_get_cursorpos(state, &cursor_pos);
5023
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005024 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5025 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005026 {
5027 int repeat = 0;
5028
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005029 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5030 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005031 {
5032 VTermScreenCell cell;
5033 int same_attr;
5034 int same_chars = TRUE;
5035 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005036 int is_cursor_pos = (pos.col == cursor_pos.col
5037 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005038
5039 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005040 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005041
5042 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5043 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005044 int c = cell.chars[i];
5045 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005046 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005047
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005048 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005049 if (i == 0)
5050 {
5051 c = (c == NUL) ? ' ' : c;
5052 pc = (pc == NUL) ? ' ' : pc;
5053 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005054 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005055 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005056 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005057 break;
5058 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005059 same_attr = vtermAttr2hl(&cell.attrs)
5060 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005061 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5062 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005063 if (same_chars && cell.width == prev_cell.width && same_attr
5064 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005065 {
5066 ++repeat;
5067 }
5068 else
5069 {
5070 if (repeat > 0)
5071 {
5072 fprintf(fd, "@%d", repeat);
5073 repeat = 0;
5074 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005075 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005076
5077 if (cell.chars[0] == NUL)
5078 fputs(" ", fd);
5079 else
5080 {
5081 char_u charbuf[10];
5082 int len;
5083
5084 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5085 && cell.chars[i] != NUL; ++i)
5086 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005087 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005088 fwrite(charbuf, len, 1, fd);
5089 }
5090 }
5091
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005092 // When only the characters differ we don't write anything, the
5093 // following "|", "@" or NL will indicate using the same
5094 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005095 if (cell.width != prev_cell.width || !same_attr)
5096 {
5097 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005098 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005099 else
5100 fputs("+", fd);
5101
5102 if (same_attr)
5103 {
5104 fputs("&", fd);
5105 }
5106 else
5107 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005108 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005109 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005110 fputs("&", fd);
5111 else
5112 {
5113 fputs("#", fd);
5114 dump_term_color(fd, &cell.fg);
5115 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005116 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005117 fputs("&", fd);
5118 else
5119 {
5120 fputs("#", fd);
5121 dump_term_color(fd, &cell.bg);
5122 }
5123 }
5124 }
5125
5126 prev_cell = cell;
5127 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005128
5129 if (cell.width == 2)
5130 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005131 }
5132 if (repeat > 0)
5133 fprintf(fd, "@%d", repeat);
5134 fputs("\n", fd);
5135 }
5136
5137 fclose(fd);
5138}
5139
5140/*
5141 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5142 */
5143 static void
5144dump_is_corrupt(garray_T *gap)
5145{
5146 ga_concat(gap, (char_u *)"CORRUPT");
5147}
5148
5149 static void
5150append_cell(garray_T *gap, cellattr_T *cell)
5151{
5152 if (ga_grow(gap, 1) == OK)
5153 {
5154 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5155 ++gap->ga_len;
5156 }
5157}
5158
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005159 static void
5160clear_cellattr(cellattr_T *cell)
5161{
5162 CLEAR_FIELD(*cell);
5163 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5164 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5165}
5166
Bram Moolenaard96ff162018-02-18 22:13:29 +01005167/*
5168 * Read the dump file from "fd" and append lines to the current buffer.
5169 * Return the cell width of the longest line.
5170 */
5171 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005172read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005173{
5174 int c;
5175 garray_T ga_text;
5176 garray_T ga_cell;
5177 char_u *prev_char = NULL;
5178 int attr = 0;
5179 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005180 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005181 term_T *term = curbuf->b_term;
5182 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005183 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005184
5185 ga_init2(&ga_text, 1, 90);
5186 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005187 clear_cellattr(&cell);
5188 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005189 cursor_pos->row = -1;
5190 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005191
5192 c = fgetc(fd);
5193 for (;;)
5194 {
5195 if (c == EOF)
5196 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005197 if (c == '\r')
5198 {
5199 // DOS line endings? Ignore.
5200 c = fgetc(fd);
5201 }
5202 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005203 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005204 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005205 if (ga_text.ga_data == NULL)
5206 dump_is_corrupt(&ga_text);
5207 if (ga_grow(&term->tl_scrollback, 1) == OK)
5208 {
5209 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5210 + term->tl_scrollback.ga_len;
5211
5212 if (max_cells < ga_cell.ga_len)
5213 max_cells = ga_cell.ga_len;
5214 line->sb_cols = ga_cell.ga_len;
5215 line->sb_cells = ga_cell.ga_data;
5216 line->sb_fill_attr = term->tl_default_color;
5217 ++term->tl_scrollback.ga_len;
5218 ga_init(&ga_cell);
5219
5220 ga_append(&ga_text, NUL);
5221 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5222 ga_text.ga_len, FALSE);
5223 }
5224 else
5225 ga_clear(&ga_cell);
5226 ga_text.ga_len = 0;
5227
5228 c = fgetc(fd);
5229 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005230 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005231 {
5232 int prev_len = ga_text.ga_len;
5233
Bram Moolenaar9271d052018-02-25 21:39:46 +01005234 if (c == '>')
5235 {
5236 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005237 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005238 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5239 cursor_pos->col = ga_cell.ga_len;
5240 }
5241
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005242 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005243 c = fgetc(fd);
5244 if (c != EOF)
5245 ga_append(&ga_text, c);
5246 for (;;)
5247 {
5248 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005249 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005250 || c == EOF || c == '\n')
5251 break;
5252 ga_append(&ga_text, c);
5253 }
5254
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005255 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005256 vim_free(prev_char);
5257 if (ga_text.ga_data != NULL)
5258 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5259 ga_text.ga_len - prev_len);
5260
Bram Moolenaar9271d052018-02-25 21:39:46 +01005261 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005262 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005263 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005264 }
5265 else if (c == '+' || c == '*')
5266 {
5267 int is_bg;
5268
5269 cell.width = c == '+' ? 1 : 2;
5270
5271 c = fgetc(fd);
5272 if (c == '&')
5273 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005274 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005275 c = fgetc(fd);
5276 }
5277 else if (isdigit(c))
5278 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005279 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005280 attr = 0;
5281 while (isdigit(c))
5282 {
5283 attr = attr * 10 + (c - '0');
5284 c = fgetc(fd);
5285 }
5286 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005287
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005288 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005289 for (is_bg = 0; is_bg <= 1; ++is_bg)
5290 {
5291 if (c == '&')
5292 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005293 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005294 c = fgetc(fd);
5295 }
5296 else if (c == '#')
5297 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005298 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005299
5300 c = fgetc(fd);
5301 red = hex2nr(c);
5302 c = fgetc(fd);
5303 red = (red << 4) + hex2nr(c);
5304 c = fgetc(fd);
5305 green = hex2nr(c);
5306 c = fgetc(fd);
5307 green = (green << 4) + hex2nr(c);
5308 c = fgetc(fd);
5309 blue = hex2nr(c);
5310 c = fgetc(fd);
5311 blue = (blue << 4) + hex2nr(c);
5312 c = fgetc(fd);
5313 if (!isdigit(c))
5314 dump_is_corrupt(&ga_text);
5315 while (isdigit(c))
5316 {
5317 index = index * 10 + (c - '0');
5318 c = fgetc(fd);
5319 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005320 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005321 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005322 type = VTERM_COLOR_RGB;
5323 if (index == 0)
5324 {
5325 if (is_bg)
5326 type |= VTERM_COLOR_DEFAULT_BG;
5327 else
5328 type |= VTERM_COLOR_DEFAULT_FG;
5329 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005330 }
5331 else
5332 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005333 type = VTERM_COLOR_INDEXED;
5334 index -= 1;
5335 }
5336 if (is_bg)
5337 {
5338 cell.bg.type = type;
5339 cell.bg.red = red;
5340 cell.bg.green = green;
5341 cell.bg.blue = blue;
5342 cell.bg.index = index;
5343 }
5344 else
5345 {
5346 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005347 cell.fg.red = red;
5348 cell.fg.green = green;
5349 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005350 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005351 }
5352 }
5353 else
5354 dump_is_corrupt(&ga_text);
5355 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005356 }
5357 else
5358 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005359 }
5360 else
5361 dump_is_corrupt(&ga_text);
5362
5363 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005364 if (cell.width == 2)
5365 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005366 }
5367 else if (c == '@')
5368 {
5369 if (prev_char == NULL)
5370 dump_is_corrupt(&ga_text);
5371 else
5372 {
5373 int count = 0;
5374
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005375 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005376 for (;;)
5377 {
5378 c = fgetc(fd);
5379 if (!isdigit(c))
5380 break;
5381 count = count * 10 + (c - '0');
5382 }
5383
5384 while (count-- > 0)
5385 {
5386 ga_concat(&ga_text, prev_char);
5387 append_cell(&ga_cell, &cell);
5388 }
5389 }
5390 }
5391 else
5392 {
5393 dump_is_corrupt(&ga_text);
5394 c = fgetc(fd);
5395 }
5396 }
5397
5398 if (ga_text.ga_len > 0)
5399 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005400 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005401 dump_is_corrupt(&ga_text);
5402 ga_append(&ga_text, NUL);
5403 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5404 ga_text.ga_len, FALSE);
5405 }
5406
5407 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005408 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005409 vim_free(prev_char);
5410
5411 return max_cells;
5412}
5413
5414/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005415 * Return an allocated string with at least "text_width" "=" characters and
5416 * "fname" inserted in the middle.
5417 */
5418 static char_u *
5419get_separator(int text_width, char_u *fname)
5420{
5421 int width = MAX(text_width, curwin->w_width);
5422 char_u *textline;
5423 int fname_size;
5424 char_u *p = fname;
5425 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005426 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005427
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005428 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005429 if (textline == NULL)
5430 return NULL;
5431
5432 fname_size = vim_strsize(fname);
5433 if (fname_size < width - 8)
5434 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005435 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005436 width = MAX(text_width, fname_size + 8);
5437 }
5438 else if (fname_size > width - 8)
5439 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005440 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005441 p = gettail(fname);
5442 fname_size = vim_strsize(p);
5443 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005444 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005445 while (fname_size > width - 8)
5446 {
5447 p += (*mb_ptr2len)(p);
5448 fname_size = vim_strsize(p);
5449 }
5450
5451 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5452 textline[i] = '=';
5453 textline[i++] = ' ';
5454
5455 STRCPY(textline + i, p);
5456 off = STRLEN(textline);
5457 textline[off] = ' ';
5458 for (i = 1; i < (width - fname_size) / 2; ++i)
5459 textline[off + i] = '=';
5460 textline[off + i] = NUL;
5461
5462 return textline;
5463}
5464
5465/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005466 * Common for "term_dumpdiff()" and "term_dumpload()".
5467 */
5468 static void
5469term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5470{
5471 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005472 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005473 char_u buf1[NUMBUFLEN];
5474 char_u buf2[NUMBUFLEN];
5475 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005476 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005477 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005478 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005479 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005480 char_u *textline = NULL;
5481
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005482 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005483 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005484 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005485 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005486 if (fname1 == NULL || (do_diff && fname2 == NULL))
5487 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005488 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005489 return;
5490 }
5491 fd1 = mch_fopen((char *)fname1, READBIN);
5492 if (fd1 == NULL)
5493 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005494 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005495 return;
5496 }
5497 if (do_diff)
5498 {
5499 fd2 = mch_fopen((char *)fname2, READBIN);
5500 if (fd2 == NULL)
5501 {
5502 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005503 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005504 return;
5505 }
5506 }
5507
5508 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005509 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5510 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5511 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5512 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5513 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005514
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005515 if (opt.jo_term_name == NULL)
5516 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005517 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005518
Bram Moolenaar51e14382019-05-25 20:21:28 +02005519 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005520 if (fname_tofree != NULL)
5521 {
5522 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5523 opt.jo_term_name = fname_tofree;
5524 }
5525 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005526
Bram Moolenaar87abab92019-06-03 21:14:59 +02005527 if (opt.jo_bufnr_buf != NULL)
5528 {
5529 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5530
5531 // With "bufnr" argument: enter the window with this buffer and make it
5532 // empty.
5533 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005534 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005535 else
5536 {
5537 buf = curbuf;
5538 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005539 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005540 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005541 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005542 }
5543 }
5544 else
5545 // Create a new terminal window.
5546 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5547
Bram Moolenaard96ff162018-02-18 22:13:29 +01005548 if (buf != NULL && buf->b_term != NULL)
5549 {
5550 int i;
5551 linenr_T bot_lnum;
5552 linenr_T lnum;
5553 term_T *term = buf->b_term;
5554 int width;
5555 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005556 VTermPos cursor_pos1;
5557 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005558
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005559 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005560
Bram Moolenaard96ff162018-02-18 22:13:29 +01005561 rettv->vval.v_number = buf->b_fnum;
5562
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005563 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005564 width = read_dump_file(fd1, &cursor_pos1);
5565
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005566 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005567 if (cursor_pos1.row >= 0)
5568 {
5569 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5570 coladvance(cursor_pos1.col);
5571 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005572
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005573 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005574 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005575
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005576 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005577 if (!do_diff)
5578 goto theend;
5579
5580 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5581
Bram Moolenaar4a696342018-04-05 18:45:26 +02005582 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005583 if (textline == NULL)
5584 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005585 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5586 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5587 vim_free(textline);
5588
5589 textline = get_separator(width, fname2);
5590 if (textline == NULL)
5591 goto theend;
5592 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5593 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005594 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005595
5596 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005597 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005598 if (width2 > width)
5599 {
5600 vim_free(textline);
5601 textline = alloc(width2 + 1);
5602 if (textline == NULL)
5603 goto theend;
5604 width = width2;
5605 textline[width] = NUL;
5606 }
5607 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5608
5609 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5610 {
5611 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5612 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005613 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005614 for (i = 0; i < width; ++i)
5615 textline[i] = '-';
5616 }
5617 else
5618 {
5619 char_u *line1;
5620 char_u *line2;
5621 char_u *p1;
5622 char_u *p2;
5623 int col;
5624 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5625 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5626 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5627 ->sb_cells;
5628
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005629 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005630 line1 = vim_strsave(ml_get(lnum));
5631 if (line1 == NULL)
5632 break;
5633 p1 = line1;
5634
5635 line2 = ml_get(lnum + bot_lnum);
5636 p2 = line2;
5637 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5638 {
5639 int len1 = utfc_ptr2len(p1);
5640 int len2 = utfc_ptr2len(p2);
5641
5642 textline[col] = ' ';
5643 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005644 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005645 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005646 else if (lnum == cursor_pos1.row + 1
5647 && col == cursor_pos1.col
5648 && (cursor_pos1.row != cursor_pos2.row
5649 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005650 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005651 textline[col] = '>';
5652 else if (lnum == cursor_pos2.row + 1
5653 && col == cursor_pos2.col
5654 && (cursor_pos1.row != cursor_pos2.row
5655 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005656 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005657 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005658 else if (cellattr1 != NULL && cellattr2 != NULL)
5659 {
5660 if ((cellattr1 + col)->width
5661 != (cellattr2 + col)->width)
5662 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005663 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005664 &(cellattr2 + col)->fg))
5665 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005666 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005667 &(cellattr2 + col)->bg))
5668 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005669 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5670 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005671 textline[col] = 'a';
5672 }
5673 p1 += len1;
5674 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005675 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005676 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005677
5678 while (col < width)
5679 {
5680 if (*p1 == NUL && *p2 == NUL)
5681 textline[col] = '?';
5682 else if (*p1 == NUL)
5683 {
5684 textline[col] = '+';
5685 p2 += utfc_ptr2len(p2);
5686 }
5687 else
5688 {
5689 textline[col] = '-';
5690 p1 += utfc_ptr2len(p1);
5691 }
5692 ++col;
5693 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005694
5695 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005696 }
5697 if (add_empty_scrollback(term, &term->tl_default_color,
5698 term->tl_top_diff_rows) == OK)
5699 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5700 ++bot_lnum;
5701 }
5702
5703 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5704 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005705 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005706 for (i = 0; i < width; ++i)
5707 textline[i] = '+';
5708 if (add_empty_scrollback(term, &term->tl_default_color,
5709 term->tl_top_diff_rows) == OK)
5710 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5711 ++lnum;
5712 ++bot_lnum;
5713 }
5714
5715 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005716
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005717 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005718 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005719 }
5720
5721theend:
5722 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005723 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005724 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005725 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005726 fclose(fd2);
5727}
5728
5729/*
5730 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5731 * bottom files.
5732 * Return FAIL when this is not possible.
5733 */
5734 int
5735term_swap_diff()
5736{
5737 term_T *term = curbuf->b_term;
5738 linenr_T line_count;
5739 linenr_T top_rows;
5740 linenr_T bot_rows;
5741 linenr_T bot_start;
5742 linenr_T lnum;
5743 char_u *p;
5744 sb_line_T *sb_line;
5745
5746 if (term == NULL
5747 || !term_is_finished(curbuf)
5748 || term->tl_top_diff_rows == 0
5749 || term->tl_scrollback.ga_len == 0)
5750 return FAIL;
5751
5752 line_count = curbuf->b_ml.ml_line_count;
5753 top_rows = term->tl_top_diff_rows;
5754 bot_rows = term->tl_bot_diff_rows;
5755 bot_start = line_count - bot_rows;
5756 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5757
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005758 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005759 for (lnum = 1; lnum <= top_rows; ++lnum)
5760 {
5761 p = vim_strsave(ml_get(1));
5762 if (p == NULL)
5763 return OK;
5764 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005765 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005766 vim_free(p);
5767 }
5768
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005769 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005770 for (lnum = 1; lnum <= bot_rows; ++lnum)
5771 {
5772 p = vim_strsave(ml_get(bot_start + lnum));
5773 if (p == NULL)
5774 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005775 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005776 ml_append(lnum - 1, p, 0, FALSE);
5777 vim_free(p);
5778 }
5779
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005780 // move top title to bottom
5781 p = vim_strsave(ml_get(bot_rows + 1));
5782 if (p == NULL)
5783 return OK;
5784 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005785 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005786 vim_free(p);
5787
5788 // move bottom title to top
5789 p = vim_strsave(ml_get(line_count - top_rows));
5790 if (p == NULL)
5791 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005792 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005793 ml_append(bot_rows, p, 0, FALSE);
5794 vim_free(p);
5795
Bram Moolenaard96ff162018-02-18 22:13:29 +01005796 if (top_rows == bot_rows)
5797 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005798 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005799 for (lnum = 0; lnum < top_rows; ++lnum)
5800 {
5801 sb_line_T temp;
5802
5803 temp = *(sb_line + lnum);
5804 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5805 *(sb_line + bot_start + lnum) = temp;
5806 }
5807 }
5808 else
5809 {
5810 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005811 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005812
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005813 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005814 if (temp != NULL)
5815 {
5816 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5817 mch_memmove(term->tl_scrollback.ga_data,
5818 temp + bot_start,
5819 sizeof(sb_line_T) * bot_rows);
5820 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5821 temp + top_rows,
5822 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5823 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5824 + line_count - top_rows,
5825 temp,
5826 sizeof(sb_line_T) * top_rows);
5827 vim_free(temp);
5828 }
5829 }
5830
5831 term->tl_top_diff_rows = bot_rows;
5832 term->tl_bot_diff_rows = top_rows;
5833
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005834 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005835 return OK;
5836}
5837
5838/*
5839 * "term_dumpdiff(filename, filename, options)" function
5840 */
5841 void
5842f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5843{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005844 if (in_vim9script()
5845 && (check_for_string_arg(argvars, 0) == FAIL
5846 || check_for_string_arg(argvars, 1) == FAIL
5847 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5848 return;
5849
Bram Moolenaard96ff162018-02-18 22:13:29 +01005850 term_load_dump(argvars, rettv, TRUE);
5851}
5852
5853/*
5854 * "term_dumpload(filename, options)" function
5855 */
5856 void
5857f_term_dumpload(typval_T *argvars, typval_T *rettv)
5858{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005859 if (in_vim9script()
5860 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02005861 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005862 return;
5863
Bram Moolenaard96ff162018-02-18 22:13:29 +01005864 term_load_dump(argvars, rettv, FALSE);
5865}
5866
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005867/*
5868 * "term_getaltscreen(buf)" function
5869 */
5870 void
5871f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5872{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005873 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005874
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005875 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5876 return;
5877
5878 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005879 if (buf == NULL)
5880 return;
5881 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5882}
5883
5884/*
5885 * "term_getattr(attr, name)" function
5886 */
5887 void
5888f_term_getattr(typval_T *argvars, typval_T *rettv)
5889{
5890 int attr;
5891 size_t i;
5892 char_u *name;
5893
5894 static struct {
5895 char *name;
5896 int attr;
5897 } attrs[] = {
5898 {"bold", HL_BOLD},
5899 {"italic", HL_ITALIC},
5900 {"underline", HL_UNDERLINE},
5901 {"strike", HL_STRIKETHROUGH},
5902 {"reverse", HL_INVERSE},
5903 };
5904
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02005905 if (in_vim9script()
5906 && (check_for_number_arg(argvars, 0) == FAIL
5907 || check_for_string_arg(argvars, 1) == FAIL))
5908 return;
5909
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005910 attr = tv_get_number(&argvars[0]);
5911 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005912 if (name == NULL)
5913 return;
5914
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005915 if (attr > HL_ALL)
5916 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02005917 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005918 if (STRCMP(name, attrs[i].name) == 0)
5919 {
5920 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5921 break;
5922 }
5923}
5924
5925/*
5926 * "term_getcursor(buf)" function
5927 */
5928 void
5929f_term_getcursor(typval_T *argvars, typval_T *rettv)
5930{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005931 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005932 term_T *term;
5933 list_T *l;
5934 dict_T *d;
5935
5936 if (rettv_list_alloc(rettv) == FAIL)
5937 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005938
5939 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5940 return;
5941
5942 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005943 if (buf == NULL)
5944 return;
5945 term = buf->b_term;
5946
5947 l = rettv->vval.v_list;
5948 list_append_number(l, term->tl_cursor_pos.row + 1);
5949 list_append_number(l, term->tl_cursor_pos.col + 1);
5950
5951 d = dict_alloc();
5952 if (d != NULL)
5953 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005954 dict_add_number(d, "visible", term->tl_cursor_visible);
5955 dict_add_number(d, "blink", blink_state_is_inverted()
5956 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5957 dict_add_number(d, "shape", term->tl_cursor_shape);
5958 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005959 list_append_dict(l, d);
5960 }
5961}
5962
5963/*
5964 * "term_getjob(buf)" function
5965 */
5966 void
5967f_term_getjob(typval_T *argvars, typval_T *rettv)
5968{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005969 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005970
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005971 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5972 return;
5973
5974 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005975 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005976 {
5977 rettv->v_type = VAR_SPECIAL;
5978 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005979 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005980 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005981
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005982 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005983 rettv->vval.v_job = buf->b_term->tl_job;
5984 if (rettv->vval.v_job != NULL)
5985 ++rettv->vval.v_job->jv_refcount;
5986}
5987
5988 static int
5989get_row_number(typval_T *tv, term_T *term)
5990{
5991 if (tv->v_type == VAR_STRING
5992 && tv->vval.v_string != NULL
5993 && STRCMP(tv->vval.v_string, ".") == 0)
5994 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005995 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005996}
5997
5998/*
5999 * "term_getline(buf, row)" function
6000 */
6001 void
6002f_term_getline(typval_T *argvars, typval_T *rettv)
6003{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006004 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006005 term_T *term;
6006 int row;
6007
6008 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006009
6010 if (in_vim9script()
6011 && (check_for_buffer_arg(argvars, 0) == FAIL
6012 || check_for_lnum_arg(argvars, 1) == FAIL))
6013 return;
6014
6015 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006016 if (buf == NULL)
6017 return;
6018 term = buf->b_term;
6019 row = get_row_number(&argvars[1], term);
6020
6021 if (term->tl_vterm == NULL)
6022 {
6023 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6024
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006025 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006026 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6027 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6028 }
6029 else
6030 {
6031 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6032 VTermRect rect;
6033 int len;
6034 char_u *p;
6035
6036 if (row < 0 || row >= term->tl_rows)
6037 return;
6038 len = term->tl_cols * MB_MAXBYTES + 1;
6039 p = alloc(len);
6040 if (p == NULL)
6041 return;
6042 rettv->vval.v_string = p;
6043
6044 rect.start_col = 0;
6045 rect.end_col = term->tl_cols;
6046 rect.start_row = row;
6047 rect.end_row = row + 1;
6048 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6049 }
6050}
6051
6052/*
6053 * "term_getscrolled(buf)" function
6054 */
6055 void
6056f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6057{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006058 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006059
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006060 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6061 return;
6062
6063 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006064 if (buf == NULL)
6065 return;
6066 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6067}
6068
6069/*
6070 * "term_getsize(buf)" function
6071 */
6072 void
6073f_term_getsize(typval_T *argvars, typval_T *rettv)
6074{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006075 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006076 list_T *l;
6077
6078 if (rettv_list_alloc(rettv) == FAIL)
6079 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006080
6081 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6082 return;
6083
6084 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006085 if (buf == NULL)
6086 return;
6087
6088 l = rettv->vval.v_list;
6089 list_append_number(l, buf->b_term->tl_rows);
6090 list_append_number(l, buf->b_term->tl_cols);
6091}
6092
6093/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006094 * "term_setsize(buf, rows, cols)" function
6095 */
6096 void
6097f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6098{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006099 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006100 term_T *term;
6101 varnumber_T rows, cols;
6102
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006103 if (in_vim9script()
6104 && (check_for_buffer_arg(argvars, 0) == FAIL
6105 || check_for_number_arg(argvars, 1) == FAIL
6106 || check_for_number_arg(argvars, 2) == FAIL))
6107 return;
6108
6109 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006110 if (buf == NULL)
6111 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006112 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006113 return;
6114 }
6115 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006116 return;
6117 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006118 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006119 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006120 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006121 cols = cols <= 0 ? term->tl_cols : cols;
6122 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006123 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006124
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006125 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006126 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6127 term_report_winsize(term, term->tl_rows, term->tl_cols);
6128}
6129
6130/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006131 * "term_getstatus(buf)" function
6132 */
6133 void
6134f_term_getstatus(typval_T *argvars, typval_T *rettv)
6135{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006136 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006137 term_T *term;
6138 char_u val[100];
6139
6140 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006141
6142 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6143 return;
6144
6145 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006146 if (buf == NULL)
6147 return;
6148 term = buf->b_term;
6149
6150 if (term_job_running(term))
6151 STRCPY(val, "running");
6152 else
6153 STRCPY(val, "finished");
6154 if (term->tl_normal_mode)
6155 STRCAT(val, ",normal");
6156 rettv->vval.v_string = vim_strsave(val);
6157}
6158
6159/*
6160 * "term_gettitle(buf)" function
6161 */
6162 void
6163f_term_gettitle(typval_T *argvars, typval_T *rettv)
6164{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006165 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006166
6167 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006168
6169 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6170 return;
6171
6172 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006173 if (buf == NULL)
6174 return;
6175
6176 if (buf->b_term->tl_title != NULL)
6177 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6178}
6179
6180/*
6181 * "term_gettty(buf)" function
6182 */
6183 void
6184f_term_gettty(typval_T *argvars, typval_T *rettv)
6185{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006186 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006187 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006188 int num = 0;
6189
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006190 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006191 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006192 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6193 return;
6194
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006195 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006196 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006197 if (buf == NULL)
6198 return;
6199 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006200 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006201
6202 switch (num)
6203 {
6204 case 0:
6205 if (buf->b_term->tl_job != NULL)
6206 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006207 break;
6208 case 1:
6209 if (buf->b_term->tl_job != NULL)
6210 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006211 break;
6212 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006213 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006214 return;
6215 }
6216 if (p != NULL)
6217 rettv->vval.v_string = vim_strsave(p);
6218}
6219
6220/*
6221 * "term_list()" function
6222 */
6223 void
6224f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6225{
6226 term_T *tp;
6227 list_T *l;
6228
6229 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6230 return;
6231
6232 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006233 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006234 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006235 if (list_append_number(l,
6236 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6237 return;
6238}
6239
6240/*
6241 * "term_scrape(buf, row)" function
6242 */
6243 void
6244f_term_scrape(typval_T *argvars, typval_T *rettv)
6245{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006246 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006247 VTermScreen *screen = NULL;
6248 VTermPos pos;
6249 list_T *l;
6250 term_T *term;
6251 char_u *p;
6252 sb_line_T *line;
6253
6254 if (rettv_list_alloc(rettv) == FAIL)
6255 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006256
6257 if (in_vim9script()
6258 && (check_for_buffer_arg(argvars, 0) == FAIL
6259 || check_for_lnum_arg(argvars, 1) == FAIL))
6260 return;
6261
6262 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006263 if (buf == NULL)
6264 return;
6265 term = buf->b_term;
6266
6267 l = rettv->vval.v_list;
6268 pos.row = get_row_number(&argvars[1], term);
6269
6270 if (term->tl_vterm != NULL)
6271 {
6272 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006273 if (screen == NULL) // can't really happen
6274 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006275 p = NULL;
6276 line = NULL;
6277 }
6278 else
6279 {
6280 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6281
6282 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6283 return;
6284 p = ml_get_buf(buf, lnum + 1, FALSE);
6285 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6286 }
6287
6288 for (pos.col = 0; pos.col < term->tl_cols; )
6289 {
6290 dict_T *dcell;
6291 int width;
6292 VTermScreenCellAttrs attrs;
6293 VTermColor fg, bg;
6294 char_u rgb[8];
6295 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6296 int off = 0;
6297 int i;
6298
6299 if (screen == NULL)
6300 {
6301 cellattr_T *cellattr;
6302 int len;
6303
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006304 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006305 if (pos.col >= line->sb_cols)
6306 break;
6307 cellattr = line->sb_cells + pos.col;
6308 width = cellattr->width;
6309 attrs = cellattr->attrs;
6310 fg = cellattr->fg;
6311 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006312 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006313 mch_memmove(mbs, p, len);
6314 mbs[len] = NUL;
6315 p += len;
6316 }
6317 else
6318 {
6319 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006320
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006321 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6322 break;
6323 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6324 {
6325 if (cell.chars[i] == 0)
6326 break;
6327 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6328 }
6329 mbs[off] = NUL;
6330 width = cell.width;
6331 attrs = cell.attrs;
6332 fg = cell.fg;
6333 bg = cell.bg;
6334 }
6335 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006336 if (dcell == NULL)
6337 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006338 list_append_dict(l, dcell);
6339
Bram Moolenaare0be1672018-07-08 16:50:37 +02006340 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006341
6342 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6343 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006344 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006345 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6346 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006347 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006348
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006349 dict_add_number(dcell, "attr",
6350 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006351 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006352
6353 ++pos.col;
6354 if (width == 2)
6355 ++pos.col;
6356 }
6357}
6358
6359/*
6360 * "term_sendkeys(buf, keys)" function
6361 */
6362 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006363f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006364{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006365 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006366 char_u *msg;
6367 term_T *term;
6368
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006369 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006370 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006371 || check_for_string_arg(argvars, 1) == FAIL))
6372 return;
6373
6374 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006375 if (buf == NULL)
6376 return;
6377
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006378 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006379 if (msg == NULL)
6380 return;
6381 term = buf->b_term;
6382 if (term->tl_vterm == NULL)
6383 return;
6384
6385 while (*msg != NUL)
6386 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006387 int c;
6388
6389 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6390 {
6391 c = TO_SPECIAL(msg[1], msg[2]);
6392 msg += 3;
6393 }
6394 else
6395 {
6396 c = PTR2CHAR(msg);
6397 msg += MB_CPTR2LEN(msg);
6398 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006399 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006400 }
6401}
6402
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006403#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6404/*
6405 * "term_getansicolors(buf)" function
6406 */
6407 void
6408f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6409{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006410 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006411 term_T *term;
6412 VTermState *state;
6413 VTermColor color;
6414 char_u hexbuf[10];
6415 int index;
6416 list_T *list;
6417
6418 if (rettv_list_alloc(rettv) == FAIL)
6419 return;
6420
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006421 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6422 return;
6423
6424 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006425 if (buf == NULL)
6426 return;
6427 term = buf->b_term;
6428 if (term->tl_vterm == NULL)
6429 return;
6430
6431 list = rettv->vval.v_list;
6432 state = vterm_obtain_state(term->tl_vterm);
6433 for (index = 0; index < 16; index++)
6434 {
6435 vterm_state_get_palette_color(state, index, &color);
6436 sprintf((char *)hexbuf, "#%02x%02x%02x",
6437 color.red, color.green, color.blue);
6438 if (list_append_string(list, hexbuf, 7) == FAIL)
6439 return;
6440 }
6441}
6442
6443/*
6444 * "term_setansicolors(buf, list)" function
6445 */
6446 void
6447f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6448{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006449 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006450 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006451 listitem_T *li;
6452 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006453
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006454 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006455 && (check_for_buffer_arg(argvars, 0) == FAIL
6456 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006457 return;
6458
6459 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006460 if (buf == NULL)
6461 return;
6462 term = buf->b_term;
6463 if (term->tl_vterm == NULL)
6464 return;
6465
6466 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
6467 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006468 emsg(_(e_list_required));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006469 return;
6470 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01006471 if (argvars[1].vval.v_list->lv_first == &range_list_item
6472 || argvars[1].vval.v_list->lv_len != 16)
6473 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006474 emsg(_(e_invalid_argument));
LemonBoyb2b3acb2022-05-20 10:10:34 +01006475 return;
6476 }
6477
6478 if (term->tl_palette == NULL)
6479 term->tl_palette = ALLOC_MULT(long_u, 16);
6480 if (term->tl_palette == NULL)
6481 return;
6482
6483 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6484 {
6485 char_u *color_name;
6486 guicolor_T guicolor;
6487
6488 color_name = tv_get_string_chk(&li->li_tv);
6489 if (color_name == NULL)
6490 return;
6491
6492 guicolor = GUI_GET_COLOR(color_name);
6493 if (guicolor == INVALCOLOR)
6494 {
6495 semsg(_(e_cannot_allocate_color_str), color_name);
6496 return;
6497 }
6498
6499 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6500 }
6501
6502 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006503}
6504#endif
6505
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006506/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006507 * "term_setapi(buf, api)" function
6508 */
6509 void
6510f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6511{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006512 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006513 term_T *term;
6514 char_u *api;
6515
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006516 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006517 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006518 || check_for_string_arg(argvars, 1) == FAIL))
6519 return;
6520
6521 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006522 if (buf == NULL)
6523 return;
6524 term = buf->b_term;
6525 vim_free(term->tl_api);
6526 api = tv_get_string_chk(&argvars[1]);
6527 if (api != NULL)
6528 term->tl_api = vim_strsave(api);
6529 else
6530 term->tl_api = NULL;
6531}
6532
6533/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006534 * "term_setrestore(buf, command)" function
6535 */
6536 void
6537f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6538{
6539#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006540 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006541 term_T *term;
6542 char_u *cmd;
6543
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006544 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006545 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006546 || check_for_string_arg(argvars, 1) == FAIL))
6547 return;
6548
6549 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006550 if (buf == NULL)
6551 return;
6552 term = buf->b_term;
6553 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006554 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006555 if (cmd != NULL)
6556 term->tl_command = vim_strsave(cmd);
6557 else
6558 term->tl_command = NULL;
6559#endif
6560}
6561
6562/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006563 * "term_setkill(buf, how)" function
6564 */
6565 void
6566f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6567{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006568 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006569 term_T *term;
6570 char_u *how;
6571
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006572 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006573 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006574 || check_for_string_arg(argvars, 1) == FAIL))
6575 return;
6576
6577 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006578 if (buf == NULL)
6579 return;
6580 term = buf->b_term;
6581 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006582 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006583 if (how != NULL)
6584 term->tl_kill = vim_strsave(how);
6585 else
6586 term->tl_kill = NULL;
6587}
6588
6589/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006590 * "term_start(command, options)" function
6591 */
6592 void
6593f_term_start(typval_T *argvars, typval_T *rettv)
6594{
6595 jobopt_T opt;
6596 buf_T *buf;
6597
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006598 if (in_vim9script()
6599 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6600 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6601 return;
6602
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006603 init_job_options(&opt);
6604 if (argvars[1].v_type != VAR_UNKNOWN
6605 && get_job_options(&argvars[1], &opt,
6606 JO_TIMEOUT_ALL + JO_STOPONEXIT
6607 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6608 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6609 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6610 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006611 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006612 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006613 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006614 return;
6615
Bram Moolenaar13568252018-03-16 20:46:58 +01006616 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006617
6618 if (buf != NULL && buf->b_term != NULL)
6619 rettv->vval.v_number = buf->b_fnum;
6620}
6621
6622/*
6623 * "term_wait" function
6624 */
6625 void
6626f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6627{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006628 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006629
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006630 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006631 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006632 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006633 return;
6634
6635 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006636 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006637 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006638 if (buf->b_term->tl_job == NULL)
6639 {
6640 ch_log(NULL, "term_wait(): no job to wait for");
6641 return;
6642 }
6643 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006644 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006645 return;
6646
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006647 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006648 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006649 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6650 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006651 // The job is dead, keep reading channel I/O until the channel is
6652 // closed. buf->b_term may become NULL if the terminal was closed while
6653 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006654 ch_log(NULL, "term_wait(): waiting for channel to close");
6655 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6656 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006657 term_flush_messages();
6658
Bram Moolenaard45aa552018-05-21 22:50:29 +02006659 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006660 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006661 // If the terminal is closed when the channel is closed the
6662 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006663 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006664 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6665 // came here from a close callback, only wait one time
6666 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006667 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006668
6669 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006670 }
6671 else
6672 {
6673 long wait = 10L;
6674
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006675 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006676
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006677 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006678 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006679 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006680 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006681
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006682 // Flushing messages on channels is hopefully sufficient.
6683 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006684 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006685 }
6686}
6687
6688/*
6689 * Called when a channel has sent all the lines to a terminal.
6690 * Send a CTRL-D to mark the end of the text.
6691 */
6692 void
6693term_send_eof(channel_T *ch)
6694{
6695 term_T *term;
6696
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006697 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006698 if (term->tl_job == ch->ch_job)
6699 {
6700 if (term->tl_eof_chars != NULL)
6701 {
6702 channel_send(ch, PART_IN, term->tl_eof_chars,
6703 (int)STRLEN(term->tl_eof_chars), NULL);
6704 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6705 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006706# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006707 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006708 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006709 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6710# endif
6711 }
6712}
6713
Bram Moolenaar113e1072019-01-20 15:30:40 +01006714#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006715 job_T *
6716term_getjob(term_T *term)
6717{
6718 return term != NULL ? term->tl_job : NULL;
6719}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006720#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006721
Bram Moolenaar4f974752019-02-17 17:44:42 +01006722# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006723
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006724///////////////////////////////////////
6725// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006726#ifdef PROTO
6727typedef int COORD;
6728typedef int DWORD;
6729typedef int HANDLE;
6730typedef int *DWORD_PTR;
6731typedef int HPCON;
6732typedef int HRESULT;
6733typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006734typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006735typedef int PSIZE_T;
6736typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006737typedef int BOOL;
6738# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006739#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006740
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006741HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6742HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6743HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006744BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6745BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6746void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006747
6748 static int
6749dyn_conpty_init(int verbose)
6750{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006751 static HMODULE hKerneldll = NULL;
6752 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006753 static struct
6754 {
6755 char *name;
6756 FARPROC *ptr;
6757 } conpty_entry[] =
6758 {
6759 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6760 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6761 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6762 {"InitializeProcThreadAttributeList",
6763 (FARPROC*)&pInitializeProcThreadAttributeList},
6764 {"UpdateProcThreadAttribute",
6765 (FARPROC*)&pUpdateProcThreadAttribute},
6766 {"DeleteProcThreadAttributeList",
6767 (FARPROC*)&pDeleteProcThreadAttributeList},
6768 {NULL, NULL}
6769 };
6770
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006771 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006772 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006773 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006774 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006775 return FAIL;
6776 }
6777
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006778 // No need to initialize twice.
6779 if (hKerneldll)
6780 return OK;
6781
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006782 hKerneldll = vimLoadLib("kernel32.dll");
6783 for (i = 0; conpty_entry[i].name != NULL
6784 && conpty_entry[i].ptr != NULL; ++i)
6785 {
6786 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6787 conpty_entry[i].name)) == NULL)
6788 {
6789 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006790 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006791 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006792 return FAIL;
6793 }
6794 }
6795
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006796 return OK;
6797}
6798
6799 static int
6800conpty_term_and_job_init(
6801 term_T *term,
6802 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006803 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006804 jobopt_T *opt,
6805 jobopt_T *orig_opt)
6806{
6807 WCHAR *cmd_wchar = NULL;
6808 WCHAR *cmd_wchar_copy = NULL;
6809 WCHAR *cwd_wchar = NULL;
6810 WCHAR *env_wchar = NULL;
6811 channel_T *channel = NULL;
6812 job_T *job = NULL;
6813 HANDLE jo = NULL;
6814 garray_T ga_cmd, ga_env;
6815 char_u *cmd = NULL;
6816 HRESULT hr;
6817 COORD consize;
6818 SIZE_T breq;
6819 PROCESS_INFORMATION proc_info;
6820 HANDLE i_theirs = NULL;
6821 HANDLE o_theirs = NULL;
6822 HANDLE i_ours = NULL;
6823 HANDLE o_ours = NULL;
6824
Bram Moolenaar04935fb2022-01-08 16:19:22 +00006825 ga_init2(&ga_cmd, sizeof(char*), 20);
6826 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006827
6828 if (argvar->v_type == VAR_STRING)
6829 {
6830 cmd = argvar->vval.v_string;
6831 }
6832 else if (argvar->v_type == VAR_LIST)
6833 {
6834 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6835 goto failed;
6836 cmd = ga_cmd.ga_data;
6837 }
6838 if (cmd == NULL || *cmd == NUL)
6839 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006840 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006841 goto failed;
6842 }
6843
6844 term->tl_arg0_cmd = vim_strsave(cmd);
6845
6846 cmd_wchar = enc_to_utf16(cmd, NULL);
6847
6848 if (cmd_wchar != NULL)
6849 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006850 // Request by CreateProcessW
6851 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006852 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006853 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6854 }
6855
6856 ga_clear(&ga_cmd);
6857 if (cmd_wchar == NULL)
6858 goto failed;
6859 if (opt->jo_cwd != NULL)
6860 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6861
6862 win32_build_env(opt->jo_env, &ga_env, TRUE);
6863 env_wchar = ga_env.ga_data;
6864
6865 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6866 goto failed;
6867 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6868 goto failed;
6869
6870 consize.X = term->tl_cols;
6871 consize.Y = term->tl_rows;
6872 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6873 &term->tl_conpty);
6874 if (FAILED(hr))
6875 goto failed;
6876
6877 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6878
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006879 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006880 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006881 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006882 if (!term->tl_siex.lpAttributeList)
6883 goto failed;
6884 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6885 0, &breq))
6886 goto failed;
6887 if (!pUpdateProcThreadAttribute(
6888 term->tl_siex.lpAttributeList, 0,
6889 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6890 sizeof(HPCON), NULL, NULL))
6891 goto failed;
6892
6893 channel = add_channel();
6894 if (channel == NULL)
6895 goto failed;
6896
6897 job = job_alloc();
6898 if (job == NULL)
6899 goto failed;
6900 if (argvar->v_type == VAR_STRING)
6901 {
6902 int argc;
6903
6904 build_argv_from_string(cmd, &job->jv_argv, &argc);
6905 }
6906 else
6907 {
6908 int argc;
6909
6910 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6911 }
6912
6913 if (opt->jo_set & JO_IN_BUF)
6914 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6915
6916 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6917 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02006918 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006919 env_wchar, cwd_wchar,
6920 &term->tl_siex.StartupInfo, &proc_info))
6921 goto failed;
6922
6923 CloseHandle(i_theirs);
6924 CloseHandle(o_theirs);
6925
6926 channel_set_pipes(channel,
6927 (sock_T)i_ours,
6928 (sock_T)o_ours,
6929 (sock_T)o_ours);
6930
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006931 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006932 channel->ch_write_text_mode = TRUE;
6933
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006934 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006935 channel->ch_anonymous_pipe = TRUE;
6936
6937 jo = CreateJobObject(NULL, NULL);
6938 if (jo == NULL)
6939 goto failed;
6940
6941 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6942 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006943 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006944 CloseHandle(jo);
6945 jo = NULL;
6946 }
6947
6948 ResumeThread(proc_info.hThread);
6949 CloseHandle(proc_info.hThread);
6950
6951 vim_free(cmd_wchar);
6952 vim_free(cmd_wchar_copy);
6953 vim_free(cwd_wchar);
6954 vim_free(env_wchar);
6955
6956 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6957 goto failed;
6958
Bram Moolenaar30b9a412022-05-26 14:06:37 +01006959#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01006960 if (term_use_palette())
6961 {
6962 if (term->tl_palette != NULL)
6963 set_vterm_palette(term->tl_vterm, term->tl_palette);
6964 else
6965 init_vterm_ansi_colors(term->tl_vterm);
6966 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01006967#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006968
6969 channel_set_job(channel, job, opt);
6970 job_set_options(job, opt);
6971
6972 job->jv_channel = channel;
6973 job->jv_proc_info = proc_info;
6974 job->jv_job_object = jo;
6975 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006976 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006977 ++job->jv_refcount;
6978 term->tl_job = job;
6979
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006980 // Redirecting stdout and stderr doesn't work at the job level. Instead
6981 // open the file here and handle it in. opt->jo_io was changed in
6982 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006983 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6984 {
6985 char_u *fname = opt->jo_io_name[PART_OUT];
6986
6987 ch_log(channel, "Opening output file %s", fname);
6988 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6989 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006990 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006991 }
6992
6993 return OK;
6994
6995failed:
6996 ga_clear(&ga_cmd);
6997 ga_clear(&ga_env);
6998 vim_free(cmd_wchar);
6999 vim_free(cmd_wchar_copy);
7000 vim_free(cwd_wchar);
7001 if (channel != NULL)
7002 channel_clear(channel);
7003 if (job != NULL)
7004 {
7005 job->jv_channel = NULL;
7006 job_cleanup(job);
7007 }
7008 term->tl_job = NULL;
7009 if (jo != NULL)
7010 CloseHandle(jo);
7011
7012 if (term->tl_siex.lpAttributeList != NULL)
7013 {
7014 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7015 vim_free(term->tl_siex.lpAttributeList);
7016 }
7017 term->tl_siex.lpAttributeList = NULL;
7018 if (o_theirs != NULL)
7019 CloseHandle(o_theirs);
7020 if (o_ours != NULL)
7021 CloseHandle(o_ours);
7022 if (i_ours != NULL)
7023 CloseHandle(i_ours);
7024 if (i_theirs != NULL)
7025 CloseHandle(i_theirs);
7026 if (term->tl_conpty != NULL)
7027 pClosePseudoConsole(term->tl_conpty);
7028 term->tl_conpty = NULL;
7029 return FAIL;
7030}
7031
7032 static void
7033conpty_term_report_winsize(term_T *term, int rows, int cols)
7034{
7035 COORD consize;
7036
7037 consize.X = cols;
7038 consize.Y = rows;
7039 pResizePseudoConsole(term->tl_conpty, consize);
7040}
7041
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007042 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007043term_free_conpty(term_T *term)
7044{
7045 if (term->tl_siex.lpAttributeList != NULL)
7046 {
7047 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7048 vim_free(term->tl_siex.lpAttributeList);
7049 }
7050 term->tl_siex.lpAttributeList = NULL;
7051 if (term->tl_conpty != NULL)
7052 pClosePseudoConsole(term->tl_conpty);
7053 term->tl_conpty = NULL;
7054}
7055
7056 int
7057use_conpty(void)
7058{
7059 return has_conpty;
7060}
7061
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007062# ifndef PROTO
7063
7064#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7065#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007066#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007067
7068void* (*winpty_config_new)(UINT64, void*);
7069void* (*winpty_open)(void*, void*);
7070void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7071BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7072void (*winpty_config_set_mouse_mode)(void*, int);
7073void (*winpty_config_set_initial_size)(void*, int, int);
7074LPCWSTR (*winpty_conin_name)(void*);
7075LPCWSTR (*winpty_conout_name)(void*);
7076LPCWSTR (*winpty_conerr_name)(void*);
7077void (*winpty_free)(void*);
7078void (*winpty_config_free)(void*);
7079void (*winpty_spawn_config_free)(void*);
7080void (*winpty_error_free)(void*);
7081LPCWSTR (*winpty_error_msg)(void*);
7082BOOL (*winpty_set_size)(void*, int, int, void*);
7083HANDLE (*winpty_agent_process)(void*);
7084
7085#define WINPTY_DLL "winpty.dll"
7086
7087static HINSTANCE hWinPtyDLL = NULL;
7088# endif
7089
7090 static int
7091dyn_winpty_init(int verbose)
7092{
7093 int i;
7094 static struct
7095 {
7096 char *name;
7097 FARPROC *ptr;
7098 } winpty_entry[] =
7099 {
7100 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7101 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7102 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7103 {"winpty_config_set_mouse_mode",
7104 (FARPROC*)&winpty_config_set_mouse_mode},
7105 {"winpty_config_set_initial_size",
7106 (FARPROC*)&winpty_config_set_initial_size},
7107 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7108 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7109 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7110 {"winpty_free", (FARPROC*)&winpty_free},
7111 {"winpty_open", (FARPROC*)&winpty_open},
7112 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7113 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7114 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7115 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7116 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7117 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7118 {NULL, NULL}
7119 };
7120
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007121 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007122 if (hWinPtyDLL)
7123 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007124 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7125 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007126 if (*p_winptydll != NUL)
7127 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7128 if (!hWinPtyDLL)
7129 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7130 if (!hWinPtyDLL)
7131 {
7132 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007133 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007134 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7135 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007136 return FAIL;
7137 }
7138 for (i = 0; winpty_entry[i].name != NULL
7139 && winpty_entry[i].ptr != NULL; ++i)
7140 {
7141 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7142 winpty_entry[i].name)) == NULL)
7143 {
7144 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007145 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007146 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007147 return FAIL;
7148 }
7149 }
7150
7151 return OK;
7152}
7153
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007154 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007155winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007156 term_T *term,
7157 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007158 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007159 jobopt_T *opt,
7160 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007161{
7162 WCHAR *cmd_wchar = NULL;
7163 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007164 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007165 channel_T *channel = NULL;
7166 job_T *job = NULL;
7167 DWORD error;
7168 HANDLE jo = NULL;
7169 HANDLE child_process_handle;
7170 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007171 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007172 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007173 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007174 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007175
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007176 ga_init2(&ga_cmd, sizeof(char*), 20);
7177 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007178
7179 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007180 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007181 cmd = argvar->vval.v_string;
7182 }
7183 else if (argvar->v_type == VAR_LIST)
7184 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007185 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007186 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007187 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007188 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007189 if (cmd == NULL || *cmd == NUL)
7190 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007191 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007192 goto failed;
7193 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007194
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007195 term->tl_arg0_cmd = vim_strsave(cmd);
7196
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007197 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007198 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007199 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007200 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007201 if (opt->jo_cwd != NULL)
7202 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007203
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007204 win32_build_env(opt->jo_env, &ga_env, TRUE);
7205 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007206
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007207 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7208 if (term->tl_winpty_config == NULL)
7209 goto failed;
7210
7211 winpty_config_set_mouse_mode(term->tl_winpty_config,
7212 WINPTY_MOUSE_MODE_FORCE);
7213 winpty_config_set_initial_size(term->tl_winpty_config,
7214 term->tl_cols, term->tl_rows);
7215 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7216 if (term->tl_winpty == NULL)
7217 goto failed;
7218
7219 spawn_config = winpty_spawn_config_new(
7220 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7221 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7222 NULL,
7223 cmd_wchar,
7224 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007225 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007226 &winpty_err);
7227 if (spawn_config == NULL)
7228 goto failed;
7229
7230 channel = add_channel();
7231 if (channel == NULL)
7232 goto failed;
7233
7234 job = job_alloc();
7235 if (job == NULL)
7236 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007237 if (argvar->v_type == VAR_STRING)
7238 {
7239 int argc;
7240
7241 build_argv_from_string(cmd, &job->jv_argv, &argc);
7242 }
7243 else
7244 {
7245 int argc;
7246
7247 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7248 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007249
7250 if (opt->jo_set & JO_IN_BUF)
7251 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7252
7253 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7254 &child_thread_handle, &error, &winpty_err))
7255 goto failed;
7256
7257 channel_set_pipes(channel,
7258 (sock_T)CreateFileW(
7259 winpty_conin_name(term->tl_winpty),
7260 GENERIC_WRITE, 0, NULL,
7261 OPEN_EXISTING, 0, NULL),
7262 (sock_T)CreateFileW(
7263 winpty_conout_name(term->tl_winpty),
7264 GENERIC_READ, 0, NULL,
7265 OPEN_EXISTING, 0, NULL),
7266 (sock_T)CreateFileW(
7267 winpty_conerr_name(term->tl_winpty),
7268 GENERIC_READ, 0, NULL,
7269 OPEN_EXISTING, 0, NULL));
7270
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007271 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007272 channel->ch_write_text_mode = TRUE;
7273
7274 jo = CreateJobObject(NULL, NULL);
7275 if (jo == NULL)
7276 goto failed;
7277
7278 if (!AssignProcessToJobObject(jo, child_process_handle))
7279 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007280 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007281 CloseHandle(jo);
7282 jo = NULL;
7283 }
7284
7285 winpty_spawn_config_free(spawn_config);
7286 vim_free(cmd_wchar);
7287 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007288 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007289
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007290 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7291 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007292
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007293#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007294 if (term_use_palette())
7295 {
7296 if (term->tl_palette != NULL)
7297 set_vterm_palette(term->tl_vterm, term->tl_palette);
7298 else
7299 init_vterm_ansi_colors(term->tl_vterm);
7300 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007301#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007302
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007303 channel_set_job(channel, job, opt);
7304 job_set_options(job, opt);
7305
7306 job->jv_channel = channel;
7307 job->jv_proc_info.hProcess = child_process_handle;
7308 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7309 job->jv_job_object = jo;
7310 job->jv_status = JOB_STARTED;
7311 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007312 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007313 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007314 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007315 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007316 ++job->jv_refcount;
7317 term->tl_job = job;
7318
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007319 // Redirecting stdout and stderr doesn't work at the job level. Instead
7320 // open the file here and handle it in. opt->jo_io was changed in
7321 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007322 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7323 {
7324 char_u *fname = opt->jo_io_name[PART_OUT];
7325
7326 ch_log(channel, "Opening output file %s", fname);
7327 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7328 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007329 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007330 }
7331
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007332 return OK;
7333
7334failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007335 ga_clear(&ga_cmd);
7336 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007337 vim_free(cmd_wchar);
7338 vim_free(cwd_wchar);
7339 if (spawn_config != NULL)
7340 winpty_spawn_config_free(spawn_config);
7341 if (channel != NULL)
7342 channel_clear(channel);
7343 if (job != NULL)
7344 {
7345 job->jv_channel = NULL;
7346 job_cleanup(job);
7347 }
7348 term->tl_job = NULL;
7349 if (jo != NULL)
7350 CloseHandle(jo);
7351 if (term->tl_winpty != NULL)
7352 winpty_free(term->tl_winpty);
7353 term->tl_winpty = NULL;
7354 if (term->tl_winpty_config != NULL)
7355 winpty_config_free(term->tl_winpty_config);
7356 term->tl_winpty_config = NULL;
7357 if (winpty_err != NULL)
7358 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007359 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007360 (short_u *)winpty_error_msg(winpty_err), NULL);
7361
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007362 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007363 winpty_error_free(winpty_err);
7364 }
7365 return FAIL;
7366}
7367
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007368/*
7369 * Create a new terminal of "rows" by "cols" cells.
7370 * Store a reference in "term".
7371 * Return OK or FAIL.
7372 */
7373 static int
7374term_and_job_init(
7375 term_T *term,
7376 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007377 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007378 jobopt_T *opt,
7379 jobopt_T *orig_opt)
7380{
7381 int use_winpty = FALSE;
7382 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007383 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007384
7385 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7386 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7387
7388 if (!has_winpty && !has_conpty)
7389 // If neither is available give the errors for winpty, since when
7390 // conpty is not available it can't be installed either.
7391 return dyn_winpty_init(TRUE);
7392
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007393 if (opt->jo_tty_type != NUL)
7394 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007395
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007396 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007397 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007398 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007399 use_conpty = TRUE;
7400 else if (has_winpty)
7401 use_winpty = TRUE;
7402 // else: error
7403 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007404 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007405 {
7406 if (has_winpty)
7407 use_winpty = TRUE;
7408 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007409 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007410 {
7411 if (has_conpty)
7412 use_conpty = TRUE;
7413 else
7414 return dyn_conpty_init(TRUE);
7415 }
7416
7417 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007418 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007419
7420 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007421 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007422
7423 // error
7424 return dyn_winpty_init(TRUE);
7425}
7426
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007427 static int
7428create_pty_only(term_T *term, jobopt_T *options)
7429{
7430 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7431 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7432 char in_name[80], out_name[80];
7433 channel_T *channel = NULL;
7434
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007435 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7436 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007437
7438 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7439 GetCurrentProcessId(),
7440 curbuf->b_fnum);
7441 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7442 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7443 PIPE_UNLIMITED_INSTANCES,
7444 0, 0, NMPWAIT_NOWAIT, NULL);
7445 if (hPipeIn == INVALID_HANDLE_VALUE)
7446 goto failed;
7447
7448 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7449 GetCurrentProcessId(),
7450 curbuf->b_fnum);
7451 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7452 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7453 PIPE_UNLIMITED_INSTANCES,
7454 0, 0, 0, NULL);
7455 if (hPipeOut == INVALID_HANDLE_VALUE)
7456 goto failed;
7457
7458 ConnectNamedPipe(hPipeIn, NULL);
7459 ConnectNamedPipe(hPipeOut, NULL);
7460
7461 term->tl_job = job_alloc();
7462 if (term->tl_job == NULL)
7463 goto failed;
7464 ++term->tl_job->jv_refcount;
7465
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007466 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007467 term->tl_job->jv_status = JOB_FINISHED;
7468
7469 channel = add_channel();
7470 if (channel == NULL)
7471 goto failed;
7472 term->tl_job->jv_channel = channel;
7473 channel->ch_keep_open = TRUE;
7474 channel->ch_named_pipe = TRUE;
7475
7476 channel_set_pipes(channel,
7477 (sock_T)hPipeIn,
7478 (sock_T)hPipeOut,
7479 (sock_T)hPipeOut);
7480 channel_set_job(channel, term->tl_job, options);
7481 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7482 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7483
7484 return OK;
7485
7486failed:
7487 if (hPipeIn != NULL)
7488 CloseHandle(hPipeIn);
7489 if (hPipeOut != NULL)
7490 CloseHandle(hPipeOut);
7491 return FAIL;
7492}
7493
7494/*
7495 * Free the terminal emulator part of "term".
7496 */
7497 static void
7498term_free_vterm(term_T *term)
7499{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007500 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007501 if (term->tl_winpty != NULL)
7502 winpty_free(term->tl_winpty);
7503 term->tl_winpty = NULL;
7504 if (term->tl_winpty_config != NULL)
7505 winpty_config_free(term->tl_winpty_config);
7506 term->tl_winpty_config = NULL;
7507 if (term->tl_vterm != NULL)
7508 vterm_free(term->tl_vterm);
7509 term->tl_vterm = NULL;
7510}
7511
7512/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007513 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007514 */
7515 static void
7516term_report_winsize(term_T *term, int rows, int cols)
7517{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007518 if (term->tl_conpty)
7519 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007520 if (term->tl_winpty)
7521 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7522}
7523
7524 int
7525terminal_enabled(void)
7526{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007527 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007528}
7529
7530# else
7531
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007532///////////////////////////////////////
7533// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007534
7535/*
7536 * Create a new terminal of "rows" by "cols" cells.
7537 * Start job for "cmd".
7538 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007539 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007540 * Return OK or FAIL.
7541 */
7542 static int
7543term_and_job_init(
7544 term_T *term,
7545 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007546 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007547 jobopt_T *opt,
7548 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007549{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007550 term->tl_arg0_cmd = NULL;
7551
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007552 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7553 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007554
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007555#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007556 if (term_use_palette())
7557 {
7558 if (term->tl_palette != NULL)
7559 set_vterm_palette(term->tl_vterm, term->tl_palette);
7560 else
7561 init_vterm_ansi_colors(term->tl_vterm);
7562 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007563#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007564
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007565 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007566 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007567 if (term->tl_job != NULL)
7568 ++term->tl_job->jv_refcount;
7569
7570 return term->tl_job != NULL
7571 && term->tl_job->jv_channel != NULL
7572 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7573}
7574
7575 static int
7576create_pty_only(term_T *term, jobopt_T *opt)
7577{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007578 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7579 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007580
7581 term->tl_job = job_alloc();
7582 if (term->tl_job == NULL)
7583 return FAIL;
7584 ++term->tl_job->jv_refcount;
7585
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007586 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007587 term->tl_job->jv_status = JOB_FINISHED;
7588
7589 return mch_create_pty_channel(term->tl_job, opt);
7590}
7591
7592/*
7593 * Free the terminal emulator part of "term".
7594 */
7595 static void
7596term_free_vterm(term_T *term)
7597{
7598 if (term->tl_vterm != NULL)
7599 vterm_free(term->tl_vterm);
7600 term->tl_vterm = NULL;
7601}
7602
7603/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007604 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007605 */
7606 static void
7607term_report_winsize(term_T *term, int rows, int cols)
7608{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007609 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007610 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
7611 {
7612 int fd = -1;
7613 int part;
7614
7615 for (part = PART_OUT; part < PART_COUNT; ++part)
7616 {
7617 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01007618 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007619 break;
7620 }
7621 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7622 mch_signal_job(term->tl_job, (char_u *)"winch");
7623 }
7624}
7625
7626# endif
7627
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007628#endif // FEAT_TERMINAL