blob: fddd087c9b279969cec22f3b87cb875cbdcf8f94 [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 Moolenaar0ce74132018-06-18 22:15:50 +02001289 update_screen(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 }
2020 redraw_win_later(wp, 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);
2139 redraw_buf_and_status_later(curbuf, NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002140#ifdef FEAT_PROP_POPUP
2141 if (WIN_IS_POPUP(curwin))
Bram Moolenaard5bc32d2020-03-22 19:25:50 +01002142 redraw_later(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 Moolenaar6eddadf2018-05-06 16:40:16 +02003018 redraw_buf_later(term->tl_buffer, 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 Moolenaar2e6ab182017-09-20 10:03:07 +02003071 redraw_buf_later(term->tl_buffer, NOT_VALID);
3072 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)
3156 maketitle();
3157 break;
3158
3159 case VTERM_PROP_CURSORVISIBLE:
3160 term->tl_cursor_visible = value->boolean;
3161 may_toggle_cursor(term);
3162 out_flush();
3163 break;
3164
3165 case VTERM_PROP_CURSORBLINK:
3166 term->tl_cursor_blink = value->boolean;
3167 may_set_cursor_props(term);
3168 break;
3169
3170 case VTERM_PROP_CURSORSHAPE:
3171 term->tl_cursor_shape = value->number;
3172 may_set_cursor_props(term);
3173 break;
3174
3175 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003176 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003177 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003178 if (strval == NULL)
3179 break;
3180 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003181 may_set_cursor_props(term);
3182 break;
3183
3184 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003185 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003186 term->tl_using_altscreen = value->boolean;
3187 break;
3188
3189 default:
3190 break;
3191 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003192 vim_free(strval);
3193
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003194 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003195 return 1;
3196}
3197
3198/*
3199 * The job running in the terminal resized the terminal.
3200 */
3201 static int
3202handle_resize(int rows, int cols, void *user)
3203{
3204 term_T *term = (term_T *)user;
3205 win_T *wp;
3206
3207 term->tl_rows = rows;
3208 term->tl_cols = cols;
3209 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003210 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003211 term->tl_vterm_size_changed = FALSE;
3212 else
3213 {
3214 FOR_ALL_WINDOWS(wp)
3215 {
3216 if (wp->w_buffer == term->tl_buffer)
3217 {
3218 win_setheight_win(rows, wp);
3219 win_setwidth_win(cols, wp);
3220 }
3221 }
3222 redraw_buf_later(term->tl_buffer, NOT_VALID);
3223 }
3224 return 1;
3225}
3226
3227/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003228 * If the number of lines that are stored goes over 'termscrollback' then
3229 * delete the first 10%.
3230 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3231 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003232 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003233 static void
3234limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003235{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003236 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003237 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003238 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003239 int i;
3240
3241 curbuf = term->tl_buffer;
3242 for (i = 0; i < todo; ++i)
3243 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003244 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3245 if (update_buffer)
Bram Moolenaarca70c072020-05-30 20:30:46 +02003246 ml_delete(1);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003247 }
3248 curbuf = curwin->w_buffer;
3249
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003250 gap->ga_len -= todo;
3251 mch_memmove(gap->ga_data,
3252 (sb_line_T *)gap->ga_data + todo,
3253 sizeof(sb_line_T) * gap->ga_len);
3254 if (update_buffer)
3255 term->tl_scrollback_scrolled -= todo;
3256 }
3257}
3258
3259/*
3260 * Handle a line that is pushed off the top of the screen.
3261 */
3262 static int
3263handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3264{
3265 term_T *term = (term_T *)user;
3266 garray_T *gap;
3267 int update_buffer;
3268
3269 if (term->tl_normal_mode)
3270 {
3271 // In Terminal-Normal mode the user interacts with the buffer, thus we
3272 // must not change it. Postpone adding the scrollback lines.
3273 gap = &term->tl_scrollback_postponed;
3274 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003275 }
3276 else
3277 {
3278 // First remove the lines that were appended before, the pushed line
3279 // goes above it.
3280 cleanup_scrollback(term);
3281 gap = &term->tl_scrollback;
3282 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003283 }
3284
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003285 limit_scrollback(term, gap, update_buffer);
3286
3287 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003288 {
3289 cellattr_T *p = NULL;
3290 int len = 0;
3291 int i;
3292 int c;
3293 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003294 int text_len;
3295 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003296 sb_line_T *line;
3297 garray_T ga;
3298 cellattr_T fill_attr = term->tl_default_color;
3299
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003300 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003301 for (i = 0; i < cols; ++i)
3302 if (cells[i].chars[0] != 0)
3303 len = i + 1;
3304 else
3305 cell2cellattr(&cells[i], &fill_attr);
3306
3307 ga_init2(&ga, 1, 100);
3308 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003309 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003310 if (p != NULL)
3311 {
3312 for (col = 0; col < len; col += cells[col].width)
3313 {
3314 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3315 {
3316 ga.ga_len = 0;
3317 break;
3318 }
3319 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3320 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3321 (char_u *)ga.ga_data + ga.ga_len);
3322 cell2cellattr(&cells[col], &p[col]);
3323 }
3324 }
3325 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003326 {
3327 if (update_buffer)
3328 text = (char_u *)"";
3329 else
3330 text = vim_strsave((char_u *)"");
3331 text_len = 0;
3332 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003333 else
3334 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003335 text = ga.ga_data;
3336 text_len = ga.ga_len;
3337 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003338 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003339 if (update_buffer)
3340 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003341
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003342 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003343 line->sb_cols = len;
3344 line->sb_cells = p;
3345 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003346 if (update_buffer)
3347 {
3348 line->sb_text = NULL;
3349 ++term->tl_scrollback_scrolled;
3350 ga_clear(&ga); // free the text
3351 }
3352 else
3353 {
3354 line->sb_text = text;
3355 ga_init(&ga); // text is kept in tl_scrollback_postponed
3356 }
3357 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003358 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003359 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003360}
3361
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003362/*
3363 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3364 * received and stored in tl_scrollback_postponed.
3365 */
3366 static void
3367handle_postponed_scrollback(term_T *term)
3368{
3369 int i;
3370
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003371 if (term->tl_scrollback_postponed.ga_len == 0)
3372 return;
3373 ch_log(NULL, "Moving postponed scrollback to scrollback");
3374
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003375 // First remove the lines that were appended before, the pushed lines go
3376 // above it.
3377 cleanup_scrollback(term);
3378
3379 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3380 {
3381 char_u *text;
3382 sb_line_T *pp_line;
3383 sb_line_T *line;
3384
3385 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3386 break;
3387 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3388
3389 text = pp_line->sb_text;
3390 if (text == NULL)
3391 text = (char_u *)"";
3392 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3393 vim_free(pp_line->sb_text);
3394
3395 line = (sb_line_T *)term->tl_scrollback.ga_data
3396 + term->tl_scrollback.ga_len;
3397 line->sb_cols = pp_line->sb_cols;
3398 line->sb_cells = pp_line->sb_cells;
3399 line->sb_fill_attr = pp_line->sb_fill_attr;
3400 line->sb_text = NULL;
3401 ++term->tl_scrollback_scrolled;
3402 ++term->tl_scrollback.ga_len;
3403 }
3404
3405 ga_clear(&term->tl_scrollback_postponed);
3406 limit_scrollback(term, &term->tl_scrollback, TRUE);
3407}
3408
LemonBoy77771d32022-04-13 11:47:25 +01003409/*
3410 * Called when the terminal wants to ring the system bell.
3411 */
3412 static int
3413handle_bell(void *user UNUSED)
3414{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003415 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003416 return 0;
3417}
3418
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003419static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003420 handle_damage, // damage
3421 handle_moverect, // moverect
3422 handle_movecursor, // movecursor
3423 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003424 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003425 handle_resize, // resize
3426 handle_pushline, // sb_pushline
3427 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003428};
3429
3430/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003431 * Do the work after the channel of a terminal was closed.
3432 * Must be called only when updating_screen is FALSE.
3433 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3434 */
3435 static int
3436term_after_channel_closed(term_T *term)
3437{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003438 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003439 if (!term->tl_normal_mode)
3440 {
3441 int fnum = term->tl_buffer->b_fnum;
3442
3443 cleanup_vterm(term);
3444
3445 if (term->tl_finish == TL_FINISH_CLOSE)
3446 {
3447 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003448 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003449#ifdef FEAT_PROP_POPUP
3450 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003451
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003452 // If this was a terminal in a popup window, go back to the
3453 // previous window.
3454 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3455 {
3456 pwin = curwin;
3457 if (win_valid(prevwin))
3458 win_enter(prevwin, FALSE);
3459 }
3460 else
3461#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003462 // If this is the last normal window: exit Vim.
3463 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3464 {
3465 exarg_T ea;
3466
Bram Moolenaara80faa82020-04-12 19:37:17 +02003467 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003468 ex_quit(&ea);
3469 return TRUE;
3470 }
3471
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003472 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003473 ch_log(NULL, "terminal job finished, closing window");
3474 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003475 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003476 if (curwin == aucmd_win)
3477 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003478 if (do_set_w_closing)
3479 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003480 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003481 if (do_set_w_closing)
3482 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003483 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003484#ifdef FEAT_PROP_POPUP
3485 if (pwin != NULL)
3486 popup_close_with_retval(pwin, 0);
3487#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003488 return TRUE;
3489 }
3490 if (term->tl_finish == TL_FINISH_OPEN
3491 && term->tl_buffer->b_nwindows == 0)
3492 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003493 char *cmd = term->tl_opencmd == NULL
3494 ? "botright sbuf %d"
3495 : (char *)term->tl_opencmd;
3496 size_t len = strlen(cmd) + 50;
3497 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003498
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003499 if (buf != NULL)
3500 {
3501 ch_log(NULL, "terminal job finished, opening window");
3502 vim_snprintf(buf, len, cmd, fnum);
3503 do_cmdline_cmd((char_u *)buf);
3504 vim_free(buf);
3505 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003506 }
3507 else
3508 ch_log(NULL, "terminal job finished");
3509 }
3510
3511 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3512 return FALSE;
3513}
3514
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003515#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3516/*
3517 * If the current window is a terminal in a popup window and the job has
3518 * finished, close the popup window and to back to the previous window.
3519 * Otherwise return FAIL.
3520 */
3521 int
3522may_close_term_popup(void)
3523{
3524 if (popup_is_popup(curwin) && curbuf->b_term != NULL
Bram Moolenaar9e636b92022-05-29 22:37:05 +01003525 && !term_job_running_not_none(curbuf->b_term))
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003526 {
3527 win_T *pwin = curwin;
3528
3529 if (win_valid(prevwin))
3530 win_enter(prevwin, FALSE);
3531 popup_close_with_retval(pwin, 0);
3532 return OK;
3533 }
3534 return FAIL;
3535}
3536#endif
3537
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003538/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003539 * Called when a channel is going to be closed, before invoking the close
3540 * callback.
3541 */
3542 void
3543term_channel_closing(channel_T *ch)
3544{
3545 term_T *term;
3546
3547 for (term = first_term; term != NULL; term = term->tl_next)
3548 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3549 term->tl_channel_closing = TRUE;
3550}
3551
3552/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003553 * Called when a channel has been closed.
3554 * If this was a channel for a terminal window then finish it up.
3555 */
3556 void
3557term_channel_closed(channel_T *ch)
3558{
3559 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003560 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003561 int did_one = FALSE;
3562
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003563 for (term = first_term; term != NULL; term = next_term)
3564 {
3565 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003566 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003567 {
3568 term->tl_channel_closed = TRUE;
3569 did_one = TRUE;
3570
Bram Moolenaard23a8232018-02-10 18:45:26 +01003571 VIM_CLEAR(term->tl_title);
3572 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003573#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003574 if (term->tl_out_fd != NULL)
3575 {
3576 fclose(term->tl_out_fd);
3577 term->tl_out_fd = NULL;
3578 }
3579#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003580
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003581 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003582 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003583 // Cannot open or close windows now. Can happen when
3584 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003585 term->tl_channel_recently_closed = TRUE;
3586 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003587 }
3588
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003589 if (term_after_channel_closed(term))
3590 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003591 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003592 }
3593
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003594 if (did_one)
3595 {
3596 redraw_statuslines();
3597
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003598 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003599 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003600 typebuf_was_filled = TRUE;
3601
3602 term = curbuf->b_term;
3603 if (term != NULL)
3604 {
3605 if (term->tl_job == ch->ch_job)
3606 maketitle();
3607 update_cursor(term, term->tl_cursor_visible);
3608 }
3609 }
3610}
3611
3612/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003613 * To be called after resetting updating_screen: handle any terminal where the
3614 * channel was closed.
3615 */
3616 void
3617term_check_channel_closed_recently()
3618{
3619 term_T *term;
3620 term_T *next_term;
3621
3622 for (term = first_term; term != NULL; term = next_term)
3623 {
3624 next_term = term->tl_next;
3625 if (term->tl_channel_recently_closed)
3626 {
3627 term->tl_channel_recently_closed = FALSE;
3628 if (term_after_channel_closed(term))
3629 // start over, the list may have changed
3630 next_term = first_term;
3631 }
3632 }
3633}
3634
3635/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003636 * Fill one screen line from a line of the terminal.
3637 * Advances "pos" to past the last column.
3638 */
3639 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003640term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003641 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003642 win_T *wp,
3643 VTermScreen *screen,
3644 VTermPos *pos,
3645 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003646{
3647 int off = screen_get_current_line_off();
3648
3649 for (pos->col = 0; pos->col < max_col; )
3650 {
3651 VTermScreenCell cell;
3652 int c;
3653
3654 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003655 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003656
3657 c = cell.chars[0];
3658 if (c == NUL)
3659 {
3660 ScreenLines[off] = ' ';
3661 if (enc_utf8)
3662 ScreenLinesUC[off] = NUL;
3663 }
3664 else
3665 {
3666 if (enc_utf8)
3667 {
3668 int i;
3669
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003670 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003671 for (i = 0; i < Screen_mco
3672 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3673 {
3674 ScreenLinesC[i][off] = cell.chars[i + 1];
3675 if (cell.chars[i + 1] == 0)
3676 break;
3677 }
3678 if (c >= 0x80 || (Screen_mco > 0
3679 && ScreenLinesC[0][off] != 0))
3680 {
3681 ScreenLines[off] = ' ';
3682 ScreenLinesUC[off] = c;
3683 }
3684 else
3685 {
3686 ScreenLines[off] = c;
3687 ScreenLinesUC[off] = NUL;
3688 }
3689 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003690#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003691 else if (has_mbyte && c >= 0x80)
3692 {
3693 char_u mb[MB_MAXBYTES+1];
3694 WCHAR wc = c;
3695
3696 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3697 (char*)mb, 2, 0, 0) > 1)
3698 {
3699 ScreenLines[off] = mb[0];
3700 ScreenLines[off + 1] = mb[1];
3701 cell.width = mb_ptr2cells(mb);
3702 }
3703 else
3704 ScreenLines[off] = c;
3705 }
3706#endif
3707 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003708 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003709 ScreenLines[off] = c;
3710 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003711 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3712 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003713
3714 ++pos->col;
3715 ++off;
3716 if (cell.width == 2)
3717 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003718 // don't set the second byte to NUL for a DBCS encoding, it
3719 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003720 if (enc_utf8)
3721 {
3722 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003723 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003724 }
3725 else if (!has_mbyte)
3726 {
3727 // Can't show a double-width character with a single-byte
3728 // 'encoding', just use a space.
3729 ScreenLines[off] = ' ';
3730 ScreenAttrs[off] = ScreenAttrs[off - 1];
3731 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003732
3733 ++pos->col;
3734 ++off;
3735 }
3736 }
3737}
3738
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003739#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003740 static void
3741update_system_term(term_T *term)
3742{
3743 VTermPos pos;
3744 VTermScreen *screen;
3745
3746 if (term->tl_vterm == NULL)
3747 return;
3748 screen = vterm_obtain_screen(term->tl_vterm);
3749
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003750 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003751 while (term->tl_toprow > 0
3752 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3753 {
3754 int save_p_more = p_more;
3755
3756 p_more = FALSE;
3757 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003758 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003759 p_more = save_p_more;
3760 --term->tl_toprow;
3761 }
3762
3763 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3764 && pos.row < Rows; ++pos.row)
3765 {
3766 if (pos.row < term->tl_rows)
3767 {
3768 int max_col = MIN(Columns, term->tl_cols);
3769
Bram Moolenaar83d47902020-03-26 20:34:00 +01003770 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003771 }
3772 else
3773 pos.col = 0;
3774
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003775 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003776 }
3777
3778 term->tl_dirty_row_start = MAX_ROW;
3779 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003780}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003781#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003782
3783/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003784 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3785 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003786 * Terminal-Normal mode.
3787 */
3788 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003789term_do_update_window(win_T *wp)
3790{
3791 term_T *term = wp->w_buffer->b_term;
3792
3793 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3794}
3795
3796/*
3797 * Called to update a window that contains an active terminal.
3798 */
3799 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003800term_update_window(win_T *wp)
3801{
3802 term_T *term = wp->w_buffer->b_term;
3803 VTerm *vterm;
3804 VTermScreen *screen;
3805 VTermState *state;
3806 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003807 int rows, cols;
3808 int newrows, newcols;
3809 int minsize;
3810 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003811
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003812 vterm = term->tl_vterm;
3813 screen = vterm_obtain_screen(vterm);
3814 state = vterm_obtain_state(vterm);
3815
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003816 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3817 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003818 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003819 {
3820 term->tl_dirty_row_start = 0;
3821 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003822
3823 if (term->tl_postponed_scroll > 0
3824 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003825 // Scrolling is usually faster than redrawing, when there are only
3826 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003827 term_scroll_up(term, 0, term->tl_postponed_scroll);
3828 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003829 }
3830
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003831 /*
3832 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003833 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003834 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003835 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003836
Bram Moolenaar498c2562018-04-15 23:45:15 +02003837 newrows = 99999;
3838 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003839 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003840 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003841 // Always use curwin, it may be a popup window.
3842 win_T *wwp = twp == NULL ? curwin : twp;
3843
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003844 // When more than one window shows the same terminal, use the
3845 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003846 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003847 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003848 newrows = MIN(newrows, wwp->w_height);
3849 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003850 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003851 if (twp == NULL)
3852 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003853 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003854 if (newrows == 99999 || newcols == 99999)
3855 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003856 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3857 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3858
Bram Moolenaareba13e42021-02-23 17:47:23 +01003859 // If no cell is visible there is no point in resizing. Also, vterm can't
3860 // handle a zero height.
3861 if (newrows == 0 || newcols == 0)
3862 return;
3863
Bram Moolenaar498c2562018-04-15 23:45:15 +02003864 if (term->tl_rows != newrows || term->tl_cols != newcols)
3865 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003866 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003867 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003868 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003869 newrows);
3870 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003871
3872 // Updating the terminal size will cause the snapshot to be cleared.
3873 // When not in terminal_loop() we need to restore it.
3874 if (term != in_terminal_loop)
3875 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003876 }
3877
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003878 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003879 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003880 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003881
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003882 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3883 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003884 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003885 if (pos.row < term->tl_rows)
3886 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003887 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003888
Bram Moolenaar83d47902020-03-26 20:34:00 +01003889 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003890 }
3891 else
3892 pos.col = 0;
3893
Bram Moolenaarf118d482018-03-13 13:14:00 +01003894 screen_line(wp->w_winrow + pos.row
3895#ifdef FEAT_MENU
3896 + winbar_height(wp)
3897#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003898 , wp->w_wincol, pos.col, wp->w_width,
3899#ifdef FEAT_PROP_POPUP
3900 popup_is_popup(wp) ? SLF_POPUP :
3901#endif
3902 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003903 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00003904}
3905
3906/*
3907 * Called after updating all windows: may reset dirty rows.
3908 */
3909 void
3910term_did_update_window(win_T *wp)
3911{
3912 term_T *term = wp->w_buffer->b_term;
3913
3914 if (term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode
3915 && wp->w_redr_type == 0)
3916 {
3917 term->tl_dirty_row_start = MAX_ROW;
3918 term->tl_dirty_row_end = 0;
3919 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003920}
3921
3922/*
3923 * Return TRUE if "wp" is a terminal window where the job has finished.
3924 */
3925 int
3926term_is_finished(buf_T *buf)
3927{
3928 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3929}
3930
3931/*
3932 * Return TRUE if "wp" is a terminal window where the job has finished or we
3933 * are in Terminal-Normal mode, thus we show the buffer contents.
3934 */
3935 int
3936term_show_buffer(buf_T *buf)
3937{
3938 term_T *term = buf->b_term;
3939
3940 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3941}
3942
3943/*
3944 * The current buffer is going to be changed. If there is terminal
3945 * highlighting remove it now.
3946 */
3947 void
3948term_change_in_curbuf(void)
3949{
3950 term_T *term = curbuf->b_term;
3951
3952 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3953 {
3954 free_scrollback(term);
3955 redraw_buf_later(term->tl_buffer, NOT_VALID);
3956
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003957 // The buffer is now like a normal buffer, it cannot be easily
3958 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003959 set_string_option_direct((char_u *)"buftype", -1,
3960 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3961 }
3962}
3963
3964/*
3965 * Get the screen attribute for a position in the buffer.
3966 * Use a negative "col" to get the filler background color.
3967 */
3968 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003969term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003970{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003971 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003972 term_T *term = buf->b_term;
3973 sb_line_T *line;
3974 cellattr_T *cellattr;
3975
3976 if (lnum > term->tl_scrollback.ga_len)
3977 cellattr = &term->tl_default_color;
3978 else
3979 {
3980 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3981 if (col < 0 || col >= line->sb_cols)
3982 cellattr = &line->sb_fill_attr;
3983 else
3984 cellattr = line->sb_cells + col;
3985 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003986 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003987}
3988
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003989/*
3990 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003991 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003992 */
3993 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003994cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003995{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003996 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
3997 if (rgb->index == 0)
3998 rgb->type = VTERM_COLOR_RGB;
3999 else
4000 {
4001 rgb->type = VTERM_COLOR_INDEXED;
4002 --rgb->index;
4003 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004004}
4005
4006/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004007 * Initialize vterm color from the synID.
4008 * Returns TRUE if color is set to "fg" and "bg".
4009 * Otherwise returns FALSE.
4010 */
4011 static int
4012get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4013{
4014#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4015 // Use the actual color for the GUI and when 'termguicolors' is set.
4016 if (0
4017# ifdef FEAT_GUI
4018 || gui.in_use
4019# endif
4020# ifdef FEAT_TERMGUICOLORS
4021 || p_tgc
4022# ifdef FEAT_VTP
4023 // Finally get INVALCOLOR on this execution path
4024 || (!p_tgc && t_colors >= 256)
4025# endif
4026# endif
4027 )
4028 {
4029 guicolor_T fg_rgb = INVALCOLOR;
4030 guicolor_T bg_rgb = INVALCOLOR;
4031
4032 if (id > 0)
4033 syn_id2colors(id, &fg_rgb, &bg_rgb);
4034
4035 if (fg_rgb != INVALCOLOR)
4036 {
4037 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4038 fg->red = (unsigned)(rgb >> 16);
4039 fg->green = (unsigned)(rgb >> 8) & 255;
4040 fg->blue = (unsigned)rgb & 255;
4041 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4042 }
4043 else
4044 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4045
4046 if (bg_rgb != INVALCOLOR)
4047 {
4048 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4049 bg->red = (unsigned)(rgb >> 16);
4050 bg->green = (unsigned)(rgb >> 8) & 255;
4051 bg->blue = (unsigned)rgb & 255;
4052 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4053 }
4054 else
4055 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4056
4057 return TRUE;
4058 }
4059 else
4060#endif
4061 if (t_colors >= 16)
4062 {
4063 int cterm_fg = -1;
4064 int cterm_bg = -1;
4065
4066 if (id > 0)
4067 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4068
4069 if (cterm_fg >= 0)
4070 {
4071 cterm_color2vterm(cterm_fg, fg);
4072 fg->type |= VTERM_COLOR_DEFAULT_FG;
4073 }
4074 else
4075 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4076
4077 if (cterm_bg >= 0)
4078 {
4079 cterm_color2vterm(cterm_bg, bg);
4080 bg->type |= VTERM_COLOR_DEFAULT_BG;
4081 }
4082 else
4083 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4084
4085 return TRUE;
4086 }
4087
4088 return FALSE;
4089}
4090
4091 void
4092term_reset_wincolor(win_T *wp)
4093{
4094 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4095 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4096}
4097
4098/*
4099 * Cache the color of 'wincolor'.
4100 */
4101 void
4102term_update_wincolor(win_T *wp)
4103{
4104 int id = 0;
4105
4106 if (*wp->w_p_wcr != NUL)
4107 id = syn_name2id(wp->w_p_wcr);
4108 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4109 &wp->w_term_wincolor.bg))
4110 term_reset_wincolor(wp);
4111}
4112
4113/*
4114 * Called when option 'termguicolors' was set,
4115 * or when any highlight is changed.
4116 */
4117 void
4118term_update_wincolor_all()
4119{
4120 win_T *wp = NULL;
4121 int did_curwin = FALSE;
4122
4123 while (for_all_windows_and_curwin(&wp, &did_curwin))
4124 term_update_wincolor(wp);
4125}
4126
4127/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004128 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004129 */
4130 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004131init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004132{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004133 VTermColor *fg, *bg;
4134 int fgval, bgval;
4135 int id;
4136
Bram Moolenaara80faa82020-04-12 19:37:17 +02004137 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004138 term->tl_default_color.width = 1;
4139 fg = &term->tl_default_color.fg;
4140 bg = &term->tl_default_color.bg;
4141
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004142 // Vterm uses a default black background. Set it to white when
4143 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004144 if (*p_bg == 'l')
4145 {
4146 fgval = 0;
4147 bgval = 255;
4148 }
4149 else
4150 {
4151 fgval = 255;
4152 bgval = 0;
4153 }
4154 fg->red = fg->green = fg->blue = fgval;
4155 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004156 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4157 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004158
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004159 // The highlight group overrules the defaults.
4160 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004161
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004162 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004163 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004164#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004165 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004166#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004167
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004168 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004169 if (cterm_normal_fg_color > 0)
4170 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004171 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004172# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4173# ifdef VIMDLL
4174 if (!gui.in_use)
4175# endif
4176 {
4177 tmp = fg->red;
4178 fg->red = fg->blue;
4179 fg->blue = tmp;
4180 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004181# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004182 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004183# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004184 else
4185 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004186# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004187
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004188 if (cterm_normal_bg_color > 0)
4189 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004190 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004191# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4192# ifdef VIMDLL
4193 if (!gui.in_use)
4194# endif
4195 {
4196 tmp = fg->red;
4197 fg->red = fg->blue;
4198 fg->blue = tmp;
4199 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004200# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004201 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004202# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004203 else
4204 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004205# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004206 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004207}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004208
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004209#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4210/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004211 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4212 * "ansi_colors" argument in term_start()) shall be applied.
4213 */
4214 static int
4215term_use_palette()
4216{
4217 if (0
4218#ifdef FEAT_GUI
4219 || gui.in_use
4220#endif
4221#ifdef FEAT_TERMGUICOLORS
4222 || p_tgc
4223#endif
4224 )
4225 return TRUE;
4226 return FALSE;
4227}
4228
4229/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004230 * Set the 16 ANSI colors from array of RGB values
4231 */
4232 static void
4233set_vterm_palette(VTerm *vterm, long_u *rgb)
4234{
4235 int index = 0;
4236 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004237
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004238 for (; index < 16; index++)
4239 {
4240 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004241
Millyb771b6b2021-11-23 12:07:25 +00004242 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004243 color.red = (unsigned)(rgb[index] >> 16);
4244 color.green = (unsigned)(rgb[index] >> 8) & 255;
4245 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004246 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004247 vterm_state_set_palette_color(state, index, &color);
4248 }
4249}
4250
4251/*
4252 * Set the ANSI color palette from a list of colors
4253 */
4254 static int
4255set_ansi_colors_list(VTerm *vterm, list_T *list)
4256{
4257 int n = 0;
4258 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004259 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004260
Bram Moolenaarb0992022020-01-30 14:55:42 +01004261 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004262 {
4263 char_u *color_name;
4264 guicolor_T guicolor;
4265
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004266 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004267 if (color_name == NULL)
4268 return FAIL;
4269
4270 guicolor = GUI_GET_COLOR(color_name);
4271 if (guicolor == INVALCOLOR)
4272 return FAIL;
4273
4274 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4275 }
4276
4277 if (n != 16 || li != NULL)
4278 return FAIL;
4279
4280 set_vterm_palette(vterm, rgb);
4281
4282 return OK;
4283}
4284
4285/*
4286 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4287 */
4288 static void
4289init_vterm_ansi_colors(VTerm *vterm)
4290{
4291 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4292
LemonBoyb2b3acb2022-05-20 10:10:34 +01004293 if (var == NULL)
4294 return;
4295
4296 if (var->di_tv.v_type != VAR_LIST
4297 || var->di_tv.vval.v_list == NULL
4298 || var->di_tv.vval.v_list->lv_first == &range_list_item
4299 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004300 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004301}
4302#endif
4303
Bram Moolenaar52acb112018-03-18 19:20:22 +01004304/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004305 * Handles a "drop" command from the job in the terminal.
4306 * "item" is the file name, "item->li_next" may have options.
4307 */
4308 static void
4309handle_drop_command(listitem_T *item)
4310{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004311 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004312 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004313 int bufnr;
4314 win_T *wp;
4315 tabpage_T *tp;
4316 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004317 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004318
4319 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4320 FOR_ALL_TAB_WINDOWS(tp, wp)
4321 {
4322 if (wp->w_buffer->b_fnum == bufnr)
4323 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004324 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004325 goto_tabpage_win(tp, wp);
4326 return;
4327 }
4328 }
4329
Bram Moolenaara80faa82020-04-12 19:37:17 +02004330 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004331
4332 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4333 && opt_item->li_tv.vval.v_dict != NULL)
4334 {
4335 dict_T *dict = opt_item->li_tv.vval.v_dict;
4336 char_u *p;
4337
Bram Moolenaar8f667172018-12-14 15:38:31 +01004338 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004339 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004340 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004341 if (p != NULL)
4342 {
4343 if (check_ff_value(p) == FAIL)
4344 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4345 else
4346 ea.force_ff = *p;
4347 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01004348 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004349 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004350 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004351 if (p != NULL)
4352 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004353 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004354 if (ea.cmd != NULL)
4355 {
4356 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4357 ea.force_enc = 11;
4358 tofree = ea.cmd;
4359 }
4360 }
4361
Bram Moolenaar8f667172018-12-14 15:38:31 +01004362 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004363 if (p != NULL)
4364 get_bad_opt(p, &ea);
4365
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004366 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004367 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004368 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004369 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004370 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004371 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004372 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004373 ea.force_bin = FORCE_NOBIN;
4374 }
4375
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004376 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004377 if (ea.cmd == NULL)
4378 ea.cmd = (char_u *)"split";
4379 ea.arg = fname;
4380 ea.cmdidx = CMD_split;
4381 ex_splitview(&ea);
4382
4383 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004384}
4385
4386/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004387 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4388 */
4389 static int
4390is_permitted_term_api(char_u *func, char_u *pat)
4391{
4392 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4393}
4394
4395/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004396 * Handles a function call from the job running in a terminal.
4397 * "item" is the function name, "item->li_next" has the arguments.
4398 */
4399 static void
4400handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4401{
4402 char_u *func;
4403 typval_T argvars[2];
4404 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004405 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004406
4407 if (item->li_next == NULL)
4408 {
4409 ch_log(channel, "Missing function arguments for call");
4410 return;
4411 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004412 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004413
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004414 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004415 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004416 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004417 return;
4418 }
4419
4420 argvars[0].v_type = VAR_NUMBER;
4421 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4422 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004423 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004424 funcexe.fe_firstline = 1L;
4425 funcexe.fe_lastline = 1L;
4426 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004427 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004428 {
4429 clear_tv(&rettv);
4430 ch_log(channel, "Function %s called", func);
4431 }
4432 else
4433 ch_log(channel, "Calling function %s failed", func);
4434}
4435
4436/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004437 * URL decoding (also know as Percent-encoding).
4438 *
4439 * Note this function currently is only used for decoding shell's
4440 * OSC 7 escape sequence which we can assume all bytes are valid
4441 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4442 * encoding bytes like 0xfe, 0xff.
4443 */
4444 static size_t
4445url_decode(const char *src, const size_t len, char_u *dst)
4446{
4447 size_t i = 0, j = 0;
4448
4449 while (i < len)
4450 {
4451 if (src[i] == '%' && i + 2 < len)
4452 {
4453 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4454 j++;
4455 i += 3;
4456 }
4457 else
4458 {
4459 dst[j] = src[i];
4460 i++;
4461 j++;
4462 }
4463 }
4464 dst[j] = '\0';
4465 return j;
4466}
4467
4468/*
4469 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4470 *
4471 * The OSC 7 sequence has the format of
4472 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4473 * and what VTerm provides via VTermStringFragment is
4474 * "file://HOSTNAME/CURRENT/DIR"
4475 */
4476 static void
4477sync_shell_dir(VTermStringFragment *frag)
4478{
4479 int offset = 7; // len of "file://" is 7
4480 char *pos = (char *)frag->str + offset;
4481 char_u *new_dir;
4482
4483 // remove HOSTNAME to get PWD
Bram Moolenaar918b0892021-05-08 20:09:24 +02004484 while (*pos != '/' && offset < (int)frag->len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004485 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004486 offset += 1;
4487 pos += 1;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004488 }
4489
Bram Moolenaar918b0892021-05-08 20:09:24 +02004490 if (offset >= (int)frag->len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004491 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004492 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004493 frag->str);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004494 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004495 }
4496
4497 new_dir = alloc(frag->len - offset + 1);
4498 url_decode(pos, frag->len-offset, new_dir);
4499 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4500 vim_free(new_dir);
4501}
4502
4503/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004504 * Called by libvterm when it cannot recognize an OSC sequence.
4505 * We recognize a terminal API command.
4506 */
4507 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004508parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004509{
4510 term_T *term = (term_T *)user;
4511 js_read_T reader;
4512 typval_T tv;
4513 channel_T *channel = term->tl_job == NULL ? NULL
4514 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004515 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004516
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004517 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
4518 if (p_asd && command == 7)
4519 {
4520 sync_shell_dir(&frag);
4521 return 1;
4522 }
4523
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004524 if (command != 51)
4525 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004526
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004527 // Concatenate what was received until the final piece is found.
4528 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4529 {
4530 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004531 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004532 }
4533 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004534 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004535 if (!frag.final)
4536 return 1;
4537
4538 ((char *)gap->ga_data)[gap->ga_len] = 0;
4539 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004540 reader.js_fill = NULL;
4541 reader.js_used = 0;
4542 if (json_decode(&reader, &tv, 0) == OK
4543 && tv.v_type == VAR_LIST
4544 && tv.vval.v_list != NULL)
4545 {
4546 listitem_T *item = tv.vval.v_list->lv_first;
4547
4548 if (item == NULL)
4549 ch_log(channel, "Missing command");
4550 else
4551 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004552 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004553
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004554 // Make sure an invoked command doesn't delete the buffer (and the
4555 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004556 ++term->tl_buffer->b_locked;
4557
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004558 item = item->li_next;
4559 if (item == NULL)
4560 ch_log(channel, "Missing argument for %s", cmd);
4561 else if (STRCMP(cmd, "drop") == 0)
4562 handle_drop_command(item);
4563 else if (STRCMP(cmd, "call") == 0)
4564 handle_call_command(term, channel, item);
4565 else
4566 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004567 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004568 }
4569 }
4570 else
4571 ch_log(channel, "Invalid JSON received");
4572
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004573 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004574 clear_tv(&tv);
4575 return 1;
4576}
4577
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004578/*
4579 * Called by libvterm when it cannot recognize a CSI sequence.
4580 * We recognize the window position report.
4581 */
4582 static int
4583parse_csi(
4584 const char *leader UNUSED,
4585 const long args[],
4586 int argcount,
4587 const char *intermed UNUSED,
4588 char command,
4589 void *user)
4590{
4591 term_T *term = (term_T *)user;
4592 char buf[100];
4593 int len;
4594 int x = 0;
4595 int y = 0;
4596 win_T *wp;
4597
4598 // We recognize only CSI 13 t
4599 if (command != 't' || argcount != 1 || args[0] != 13)
4600 return 0; // not handled
4601
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004602 // When getting the window position is not possible or it fails it results
4603 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004604#if defined(FEAT_GUI) \
4605 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4606 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004607 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004608#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004609
4610 FOR_ALL_WINDOWS(wp)
4611 if (wp->w_buffer == term->tl_buffer)
4612 break;
4613 if (wp != NULL)
4614 {
4615#ifdef FEAT_GUI
4616 if (gui.in_use)
4617 {
4618 x += wp->w_wincol * gui.char_width;
4619 y += W_WINROW(wp) * gui.char_height;
4620 }
4621 else
4622#endif
4623 {
4624 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004625 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004626 x += wp->w_wincol * 7;
4627 y += W_WINROW(wp) * 10;
4628 }
4629 }
4630
4631 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4632 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4633 (char_u *)buf, len, NULL);
4634 return 1;
4635}
4636
Bram Moolenaard8637282020-05-20 18:41:41 +02004637static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004638 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004639 parse_csi, // csi
4640 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004641 NULL, // dcs
4642 NULL, // apc
4643 NULL, // pm
4644 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004645};
4646
4647/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004648 * Use Vim's allocation functions for vterm so profiling works.
4649 */
4650 static void *
4651vterm_malloc(size_t size, void *data UNUSED)
4652{
Bram Moolenaar88137392021-11-12 16:01:15 +00004653 // make sure that the length is not zero
4654 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004655}
4656
4657 static void
4658vterm_memfree(void *ptr, void *data UNUSED)
4659{
4660 vim_free(ptr);
4661}
4662
4663static VTermAllocatorFunctions vterm_allocator = {
4664 &vterm_malloc,
4665 &vterm_memfree
4666};
4667
4668/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004669 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004670 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004671 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004672 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004673create_vterm(term_T *term, int rows, int cols)
4674{
4675 VTerm *vterm;
4676 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004677 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004678 VTermValue value;
4679
Bram Moolenaar756ef112018-04-10 12:04:27 +02004680 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004681 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004682 if (vterm == NULL)
4683 return FAIL;
4684
4685 // Allocate screen and state here, so we can bail out if that fails.
4686 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004687 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004688 if (state == NULL || screen == NULL)
4689 {
4690 vterm_free(vterm);
4691 return FAIL;
4692 }
4693
Bram Moolenaar52acb112018-03-18 19:20:22 +01004694 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004695 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004696 vterm_set_utf8(vterm, 1);
4697
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004698 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004699
4700 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004701 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004702 &term->tl_default_color.fg,
4703 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004704
Bram Moolenaar9e587872019-05-13 20:27:23 +02004705 if (t_colors < 16)
4706 // Less than 16 colors: assume that bold means using a bright color for
4707 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004708 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4709
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004710 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004711 vterm_screen_reset(screen, 1 /* hard */);
4712
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004713 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004714 vterm_screen_enable_altscreen(screen, 1);
4715
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004716 // For unix do not use a blinking cursor. In an xterm this causes the
4717 // cursor to blink if it's blinking in the xterm.
4718 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004719#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004720 if (GetCaretBlinkTime() == INFINITE)
4721 value.boolean = 0;
4722 else
4723 value.boolean = 1;
4724#else
4725 value.boolean = 0;
4726#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004727 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004728 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004729
4730 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004731}
4732
4733/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004734 * Reset the terminal palette to its default value.
4735 */
4736 static void
4737term_reset_palette(VTerm *vterm)
4738{
4739 VTermState *state = vterm_obtain_state(vterm);
4740 int index;
4741
4742 for (index = 0; index < 16; index++)
4743 {
4744 VTermColor color;
4745
4746 color.type = VTERM_COLOR_INDEXED;
4747 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4748 &color.index);
4749 // The first valid index starts at 1.
4750 color.index -= 1;
4751
4752 vterm_state_set_palette_color(state, index, &color);
4753 }
4754}
4755
4756 static void
4757term_update_palette(term_T *term)
4758{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004759#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004760 if (term_use_palette()
4761 && (term->tl_palette != NULL
4762 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004763 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004764 {
4765 if (term->tl_palette != NULL)
4766 set_vterm_palette(term->tl_vterm, term->tl_palette);
4767 else
4768 init_vterm_ansi_colors(term->tl_vterm);
4769 }
4770 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004771#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004772 term_reset_palette(term->tl_vterm);
4773}
4774
4775/*
4776 * Called when option 'termguicolors' is changed.
4777 */
4778 void
4779term_update_palette_all()
4780{
4781 term_T *term;
4782
4783 FOR_ALL_TERMS(term)
4784 {
4785 if (term->tl_vterm == NULL)
4786 continue;
4787 term_update_palette(term);
4788 }
4789}
4790
4791/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004792 * Called when option 'background' or 'termguicolors' was set,
4793 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02004794 */
4795 void
4796term_update_colors_all(void)
4797{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004798 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02004799
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004800 FOR_ALL_TERMS(term)
4801 {
4802 if (term->tl_vterm == NULL)
4803 continue;
4804 init_default_colors(term);
4805 vterm_state_set_default_colors(
4806 vterm_obtain_state(term->tl_vterm),
4807 &term->tl_default_color.fg,
4808 &term->tl_default_color.bg);
4809 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004810}
4811
4812/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004813 * Return the text to show for the buffer name and status.
4814 */
4815 char_u *
4816term_get_status_text(term_T *term)
4817{
4818 if (term->tl_status_text == NULL)
4819 {
4820 char_u *txt;
4821 size_t len;
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004822 char_u *fname;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004823
4824 if (term->tl_normal_mode)
4825 {
4826 if (term_job_running(term))
4827 txt = (char_u *)_("Terminal");
4828 else
4829 txt = (char_u *)_("Terminal-finished");
4830 }
4831 else if (term->tl_title != NULL)
4832 txt = term->tl_title;
4833 else if (term_none_open(term))
4834 txt = (char_u *)_("active");
4835 else if (term_job_running(term))
4836 txt = (char_u *)_("running");
4837 else
4838 txt = (char_u *)_("finished");
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004839 fname = buf_get_fname(term->tl_buffer);
4840 len = 9 + STRLEN(fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004841 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004842 if (term->tl_status_text != NULL)
4843 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004844 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004845 }
4846 return term->tl_status_text;
4847}
4848
4849/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00004850 * Clear the cached value of the status text.
4851 */
4852 void
4853term_clear_status_text(term_T *term)
4854{
4855 VIM_CLEAR(term->tl_status_text);
4856}
4857
4858/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004859 * Mark references in jobs of terminals.
4860 */
4861 int
4862set_ref_in_term(int copyID)
4863{
4864 int abort = FALSE;
4865 term_T *term;
4866 typval_T tv;
4867
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004868 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004869 if (term->tl_job != NULL)
4870 {
4871 tv.v_type = VAR_JOB;
4872 tv.vval.v_job = term->tl_job;
4873 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4874 }
4875 return abort;
4876}
4877
4878/*
4879 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004880 * Returns NULL when the buffer is not for a terminal window and logs a message
4881 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004882 */
4883 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004884term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004885{
4886 buf_T *buf;
4887
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004888 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004889 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004890 --emsg_off;
4891 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004892 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01004893 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004894 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004895 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004896 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004897 return buf;
4898}
4899
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004900 static void
4901clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004902{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004903 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004904 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4905 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004906}
4907
4908 static void
4909dump_term_color(FILE *fd, VTermColor *color)
4910{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004911 int index;
4912
4913 if (VTERM_COLOR_IS_INDEXED(color))
4914 index = color->index + 1;
4915 else if (color->type == 0)
4916 // use RGB values
4917 index = 255;
4918 else
4919 // default color
4920 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004921 fprintf(fd, "%02x%02x%02x%d",
4922 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004923 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004924}
4925
4926/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004927 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004928 *
4929 * Each screen cell in full is:
4930 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4931 * {characters} is a space for an empty cell
4932 * For a double-width character "+" is changed to "*" and the next cell is
4933 * skipped.
4934 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4935 * when "&" use the same as the previous cell.
4936 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4937 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4938 * {color-idx} is a number from 0 to 255
4939 *
4940 * Screen cell with same width, attributes and color as the previous one:
4941 * |{characters}
4942 *
4943 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4944 *
4945 * Repeating the previous screen cell:
4946 * @{count}
4947 */
4948 void
4949f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4950{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02004951 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004952 term_T *term;
4953 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004954 int max_height = 0;
4955 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004956 stat_T st;
4957 FILE *fd;
4958 VTermPos pos;
4959 VTermScreen *screen;
4960 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004961 VTermState *state;
4962 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004963
4964 if (check_restricted() || check_secure())
4965 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02004966
4967 if (in_vim9script()
4968 && (check_for_buffer_arg(argvars, 0) == FAIL
4969 || check_for_string_arg(argvars, 1) == FAIL
4970 || check_for_opt_dict_arg(argvars, 2) == FAIL))
4971 return;
4972
4973 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004974 if (buf == NULL)
4975 return;
4976 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004977 if (term->tl_vterm == NULL)
4978 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00004979 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004980 return;
4981 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004982
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004983 if (argvars[2].v_type != VAR_UNKNOWN)
4984 {
4985 dict_T *d;
4986
4987 if (argvars[2].v_type != VAR_DICT)
4988 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00004989 emsg(_(e_dictionary_required));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004990 return;
4991 }
4992 d = argvars[2].vval.v_dict;
4993 if (d != NULL)
4994 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004995 max_height = dict_get_number(d, (char_u *)"rows");
4996 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004997 }
4998 }
4999
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005000 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005001 if (fname == NULL)
5002 return;
5003 if (mch_stat((char *)fname, &st) >= 0)
5004 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005005 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005006 return;
5007 }
5008
Bram Moolenaard96ff162018-02-18 22:13:29 +01005009 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5010 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005011 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005012 return;
5013 }
5014
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005015 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005016
5017 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005018 state = vterm_obtain_state(term->tl_vterm);
5019 vterm_state_get_cursorpos(state, &cursor_pos);
5020
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005021 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5022 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005023 {
5024 int repeat = 0;
5025
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005026 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5027 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005028 {
5029 VTermScreenCell cell;
5030 int same_attr;
5031 int same_chars = TRUE;
5032 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005033 int is_cursor_pos = (pos.col == cursor_pos.col
5034 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005035
5036 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005037 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005038
5039 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5040 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005041 int c = cell.chars[i];
5042 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005043 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005044
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005045 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005046 if (i == 0)
5047 {
5048 c = (c == NUL) ? ' ' : c;
5049 pc = (pc == NUL) ? ' ' : pc;
5050 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005051 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005052 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005053 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005054 break;
5055 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005056 same_attr = vtermAttr2hl(&cell.attrs)
5057 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005058 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5059 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005060 if (same_chars && cell.width == prev_cell.width && same_attr
5061 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005062 {
5063 ++repeat;
5064 }
5065 else
5066 {
5067 if (repeat > 0)
5068 {
5069 fprintf(fd, "@%d", repeat);
5070 repeat = 0;
5071 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005072 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005073
5074 if (cell.chars[0] == NUL)
5075 fputs(" ", fd);
5076 else
5077 {
5078 char_u charbuf[10];
5079 int len;
5080
5081 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5082 && cell.chars[i] != NUL; ++i)
5083 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005084 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005085 fwrite(charbuf, len, 1, fd);
5086 }
5087 }
5088
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005089 // When only the characters differ we don't write anything, the
5090 // following "|", "@" or NL will indicate using the same
5091 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005092 if (cell.width != prev_cell.width || !same_attr)
5093 {
5094 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005095 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005096 else
5097 fputs("+", fd);
5098
5099 if (same_attr)
5100 {
5101 fputs("&", fd);
5102 }
5103 else
5104 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005105 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005106 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005107 fputs("&", fd);
5108 else
5109 {
5110 fputs("#", fd);
5111 dump_term_color(fd, &cell.fg);
5112 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005113 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005114 fputs("&", fd);
5115 else
5116 {
5117 fputs("#", fd);
5118 dump_term_color(fd, &cell.bg);
5119 }
5120 }
5121 }
5122
5123 prev_cell = cell;
5124 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005125
5126 if (cell.width == 2)
5127 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005128 }
5129 if (repeat > 0)
5130 fprintf(fd, "@%d", repeat);
5131 fputs("\n", fd);
5132 }
5133
5134 fclose(fd);
5135}
5136
5137/*
5138 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5139 */
5140 static void
5141dump_is_corrupt(garray_T *gap)
5142{
5143 ga_concat(gap, (char_u *)"CORRUPT");
5144}
5145
5146 static void
5147append_cell(garray_T *gap, cellattr_T *cell)
5148{
5149 if (ga_grow(gap, 1) == OK)
5150 {
5151 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5152 ++gap->ga_len;
5153 }
5154}
5155
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005156 static void
5157clear_cellattr(cellattr_T *cell)
5158{
5159 CLEAR_FIELD(*cell);
5160 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5161 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5162}
5163
Bram Moolenaard96ff162018-02-18 22:13:29 +01005164/*
5165 * Read the dump file from "fd" and append lines to the current buffer.
5166 * Return the cell width of the longest line.
5167 */
5168 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005169read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005170{
5171 int c;
5172 garray_T ga_text;
5173 garray_T ga_cell;
5174 char_u *prev_char = NULL;
5175 int attr = 0;
5176 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005177 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005178 term_T *term = curbuf->b_term;
5179 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005180 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005181
5182 ga_init2(&ga_text, 1, 90);
5183 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005184 clear_cellattr(&cell);
5185 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005186 cursor_pos->row = -1;
5187 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005188
5189 c = fgetc(fd);
5190 for (;;)
5191 {
5192 if (c == EOF)
5193 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005194 if (c == '\r')
5195 {
5196 // DOS line endings? Ignore.
5197 c = fgetc(fd);
5198 }
5199 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005200 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005201 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005202 if (ga_text.ga_data == NULL)
5203 dump_is_corrupt(&ga_text);
5204 if (ga_grow(&term->tl_scrollback, 1) == OK)
5205 {
5206 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5207 + term->tl_scrollback.ga_len;
5208
5209 if (max_cells < ga_cell.ga_len)
5210 max_cells = ga_cell.ga_len;
5211 line->sb_cols = ga_cell.ga_len;
5212 line->sb_cells = ga_cell.ga_data;
5213 line->sb_fill_attr = term->tl_default_color;
5214 ++term->tl_scrollback.ga_len;
5215 ga_init(&ga_cell);
5216
5217 ga_append(&ga_text, NUL);
5218 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5219 ga_text.ga_len, FALSE);
5220 }
5221 else
5222 ga_clear(&ga_cell);
5223 ga_text.ga_len = 0;
5224
5225 c = fgetc(fd);
5226 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005227 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005228 {
5229 int prev_len = ga_text.ga_len;
5230
Bram Moolenaar9271d052018-02-25 21:39:46 +01005231 if (c == '>')
5232 {
5233 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005234 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005235 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5236 cursor_pos->col = ga_cell.ga_len;
5237 }
5238
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005239 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005240 c = fgetc(fd);
5241 if (c != EOF)
5242 ga_append(&ga_text, c);
5243 for (;;)
5244 {
5245 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005246 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005247 || c == EOF || c == '\n')
5248 break;
5249 ga_append(&ga_text, c);
5250 }
5251
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005252 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005253 vim_free(prev_char);
5254 if (ga_text.ga_data != NULL)
5255 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5256 ga_text.ga_len - prev_len);
5257
Bram Moolenaar9271d052018-02-25 21:39:46 +01005258 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005259 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005260 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005261 }
5262 else if (c == '+' || c == '*')
5263 {
5264 int is_bg;
5265
5266 cell.width = c == '+' ? 1 : 2;
5267
5268 c = fgetc(fd);
5269 if (c == '&')
5270 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005271 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005272 c = fgetc(fd);
5273 }
5274 else if (isdigit(c))
5275 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005276 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005277 attr = 0;
5278 while (isdigit(c))
5279 {
5280 attr = attr * 10 + (c - '0');
5281 c = fgetc(fd);
5282 }
5283 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005284
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005285 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005286 for (is_bg = 0; is_bg <= 1; ++is_bg)
5287 {
5288 if (c == '&')
5289 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005290 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005291 c = fgetc(fd);
5292 }
5293 else if (c == '#')
5294 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005295 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005296
5297 c = fgetc(fd);
5298 red = hex2nr(c);
5299 c = fgetc(fd);
5300 red = (red << 4) + hex2nr(c);
5301 c = fgetc(fd);
5302 green = hex2nr(c);
5303 c = fgetc(fd);
5304 green = (green << 4) + hex2nr(c);
5305 c = fgetc(fd);
5306 blue = hex2nr(c);
5307 c = fgetc(fd);
5308 blue = (blue << 4) + hex2nr(c);
5309 c = fgetc(fd);
5310 if (!isdigit(c))
5311 dump_is_corrupt(&ga_text);
5312 while (isdigit(c))
5313 {
5314 index = index * 10 + (c - '0');
5315 c = fgetc(fd);
5316 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005317 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005318 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005319 type = VTERM_COLOR_RGB;
5320 if (index == 0)
5321 {
5322 if (is_bg)
5323 type |= VTERM_COLOR_DEFAULT_BG;
5324 else
5325 type |= VTERM_COLOR_DEFAULT_FG;
5326 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005327 }
5328 else
5329 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005330 type = VTERM_COLOR_INDEXED;
5331 index -= 1;
5332 }
5333 if (is_bg)
5334 {
5335 cell.bg.type = type;
5336 cell.bg.red = red;
5337 cell.bg.green = green;
5338 cell.bg.blue = blue;
5339 cell.bg.index = index;
5340 }
5341 else
5342 {
5343 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005344 cell.fg.red = red;
5345 cell.fg.green = green;
5346 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005347 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005348 }
5349 }
5350 else
5351 dump_is_corrupt(&ga_text);
5352 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005353 }
5354 else
5355 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005356 }
5357 else
5358 dump_is_corrupt(&ga_text);
5359
5360 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005361 if (cell.width == 2)
5362 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005363 }
5364 else if (c == '@')
5365 {
5366 if (prev_char == NULL)
5367 dump_is_corrupt(&ga_text);
5368 else
5369 {
5370 int count = 0;
5371
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005372 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005373 for (;;)
5374 {
5375 c = fgetc(fd);
5376 if (!isdigit(c))
5377 break;
5378 count = count * 10 + (c - '0');
5379 }
5380
5381 while (count-- > 0)
5382 {
5383 ga_concat(&ga_text, prev_char);
5384 append_cell(&ga_cell, &cell);
5385 }
5386 }
5387 }
5388 else
5389 {
5390 dump_is_corrupt(&ga_text);
5391 c = fgetc(fd);
5392 }
5393 }
5394
5395 if (ga_text.ga_len > 0)
5396 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005397 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005398 dump_is_corrupt(&ga_text);
5399 ga_append(&ga_text, NUL);
5400 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5401 ga_text.ga_len, FALSE);
5402 }
5403
5404 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005405 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005406 vim_free(prev_char);
5407
5408 return max_cells;
5409}
5410
5411/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005412 * Return an allocated string with at least "text_width" "=" characters and
5413 * "fname" inserted in the middle.
5414 */
5415 static char_u *
5416get_separator(int text_width, char_u *fname)
5417{
5418 int width = MAX(text_width, curwin->w_width);
5419 char_u *textline;
5420 int fname_size;
5421 char_u *p = fname;
5422 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005423 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005424
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005425 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005426 if (textline == NULL)
5427 return NULL;
5428
5429 fname_size = vim_strsize(fname);
5430 if (fname_size < width - 8)
5431 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005432 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005433 width = MAX(text_width, fname_size + 8);
5434 }
5435 else if (fname_size > width - 8)
5436 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005437 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005438 p = gettail(fname);
5439 fname_size = vim_strsize(p);
5440 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005441 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005442 while (fname_size > width - 8)
5443 {
5444 p += (*mb_ptr2len)(p);
5445 fname_size = vim_strsize(p);
5446 }
5447
5448 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5449 textline[i] = '=';
5450 textline[i++] = ' ';
5451
5452 STRCPY(textline + i, p);
5453 off = STRLEN(textline);
5454 textline[off] = ' ';
5455 for (i = 1; i < (width - fname_size) / 2; ++i)
5456 textline[off + i] = '=';
5457 textline[off + i] = NUL;
5458
5459 return textline;
5460}
5461
5462/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005463 * Common for "term_dumpdiff()" and "term_dumpload()".
5464 */
5465 static void
5466term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5467{
5468 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005469 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005470 char_u buf1[NUMBUFLEN];
5471 char_u buf2[NUMBUFLEN];
5472 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005473 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005474 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005475 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005476 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005477 char_u *textline = NULL;
5478
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005479 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005480 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005481 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005482 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005483 if (fname1 == NULL || (do_diff && fname2 == NULL))
5484 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005485 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005486 return;
5487 }
5488 fd1 = mch_fopen((char *)fname1, READBIN);
5489 if (fd1 == NULL)
5490 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005491 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005492 return;
5493 }
5494 if (do_diff)
5495 {
5496 fd2 = mch_fopen((char *)fname2, READBIN);
5497 if (fd2 == NULL)
5498 {
5499 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005500 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005501 return;
5502 }
5503 }
5504
5505 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005506 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5507 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5508 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5509 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5510 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005511
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005512 if (opt.jo_term_name == NULL)
5513 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005514 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005515
Bram Moolenaar51e14382019-05-25 20:21:28 +02005516 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005517 if (fname_tofree != NULL)
5518 {
5519 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5520 opt.jo_term_name = fname_tofree;
5521 }
5522 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005523
Bram Moolenaar87abab92019-06-03 21:14:59 +02005524 if (opt.jo_bufnr_buf != NULL)
5525 {
5526 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5527
5528 // With "bufnr" argument: enter the window with this buffer and make it
5529 // empty.
5530 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005531 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005532 else
5533 {
5534 buf = curbuf;
5535 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005536 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005537 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005538 redraw_later(NOT_VALID);
5539 }
5540 }
5541 else
5542 // Create a new terminal window.
5543 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5544
Bram Moolenaard96ff162018-02-18 22:13:29 +01005545 if (buf != NULL && buf->b_term != NULL)
5546 {
5547 int i;
5548 linenr_T bot_lnum;
5549 linenr_T lnum;
5550 term_T *term = buf->b_term;
5551 int width;
5552 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005553 VTermPos cursor_pos1;
5554 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005555
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005556 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005557
Bram Moolenaard96ff162018-02-18 22:13:29 +01005558 rettv->vval.v_number = buf->b_fnum;
5559
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005560 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005561 width = read_dump_file(fd1, &cursor_pos1);
5562
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005563 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005564 if (cursor_pos1.row >= 0)
5565 {
5566 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5567 coladvance(cursor_pos1.col);
5568 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005569
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005570 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005571 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005572
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005573 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005574 if (!do_diff)
5575 goto theend;
5576
5577 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5578
Bram Moolenaar4a696342018-04-05 18:45:26 +02005579 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005580 if (textline == NULL)
5581 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005582 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5583 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5584 vim_free(textline);
5585
5586 textline = get_separator(width, fname2);
5587 if (textline == NULL)
5588 goto theend;
5589 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5590 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005591 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005592
5593 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005594 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005595 if (width2 > width)
5596 {
5597 vim_free(textline);
5598 textline = alloc(width2 + 1);
5599 if (textline == NULL)
5600 goto theend;
5601 width = width2;
5602 textline[width] = NUL;
5603 }
5604 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5605
5606 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5607 {
5608 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5609 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005610 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005611 for (i = 0; i < width; ++i)
5612 textline[i] = '-';
5613 }
5614 else
5615 {
5616 char_u *line1;
5617 char_u *line2;
5618 char_u *p1;
5619 char_u *p2;
5620 int col;
5621 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5622 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5623 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5624 ->sb_cells;
5625
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005626 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005627 line1 = vim_strsave(ml_get(lnum));
5628 if (line1 == NULL)
5629 break;
5630 p1 = line1;
5631
5632 line2 = ml_get(lnum + bot_lnum);
5633 p2 = line2;
5634 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5635 {
5636 int len1 = utfc_ptr2len(p1);
5637 int len2 = utfc_ptr2len(p2);
5638
5639 textline[col] = ' ';
5640 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005641 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005642 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005643 else if (lnum == cursor_pos1.row + 1
5644 && col == cursor_pos1.col
5645 && (cursor_pos1.row != cursor_pos2.row
5646 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005647 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005648 textline[col] = '>';
5649 else if (lnum == cursor_pos2.row + 1
5650 && col == cursor_pos2.col
5651 && (cursor_pos1.row != cursor_pos2.row
5652 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005653 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005654 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005655 else if (cellattr1 != NULL && cellattr2 != NULL)
5656 {
5657 if ((cellattr1 + col)->width
5658 != (cellattr2 + col)->width)
5659 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005660 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005661 &(cellattr2 + col)->fg))
5662 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005663 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005664 &(cellattr2 + col)->bg))
5665 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005666 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5667 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005668 textline[col] = 'a';
5669 }
5670 p1 += len1;
5671 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005672 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005673 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005674
5675 while (col < width)
5676 {
5677 if (*p1 == NUL && *p2 == NUL)
5678 textline[col] = '?';
5679 else if (*p1 == NUL)
5680 {
5681 textline[col] = '+';
5682 p2 += utfc_ptr2len(p2);
5683 }
5684 else
5685 {
5686 textline[col] = '-';
5687 p1 += utfc_ptr2len(p1);
5688 }
5689 ++col;
5690 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005691
5692 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005693 }
5694 if (add_empty_scrollback(term, &term->tl_default_color,
5695 term->tl_top_diff_rows) == OK)
5696 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5697 ++bot_lnum;
5698 }
5699
5700 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5701 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005702 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005703 for (i = 0; i < width; ++i)
5704 textline[i] = '+';
5705 if (add_empty_scrollback(term, &term->tl_default_color,
5706 term->tl_top_diff_rows) == OK)
5707 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5708 ++lnum;
5709 ++bot_lnum;
5710 }
5711
5712 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005713
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005714 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005715 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005716 }
5717
5718theend:
5719 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005720 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005721 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005722 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005723 fclose(fd2);
5724}
5725
5726/*
5727 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5728 * bottom files.
5729 * Return FAIL when this is not possible.
5730 */
5731 int
5732term_swap_diff()
5733{
5734 term_T *term = curbuf->b_term;
5735 linenr_T line_count;
5736 linenr_T top_rows;
5737 linenr_T bot_rows;
5738 linenr_T bot_start;
5739 linenr_T lnum;
5740 char_u *p;
5741 sb_line_T *sb_line;
5742
5743 if (term == NULL
5744 || !term_is_finished(curbuf)
5745 || term->tl_top_diff_rows == 0
5746 || term->tl_scrollback.ga_len == 0)
5747 return FAIL;
5748
5749 line_count = curbuf->b_ml.ml_line_count;
5750 top_rows = term->tl_top_diff_rows;
5751 bot_rows = term->tl_bot_diff_rows;
5752 bot_start = line_count - bot_rows;
5753 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5754
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005755 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005756 for (lnum = 1; lnum <= top_rows; ++lnum)
5757 {
5758 p = vim_strsave(ml_get(1));
5759 if (p == NULL)
5760 return OK;
5761 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005762 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005763 vim_free(p);
5764 }
5765
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005766 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005767 for (lnum = 1; lnum <= bot_rows; ++lnum)
5768 {
5769 p = vim_strsave(ml_get(bot_start + lnum));
5770 if (p == NULL)
5771 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005772 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005773 ml_append(lnum - 1, p, 0, FALSE);
5774 vim_free(p);
5775 }
5776
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005777 // move top title to bottom
5778 p = vim_strsave(ml_get(bot_rows + 1));
5779 if (p == NULL)
5780 return OK;
5781 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005782 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005783 vim_free(p);
5784
5785 // move bottom title to top
5786 p = vim_strsave(ml_get(line_count - top_rows));
5787 if (p == NULL)
5788 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005789 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005790 ml_append(bot_rows, p, 0, FALSE);
5791 vim_free(p);
5792
Bram Moolenaard96ff162018-02-18 22:13:29 +01005793 if (top_rows == bot_rows)
5794 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005795 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005796 for (lnum = 0; lnum < top_rows; ++lnum)
5797 {
5798 sb_line_T temp;
5799
5800 temp = *(sb_line + lnum);
5801 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5802 *(sb_line + bot_start + lnum) = temp;
5803 }
5804 }
5805 else
5806 {
5807 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005808 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005809
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005810 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005811 if (temp != NULL)
5812 {
5813 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5814 mch_memmove(term->tl_scrollback.ga_data,
5815 temp + bot_start,
5816 sizeof(sb_line_T) * bot_rows);
5817 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5818 temp + top_rows,
5819 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5820 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5821 + line_count - top_rows,
5822 temp,
5823 sizeof(sb_line_T) * top_rows);
5824 vim_free(temp);
5825 }
5826 }
5827
5828 term->tl_top_diff_rows = bot_rows;
5829 term->tl_bot_diff_rows = top_rows;
5830
5831 update_screen(NOT_VALID);
5832 return OK;
5833}
5834
5835/*
5836 * "term_dumpdiff(filename, filename, options)" function
5837 */
5838 void
5839f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5840{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005841 if (in_vim9script()
5842 && (check_for_string_arg(argvars, 0) == FAIL
5843 || check_for_string_arg(argvars, 1) == FAIL
5844 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5845 return;
5846
Bram Moolenaard96ff162018-02-18 22:13:29 +01005847 term_load_dump(argvars, rettv, TRUE);
5848}
5849
5850/*
5851 * "term_dumpload(filename, options)" function
5852 */
5853 void
5854f_term_dumpload(typval_T *argvars, typval_T *rettv)
5855{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005856 if (in_vim9script()
5857 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02005858 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005859 return;
5860
Bram Moolenaard96ff162018-02-18 22:13:29 +01005861 term_load_dump(argvars, rettv, FALSE);
5862}
5863
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005864/*
5865 * "term_getaltscreen(buf)" function
5866 */
5867 void
5868f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5869{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005870 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005871
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005872 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5873 return;
5874
5875 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005876 if (buf == NULL)
5877 return;
5878 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5879}
5880
5881/*
5882 * "term_getattr(attr, name)" function
5883 */
5884 void
5885f_term_getattr(typval_T *argvars, typval_T *rettv)
5886{
5887 int attr;
5888 size_t i;
5889 char_u *name;
5890
5891 static struct {
5892 char *name;
5893 int attr;
5894 } attrs[] = {
5895 {"bold", HL_BOLD},
5896 {"italic", HL_ITALIC},
5897 {"underline", HL_UNDERLINE},
5898 {"strike", HL_STRIKETHROUGH},
5899 {"reverse", HL_INVERSE},
5900 };
5901
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02005902 if (in_vim9script()
5903 && (check_for_number_arg(argvars, 0) == FAIL
5904 || check_for_string_arg(argvars, 1) == FAIL))
5905 return;
5906
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005907 attr = tv_get_number(&argvars[0]);
5908 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005909 if (name == NULL)
5910 return;
5911
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005912 if (attr > HL_ALL)
5913 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02005914 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005915 if (STRCMP(name, attrs[i].name) == 0)
5916 {
5917 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5918 break;
5919 }
5920}
5921
5922/*
5923 * "term_getcursor(buf)" function
5924 */
5925 void
5926f_term_getcursor(typval_T *argvars, typval_T *rettv)
5927{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005928 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005929 term_T *term;
5930 list_T *l;
5931 dict_T *d;
5932
5933 if (rettv_list_alloc(rettv) == FAIL)
5934 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005935
5936 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5937 return;
5938
5939 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005940 if (buf == NULL)
5941 return;
5942 term = buf->b_term;
5943
5944 l = rettv->vval.v_list;
5945 list_append_number(l, term->tl_cursor_pos.row + 1);
5946 list_append_number(l, term->tl_cursor_pos.col + 1);
5947
5948 d = dict_alloc();
5949 if (d != NULL)
5950 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005951 dict_add_number(d, "visible", term->tl_cursor_visible);
5952 dict_add_number(d, "blink", blink_state_is_inverted()
5953 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5954 dict_add_number(d, "shape", term->tl_cursor_shape);
5955 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005956 list_append_dict(l, d);
5957 }
5958}
5959
5960/*
5961 * "term_getjob(buf)" function
5962 */
5963 void
5964f_term_getjob(typval_T *argvars, typval_T *rettv)
5965{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005966 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005967
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005968 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5969 return;
5970
5971 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005972 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005973 {
5974 rettv->v_type = VAR_SPECIAL;
5975 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005976 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005977 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005978
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005979 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005980 rettv->vval.v_job = buf->b_term->tl_job;
5981 if (rettv->vval.v_job != NULL)
5982 ++rettv->vval.v_job->jv_refcount;
5983}
5984
5985 static int
5986get_row_number(typval_T *tv, term_T *term)
5987{
5988 if (tv->v_type == VAR_STRING
5989 && tv->vval.v_string != NULL
5990 && STRCMP(tv->vval.v_string, ".") == 0)
5991 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005992 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005993}
5994
5995/*
5996 * "term_getline(buf, row)" function
5997 */
5998 void
5999f_term_getline(typval_T *argvars, typval_T *rettv)
6000{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006001 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006002 term_T *term;
6003 int row;
6004
6005 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006006
6007 if (in_vim9script()
6008 && (check_for_buffer_arg(argvars, 0) == FAIL
6009 || check_for_lnum_arg(argvars, 1) == FAIL))
6010 return;
6011
6012 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006013 if (buf == NULL)
6014 return;
6015 term = buf->b_term;
6016 row = get_row_number(&argvars[1], term);
6017
6018 if (term->tl_vterm == NULL)
6019 {
6020 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6021
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006022 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006023 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6024 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6025 }
6026 else
6027 {
6028 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6029 VTermRect rect;
6030 int len;
6031 char_u *p;
6032
6033 if (row < 0 || row >= term->tl_rows)
6034 return;
6035 len = term->tl_cols * MB_MAXBYTES + 1;
6036 p = alloc(len);
6037 if (p == NULL)
6038 return;
6039 rettv->vval.v_string = p;
6040
6041 rect.start_col = 0;
6042 rect.end_col = term->tl_cols;
6043 rect.start_row = row;
6044 rect.end_row = row + 1;
6045 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6046 }
6047}
6048
6049/*
6050 * "term_getscrolled(buf)" function
6051 */
6052 void
6053f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6054{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006055 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006056
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006057 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6058 return;
6059
6060 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006061 if (buf == NULL)
6062 return;
6063 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6064}
6065
6066/*
6067 * "term_getsize(buf)" function
6068 */
6069 void
6070f_term_getsize(typval_T *argvars, typval_T *rettv)
6071{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006072 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006073 list_T *l;
6074
6075 if (rettv_list_alloc(rettv) == FAIL)
6076 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006077
6078 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6079 return;
6080
6081 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006082 if (buf == NULL)
6083 return;
6084
6085 l = rettv->vval.v_list;
6086 list_append_number(l, buf->b_term->tl_rows);
6087 list_append_number(l, buf->b_term->tl_cols);
6088}
6089
6090/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006091 * "term_setsize(buf, rows, cols)" function
6092 */
6093 void
6094f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6095{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006096 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006097 term_T *term;
6098 varnumber_T rows, cols;
6099
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006100 if (in_vim9script()
6101 && (check_for_buffer_arg(argvars, 0) == FAIL
6102 || check_for_number_arg(argvars, 1) == FAIL
6103 || check_for_number_arg(argvars, 2) == FAIL))
6104 return;
6105
6106 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006107 if (buf == NULL)
6108 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006109 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006110 return;
6111 }
6112 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006113 return;
6114 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006115 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006116 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006117 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006118 cols = cols <= 0 ? term->tl_cols : cols;
6119 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006120 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006121
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006122 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006123 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6124 term_report_winsize(term, term->tl_rows, term->tl_cols);
6125}
6126
6127/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006128 * "term_getstatus(buf)" function
6129 */
6130 void
6131f_term_getstatus(typval_T *argvars, typval_T *rettv)
6132{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006133 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006134 term_T *term;
6135 char_u val[100];
6136
6137 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006138
6139 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6140 return;
6141
6142 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006143 if (buf == NULL)
6144 return;
6145 term = buf->b_term;
6146
6147 if (term_job_running(term))
6148 STRCPY(val, "running");
6149 else
6150 STRCPY(val, "finished");
6151 if (term->tl_normal_mode)
6152 STRCAT(val, ",normal");
6153 rettv->vval.v_string = vim_strsave(val);
6154}
6155
6156/*
6157 * "term_gettitle(buf)" function
6158 */
6159 void
6160f_term_gettitle(typval_T *argvars, typval_T *rettv)
6161{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006162 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006163
6164 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006165
6166 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6167 return;
6168
6169 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006170 if (buf == NULL)
6171 return;
6172
6173 if (buf->b_term->tl_title != NULL)
6174 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6175}
6176
6177/*
6178 * "term_gettty(buf)" function
6179 */
6180 void
6181f_term_gettty(typval_T *argvars, typval_T *rettv)
6182{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006183 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006184 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006185 int num = 0;
6186
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006187 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006188 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006189 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6190 return;
6191
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006192 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006193 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006194 if (buf == NULL)
6195 return;
6196 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006197 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006198
6199 switch (num)
6200 {
6201 case 0:
6202 if (buf->b_term->tl_job != NULL)
6203 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006204 break;
6205 case 1:
6206 if (buf->b_term->tl_job != NULL)
6207 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006208 break;
6209 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006210 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006211 return;
6212 }
6213 if (p != NULL)
6214 rettv->vval.v_string = vim_strsave(p);
6215}
6216
6217/*
6218 * "term_list()" function
6219 */
6220 void
6221f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6222{
6223 term_T *tp;
6224 list_T *l;
6225
6226 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6227 return;
6228
6229 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006230 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006231 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006232 if (list_append_number(l,
6233 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6234 return;
6235}
6236
6237/*
6238 * "term_scrape(buf, row)" function
6239 */
6240 void
6241f_term_scrape(typval_T *argvars, typval_T *rettv)
6242{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006243 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006244 VTermScreen *screen = NULL;
6245 VTermPos pos;
6246 list_T *l;
6247 term_T *term;
6248 char_u *p;
6249 sb_line_T *line;
6250
6251 if (rettv_list_alloc(rettv) == FAIL)
6252 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006253
6254 if (in_vim9script()
6255 && (check_for_buffer_arg(argvars, 0) == FAIL
6256 || check_for_lnum_arg(argvars, 1) == FAIL))
6257 return;
6258
6259 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006260 if (buf == NULL)
6261 return;
6262 term = buf->b_term;
6263
6264 l = rettv->vval.v_list;
6265 pos.row = get_row_number(&argvars[1], term);
6266
6267 if (term->tl_vterm != NULL)
6268 {
6269 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006270 if (screen == NULL) // can't really happen
6271 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006272 p = NULL;
6273 line = NULL;
6274 }
6275 else
6276 {
6277 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6278
6279 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6280 return;
6281 p = ml_get_buf(buf, lnum + 1, FALSE);
6282 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6283 }
6284
6285 for (pos.col = 0; pos.col < term->tl_cols; )
6286 {
6287 dict_T *dcell;
6288 int width;
6289 VTermScreenCellAttrs attrs;
6290 VTermColor fg, bg;
6291 char_u rgb[8];
6292 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6293 int off = 0;
6294 int i;
6295
6296 if (screen == NULL)
6297 {
6298 cellattr_T *cellattr;
6299 int len;
6300
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006301 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006302 if (pos.col >= line->sb_cols)
6303 break;
6304 cellattr = line->sb_cells + pos.col;
6305 width = cellattr->width;
6306 attrs = cellattr->attrs;
6307 fg = cellattr->fg;
6308 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006309 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006310 mch_memmove(mbs, p, len);
6311 mbs[len] = NUL;
6312 p += len;
6313 }
6314 else
6315 {
6316 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006317
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006318 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6319 break;
6320 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6321 {
6322 if (cell.chars[i] == 0)
6323 break;
6324 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6325 }
6326 mbs[off] = NUL;
6327 width = cell.width;
6328 attrs = cell.attrs;
6329 fg = cell.fg;
6330 bg = cell.bg;
6331 }
6332 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006333 if (dcell == NULL)
6334 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006335 list_append_dict(l, dcell);
6336
Bram Moolenaare0be1672018-07-08 16:50:37 +02006337 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006338
6339 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6340 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006341 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006342 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6343 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006344 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006345
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006346 dict_add_number(dcell, "attr",
6347 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006348 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006349
6350 ++pos.col;
6351 if (width == 2)
6352 ++pos.col;
6353 }
6354}
6355
6356/*
6357 * "term_sendkeys(buf, keys)" function
6358 */
6359 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006360f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006361{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006362 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006363 char_u *msg;
6364 term_T *term;
6365
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006366 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006367 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006368 || check_for_string_arg(argvars, 1) == FAIL))
6369 return;
6370
6371 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006372 if (buf == NULL)
6373 return;
6374
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006375 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006376 if (msg == NULL)
6377 return;
6378 term = buf->b_term;
6379 if (term->tl_vterm == NULL)
6380 return;
6381
6382 while (*msg != NUL)
6383 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006384 int c;
6385
6386 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6387 {
6388 c = TO_SPECIAL(msg[1], msg[2]);
6389 msg += 3;
6390 }
6391 else
6392 {
6393 c = PTR2CHAR(msg);
6394 msg += MB_CPTR2LEN(msg);
6395 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006396 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006397 }
6398}
6399
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006400#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6401/*
6402 * "term_getansicolors(buf)" function
6403 */
6404 void
6405f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6406{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006407 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006408 term_T *term;
6409 VTermState *state;
6410 VTermColor color;
6411 char_u hexbuf[10];
6412 int index;
6413 list_T *list;
6414
6415 if (rettv_list_alloc(rettv) == FAIL)
6416 return;
6417
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006418 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6419 return;
6420
6421 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006422 if (buf == NULL)
6423 return;
6424 term = buf->b_term;
6425 if (term->tl_vterm == NULL)
6426 return;
6427
6428 list = rettv->vval.v_list;
6429 state = vterm_obtain_state(term->tl_vterm);
6430 for (index = 0; index < 16; index++)
6431 {
6432 vterm_state_get_palette_color(state, index, &color);
6433 sprintf((char *)hexbuf, "#%02x%02x%02x",
6434 color.red, color.green, color.blue);
6435 if (list_append_string(list, hexbuf, 7) == FAIL)
6436 return;
6437 }
6438}
6439
6440/*
6441 * "term_setansicolors(buf, list)" function
6442 */
6443 void
6444f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6445{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006446 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006447 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006448 listitem_T *li;
6449 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006450
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006451 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006452 && (check_for_buffer_arg(argvars, 0) == FAIL
6453 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006454 return;
6455
6456 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006457 if (buf == NULL)
6458 return;
6459 term = buf->b_term;
6460 if (term->tl_vterm == NULL)
6461 return;
6462
6463 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
6464 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006465 emsg(_(e_list_required));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006466 return;
6467 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01006468 if (argvars[1].vval.v_list->lv_first == &range_list_item
6469 || argvars[1].vval.v_list->lv_len != 16)
6470 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006471 emsg(_(e_invalid_argument));
LemonBoyb2b3acb2022-05-20 10:10:34 +01006472 return;
6473 }
6474
6475 if (term->tl_palette == NULL)
6476 term->tl_palette = ALLOC_MULT(long_u, 16);
6477 if (term->tl_palette == NULL)
6478 return;
6479
6480 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6481 {
6482 char_u *color_name;
6483 guicolor_T guicolor;
6484
6485 color_name = tv_get_string_chk(&li->li_tv);
6486 if (color_name == NULL)
6487 return;
6488
6489 guicolor = GUI_GET_COLOR(color_name);
6490 if (guicolor == INVALCOLOR)
6491 {
6492 semsg(_(e_cannot_allocate_color_str), color_name);
6493 return;
6494 }
6495
6496 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6497 }
6498
6499 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006500}
6501#endif
6502
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006503/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006504 * "term_setapi(buf, api)" function
6505 */
6506 void
6507f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6508{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006509 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006510 term_T *term;
6511 char_u *api;
6512
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006513 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006514 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006515 || check_for_string_arg(argvars, 1) == FAIL))
6516 return;
6517
6518 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006519 if (buf == NULL)
6520 return;
6521 term = buf->b_term;
6522 vim_free(term->tl_api);
6523 api = tv_get_string_chk(&argvars[1]);
6524 if (api != NULL)
6525 term->tl_api = vim_strsave(api);
6526 else
6527 term->tl_api = NULL;
6528}
6529
6530/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006531 * "term_setrestore(buf, command)" function
6532 */
6533 void
6534f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6535{
6536#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006537 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006538 term_T *term;
6539 char_u *cmd;
6540
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006541 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006542 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006543 || check_for_string_arg(argvars, 1) == FAIL))
6544 return;
6545
6546 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006547 if (buf == NULL)
6548 return;
6549 term = buf->b_term;
6550 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006551 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006552 if (cmd != NULL)
6553 term->tl_command = vim_strsave(cmd);
6554 else
6555 term->tl_command = NULL;
6556#endif
6557}
6558
6559/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006560 * "term_setkill(buf, how)" function
6561 */
6562 void
6563f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6564{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006565 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006566 term_T *term;
6567 char_u *how;
6568
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006569 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006570 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006571 || check_for_string_arg(argvars, 1) == FAIL))
6572 return;
6573
6574 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006575 if (buf == NULL)
6576 return;
6577 term = buf->b_term;
6578 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006579 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006580 if (how != NULL)
6581 term->tl_kill = vim_strsave(how);
6582 else
6583 term->tl_kill = NULL;
6584}
6585
6586/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006587 * "term_start(command, options)" function
6588 */
6589 void
6590f_term_start(typval_T *argvars, typval_T *rettv)
6591{
6592 jobopt_T opt;
6593 buf_T *buf;
6594
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006595 if (in_vim9script()
6596 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6597 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6598 return;
6599
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006600 init_job_options(&opt);
6601 if (argvars[1].v_type != VAR_UNKNOWN
6602 && get_job_options(&argvars[1], &opt,
6603 JO_TIMEOUT_ALL + JO_STOPONEXIT
6604 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6605 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6606 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6607 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006608 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006609 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006610 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006611 return;
6612
Bram Moolenaar13568252018-03-16 20:46:58 +01006613 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006614
6615 if (buf != NULL && buf->b_term != NULL)
6616 rettv->vval.v_number = buf->b_fnum;
6617}
6618
6619/*
6620 * "term_wait" function
6621 */
6622 void
6623f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6624{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006625 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006626
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006627 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006628 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006629 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006630 return;
6631
6632 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006633 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006634 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006635 if (buf->b_term->tl_job == NULL)
6636 {
6637 ch_log(NULL, "term_wait(): no job to wait for");
6638 return;
6639 }
6640 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006641 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006642 return;
6643
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006644 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006645 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006646 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6647 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006648 // The job is dead, keep reading channel I/O until the channel is
6649 // closed. buf->b_term may become NULL if the terminal was closed while
6650 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006651 ch_log(NULL, "term_wait(): waiting for channel to close");
6652 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6653 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006654 term_flush_messages();
6655
Bram Moolenaard45aa552018-05-21 22:50:29 +02006656 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006657 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006658 // If the terminal is closed when the channel is closed the
6659 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006660 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006661 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6662 // came here from a close callback, only wait one time
6663 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006664 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006665
6666 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006667 }
6668 else
6669 {
6670 long wait = 10L;
6671
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006672 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006673
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006674 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006675 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006676 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006677 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006678
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006679 // Flushing messages on channels is hopefully sufficient.
6680 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006681 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006682 }
6683}
6684
6685/*
6686 * Called when a channel has sent all the lines to a terminal.
6687 * Send a CTRL-D to mark the end of the text.
6688 */
6689 void
6690term_send_eof(channel_T *ch)
6691{
6692 term_T *term;
6693
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006694 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006695 if (term->tl_job == ch->ch_job)
6696 {
6697 if (term->tl_eof_chars != NULL)
6698 {
6699 channel_send(ch, PART_IN, term->tl_eof_chars,
6700 (int)STRLEN(term->tl_eof_chars), NULL);
6701 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6702 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006703# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006704 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006705 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006706 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6707# endif
6708 }
6709}
6710
Bram Moolenaar113e1072019-01-20 15:30:40 +01006711#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006712 job_T *
6713term_getjob(term_T *term)
6714{
6715 return term != NULL ? term->tl_job : NULL;
6716}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006717#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006718
Bram Moolenaar4f974752019-02-17 17:44:42 +01006719# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006720
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006721///////////////////////////////////////
6722// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006723#ifdef PROTO
6724typedef int COORD;
6725typedef int DWORD;
6726typedef int HANDLE;
6727typedef int *DWORD_PTR;
6728typedef int HPCON;
6729typedef int HRESULT;
6730typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006731typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006732typedef int PSIZE_T;
6733typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006734typedef int BOOL;
6735# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006736#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006737
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006738HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6739HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6740HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006741BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6742BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6743void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006744
6745 static int
6746dyn_conpty_init(int verbose)
6747{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006748 static HMODULE hKerneldll = NULL;
6749 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006750 static struct
6751 {
6752 char *name;
6753 FARPROC *ptr;
6754 } conpty_entry[] =
6755 {
6756 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6757 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6758 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6759 {"InitializeProcThreadAttributeList",
6760 (FARPROC*)&pInitializeProcThreadAttributeList},
6761 {"UpdateProcThreadAttribute",
6762 (FARPROC*)&pUpdateProcThreadAttribute},
6763 {"DeleteProcThreadAttributeList",
6764 (FARPROC*)&pDeleteProcThreadAttributeList},
6765 {NULL, NULL}
6766 };
6767
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006768 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006769 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006770 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006771 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006772 return FAIL;
6773 }
6774
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006775 // No need to initialize twice.
6776 if (hKerneldll)
6777 return OK;
6778
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006779 hKerneldll = vimLoadLib("kernel32.dll");
6780 for (i = 0; conpty_entry[i].name != NULL
6781 && conpty_entry[i].ptr != NULL; ++i)
6782 {
6783 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6784 conpty_entry[i].name)) == NULL)
6785 {
6786 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006787 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006788 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006789 return FAIL;
6790 }
6791 }
6792
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006793 return OK;
6794}
6795
6796 static int
6797conpty_term_and_job_init(
6798 term_T *term,
6799 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006800 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006801 jobopt_T *opt,
6802 jobopt_T *orig_opt)
6803{
6804 WCHAR *cmd_wchar = NULL;
6805 WCHAR *cmd_wchar_copy = NULL;
6806 WCHAR *cwd_wchar = NULL;
6807 WCHAR *env_wchar = NULL;
6808 channel_T *channel = NULL;
6809 job_T *job = NULL;
6810 HANDLE jo = NULL;
6811 garray_T ga_cmd, ga_env;
6812 char_u *cmd = NULL;
6813 HRESULT hr;
6814 COORD consize;
6815 SIZE_T breq;
6816 PROCESS_INFORMATION proc_info;
6817 HANDLE i_theirs = NULL;
6818 HANDLE o_theirs = NULL;
6819 HANDLE i_ours = NULL;
6820 HANDLE o_ours = NULL;
6821
Bram Moolenaar04935fb2022-01-08 16:19:22 +00006822 ga_init2(&ga_cmd, sizeof(char*), 20);
6823 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006824
6825 if (argvar->v_type == VAR_STRING)
6826 {
6827 cmd = argvar->vval.v_string;
6828 }
6829 else if (argvar->v_type == VAR_LIST)
6830 {
6831 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6832 goto failed;
6833 cmd = ga_cmd.ga_data;
6834 }
6835 if (cmd == NULL || *cmd == NUL)
6836 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006837 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006838 goto failed;
6839 }
6840
6841 term->tl_arg0_cmd = vim_strsave(cmd);
6842
6843 cmd_wchar = enc_to_utf16(cmd, NULL);
6844
6845 if (cmd_wchar != NULL)
6846 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006847 // Request by CreateProcessW
6848 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006849 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006850 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6851 }
6852
6853 ga_clear(&ga_cmd);
6854 if (cmd_wchar == NULL)
6855 goto failed;
6856 if (opt->jo_cwd != NULL)
6857 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6858
6859 win32_build_env(opt->jo_env, &ga_env, TRUE);
6860 env_wchar = ga_env.ga_data;
6861
6862 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6863 goto failed;
6864 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6865 goto failed;
6866
6867 consize.X = term->tl_cols;
6868 consize.Y = term->tl_rows;
6869 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6870 &term->tl_conpty);
6871 if (FAILED(hr))
6872 goto failed;
6873
6874 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6875
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006876 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006877 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006878 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006879 if (!term->tl_siex.lpAttributeList)
6880 goto failed;
6881 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6882 0, &breq))
6883 goto failed;
6884 if (!pUpdateProcThreadAttribute(
6885 term->tl_siex.lpAttributeList, 0,
6886 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6887 sizeof(HPCON), NULL, NULL))
6888 goto failed;
6889
6890 channel = add_channel();
6891 if (channel == NULL)
6892 goto failed;
6893
6894 job = job_alloc();
6895 if (job == NULL)
6896 goto failed;
6897 if (argvar->v_type == VAR_STRING)
6898 {
6899 int argc;
6900
6901 build_argv_from_string(cmd, &job->jv_argv, &argc);
6902 }
6903 else
6904 {
6905 int argc;
6906
6907 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6908 }
6909
6910 if (opt->jo_set & JO_IN_BUF)
6911 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6912
6913 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6914 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02006915 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006916 env_wchar, cwd_wchar,
6917 &term->tl_siex.StartupInfo, &proc_info))
6918 goto failed;
6919
6920 CloseHandle(i_theirs);
6921 CloseHandle(o_theirs);
6922
6923 channel_set_pipes(channel,
6924 (sock_T)i_ours,
6925 (sock_T)o_ours,
6926 (sock_T)o_ours);
6927
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006928 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006929 channel->ch_write_text_mode = TRUE;
6930
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006931 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006932 channel->ch_anonymous_pipe = TRUE;
6933
6934 jo = CreateJobObject(NULL, NULL);
6935 if (jo == NULL)
6936 goto failed;
6937
6938 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6939 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006940 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006941 CloseHandle(jo);
6942 jo = NULL;
6943 }
6944
6945 ResumeThread(proc_info.hThread);
6946 CloseHandle(proc_info.hThread);
6947
6948 vim_free(cmd_wchar);
6949 vim_free(cmd_wchar_copy);
6950 vim_free(cwd_wchar);
6951 vim_free(env_wchar);
6952
6953 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6954 goto failed;
6955
Bram Moolenaar30b9a412022-05-26 14:06:37 +01006956#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01006957 if (term_use_palette())
6958 {
6959 if (term->tl_palette != NULL)
6960 set_vterm_palette(term->tl_vterm, term->tl_palette);
6961 else
6962 init_vterm_ansi_colors(term->tl_vterm);
6963 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01006964#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006965
6966 channel_set_job(channel, job, opt);
6967 job_set_options(job, opt);
6968
6969 job->jv_channel = channel;
6970 job->jv_proc_info = proc_info;
6971 job->jv_job_object = jo;
6972 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006973 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006974 ++job->jv_refcount;
6975 term->tl_job = job;
6976
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006977 // Redirecting stdout and stderr doesn't work at the job level. Instead
6978 // open the file here and handle it in. opt->jo_io was changed in
6979 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006980 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6981 {
6982 char_u *fname = opt->jo_io_name[PART_OUT];
6983
6984 ch_log(channel, "Opening output file %s", fname);
6985 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6986 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006987 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006988 }
6989
6990 return OK;
6991
6992failed:
6993 ga_clear(&ga_cmd);
6994 ga_clear(&ga_env);
6995 vim_free(cmd_wchar);
6996 vim_free(cmd_wchar_copy);
6997 vim_free(cwd_wchar);
6998 if (channel != NULL)
6999 channel_clear(channel);
7000 if (job != NULL)
7001 {
7002 job->jv_channel = NULL;
7003 job_cleanup(job);
7004 }
7005 term->tl_job = NULL;
7006 if (jo != NULL)
7007 CloseHandle(jo);
7008
7009 if (term->tl_siex.lpAttributeList != NULL)
7010 {
7011 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7012 vim_free(term->tl_siex.lpAttributeList);
7013 }
7014 term->tl_siex.lpAttributeList = NULL;
7015 if (o_theirs != NULL)
7016 CloseHandle(o_theirs);
7017 if (o_ours != NULL)
7018 CloseHandle(o_ours);
7019 if (i_ours != NULL)
7020 CloseHandle(i_ours);
7021 if (i_theirs != NULL)
7022 CloseHandle(i_theirs);
7023 if (term->tl_conpty != NULL)
7024 pClosePseudoConsole(term->tl_conpty);
7025 term->tl_conpty = NULL;
7026 return FAIL;
7027}
7028
7029 static void
7030conpty_term_report_winsize(term_T *term, int rows, int cols)
7031{
7032 COORD consize;
7033
7034 consize.X = cols;
7035 consize.Y = rows;
7036 pResizePseudoConsole(term->tl_conpty, consize);
7037}
7038
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007039 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007040term_free_conpty(term_T *term)
7041{
7042 if (term->tl_siex.lpAttributeList != NULL)
7043 {
7044 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7045 vim_free(term->tl_siex.lpAttributeList);
7046 }
7047 term->tl_siex.lpAttributeList = NULL;
7048 if (term->tl_conpty != NULL)
7049 pClosePseudoConsole(term->tl_conpty);
7050 term->tl_conpty = NULL;
7051}
7052
7053 int
7054use_conpty(void)
7055{
7056 return has_conpty;
7057}
7058
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007059# ifndef PROTO
7060
7061#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7062#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007063#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007064
7065void* (*winpty_config_new)(UINT64, void*);
7066void* (*winpty_open)(void*, void*);
7067void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7068BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7069void (*winpty_config_set_mouse_mode)(void*, int);
7070void (*winpty_config_set_initial_size)(void*, int, int);
7071LPCWSTR (*winpty_conin_name)(void*);
7072LPCWSTR (*winpty_conout_name)(void*);
7073LPCWSTR (*winpty_conerr_name)(void*);
7074void (*winpty_free)(void*);
7075void (*winpty_config_free)(void*);
7076void (*winpty_spawn_config_free)(void*);
7077void (*winpty_error_free)(void*);
7078LPCWSTR (*winpty_error_msg)(void*);
7079BOOL (*winpty_set_size)(void*, int, int, void*);
7080HANDLE (*winpty_agent_process)(void*);
7081
7082#define WINPTY_DLL "winpty.dll"
7083
7084static HINSTANCE hWinPtyDLL = NULL;
7085# endif
7086
7087 static int
7088dyn_winpty_init(int verbose)
7089{
7090 int i;
7091 static struct
7092 {
7093 char *name;
7094 FARPROC *ptr;
7095 } winpty_entry[] =
7096 {
7097 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7098 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7099 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7100 {"winpty_config_set_mouse_mode",
7101 (FARPROC*)&winpty_config_set_mouse_mode},
7102 {"winpty_config_set_initial_size",
7103 (FARPROC*)&winpty_config_set_initial_size},
7104 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7105 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7106 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7107 {"winpty_free", (FARPROC*)&winpty_free},
7108 {"winpty_open", (FARPROC*)&winpty_open},
7109 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7110 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7111 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7112 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7113 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7114 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7115 {NULL, NULL}
7116 };
7117
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007118 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007119 if (hWinPtyDLL)
7120 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007121 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7122 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007123 if (*p_winptydll != NUL)
7124 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7125 if (!hWinPtyDLL)
7126 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7127 if (!hWinPtyDLL)
7128 {
7129 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007130 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007131 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7132 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007133 return FAIL;
7134 }
7135 for (i = 0; winpty_entry[i].name != NULL
7136 && winpty_entry[i].ptr != NULL; ++i)
7137 {
7138 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7139 winpty_entry[i].name)) == NULL)
7140 {
7141 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007142 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007143 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007144 return FAIL;
7145 }
7146 }
7147
7148 return OK;
7149}
7150
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007151 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007152winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007153 term_T *term,
7154 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007155 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007156 jobopt_T *opt,
7157 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007158{
7159 WCHAR *cmd_wchar = NULL;
7160 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007161 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007162 channel_T *channel = NULL;
7163 job_T *job = NULL;
7164 DWORD error;
7165 HANDLE jo = NULL;
7166 HANDLE child_process_handle;
7167 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007168 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007169 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007170 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007171 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007172
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007173 ga_init2(&ga_cmd, sizeof(char*), 20);
7174 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007175
7176 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007177 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007178 cmd = argvar->vval.v_string;
7179 }
7180 else if (argvar->v_type == VAR_LIST)
7181 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007182 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007183 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007184 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007185 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007186 if (cmd == NULL || *cmd == NUL)
7187 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007188 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007189 goto failed;
7190 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007191
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007192 term->tl_arg0_cmd = vim_strsave(cmd);
7193
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007194 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007195 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007196 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007197 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007198 if (opt->jo_cwd != NULL)
7199 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007200
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007201 win32_build_env(opt->jo_env, &ga_env, TRUE);
7202 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007203
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007204 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7205 if (term->tl_winpty_config == NULL)
7206 goto failed;
7207
7208 winpty_config_set_mouse_mode(term->tl_winpty_config,
7209 WINPTY_MOUSE_MODE_FORCE);
7210 winpty_config_set_initial_size(term->tl_winpty_config,
7211 term->tl_cols, term->tl_rows);
7212 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7213 if (term->tl_winpty == NULL)
7214 goto failed;
7215
7216 spawn_config = winpty_spawn_config_new(
7217 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7218 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7219 NULL,
7220 cmd_wchar,
7221 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007222 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007223 &winpty_err);
7224 if (spawn_config == NULL)
7225 goto failed;
7226
7227 channel = add_channel();
7228 if (channel == NULL)
7229 goto failed;
7230
7231 job = job_alloc();
7232 if (job == NULL)
7233 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007234 if (argvar->v_type == VAR_STRING)
7235 {
7236 int argc;
7237
7238 build_argv_from_string(cmd, &job->jv_argv, &argc);
7239 }
7240 else
7241 {
7242 int argc;
7243
7244 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7245 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007246
7247 if (opt->jo_set & JO_IN_BUF)
7248 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7249
7250 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7251 &child_thread_handle, &error, &winpty_err))
7252 goto failed;
7253
7254 channel_set_pipes(channel,
7255 (sock_T)CreateFileW(
7256 winpty_conin_name(term->tl_winpty),
7257 GENERIC_WRITE, 0, NULL,
7258 OPEN_EXISTING, 0, NULL),
7259 (sock_T)CreateFileW(
7260 winpty_conout_name(term->tl_winpty),
7261 GENERIC_READ, 0, NULL,
7262 OPEN_EXISTING, 0, NULL),
7263 (sock_T)CreateFileW(
7264 winpty_conerr_name(term->tl_winpty),
7265 GENERIC_READ, 0, NULL,
7266 OPEN_EXISTING, 0, NULL));
7267
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007268 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007269 channel->ch_write_text_mode = TRUE;
7270
7271 jo = CreateJobObject(NULL, NULL);
7272 if (jo == NULL)
7273 goto failed;
7274
7275 if (!AssignProcessToJobObject(jo, child_process_handle))
7276 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007277 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007278 CloseHandle(jo);
7279 jo = NULL;
7280 }
7281
7282 winpty_spawn_config_free(spawn_config);
7283 vim_free(cmd_wchar);
7284 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007285 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007286
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007287 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7288 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007289
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007290#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007291 if (term_use_palette())
7292 {
7293 if (term->tl_palette != NULL)
7294 set_vterm_palette(term->tl_vterm, term->tl_palette);
7295 else
7296 init_vterm_ansi_colors(term->tl_vterm);
7297 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007298#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007299
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007300 channel_set_job(channel, job, opt);
7301 job_set_options(job, opt);
7302
7303 job->jv_channel = channel;
7304 job->jv_proc_info.hProcess = child_process_handle;
7305 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7306 job->jv_job_object = jo;
7307 job->jv_status = JOB_STARTED;
7308 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007309 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007310 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007311 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007312 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007313 ++job->jv_refcount;
7314 term->tl_job = job;
7315
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007316 // Redirecting stdout and stderr doesn't work at the job level. Instead
7317 // open the file here and handle it in. opt->jo_io was changed in
7318 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007319 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7320 {
7321 char_u *fname = opt->jo_io_name[PART_OUT];
7322
7323 ch_log(channel, "Opening output file %s", fname);
7324 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7325 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007326 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007327 }
7328
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007329 return OK;
7330
7331failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007332 ga_clear(&ga_cmd);
7333 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007334 vim_free(cmd_wchar);
7335 vim_free(cwd_wchar);
7336 if (spawn_config != NULL)
7337 winpty_spawn_config_free(spawn_config);
7338 if (channel != NULL)
7339 channel_clear(channel);
7340 if (job != NULL)
7341 {
7342 job->jv_channel = NULL;
7343 job_cleanup(job);
7344 }
7345 term->tl_job = NULL;
7346 if (jo != NULL)
7347 CloseHandle(jo);
7348 if (term->tl_winpty != NULL)
7349 winpty_free(term->tl_winpty);
7350 term->tl_winpty = NULL;
7351 if (term->tl_winpty_config != NULL)
7352 winpty_config_free(term->tl_winpty_config);
7353 term->tl_winpty_config = NULL;
7354 if (winpty_err != NULL)
7355 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007356 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007357 (short_u *)winpty_error_msg(winpty_err), NULL);
7358
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007359 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007360 winpty_error_free(winpty_err);
7361 }
7362 return FAIL;
7363}
7364
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007365/*
7366 * Create a new terminal of "rows" by "cols" cells.
7367 * Store a reference in "term".
7368 * Return OK or FAIL.
7369 */
7370 static int
7371term_and_job_init(
7372 term_T *term,
7373 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007374 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007375 jobopt_T *opt,
7376 jobopt_T *orig_opt)
7377{
7378 int use_winpty = FALSE;
7379 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007380 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007381
7382 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7383 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7384
7385 if (!has_winpty && !has_conpty)
7386 // If neither is available give the errors for winpty, since when
7387 // conpty is not available it can't be installed either.
7388 return dyn_winpty_init(TRUE);
7389
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007390 if (opt->jo_tty_type != NUL)
7391 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007392
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007393 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007394 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007395 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007396 use_conpty = TRUE;
7397 else if (has_winpty)
7398 use_winpty = TRUE;
7399 // else: error
7400 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007401 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007402 {
7403 if (has_winpty)
7404 use_winpty = TRUE;
7405 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007406 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007407 {
7408 if (has_conpty)
7409 use_conpty = TRUE;
7410 else
7411 return dyn_conpty_init(TRUE);
7412 }
7413
7414 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007415 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007416
7417 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007418 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007419
7420 // error
7421 return dyn_winpty_init(TRUE);
7422}
7423
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007424 static int
7425create_pty_only(term_T *term, jobopt_T *options)
7426{
7427 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7428 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7429 char in_name[80], out_name[80];
7430 channel_T *channel = NULL;
7431
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007432 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7433 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007434
7435 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7436 GetCurrentProcessId(),
7437 curbuf->b_fnum);
7438 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7439 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7440 PIPE_UNLIMITED_INSTANCES,
7441 0, 0, NMPWAIT_NOWAIT, NULL);
7442 if (hPipeIn == INVALID_HANDLE_VALUE)
7443 goto failed;
7444
7445 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7446 GetCurrentProcessId(),
7447 curbuf->b_fnum);
7448 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7449 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7450 PIPE_UNLIMITED_INSTANCES,
7451 0, 0, 0, NULL);
7452 if (hPipeOut == INVALID_HANDLE_VALUE)
7453 goto failed;
7454
7455 ConnectNamedPipe(hPipeIn, NULL);
7456 ConnectNamedPipe(hPipeOut, NULL);
7457
7458 term->tl_job = job_alloc();
7459 if (term->tl_job == NULL)
7460 goto failed;
7461 ++term->tl_job->jv_refcount;
7462
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007463 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007464 term->tl_job->jv_status = JOB_FINISHED;
7465
7466 channel = add_channel();
7467 if (channel == NULL)
7468 goto failed;
7469 term->tl_job->jv_channel = channel;
7470 channel->ch_keep_open = TRUE;
7471 channel->ch_named_pipe = TRUE;
7472
7473 channel_set_pipes(channel,
7474 (sock_T)hPipeIn,
7475 (sock_T)hPipeOut,
7476 (sock_T)hPipeOut);
7477 channel_set_job(channel, term->tl_job, options);
7478 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7479 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7480
7481 return OK;
7482
7483failed:
7484 if (hPipeIn != NULL)
7485 CloseHandle(hPipeIn);
7486 if (hPipeOut != NULL)
7487 CloseHandle(hPipeOut);
7488 return FAIL;
7489}
7490
7491/*
7492 * Free the terminal emulator part of "term".
7493 */
7494 static void
7495term_free_vterm(term_T *term)
7496{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007497 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007498 if (term->tl_winpty != NULL)
7499 winpty_free(term->tl_winpty);
7500 term->tl_winpty = NULL;
7501 if (term->tl_winpty_config != NULL)
7502 winpty_config_free(term->tl_winpty_config);
7503 term->tl_winpty_config = NULL;
7504 if (term->tl_vterm != NULL)
7505 vterm_free(term->tl_vterm);
7506 term->tl_vterm = NULL;
7507}
7508
7509/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007510 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007511 */
7512 static void
7513term_report_winsize(term_T *term, int rows, int cols)
7514{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007515 if (term->tl_conpty)
7516 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007517 if (term->tl_winpty)
7518 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7519}
7520
7521 int
7522terminal_enabled(void)
7523{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007524 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007525}
7526
7527# else
7528
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007529///////////////////////////////////////
7530// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007531
7532/*
7533 * Create a new terminal of "rows" by "cols" cells.
7534 * Start job for "cmd".
7535 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007536 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007537 * Return OK or FAIL.
7538 */
7539 static int
7540term_and_job_init(
7541 term_T *term,
7542 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007543 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007544 jobopt_T *opt,
7545 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007546{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007547 term->tl_arg0_cmd = NULL;
7548
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007549 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7550 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007551
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007552#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007553 if (term_use_palette())
7554 {
7555 if (term->tl_palette != NULL)
7556 set_vterm_palette(term->tl_vterm, term->tl_palette);
7557 else
7558 init_vterm_ansi_colors(term->tl_vterm);
7559 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007560#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007561
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007562 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007563 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007564 if (term->tl_job != NULL)
7565 ++term->tl_job->jv_refcount;
7566
7567 return term->tl_job != NULL
7568 && term->tl_job->jv_channel != NULL
7569 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7570}
7571
7572 static int
7573create_pty_only(term_T *term, jobopt_T *opt)
7574{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007575 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7576 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007577
7578 term->tl_job = job_alloc();
7579 if (term->tl_job == NULL)
7580 return FAIL;
7581 ++term->tl_job->jv_refcount;
7582
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007583 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007584 term->tl_job->jv_status = JOB_FINISHED;
7585
7586 return mch_create_pty_channel(term->tl_job, opt);
7587}
7588
7589/*
7590 * Free the terminal emulator part of "term".
7591 */
7592 static void
7593term_free_vterm(term_T *term)
7594{
7595 if (term->tl_vterm != NULL)
7596 vterm_free(term->tl_vterm);
7597 term->tl_vterm = NULL;
7598}
7599
7600/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007601 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007602 */
7603 static void
7604term_report_winsize(term_T *term, int rows, int cols)
7605{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007606 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007607 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
7608 {
7609 int fd = -1;
7610 int part;
7611
7612 for (part = PART_OUT; part < PART_COUNT; ++part)
7613 {
7614 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01007615 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007616 break;
7617 }
7618 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7619 mch_signal_job(term->tl_job, (char_u *)"winch");
7620 }
7621}
7622
7623# endif
7624
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007625#endif // FEAT_TERMINAL