blob: 25a6a5dd7618a016a8113b2fcbe429a4aec18edc [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
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000262 if (*wp->w_p_tws == NUL)
263 return FALSE;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200264
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000265 char_u *p = vim_strchr(wp->w_p_tws, 'x');
266
267 // Syntax of value was already checked when it's set.
268 if (p == NULL)
269 {
270 minsize = TRUE;
271 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200272 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000273 *rows = atoi((char *)wp->w_p_tws);
274 *cols = atoi((char *)p + 1);
Christian Brabandtceee7a82023-09-21 16:55:06 +0200275 if (*rows > VTERM_MAX_ROWS)
276 *rows = VTERM_MAX_ROWS;
277 if (*cols > VTERM_MAX_COLS)
278 *cols = VTERM_MAX_COLS;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200279 return minsize;
280}
281
282/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200283 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200284 */
285 static void
Bram Moolenaarb936b792020-09-04 18:34:09 +0200286set_term_and_win_size(term_T *term, jobopt_T *opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200287{
Bram Moolenaarb936b792020-09-04 18:34:09 +0200288 int rows, cols;
289 int minsize;
290
Bram Moolenaar13568252018-03-16 20:46:58 +0100291#ifdef FEAT_GUI
292 if (term->tl_system)
293 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100294 // Use the whole screen for the system command. However, it will start
295 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100296 term->tl_rows = Rows;
297 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200298 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100299 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100300#endif
Bram Moolenaarb936b792020-09-04 18:34:09 +0200301 term->tl_rows = curwin->w_height;
302 term->tl_cols = curwin->w_width;
303
304 minsize = parse_termwinsize(curwin, &rows, &cols);
305 if (minsize)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200306 {
Bram Moolenaarb936b792020-09-04 18:34:09 +0200307 if (term->tl_rows < rows)
308 term->tl_rows = rows;
309 if (term->tl_cols < cols)
310 term->tl_cols = cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200312 if ((opt->jo_set2 & JO2_TERM_ROWS))
313 term->tl_rows = opt->jo_term_rows;
314 else if (rows != 0)
315 term->tl_rows = rows;
316 if ((opt->jo_set2 & JO2_TERM_COLS))
317 term->tl_cols = opt->jo_term_cols;
318 else if (cols != 0)
319 term->tl_cols = cols;
320
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200321 if (!opt->jo_hidden)
Bram Moolenaarb936b792020-09-04 18:34:09 +0200322 {
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200323 if (term->tl_rows != curwin->w_height)
324 win_setheight_win(term->tl_rows, curwin);
325 if (term->tl_cols != curwin->w_width)
326 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaarb936b792020-09-04 18:34:09 +0200327
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200328 // Set 'winsize' now to avoid a resize at the next redraw.
329 if (!minsize && *curwin->w_p_tws != NUL)
330 {
331 char_u buf[100];
332
333 vim_snprintf((char *)buf, 100, "%dx%d",
334 term->tl_rows, term->tl_cols);
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100335 set_option_value_give_err((char_u *)"termwinsize",
336 0L, buf, OPT_LOCAL);
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200337 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200338 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200339}
340
341/*
342 * Initialize job options for a terminal job.
343 * Caller may overrule some of them.
344 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100345 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346init_job_options(jobopt_T *opt)
347{
348 clear_job_options(opt);
349
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100350 opt->jo_mode = CH_MODE_RAW;
351 opt->jo_out_mode = CH_MODE_RAW;
352 opt->jo_err_mode = CH_MODE_RAW;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200353 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
354}
355
356/*
357 * Set job options mandatory for a terminal job.
358 */
359 static void
360setup_job_options(jobopt_T *opt, int rows, int cols)
361{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100362#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100363 // Win32: Redirecting the job output won't work, thus always connect stdout
364 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200365 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200366#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200367 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100368 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200369 opt->jo_io[PART_OUT] = JIO_BUFFER;
370 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
371 opt->jo_modifiable[PART_OUT] = 0;
372 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
373 }
374
Bram Moolenaar4f974752019-02-17 17:44:42 +0100375#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100376 // Win32: Redirecting the job output won't work, thus always connect stderr
377 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200378 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200379#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200380 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100381 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200382 opt->jo_io[PART_ERR] = JIO_BUFFER;
383 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
384 opt->jo_modifiable[PART_ERR] = 0;
385 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
386 }
387
388 opt->jo_pty = TRUE;
389 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
390 opt->jo_term_rows = rows;
391 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
392 opt->jo_term_cols = cols;
393}
394
395/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200396 * Flush messages on channels.
397 */
398 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +0000399term_flush_messages(void)
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200400{
401 mch_check_messages();
402 parse_queued_messages();
403}
404
405/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100406 * Close a terminal buffer (and its window). Used when creating the terminal
407 * fails.
408 */
409 static void
410term_close_buffer(buf_T *buf, buf_T *old_curbuf)
411{
412 free_terminal(buf);
413 if (old_curbuf != NULL)
414 {
415 --curbuf->b_nwindows;
416 curbuf = old_curbuf;
417 curwin->w_buffer = curbuf;
418 ++curbuf->b_nwindows;
419 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100420 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100421
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100422 // Wiping out the buffer will also close the window and call
423 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100424 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
425}
426
427/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100429 * Use either "argvar" or "argv", the other must be NULL.
430 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
431 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200432 * Returns NULL when failed.
433 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100434 buf_T *
435term_start(
436 typval_T *argvar,
437 char **argv,
438 jobopt_T *opt,
439 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200440{
441 exarg_T split_ea;
442 win_T *old_curwin = curwin;
443 term_T *term;
444 buf_T *old_curbuf = NULL;
445 int res;
446 buf_T *newbuf;
Bram Moolenaare1004402020-10-24 20:49:43 +0200447 int vertical = opt->jo_vertical || (cmdmod.cmod_split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200448 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200449
450 if (check_restricted() || check_secure())
451 return NULL;
Bram Moolenaare5b44862021-05-30 13:54:03 +0200452 if (cmdwin_type != 0)
453 {
454 emsg(_(e_cannot_open_terminal_from_command_line_window));
455 return NULL;
456 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200457
458 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
459 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
460 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100461 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
462 || (argvar != NULL
463 && argvar->v_type == VAR_LIST
464 && argvar->vval.v_list != NULL
465 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200466 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000467 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200468 return NULL;
469 }
470
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200471 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200472 if (term == NULL)
473 return NULL;
474 term->tl_dirty_row_end = MAX_ROW;
475 term->tl_cursor_visible = TRUE;
476 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
477 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100478#ifdef FEAT_GUI
479 term->tl_system = (flags & TERM_START_SYSTEM);
480#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200481 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100482 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200483 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200484
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200485 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200486 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200487 if (opt->jo_curwin)
488 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100489 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100490 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200491 {
492 no_write_message();
493 vim_free(term);
494 return NULL;
495 }
496 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200497 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
498 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
499 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200500 {
501 vim_free(term);
502 return NULL;
503 }
504 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100505 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200506 {
507 buf_T *buf;
508
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100509 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100510 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200511 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
512 BLN_NEW | BLN_LISTED);
513 if (buf == NULL || ml_open(buf) == FAIL)
514 {
515 vim_free(term);
516 return NULL;
517 }
518 old_curbuf = curbuf;
519 --curbuf->b_nwindows;
520 curbuf = buf;
521 curwin->w_buffer = buf;
522 ++curbuf->b_nwindows;
523 }
524 else
525 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100526 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200527 split_ea.cmdidx = CMD_new;
528 split_ea.cmd = (char_u *)"new";
529 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100530 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200531 {
532 split_ea.line2 = opt->jo_term_rows;
533 split_ea.addr_count = 1;
534 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100535 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200536 {
537 split_ea.line2 = opt->jo_term_cols;
538 split_ea.addr_count = 1;
539 }
540
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100541 if (vertical)
Bram Moolenaare1004402020-10-24 20:49:43 +0200542 cmdmod.cmod_split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200543 ex_splitview(&split_ea);
544 if (curwin == old_curwin)
545 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100546 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200547 vim_free(term);
548 return NULL;
549 }
550 }
551 term->tl_buffer = curbuf;
552 curbuf->b_term = term;
553
554 if (!opt->jo_hidden)
555 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100556 // Only one size was taken care of with :new, do the other one. With
557 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100558 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200559 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100560 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200561 win_setwidth(opt->jo_term_cols);
562 }
563
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100564 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200565 term->tl_next = first_term;
566 first_term = term;
567
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100568 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
569
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200570 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100571 {
572 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200573 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100574 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100575 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100576 {
577 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100578 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100579 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200580 else
581 {
582 int i;
583 size_t len;
584 char_u *cmd, *p;
585
586 if (argvar->v_type == VAR_STRING)
587 {
588 cmd = argvar->vval.v_string;
589 if (cmd == NULL)
590 cmd = (char_u *)"";
591 else if (STRCMP(cmd, "NONE") == 0)
592 cmd = (char_u *)"pty";
593 }
594 else if (argvar->v_type != VAR_LIST
595 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100596 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100597 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200598 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
599 cmd = (char_u*)"";
600
601 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200602 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200603
604 for (i = 0; p != NULL; ++i)
605 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100606 // Prepend a ! to the command name to avoid the buffer name equals
607 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200608 if (i == 0)
609 vim_snprintf((char *)p, len, "!%s", cmd);
610 else
611 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
612 if (buflist_findname(p) == NULL)
613 {
614 vim_free(curbuf->b_ffname);
615 curbuf->b_ffname = p;
616 break;
617 }
618 }
619 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100620 vim_free(curbuf->b_sfname);
621 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200622 curbuf->b_fname = curbuf->b_ffname;
623
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100624 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
625
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200626 if (opt->jo_term_opencmd != NULL)
627 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
628
629 if (opt->jo_eof_chars != NULL)
630 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
631
632 set_string_option_direct((char_u *)"buftype", -1,
633 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200634 // Avoid that 'buftype' is reset when this buffer is entered.
635 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200636
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100637 // Mark the buffer as not modifiable. It can only be made modifiable after
638 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200639 curbuf->b_p_ma = FALSE;
640
Bram Moolenaarb936b792020-09-04 18:34:09 +0200641 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100642#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200643 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
644#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200645 setup_job_options(opt, term->tl_rows, term->tl_cols);
646
Bram Moolenaar13568252018-03-16 20:46:58 +0100647 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100648 return curbuf;
649
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100650#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100651 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100652 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100653 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100654 else if (argvar->v_type == VAR_STRING)
655 {
656 char_u *cmd = argvar->vval.v_string;
657
658 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
659 term->tl_command = vim_strsave(cmd);
660 }
661 else if (argvar->v_type == VAR_LIST
662 && argvar->vval.v_list != NULL
663 && argvar->vval.v_list->lv_len > 0)
664 {
665 garray_T ga;
666 listitem_T *item;
667
668 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200669 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100670 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100671 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100672 char_u *p;
673
674 if (s == NULL)
675 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100676 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100677 if (p == NULL)
678 break;
679 ga_concat(&ga, p);
680 vim_free(p);
681 ga_append(&ga, ' ');
682 }
683 if (item == NULL)
684 {
685 ga_append(&ga, NUL);
686 term->tl_command = ga.ga_data;
687 }
688 else
689 ga_clear(&ga);
690 }
691#endif
692
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100693 if (opt->jo_term_kill != NULL)
694 {
695 char_u *p = skiptowhite(opt->jo_term_kill);
696
697 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
698 }
699
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200700 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100701 {
702 char_u *p = skiptowhite(opt->jo_term_api);
703
704 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
705 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200706 else
707 term->tl_api = vim_strsave((char_u *)"Tapi_");
708
Bram Moolenaar83d47902020-03-26 20:34:00 +0100709 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
710 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
711
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100712#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100713 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
714 if (opt->jo_set2 & JO2_ANSI_COLORS)
715 {
716 term->tl_palette = ALLOC_MULT(long_u, 16);
717 if (term->tl_palette == NULL)
718 {
719 vim_free(term);
720 return NULL;
721 }
722 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
723 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100724#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100725
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100726 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100727 if (argv == NULL
728 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200729 && argvar->vval.v_string != NULL
730 && STRCMP(argvar->vval.v_string, "NONE") == 0)
731 res = create_pty_only(term, opt);
732 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200733 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200734
735 newbuf = curbuf;
736 if (res == OK)
737 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100738 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200739 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
740 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100741#ifdef FEAT_GUI
742 if (term->tl_system)
743 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100744 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100745 term->tl_toprow = msg_row + 1;
746 term->tl_dirty_row_end = 0;
747 }
748#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200749
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100750 // Make sure we don't get stuck on sending keys to the job, it leads to
751 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200752 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
753
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200754 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200755 {
756 --curbuf->b_nwindows;
757 curbuf = old_curbuf;
758 curwin->w_buffer = curbuf;
759 ++curbuf->b_nwindows;
760 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000761 else if (vgetc_busy
762#ifdef FEAT_TIMERS
763 || timer_busy
764#endif
765 || input_busy)
766 {
767 char_u ignore[4];
768
769 // When waiting for input need to return and possibly end up in
770 // terminal_loop() instead.
771 ignore[0] = K_SPECIAL;
772 ignore[1] = KS_EXTRA;
773 ignore[2] = KE_IGNORE;
774 ignore[3] = NUL;
775 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
776 typebuf_was_filled = TRUE;
777 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200778 }
779 else
780 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100781 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200782 return NULL;
783 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100784
Bram Moolenaar13568252018-03-16 20:46:58 +0100785 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200786 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
787 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788 return newbuf;
789}
790
791/*
792 * ":terminal": open a terminal window and execute a job in it.
793 */
794 void
795ex_terminal(exarg_T *eap)
796{
797 typval_T argvar[2];
798 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100799 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200800 char_u *cmd;
801 char_u *tofree = NULL;
802
803 init_job_options(&opt);
804
805 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100806 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200807 {
808 char_u *p, *ep;
809
810 cmd += 2;
811 p = skiptowhite(cmd);
812 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200813 if (ep != NULL)
814 {
815 if (ep < p)
816 p = ep;
817 else
818 ep = NULL;
819 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200820
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200821 // Note: Keep this in sync with get_terminalopt_name.
822
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200823# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
824 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
825 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200826 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200827 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100828 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200829 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200830 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200831 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200832 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200833 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200834 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200835 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100836 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100837 else if (OPTARG_HAS("shell"))
838 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200839 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100840 {
841 opt.jo_set2 |= JO2_TERM_KILL;
842 opt.jo_term_kill = ep + 1;
843 p = skiptowhite(cmd);
844 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200845 else if (OPTARG_HAS("api"))
846 {
847 opt.jo_set2 |= JO2_TERM_API;
848 if (ep != NULL)
849 {
850 opt.jo_term_api = ep + 1;
851 p = skiptowhite(cmd);
852 }
853 else
854 opt.jo_term_api = NULL;
855 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100856 else if (OPTARG_HAS("rows") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200857 {
858 opt.jo_set2 |= JO2_TERM_ROWS;
859 opt.jo_term_rows = atoi((char *)ep + 1);
860 p = skiptowhite(cmd);
861 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100862 else if (OPTARG_HAS("cols") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200863 {
864 opt.jo_set2 |= JO2_TERM_COLS;
865 opt.jo_term_cols = atoi((char *)ep + 1);
866 p = skiptowhite(cmd);
867 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200868 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200869 {
870 char_u *buf = NULL;
871 char_u *keys;
872
Bram Moolenaar21109272020-01-30 16:27:20 +0100873 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200874 p = skiptowhite(cmd);
875 *p = NUL;
zeertzjq7e0bae02023-08-11 23:15:38 +0200876 keys = replace_termcodes(ep + 1, &buf, 0,
Bram Moolenaar459fd782019-10-13 16:43:39 +0200877 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200878 opt.jo_set2 |= JO2_EOF_CHARS;
879 opt.jo_eof_chars = vim_strsave(keys);
880 vim_free(buf);
881 *p = ' ';
882 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100883#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100884 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
885 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100886 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100887 int tty_type = NUL;
888
889 p = skiptowhite(cmd);
890 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
891 tty_type = 'w';
892 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
893 tty_type = 'c';
894 else
895 {
Bram Moolenaar50809a42023-05-20 16:39:07 +0100896 semsg(_(e_invalid_value_for_argument_str), "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100897 goto theend;
898 }
899 opt.jo_set2 |= JO2_TTY_TYPE;
900 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100901 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100902#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200903 else
904 {
905 if (*p)
906 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000907 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100908 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200909 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200910# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200911 cmd = skipwhite(p);
912 }
913 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100914 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100915 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200916 tofree = cmd = vim_strsave(p_sh);
917
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100918 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100919 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200920 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100921 }
922
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200923 if (eap->addr_count > 0)
924 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100925 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200926 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
927 opt.jo_io[PART_IN] = JIO_BUFFER;
928 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
929 opt.jo_in_top = eap->line1;
930 opt.jo_in_bot = eap->line2;
931 }
932
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100933 if (opt_shell && tofree == NULL)
934 {
935#ifdef UNIX
936 char **argv = NULL;
937 char_u *tofree1 = NULL;
938 char_u *tofree2 = NULL;
939
940 // :term ++shell command
941 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
942 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100943 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100944 vim_free(tofree1);
945 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100946 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100947#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100948# ifdef MSWIN
949 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
950 char_u *newcmd;
951
952 newcmd = alloc(cmdlen);
953 if (newcmd == NULL)
954 goto theend;
955 tofree = newcmd;
956 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
957 cmd = newcmd;
958# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000959 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100960 goto theend;
961# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100962#endif
963 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100964 argvar[0].v_type = VAR_STRING;
965 argvar[0].vval.v_string = cmd;
966 argvar[1].v_type = VAR_UNKNOWN;
967 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100968
969theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100970 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200971 vim_free(opt.jo_eof_chars);
972}
973
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200974 static char_u *
975get_terminalopt_name(expand_T *xp UNUSED, int idx)
976{
977 // Note: Keep this in sync with ex_terminal.
978 static char *(p_termopt_values[]) =
979 {
980 "close",
981 "noclose",
982 "open",
983 "curwin",
984 "hidden",
985 "norestore",
986 "shell",
987 "kill=",
988 "rows=",
989 "cols=",
990 "eof=",
991 "type=",
992 "api=",
993 };
994
995 if (idx < (int)ARRAY_LENGTH(p_termopt_values))
996 return (char_u*)p_termopt_values[idx];
997 return NULL;
998}
999
1000 static char_u *
1001get_termkill_name(expand_T *xp UNUSED, int idx)
1002{
1003 // These are platform-specific values used for job_stop(). They are defined
1004 // in each platform's mch_signal_job(). Just use a unified auto-complete
1005 // list for simplicity.
1006 static char *(p_termkill_values[]) =
1007 {
1008 "term",
1009 "hup",
1010 "quit",
1011 "int",
1012 "kill",
1013 "winch",
1014 };
1015
1016 if (idx < (int)ARRAY_LENGTH(p_termkill_values))
1017 return (char_u*)p_termkill_values[idx];
1018 return NULL;
1019}
1020
1021/*
1022 * Command-line expansion for :terminal [options]
1023 */
1024 int
1025expand_terminal_opt(
1026 char_u *pat,
1027 expand_T *xp,
1028 regmatch_T *rmp,
1029 char_u ***matches,
1030 int *numMatches)
1031{
1032 if (xp->xp_pattern > xp->xp_line && *(xp->xp_pattern-1) == '=')
1033 {
1034 char_u *(*cb)(expand_T *, int) = NULL;
1035
1036 char_u *name_end = xp->xp_pattern - 1;
1037 if (name_end - xp->xp_line >= 4
1038 && STRNCMP(name_end - 4, "kill", 4) == 0)
1039 cb = get_termkill_name;
1040
1041 if (cb != NULL)
1042 {
1043 return ExpandGeneric(
1044 pat,
1045 xp,
1046 rmp,
1047 matches,
1048 numMatches,
1049 cb,
1050 FALSE);
1051 }
1052 return FAIL;
1053 }
1054 return ExpandGeneric(
1055 pat,
1056 xp,
1057 rmp,
1058 matches,
1059 numMatches,
1060 get_terminalopt_name,
1061 FALSE);
1062}
1063
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001064#if defined(FEAT_SESSION) || defined(PROTO)
1065/*
1066 * Write a :terminal command to the session file to restore the terminal in
1067 * window "wp".
1068 * Return FAIL if writing fails.
1069 */
1070 int
Bram Moolenaar0e655112020-09-11 20:36:36 +02001071term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001072{
Bram Moolenaar0e655112020-09-11 20:36:36 +02001073 const int bufnr = wp->w_buffer->b_fnum;
1074 term_T *term = wp->w_buffer->b_term;
1075
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001076 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001077 {
1078 // There are multiple views into this terminal buffer. We don't want to
1079 // create the terminal multiple times. If it's the first time, create,
1080 // otherwise link to the first buffer.
1081 char id_as_str[NUMBUFLEN];
1082 hashitem_T *entry;
1083
1084 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
1085
1086 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
1087 if (!HASHITEM_EMPTY(entry))
1088 {
1089 // we've already opened this terminal buffer
1090 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
1091 return FAIL;
1092 return put_eol(fd);
1093 }
1094 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001095
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001096 // Create the terminal and run the command. This is not without
1097 // risk, but let's assume the user only creates a session when this
1098 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001099 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1100 term->tl_cols, term->tl_rows) < 0)
1101 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001102#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001103 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1104 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001105#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001106 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1107 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001108 if (put_eol(fd) != OK)
1109 return FAIL;
1110
1111 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1112 return FAIL;
1113
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001114 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001115 {
1116 char *hash_key = alloc(NUMBUFLEN);
1117
1118 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00001119 hash_add(terminal_bufs, (char_u *)hash_key, "terminal session");
Bram Moolenaar0e655112020-09-11 20:36:36 +02001120 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001121
1122 return put_eol(fd);
1123}
1124
1125/*
1126 * Return TRUE if "buf" has a terminal that should be restored.
1127 */
1128 int
1129term_should_restore(buf_T *buf)
1130{
1131 term_T *term = buf->b_term;
1132
1133 return term != NULL && (term->tl_command == NULL
1134 || STRCMP(term->tl_command, "NONE") != 0);
1135}
1136#endif
1137
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001138/*
1139 * Free the scrollback buffer for "term".
1140 */
1141 static void
1142free_scrollback(term_T *term)
1143{
1144 int i;
1145
1146 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1147 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1148 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001149 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1150 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1151 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001152}
1153
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001154
1155// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001156static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001157
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001158/*
1159 * Free a terminal and everything it refers to.
1160 * Kills the job if there is one.
1161 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001162 * The actual terminal structure is freed later in free_unused_terminals(),
1163 * because callbacks may wipe out a buffer while the terminal is still
1164 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001165 */
1166 void
1167free_terminal(buf_T *buf)
1168{
1169 term_T *term = buf->b_term;
1170 term_T *tp;
1171
1172 if (term == NULL)
1173 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001174
1175 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001176 if (first_term == term)
1177 first_term = term->tl_next;
1178 else
1179 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1180 if (tp->tl_next == term)
1181 {
1182 tp->tl_next = term->tl_next;
1183 break;
1184 }
1185
1186 if (term->tl_job != NULL)
1187 {
1188 if (term->tl_job->jv_status != JOB_ENDED
1189 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001190 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001191 job_stop(term->tl_job, NULL, "kill");
1192 job_unref(term->tl_job);
1193 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001194 term->tl_next = terminals_to_free;
1195 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001196
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001197 buf->b_term = NULL;
1198 if (in_terminal_loop == term)
1199 in_terminal_loop = NULL;
1200}
1201
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001202 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00001203free_unused_terminals(void)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001204{
1205 while (terminals_to_free != NULL)
1206 {
1207 term_T *term = terminals_to_free;
1208
1209 terminals_to_free = term->tl_next;
1210
1211 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001212 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001213
1214 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001215 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001216 vim_free(term->tl_title);
1217#ifdef FEAT_SESSION
1218 vim_free(term->tl_command);
1219#endif
1220 vim_free(term->tl_kill);
1221 vim_free(term->tl_status_text);
1222 vim_free(term->tl_opencmd);
1223 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001224 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001225#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001226 if (term->tl_out_fd != NULL)
1227 fclose(term->tl_out_fd);
1228#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001229 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001230 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001231 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001232 vim_free(term);
1233 }
1234}
1235
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001236/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001237 * Get the part that is connected to the tty. Normally this is PART_IN, but
1238 * when writing buffer lines to the job it can be another. This makes it
1239 * possible to do "1,5term vim -".
1240 */
1241 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001242get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001243{
1244#ifdef UNIX
1245 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1246 int i;
1247
1248 for (i = 0; i < 3; ++i)
1249 {
1250 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1251
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001252 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001253 return parts[i];
1254 }
1255#endif
1256 return PART_IN;
1257}
1258
1259/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001260 * Read any vterm output and send it on the channel.
1261 */
1262 static void
1263term_forward_output(term_T *term)
1264{
1265 VTerm *vterm = term->tl_vterm;
1266 char buf[KEY_BUF_LEN];
1267 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1268
1269 if (curlen > 0)
1270 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1271 (char_u *)buf, (int)curlen, NULL);
1272}
1273
1274/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001275 * Write job output "msg[len]" to the vterm.
1276 */
1277 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001278term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001279{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001280 char_u *msg = msg_arg;
1281 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001282 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001283 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001284 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1285
1286 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1287 // the end.
1288 if (len > limit)
1289 {
1290 char_u *p = msg + len - limit;
1291
1292 p -= (*mb_head_off)(msg, p);
1293 len -= p - msg;
1294 msg = p;
1295 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001296
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001297 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001298
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001299 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001300 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001301 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001302
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001303 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001304 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1305}
1306
1307 static void
Bram Moolenaar58806c12023-04-29 14:26:02 +01001308position_cursor(win_T *wp, VTermPos *pos)
1309{
1310 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1311 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1312#ifdef FEAT_PROP_POPUP
1313 if (popup_is_popup(wp))
1314 {
1315 wp->w_wrow += popup_top_extra(wp);
1316 wp->w_wcol += popup_left_extra(wp);
1317 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
1318 }
1319 else
1320 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
1321#endif
1322 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1323}
1324
1325 static void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001326update_cursor(term_T *term, int redraw)
1327{
1328 if (term->tl_normal_mode)
1329 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001330#ifdef FEAT_GUI
1331 if (term->tl_system)
1332 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1333 term->tl_cursor_pos.col);
1334 else
1335#endif
Bram Moolenaar58806c12023-04-29 14:26:02 +01001336 if (!term_job_running(term))
1337 // avoid the cursor positioned below the last used line
Bram Moolenaar13568252018-03-16 20:46:58 +01001338 setcursor();
Bram Moolenaar58806c12023-04-29 14:26:02 +01001339 else
1340 {
1341 // do not use the window cursor position
1342 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1343 windgoto(W_WINROW(curwin) + curwin->w_wrow,
1344 curwin->w_wincol + curwin->w_wcol);
1345 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001346 if (redraw)
1347 {
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001348 aco_save_T aco;
1349
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001350 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1351 cursor_on();
1352 out_flush();
1353#ifdef FEAT_GUI
1354 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001355 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001356 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001357 gui_mch_flush();
1358 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001359#endif
Bram Moolenaar24fe33a2022-11-24 00:09:02 +00001360 // Make sure an invoked autocmd doesn't delete the buffer (and the
1361 // terminal) under our fingers.
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001362 ++term->tl_buffer->b_locked;
1363
1364 // save and restore curwin and curbuf, in case the autocmd changes them
1365 aucmd_prepbuf(&aco, curbuf);
1366 apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, FALSE, term->tl_buffer);
1367 aucmd_restbuf(&aco);
1368
1369 --term->tl_buffer->b_locked;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001370 }
1371}
1372
1373/*
1374 * Invoked when "msg" output from a job was received. Write it to the terminal
1375 * of "buffer".
1376 */
1377 void
1378write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1379{
1380 size_t len = STRLEN(msg);
1381 term_T *term = buffer->b_term;
1382
Bram Moolenaar4f974752019-02-17 17:44:42 +01001383#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001384 // Win32: Cannot redirect output of the job, intercept it here and write to
1385 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001386 if (term->tl_out_fd != NULL)
1387 {
1388 ch_log(channel, "Writing %d bytes to output file", (int)len);
1389 fwrite(msg, len, 1, term->tl_out_fd);
1390 return;
1391 }
1392#endif
1393
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001394 if (term->tl_vterm == NULL)
1395 {
1396 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1397 return;
1398 }
1399 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001400 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001401 term_write_job_output(term, msg, len);
1402
Bram Moolenaar13568252018-03-16 20:46:58 +01001403#ifdef FEAT_GUI
1404 if (term->tl_system)
1405 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001406 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001407 update_system_term(term);
1408 update_cursor(term, TRUE);
1409 }
1410 else
1411#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001412 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1413 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001414 if (!term->tl_normal_mode)
1415 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001416 // Don't use update_screen() when editing the command line, it gets
1417 // cleared.
1418 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001419 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001420 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001421 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001422 update_screen(UPD_VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001423 // update_screen() can be slow, check the terminal wasn't closed
1424 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001425 if (buffer == curbuf && curbuf->b_term != NULL)
1426 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001427 }
1428 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001429 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001430 }
1431}
1432
1433/*
1434 * Send a mouse position and click to the vterm
1435 */
1436 static int
1437term_send_mouse(VTerm *vterm, int button, int pressed)
1438{
1439 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001440 int row = mouse_row - W_WINROW(curwin);
1441 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001442
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001443#ifdef FEAT_PROP_POPUP
1444 if (popup_is_popup(curwin))
1445 {
1446 row -= popup_top_extra(curwin);
1447 col -= popup_left_extra(curwin);
1448 }
1449#endif
1450 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001451 if (button != 0)
1452 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001453 return TRUE;
1454}
1455
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001456static int enter_mouse_col = -1;
1457static int enter_mouse_row = -1;
1458
1459/*
1460 * Handle a mouse click, drag or release.
1461 * Return TRUE when a mouse event is sent to the terminal.
1462 */
1463 static int
1464term_mouse_click(VTerm *vterm, int key)
1465{
1466#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001467 // For modeless selection mouse drag and release events are ignored, unless
1468 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001469 static int ignore_drag_release = TRUE;
1470 VTermMouseState mouse_state;
1471
1472 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1473 if (mouse_state.flags == 0)
1474 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001475 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001476 switch (key)
1477 {
1478 case K_LEFTDRAG:
1479 case K_LEFTRELEASE:
1480 case K_RIGHTDRAG:
1481 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001482 // Ignore drag and release events when the button-down wasn't
1483 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001484 if (ignore_drag_release)
1485 {
1486 int save_mouse_col, save_mouse_row;
1487
1488 if (enter_mouse_col < 0)
1489 break;
1490
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001491 // mouse click in the window gave us focus, handle that
1492 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001493 save_mouse_col = mouse_col;
1494 save_mouse_row = mouse_row;
1495 mouse_col = enter_mouse_col;
1496 mouse_row = enter_mouse_row;
1497 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1498 mouse_col = save_mouse_col;
1499 mouse_row = save_mouse_row;
1500 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001501 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001502 case K_LEFTMOUSE:
1503 case K_RIGHTMOUSE:
1504 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1505 ignore_drag_release = TRUE;
1506 else
1507 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001508 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001509 if (clip_star.available)
1510 {
1511 int button, is_click, is_drag;
1512
1513 button = get_mouse_button(KEY2TERMCAP1(key),
1514 &is_click, &is_drag);
1515 if (mouse_model_popup() && button == MOUSE_LEFT
1516 && (mod_mask & MOD_MASK_SHIFT))
1517 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001518 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001519 button = MOUSE_RIGHT;
1520 mod_mask &= ~MOD_MASK_SHIFT;
1521 }
1522 clip_modeless(button, is_click, is_drag);
1523 }
1524 break;
1525
1526 case K_MIDDLEMOUSE:
1527 if (clip_star.available)
1528 insert_reg('*', TRUE);
1529 break;
1530 }
1531 enter_mouse_col = -1;
1532 return FALSE;
1533 }
1534#endif
1535 enter_mouse_col = -1;
1536
1537 switch (key)
1538 {
1539 case K_LEFTMOUSE:
1540 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1541 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1542 case K_LEFTRELEASE:
1543 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1544 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1545 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1546 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1547 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1548 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1549 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1550 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1551 }
1552 return TRUE;
1553}
1554
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001555/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001556 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1557 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001558 * Return the number of bytes in "buf".
1559 */
1560 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001561term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001562{
1563 VTerm *vterm = term->tl_vterm;
1564 VTermKey key = VTERM_KEY_NONE;
1565 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001566 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001567
1568 switch (c)
1569 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001570 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001571
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001572 // don't use VTERM_KEY_BACKSPACE, it always
1573 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001574 case K_BS: c = term_backspace_char; break;
1575
1576 case ESC: key = VTERM_KEY_ESCAPE; break;
1577 case K_DEL: key = VTERM_KEY_DEL; break;
1578 case K_DOWN: key = VTERM_KEY_DOWN; break;
1579 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1580 key = VTERM_KEY_DOWN; break;
1581 case K_END: key = VTERM_KEY_END; break;
1582 case K_S_END: mod = VTERM_MOD_SHIFT;
1583 key = VTERM_KEY_END; break;
1584 case K_C_END: mod = VTERM_MOD_CTRL;
1585 key = VTERM_KEY_END; break;
1586 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1587 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1588 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1589 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1590 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1591 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1592 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1593 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1594 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1595 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1596 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1597 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1598 case K_HOME: key = VTERM_KEY_HOME; break;
1599 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1600 key = VTERM_KEY_HOME; break;
1601 case K_C_HOME: mod = VTERM_MOD_CTRL;
1602 key = VTERM_KEY_HOME; break;
1603 case K_INS: key = VTERM_KEY_INS; break;
1604 case K_K0: key = VTERM_KEY_KP_0; break;
1605 case K_K1: key = VTERM_KEY_KP_1; break;
1606 case K_K2: key = VTERM_KEY_KP_2; break;
1607 case K_K3: key = VTERM_KEY_KP_3; break;
1608 case K_K4: key = VTERM_KEY_KP_4; break;
1609 case K_K5: key = VTERM_KEY_KP_5; break;
1610 case K_K6: key = VTERM_KEY_KP_6; break;
1611 case K_K7: key = VTERM_KEY_KP_7; break;
1612 case K_K8: key = VTERM_KEY_KP_8; break;
1613 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001614 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001615 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001616 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001617 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001618 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1619 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001620 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1621 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001622 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1623 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001624 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1625 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1626 case K_LEFT: key = VTERM_KEY_LEFT; break;
1627 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1628 key = VTERM_KEY_LEFT; break;
1629 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1630 key = VTERM_KEY_LEFT; break;
1631 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1632 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1633 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1634 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1635 key = VTERM_KEY_RIGHT; break;
1636 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1637 key = VTERM_KEY_RIGHT; break;
1638 case K_UP: key = VTERM_KEY_UP; break;
1639 case K_S_UP: mod = VTERM_MOD_SHIFT;
1640 key = VTERM_KEY_UP; break;
1641 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001642 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1643 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001644
Bram Moolenaara42ad572017-11-16 13:08:04 +01001645 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1646 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001647 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1648 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001649
1650 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001651 case K_LEFTMOUSE_NM:
1652 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001653 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001654 case K_LEFTRELEASE_NM:
1655 case K_MOUSEMOVE:
1656 case K_MIDDLEMOUSE:
1657 case K_MIDDLEDRAG:
1658 case K_MIDDLERELEASE:
1659 case K_RIGHTMOUSE:
1660 case K_RIGHTDRAG:
1661 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1662 return 0;
1663 other = TRUE;
1664 break;
1665
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001666 case K_X1MOUSE: /* TODO */ return 0;
1667 case K_X1DRAG: /* TODO */ return 0;
1668 case K_X1RELEASE: /* TODO */ return 0;
1669 case K_X2MOUSE: /* TODO */ return 0;
1670 case K_X2DRAG: /* TODO */ return 0;
1671 case K_X2RELEASE: /* TODO */ return 0;
1672
1673 case K_IGNORE: return 0;
1674 case K_NOP: return 0;
1675 case K_UNDO: return 0;
1676 case K_HELP: return 0;
1677 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1678 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1679 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1680 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1681 case K_SELECT: return 0;
1682#ifdef FEAT_GUI
1683 case K_VER_SCROLLBAR: return 0;
1684 case K_HOR_SCROLLBAR: return 0;
1685#endif
1686#ifdef FEAT_GUI_TABLINE
1687 case K_TABLINE: return 0;
1688 case K_TABMENU: return 0;
1689#endif
1690#ifdef FEAT_NETBEANS_INTG
1691 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1692#endif
1693#ifdef FEAT_DND
1694 case K_DROP: return 0;
1695#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001696 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001697 case K_PS: vterm_keyboard_start_paste(vterm);
1698 other = TRUE;
1699 break;
1700 case K_PE: vterm_keyboard_end_paste(vterm);
1701 other = TRUE;
1702 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001703 }
1704
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001705 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001706 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001707 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001708 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001709 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001710 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001711 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001712
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001713 // Ctrl-Shift-i may have the key "I" instead of "i", but for the kitty
1714 // keyboard protocol should use "i". Applies to all ascii letters.
1715 if (ASCII_ISUPPER(c)
Bram Moolenaarebed1b02022-11-24 14:05:19 +00001716 && vterm_is_kitty_keyboard(vterm)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001717 && mod == (VTERM_MOD_CTRL | VTERM_MOD_SHIFT))
1718 c = TOLOWER_ASC(c);
1719
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001720 /*
1721 * Convert special keys to vterm keys:
1722 * - Write keys to vterm: vterm_keyboard_key()
1723 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001724 */
1725 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001726 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001727 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001728 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001729 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001730 vterm_keyboard_unichar(vterm, c, mod);
1731
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001732 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001733 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1734}
1735
1736/*
1737 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001738 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001739 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001740 */
1741 static int
1742term_job_running_check(term_T *term, int check_job_status)
1743{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001744 // Also consider the job finished when the channel is closed, to avoid a
1745 // race condition when updating the title.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001746 if (term == NULL
1747 || term->tl_job == NULL
1748 || !channel_is_open(term->tl_job->jv_channel))
1749 return FALSE;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001750
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001751 job_T *job = term->tl_job;
1752
1753 // Careful: Checking the job status may invoke callbacks, which close
1754 // the buffer and terminate "term". However, "job" will not be freed
1755 // yet.
1756 if (check_job_status)
1757 job_status(job);
1758 return (job->jv_status == JOB_STARTED
1759 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001760}
1761
1762/*
1763 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001764 */
1765 int
1766term_job_running(term_T *term)
1767{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001768 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001769}
1770
1771/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001772 * Return TRUE if the job for "term" is still running, ignoring the job was
1773 * "NONE".
1774 */
1775 int
1776term_job_running_not_none(term_T *term)
1777{
1778 return term_job_running(term) && !term_none_open(term);
1779}
1780
1781/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001782 * Return TRUE if "term" has an active channel and used ":term NONE".
1783 */
1784 int
1785term_none_open(term_T *term)
1786{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001787 // Also consider the job finished when the channel is closed, to avoid a
1788 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001789 return term != NULL
1790 && term->tl_job != NULL
1791 && channel_is_open(term->tl_job->jv_channel)
1792 && term->tl_job->jv_channel->ch_keep_open;
1793}
1794
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001795//
1796// Used to confirm whether we would like to kill a terminal.
1797// Return OK when the user confirms to kill it.
1798// Return FAIL if the user selects otherwise.
1799//
1800 int
1801term_confirm_stop(buf_T *buf)
1802{
1803 char_u buff[DIALOG_MSG_SIZE];
1804 int ret;
1805
1806 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1807 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1808 if (ret == VIM_YES)
1809 return OK;
1810 else
1811 return FAIL;
1812}
1813
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001814/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001815 * Used when exiting: kill the job in "buf" if so desired.
1816 * Return OK when the job finished.
1817 * Return FAIL when the job is still running.
1818 */
1819 int
1820term_try_stop_job(buf_T *buf)
1821{
1822 int count;
1823 char *how = (char *)buf->b_term->tl_kill;
1824
1825#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001826 if ((how == NULL || *how == NUL)
1827 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001828 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001829 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001830 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001831 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001832 return FAIL;
1833 }
1834#endif
1835 if (how == NULL || *how == NUL)
1836 return FAIL;
1837
1838 job_stop(buf->b_term->tl_job, NULL, how);
1839
Bram Moolenaar9172d232019-01-29 23:06:54 +01001840 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001841 for (count = 0; count < 100; ++count)
1842 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001843 job_T *job;
1844
1845 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001846 if (!buf_valid(buf)
1847 || buf->b_term == NULL
1848 || buf->b_term->tl_job == NULL)
1849 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001850 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001851
Bram Moolenaar9172d232019-01-29 23:06:54 +01001852 // Call job_status() to update jv_status. It may cause the job to be
1853 // cleaned up but it won't be freed.
1854 job_status(job);
1855 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001856 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001857
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001858 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001859 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001860 }
1861 return FAIL;
1862}
1863
1864/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001865 * Add the last line of the scrollback buffer to the buffer in the window.
1866 */
1867 static void
1868add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1869{
1870 buf_T *buf = term->tl_buffer;
1871 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1872 linenr_T lnum = buf->b_ml.ml_line_count;
1873
Bram Moolenaar4f974752019-02-17 17:44:42 +01001874#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875 if (!enc_utf8 && enc_codepage > 0)
1876 {
1877 WCHAR *ret = NULL;
1878 int length = 0;
1879
1880 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1881 &ret, &length);
1882 if (ret != NULL)
1883 {
1884 WideCharToMultiByte_alloc(enc_codepage, 0,
1885 ret, length, (char **)&text, &len, 0, 0);
1886 vim_free(ret);
1887 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1888 vim_free(text);
1889 }
1890 }
1891 else
1892#endif
1893 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1894 if (empty)
1895 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001896 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001898 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001899 curbuf = curwin->w_buffer;
1900 }
1901}
1902
1903 static void
1904cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1905{
1906 attr->width = cell->width;
1907 attr->attrs = cell->attrs;
1908 attr->fg = cell->fg;
1909 attr->bg = cell->bg;
1910}
1911
1912 static int
1913equal_celattr(cellattr_T *a, cellattr_T *b)
1914{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001915 // We only compare the RGB colors, ignoring the ANSI index and type.
1916 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001917 return a->fg.red == b->fg.red
1918 && a->fg.green == b->fg.green
1919 && a->fg.blue == b->fg.blue
1920 && a->bg.red == b->bg.red
1921 && a->bg.green == b->bg.green
1922 && a->bg.blue == b->bg.blue;
1923}
1924
Bram Moolenaard96ff162018-02-18 22:13:29 +01001925/*
1926 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1927 * line at this position. Otherwise at the end.
1928 */
1929 static int
1930add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1931{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001932 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
1933 return FALSE;
1934
1935 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1936 + term->tl_scrollback.ga_len;
1937
1938 if (lnum > 0)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001939 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001940 int i;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001941
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001942 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001943 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001944 *line = *(line - 1);
1945 --line;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001946 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01001947 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001948 line->sb_cols = 0;
1949 line->sb_cells = NULL;
1950 line->sb_fill_attr = *fill_attr;
1951 ++term->tl_scrollback.ga_len;
1952 return OK;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001953}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001954
1955/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001956 * Remove the terminal contents from the scrollback and the buffer.
1957 * Used before adding a new scrollback line or updating the buffer for lines
1958 * displayed in the terminal.
1959 */
1960 static void
1961cleanup_scrollback(term_T *term)
1962{
1963 sb_line_T *line;
1964 garray_T *gap;
1965
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001966 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001967 gap = &term->tl_scrollback;
1968 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1969 && gap->ga_len > 0)
1970 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001971 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001972 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1973 vim_free(line->sb_cells);
1974 --gap->ga_len;
1975 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001976 curbuf = curwin->w_buffer;
1977 if (curbuf == term->tl_buffer)
1978 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001979}
1980
1981/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001982 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001983 */
1984 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001985update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001986{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001987 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001988 int len;
1989 int lines_skipped = 0;
1990 VTermPos pos;
1991 VTermScreenCell cell;
1992 cellattr_T fill_attr, new_fill_attr;
1993 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001994
1995 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1996 "Adding terminal window snapshot to buffer");
1997
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001998 // First remove the lines that were appended before, they might be
1999 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002000 cleanup_scrollback(term);
2001
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002002 screen = vterm_obtain_screen(term->tl_vterm);
2003 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002004 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
2005 {
2006 len = 0;
2007 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
2008 if (vterm_screen_get_cell(screen, pos, &cell) != 0
2009 && cell.chars[0] != NUL)
2010 {
2011 len = pos.col + 1;
2012 new_fill_attr = term->tl_default_color;
2013 }
2014 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002015 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016 cell2cellattr(&cell, &new_fill_attr);
2017
2018 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
2019 ++lines_skipped;
2020 else
2021 {
2022 while (lines_skipped > 0)
2023 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002024 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002025 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002026 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002027 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 }
2029
2030 if (len == 0)
2031 p = NULL;
2032 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002033 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002034 if ((p != NULL || len == 0)
2035 && ga_grow(&term->tl_scrollback, 1) == OK)
2036 {
2037 garray_T ga;
2038 int width;
2039 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
2040 + term->tl_scrollback.ga_len;
2041
2042 ga_init2(&ga, 1, 100);
2043 for (pos.col = 0; pos.col < len; pos.col += width)
2044 {
2045 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2046 {
2047 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02002048 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002049 if (ga_grow(&ga, 1) == OK)
2050 ga.ga_len += utf_char2bytes(' ',
2051 (char_u *)ga.ga_data + ga.ga_len);
2052 }
2053 else
2054 {
2055 width = cell.width;
2056
2057 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01002058 if (width == 2)
2059 // second cell of double-width character has the
2060 // same attributes.
2061 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002062
Bram Moolenaara79fd562018-12-20 20:47:32 +01002063 // Each character can be up to 6 bytes.
2064 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002065 {
2066 int i;
2067 int c;
2068
2069 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
2070 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2071 (char_u *)ga.ga_data + ga.ga_len);
2072 }
2073 }
2074 }
2075 line->sb_cols = len;
2076 line->sb_cells = p;
2077 line->sb_fill_attr = new_fill_attr;
2078 fill_attr = new_fill_attr;
2079 ++term->tl_scrollback.ga_len;
2080
2081 if (ga_grow(&ga, 1) == FAIL)
2082 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2083 else
2084 {
2085 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2086 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2087 }
2088 ga_clear(&ga);
2089 }
2090 else
2091 vim_free(p);
2092 }
2093 }
2094
Bram Moolenaarf3aea592018-11-11 22:18:21 +01002095 // Add trailing empty lines.
2096 for (pos.row = term->tl_scrollback.ga_len;
2097 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
2098 ++pos.row)
2099 {
2100 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
2101 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2102 }
2103
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002104 term->tl_dirty_snapshot = FALSE;
2105#ifdef FEAT_TIMERS
2106 term->tl_timer_set = FALSE;
2107#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002108}
2109
2110/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002111 * Loop over all windows in the current tab, and also curwin, which is not
2112 * encountered when using a terminal in a popup window.
2113 * Return TRUE if "*wp" was set to the next window.
2114 */
2115 static int
2116for_all_windows_and_curwin(win_T **wp, int *did_curwin)
2117{
2118 if (*wp == NULL)
2119 *wp = firstwin;
2120 else if ((*wp)->w_next != NULL)
2121 *wp = (*wp)->w_next;
2122 else if (!*did_curwin)
2123 *wp = curwin;
2124 else
2125 return FALSE;
2126 if (*wp == curwin)
2127 *did_curwin = TRUE;
2128 return TRUE;
2129}
2130
2131/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002132 * If needed, add the current lines of the terminal to scrollback and to the
2133 * buffer. Called after the job has ended and when switching to
2134 * Terminal-Normal mode.
2135 * When "redraw" is TRUE redraw the windows that show the terminal.
2136 */
2137 static void
2138may_move_terminal_to_buffer(term_T *term, int redraw)
2139{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002140 if (term->tl_vterm == NULL)
2141 return;
2142
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002143 // Update the snapshot only if something changes or the buffer does not
2144 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002145 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2146 <= term->tl_scrollback_scrolled)
2147 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002148
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002149 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002150 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2151 &term->tl_default_color.fg, &term->tl_default_color.bg);
2152
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002153 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002154 {
2155 win_T *wp = NULL;
2156 int did_curwin = FALSE;
2157
2158 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002159 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002160 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002161 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002162 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2163 wp->w_cursor.col = 0;
2164 wp->w_valid = 0;
2165 if (wp->w_cursor.lnum >= wp->w_height)
2166 {
2167 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002168
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002169 if (wp->w_topline < min_topline)
2170 wp->w_topline = min_topline;
2171 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002172 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002173 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002174 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002175 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002176}
2177
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002178#if defined(FEAT_TIMERS) || defined(PROTO)
2179/*
2180 * Check if any terminal timer expired. If so, copy text from the terminal to
2181 * the buffer.
2182 * Return the time until the next timer will expire.
2183 */
2184 int
2185term_check_timers(int next_due_arg, proftime_T *now)
2186{
2187 term_T *term;
2188 int next_due = next_due_arg;
2189
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002190 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002191 {
2192 if (term->tl_timer_set && !term->tl_normal_mode)
2193 {
2194 long this_due = proftime_time_left(&term->tl_timer_due, now);
2195
2196 if (this_due <= 1)
2197 {
2198 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002199 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002200 }
2201 else if (next_due == -1 || next_due > this_due)
2202 next_due = this_due;
2203 }
2204 }
2205
2206 return next_due;
2207}
2208#endif
2209
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002210/*
2211 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2212 * otherwise end it.
2213 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002214 static void
2215set_terminal_mode(term_T *term, int normal_mode)
2216{
2217 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002218 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002219 if (!normal_mode)
2220 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002221 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002222 if (term->tl_buffer == curbuf)
2223 maketitle();
2224}
2225
2226/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002227 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002228 * Move the vterm contents into the scrollback buffer and free the vterm.
2229 */
2230 static void
2231cleanup_vterm(term_T *term)
2232{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002233 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002234 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002235 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002237}
2238
2239/*
2240 * Switch from Terminal-Job mode to Terminal-Normal mode.
2241 * Suspends updating the terminal window.
2242 */
2243 static void
2244term_enter_normal_mode(void)
2245{
2246 term_T *term = curbuf->b_term;
2247
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002248 set_terminal_mode(term, TRUE);
2249
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002250 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002251 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002252
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002253 // Move the window cursor to the position of the cursor in the
2254 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002255 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2256 + term->tl_cursor_pos.row + 1;
2257 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002258 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2259 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002260 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002261
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002262 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002263 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2264}
2265
2266/*
2267 * Returns TRUE if the current window contains a terminal and we are in
2268 * Terminal-Normal mode.
2269 */
2270 int
2271term_in_normal_mode(void)
2272{
2273 term_T *term = curbuf->b_term;
2274
2275 return term != NULL && term->tl_normal_mode;
2276}
2277
2278/*
2279 * Switch from Terminal-Normal mode to Terminal-Job mode.
2280 * Restores updating the terminal window.
2281 */
2282 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002283term_enter_job_mode(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002284{
2285 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002286
2287 set_terminal_mode(term, FALSE);
2288
2289 if (term->tl_channel_closed)
2290 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002291 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002292#ifdef FEAT_PROP_POPUP
2293 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002294 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002295#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002296}
2297
2298/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002299 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2300 * modifiers into a basic key. However, we may only find out after calling
2301 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2302 * "no_reduce_keys" before using it.
2303 */
2304typedef enum {
2305 NRKS_NONE, // initial value
2306 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2307 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2308 // check_no_reduce_keys(), must be decremented.
2309} reduce_key_state_T;
2310
2311static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2312
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002313/*
2314 * Return TRUE if the term is using modifyOtherKeys level 2 or the kitty
2315 * keyboard protocol.
2316 */
2317 static int
2318vterm_using_key_protocol(void)
2319{
2320 return curbuf->b_term != NULL
2321 && curbuf->b_term->tl_vterm != NULL
2322 && (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm)
2323 || vterm_is_kitty_keyboard(curbuf->b_term->tl_vterm));
2324}
2325
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002326 void
2327check_no_reduce_keys(void)
2328{
2329 if (no_reduce_key_state != NRKS_CHECK
2330 || no_reduce_keys >= 1
2331 || curbuf->b_term == NULL
2332 || curbuf->b_term->tl_vterm == NULL)
2333 return;
2334
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002335 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002336 {
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002337 // "modify_other_keys" or kitty keyboard protocol was enabled while
2338 // waiting.
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002339 no_reduce_key_state = NRKS_SET;
2340 ++no_reduce_keys;
2341 }
2342}
2343
2344/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002345 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002346 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002347 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002348 */
2349 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002350term_vgetc(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002351{
2352 int c;
2353 int save_State = State;
2354
Bram Moolenaar24959102022-05-07 20:01:16 +01002355 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002356 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002357#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358 ctrl_break_was_pressed = FALSE;
2359#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002360
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002361 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002362 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002363 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002364 no_reduce_key_state = NRKS_SET;
2365 }
2366 else
2367 {
2368 no_reduce_key_state = NRKS_CHECK;
2369 }
2370
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002371 c = vgetc();
2372 got_int = FALSE;
2373 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002374
2375 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002376 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002377 no_reduce_key_state = NRKS_NONE;
2378
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002379 return c;
2380}
2381
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002382static int mouse_was_outside = FALSE;
2383
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002384/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002385 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002386 * Return FAIL when the key needs to be handled in Normal mode.
2387 * Return OK when the key was dropped or sent to the terminal.
2388 */
2389 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002390send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002391{
2392 char msg[KEY_BUF_LEN];
2393 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002394 int dragging_outside = FALSE;
2395
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002396 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002397 switch (c)
2398 {
2399 case NUL:
2400 case K_ZERO:
2401 if (typed)
2402 stuffcharReadbuff(c);
2403 return FAIL;
2404
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002405 case K_TABLINE:
2406 stuffcharReadbuff(c);
2407 return FAIL;
2408
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002409 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002410 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002411 return FAIL;
2412
2413 case K_LEFTDRAG:
2414 case K_MIDDLEDRAG:
2415 case K_RIGHTDRAG:
2416 case K_X1DRAG:
2417 case K_X2DRAG:
2418 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002419 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002420 case K_LEFTMOUSE:
2421 case K_LEFTMOUSE_NM:
2422 case K_LEFTRELEASE:
2423 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002424 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002425 case K_MIDDLEMOUSE:
2426 case K_MIDDLERELEASE:
2427 case K_RIGHTMOUSE:
2428 case K_RIGHTRELEASE:
2429 case K_X1MOUSE:
2430 case K_X1RELEASE:
2431 case K_X2MOUSE:
2432 case K_X2RELEASE:
2433
2434 case K_MOUSEUP:
2435 case K_MOUSEDOWN:
2436 case K_MOUSELEFT:
2437 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002438 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002439 int row = mouse_row;
2440 int col = mouse_col;
2441
2442#ifdef FEAT_PROP_POPUP
2443 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002444 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002445 row -= popup_top_extra(curwin);
2446 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002447 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002448#endif
2449 if (row < W_WINROW(curwin)
2450 || row >= (W_WINROW(curwin) + curwin->w_height)
2451 || col < curwin->w_wincol
2452 || col >= W_ENDCOL(curwin)
2453 || dragging_outside)
2454 {
2455 // click or scroll outside the current window or on status
2456 // line or vertical separator
2457 if (typed)
2458 {
2459 stuffcharReadbuff(c);
2460 mouse_was_outside = TRUE;
2461 }
2462 return FAIL;
2463 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002464 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002465 break;
2466
2467 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002468 case K_SCRIPT_COMMAND:
2469 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002470 }
2471 if (typed)
2472 mouse_was_outside = FALSE;
2473
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002474 // Convert the typed key to a sequence of bytes for the job.
2475 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002476 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002477 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002478 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2479 (char_u *)msg, (int)len, NULL);
2480
2481 return OK;
2482}
2483
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002484/*
2485 * Handle CTRL-W "": send register contents to the job.
2486 */
2487 static void
2488term_paste_register(int prev_c UNUSED)
2489{
2490 int c;
2491 list_T *l;
2492 listitem_T *item;
2493 long reglen = 0;
2494 int type;
2495
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002496 if (add_to_showcmd(prev_c))
2497 if (add_to_showcmd('"'))
2498 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002499
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002500 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002501 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002502
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002504 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002505 return;
2506
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002507 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002508 if (c == '=' && get_expr_register() != '=')
2509 return;
2510 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002511 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002512 return;
2513
2514 l = (list_T *)get_reg_contents(c, GREG_LIST);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002515 if (l == NULL)
2516 return;
2517
2518 type = get_reg_type(c, &reglen);
2519 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002520 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002521 char_u *s = tv_get_string(&item->li_tv);
2522#ifdef MSWIN
2523 char_u *tmp = s;
2524
2525 if (!enc_utf8 && enc_codepage > 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002526 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002527 WCHAR *ret = NULL;
2528 int length = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002529
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002530 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2531 (int)STRLEN(s), &ret, &length);
2532 if (ret != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002533 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002534 WideCharToMultiByte_alloc(CP_UTF8, 0,
2535 ret, length, (char **)&s, &length, 0, 0);
2536 vim_free(ret);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002537 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002538 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539#endif
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002540 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2541 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002542#ifdef MSWIN
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002543 if (tmp != s)
2544 vim_free(s);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002545#endif
2546
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002547 if (item->li_next != NULL || type == MLINE)
2548 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2549 (char_u *)"\r", 1, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002550 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002551 list_free(l);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002552}
2553
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002554/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002555 * Return TRUE when waiting for a character in the terminal, the cursor of the
2556 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002557 */
2558 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002559terminal_is_active(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002560{
2561 return in_terminal_loop != NULL;
2562}
2563
Bram Moolenaar83d47902020-03-26 20:34:00 +01002564/*
dundargocc57b5bc2022-11-02 13:30:51 +00002565 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002566 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002567 static int
2568term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002569{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002570 char_u *name;
2571
2572 if (wp != NULL && *wp->w_p_wcr != NUL)
2573 name = wp->w_p_wcr;
2574 else if (term->tl_highlight_name != NULL)
2575 name = term->tl_highlight_name;
2576 else
2577 name = (char_u*)"Terminal";
2578
2579 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002580}
2581
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002582#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002583 cursorentry_T *
2584term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2585{
2586 term_T *term = in_terminal_loop;
2587 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002588 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002589 guicolor_T term_fg = INVALCOLOR;
2590 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002591
Bram Moolenaara80faa82020-04-12 19:37:17 +02002592 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 entry.shape = entry.mshape =
2594 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2595 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2596 SHAPE_BLOCK;
2597 entry.percentage = 20;
2598 if (term->tl_cursor_blink)
2599 {
2600 entry.blinkwait = 700;
2601 entry.blinkon = 400;
2602 entry.blinkoff = 250;
2603 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002604
Bram Moolenaar83d47902020-03-26 20:34:00 +01002605 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002606 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002607 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002608 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002609 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002610 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002611 else
2612 *fg = gui.back_pixel;
2613
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002614 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002615 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002616 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002617 *bg = term_fg;
2618 else
2619 *bg = gui.norm_pixel;
2620 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002621 else
2622 *bg = color_name2handle(term->tl_cursor_color);
2623 entry.name = "n";
2624 entry.used_for = SHAPE_CURSOR;
2625
2626 return &entry;
2627}
2628#endif
2629
Bram Moolenaard317b382018-02-08 22:33:31 +01002630 static void
2631may_output_cursor_props(void)
2632{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002633 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002634 || last_set_cursor_shape != desired_cursor_shape
2635 || last_set_cursor_blink != desired_cursor_blink)
2636 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002637 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002638 last_set_cursor_shape = desired_cursor_shape;
2639 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002640 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002641 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002642 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002643 ui_cursor_shape_forced(TRUE);
2644 else
2645 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2646 }
2647}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002648
Bram Moolenaard317b382018-02-08 22:33:31 +01002649/*
2650 * Set the cursor color and shape, if not last set to these.
2651 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002652 static void
2653may_set_cursor_props(term_T *term)
2654{
2655#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002656 // For the GUI the cursor properties are obtained with
2657 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002658 if (gui.in_use)
2659 return;
2660#endif
2661 if (in_terminal_loop == term)
2662 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002663 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002664 desired_cursor_shape = term->tl_cursor_shape;
2665 desired_cursor_blink = term->tl_cursor_blink;
2666 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002667 }
2668}
2669
Bram Moolenaard317b382018-02-08 22:33:31 +01002670/*
2671 * Reset the desired cursor properties and restore them when needed.
2672 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002673 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002674prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002675{
2676#ifdef FEAT_GUI
2677 if (gui.in_use)
2678 return;
2679#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002680 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002681 desired_cursor_shape = -1;
2682 desired_cursor_blink = -1;
2683 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002684}
2685
2686/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002687 * Returns TRUE if the current window contains a terminal and we are sending
2688 * keys to the job.
2689 * If "check_job_status" is TRUE update the job status.
2690 */
2691 static int
2692term_use_loop_check(int check_job_status)
2693{
2694 term_T *term = curbuf->b_term;
2695
2696 return term != NULL
2697 && !term->tl_normal_mode
2698 && term->tl_vterm != NULL
2699 && term_job_running_check(term, check_job_status);
2700}
2701
2702/*
2703 * Returns TRUE if the current window contains a terminal and we are sending
2704 * keys to the job.
2705 */
2706 int
2707term_use_loop(void)
2708{
2709 return term_use_loop_check(FALSE);
2710}
2711
2712/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002713 * Called when entering a window with the mouse. If this is a terminal window
2714 * we may want to change state.
2715 */
2716 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002717term_win_entered(void)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002718{
2719 term_T *term = curbuf->b_term;
2720
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002721 if (term == NULL)
2722 return;
2723
2724 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002725 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002726 reset_VIsual_and_resel();
2727 if (State & MODE_INSERT)
2728 stop_insert_mode = TRUE;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002729 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002730 mouse_was_outside = FALSE;
2731 enter_mouse_col = mouse_col;
2732 enter_mouse_row = mouse_row;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002733}
2734
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002735 void
2736term_focus_change(int in_focus)
2737{
2738 term_T *term = curbuf->b_term;
2739
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002740 if (term == NULL || term->tl_vterm == NULL)
2741 return;
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002742
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002743 VTermState *state = vterm_obtain_state(term->tl_vterm);
2744
2745 if (in_focus)
2746 vterm_state_focus_in(state);
2747 else
2748 vterm_state_focus_out(state);
2749 term_forward_output(term);
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002750}
2751
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002752/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002753 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2754 * Return the Ctrl-key value in that case.
2755 */
2756 static int
2757raw_c_to_ctrl(int c)
2758{
2759 if ((mod_mask & MOD_MASK_CTRL)
2760 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2761 return c & 0x1f;
2762 return c;
2763}
2764
2765/*
2766 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002767 * Also when the Kitty keyboard protocol is used.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002768 * May set "mod_mask".
2769 */
2770 static int
2771ctrl_to_raw_c(int c)
2772{
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002773 if (c < 0x20 && vterm_using_key_protocol())
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002774 {
2775 mod_mask |= MOD_MASK_CTRL;
2776 return c + '@';
2777 }
2778 return c;
2779}
2780
2781/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002782 * Wait for input and send it to the job.
2783 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2784 * when there is no more typahead.
2785 * Return when the start of a CTRL-W command is typed or anything else that
2786 * should be handled as a Normal mode command.
2787 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2788 * the terminal was closed.
2789 */
2790 int
2791terminal_loop(int blocking)
2792{
2793 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002794 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002795 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002796 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002797#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002798 int tty_fd = curbuf->b_term->tl_job->jv_channel
2799 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002800#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002801 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002802
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002803 // Remember the terminal we are sending keys to. However, the terminal
2804 // might be closed while waiting for a character, e.g. typing "exit" in a
2805 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2806 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002807 in_terminal_loop = curbuf->b_term;
2808
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002809 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002810 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002811 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002812 if (termwinkey == Ctrl_W)
2813 termwinkey = 0;
2814 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002815 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002816 may_set_cursor_props(curbuf->b_term);
2817
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002818 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002819 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002820#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002821 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002822#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002823 // TODO: skip screen update when handling a sequence of keys.
2824 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002825 while (must_redraw != 0)
2826 if (update_screen(0) == FAIL)
2827 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002828 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002829 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002830 break;
2831
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002832 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002833 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002834
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002835 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002836 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002837 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002838 // Job finished while waiting for a character. Push back the
2839 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002840 if (raw_c != K_IGNORE)
2841 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002842 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002843 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002844 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002845 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002846 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002847
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002848#ifdef UNIX
2849 /*
2850 * The shell or another program may change the tty settings. Getting
2851 * them for every typed character is a bit of overhead, but it's needed
2852 * for the first character typed, e.g. when Vim starts in a shell.
2853 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002854 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002855 {
2856 ttyinfo_T info;
2857
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002858 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002859 if (get_tty_info(tty_fd, &info) == OK)
2860 term_backspace_char = info.backspace;
2861 }
2862#endif
2863
Bram Moolenaar4f974752019-02-17 17:44:42 +01002864#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002865 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2866 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002867 if (ctrl_break_was_pressed)
2868 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2869#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002870 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2871 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002872 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002873#ifdef FEAT_GUI
2874 && !curbuf->b_term->tl_system
2875#endif
2876 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002877 {
2878 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002879 int prev_raw_c = raw_c;
2880 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002881
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002882 if (add_to_showcmd(c))
2883 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002884
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002885 raw_c = term_vgetc();
2886 c = raw_c_to_ctrl(raw_c);
2887
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002889
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002890 if (!term_use_loop_check(TRUE)
2891 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002892 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002893 break;
2894
2895 if (prev_c == Ctrl_BSL)
2896 {
2897 if (c == Ctrl_N)
2898 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002899 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002900 term_enter_normal_mode();
2901 ret = FAIL;
2902 goto theend;
2903 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002904 // Send both keys to the terminal, first one here, second one
2905 // below.
2906 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2907 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002908 }
2909 else if (c == Ctrl_C)
2910 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002911 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002912 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2913 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002914 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002915 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002916 // "CTRL-W .": send CTRL-W to the job
2917 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002918 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002919 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002920 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002921 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002922 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002923 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002924 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 else if (c == 'N')
2926 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002927 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002928 term_enter_normal_mode();
2929 ret = FAIL;
2930 goto theend;
2931 }
2932 else if (c == '"')
2933 {
2934 term_paste_register(prev_c);
2935 continue;
2936 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002937 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002938 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002939 // space for CTRL-W, modifier, multi-byte char and NUL
2940 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002941
2942 // Put the command into the typeahead buffer, when using the
2943 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2944 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002945 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002946 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002947 ret = OK;
2948 goto theend;
2949 }
2950 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002951# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002952 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002953 {
2954 WCHAR wc;
2955 char_u mb[3];
2956
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002957 mb[0] = (unsigned)raw_c >> 8;
2958 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002959 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002960 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002961 }
2962# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002963 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002964 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002965 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002966 // We are sure to come back here, don't reset the cursor color
2967 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002968 restore_cursor = FALSE;
2969
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002970 ret = OK;
2971 goto theend;
2972 }
2973 }
2974 ret = FAIL;
2975
2976theend:
2977 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002978 if (restore_cursor)
2979 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002980
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002981 // Move a snapshot of the screen contents to the buffer, so that completion
2982 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002983 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2984 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002985
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002986 return ret;
2987}
2988
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002989 static void
2990may_toggle_cursor(term_T *term)
2991{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002992 if (in_terminal_loop != term)
2993 return;
2994
2995 if (term->tl_cursor_visible)
2996 cursor_on();
2997 else
2998 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002999}
3000
3001/*
3002 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01003003 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003004 */
3005 static int
3006color2index(VTermColor *color, int fg, int *boldp)
3007{
3008 int red = color->red;
3009 int blue = color->blue;
3010 int green = color->green;
3011
LemonBoyb2b3acb2022-05-20 10:10:34 +01003012 *boldp = FALSE;
3013
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003014 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003015 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01003016
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003017 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003018 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003019 // Use the color as-is if possible, give up otherwise.
3020 if (color->index < t_colors)
3021 return color->index + 1;
3022 // 8-color terminals can actually display twice as many colors by
3023 // setting the high-intensity/bold bit.
3024 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003025 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003026 *boldp = TRUE;
3027 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003028 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01003029 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003030 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01003031
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003032 if (t_colors >= 256)
3033 {
3034 if (red == blue && red == green)
3035 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003036 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003037 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003038 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
3039 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
3040 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003041 int i;
3042
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003043 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003044 return 17; // 00/00/00
3045 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003046 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003047 for (i = 0; i < 23; ++i)
3048 if (red < cutoff[i])
3049 return i + 233;
3050 return 256;
3051 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003052 {
3053 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
3054 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003055
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003056 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003057 for (ri = 0; ri < 5; ++ri)
3058 if (red < cutoff[ri])
3059 break;
3060 for (gi = 0; gi < 5; ++gi)
3061 if (green < cutoff[gi])
3062 break;
3063 for (bi = 0; bi < 5; ++bi)
3064 if (blue < cutoff[bi])
3065 break;
3066 return 17 + ri * 36 + gi * 6 + bi;
3067 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003068 }
3069 return 0;
3070}
3071
3072/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01003073 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003074 */
3075 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003076vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003077{
3078 int attr = 0;
3079
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003080 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003081 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003082 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003083 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003084 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003085 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003086 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003087 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003088 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003089 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003090 return attr;
3091}
3092
3093/*
3094 * Store Vterm attributes in "cell" from highlight flags.
3095 */
3096 static void
3097hl2vtermAttr(int attr, cellattr_T *cell)
3098{
Bram Moolenaara80faa82020-04-12 19:37:17 +02003099 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003100 if (attr & HL_BOLD)
3101 cell->attrs.bold = 1;
3102 if (attr & HL_UNDERLINE)
3103 cell->attrs.underline = 1;
3104 if (attr & HL_ITALIC)
3105 cell->attrs.italic = 1;
3106 if (attr & HL_STRIKETHROUGH)
3107 cell->attrs.strike = 1;
3108 if (attr & HL_INVERSE)
3109 cell->attrs.reverse = 1;
3110}
3111
3112/*
3113 * Convert the attributes of a vterm cell into an attribute index.
3114 */
3115 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003116cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003117 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003118 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003119 VTermScreenCellAttrs *cellattrs,
3120 VTermColor *cellfg,
3121 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003122{
3123 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003124 VTermColor *fg = cellfg;
3125 VTermColor *bg = cellbg;
3126 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3127 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3128
3129 if (is_default_fg || is_default_bg)
3130 {
3131 if (wp != NULL && *wp->w_p_wcr != NUL)
3132 {
3133 if (is_default_fg)
3134 fg = &wp->w_term_wincolor.fg;
3135 if (is_default_bg)
3136 bg = &wp->w_term_wincolor.bg;
3137 }
3138 else
3139 {
3140 if (is_default_fg)
3141 fg = &term->tl_default_color.fg;
3142 if (is_default_bg)
3143 bg = &term->tl_default_color.bg;
3144 }
3145 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003146
3147#ifdef FEAT_GUI
3148 if (gui.in_use)
3149 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003150 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3151 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3152 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153 }
3154 else
3155#endif
3156#ifdef FEAT_TERMGUICOLORS
3157 if (p_tgc)
3158 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003159 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3160 ? INVALCOLOR
3161 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3162 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3163 ? INVALCOLOR
3164 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3165 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003166 }
3167 else
3168#endif
3169 {
3170 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003171 int ctermfg = color2index(fg, TRUE, &bold);
3172 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003173
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003174 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003175 if (bold == TRUE)
3176 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003177
3178 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003179 }
3180 return 0;
3181}
3182
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003183 static void
3184set_dirty_snapshot(term_T *term)
3185{
3186 term->tl_dirty_snapshot = TRUE;
3187#ifdef FEAT_TIMERS
3188 if (!term->tl_normal_mode)
3189 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003190 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003191 profile_setlimit(100L, &term->tl_timer_due);
3192 term->tl_timer_set = TRUE;
3193 }
3194#endif
3195}
3196
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003197 static int
3198handle_damage(VTermRect rect, void *user)
3199{
3200 term_T *term = (term_T *)user;
3201
3202 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3203 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003204 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003205 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003206 return 1;
3207}
3208
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003209 static void
3210term_scroll_up(term_T *term, int start_row, int count)
3211{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003212 win_T *wp = NULL;
3213 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003214 VTermColor fg, bg;
3215 VTermScreenCellAttrs attr;
3216 int clear_attr;
3217
Bram Moolenaara80faa82020-04-12 19:37:17 +02003218 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003219
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003220 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003221 {
3222 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003223 {
3224 // Set the color to clear lines with.
3225 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3226 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003227 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003228 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003229 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003230 }
3231}
3232
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003233 static int
3234handle_moverect(VTermRect dest, VTermRect src, void *user)
3235{
3236 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003237 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003238
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003239 // Scrolling up is done much more efficiently by deleting lines instead of
3240 // redrawing the text. But avoid doing this multiple times, postpone until
3241 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003242 if (dest.start_col == src.start_col
3243 && dest.end_col == src.end_col
3244 && dest.start_row < src.start_row)
3245 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003246 if (dest.start_row == 0)
3247 term->tl_postponed_scroll += count;
3248 else
3249 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003250 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003251
3252 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3253 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003254 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003255
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003256 // Note sure if the scrolling will work correctly, let's do a complete
3257 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003258 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003259 return 1;
3260}
3261
3262 static int
3263handle_movecursor(
3264 VTermPos pos,
3265 VTermPos oldpos UNUSED,
3266 int visible,
3267 void *user)
3268{
3269 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003270 win_T *wp = NULL;
3271 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003272
3273 term->tl_cursor_pos = pos;
3274 term->tl_cursor_visible = visible;
3275
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003276 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003277 {
3278 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003279 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003280 }
3281 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003282 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003283
3284 return 1;
3285}
3286
3287 static int
3288handle_settermprop(
3289 VTermProp prop,
3290 VTermValue *value,
3291 void *user)
3292{
3293 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003294 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003295
3296 switch (prop)
3297 {
3298 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003299 if (disable_vterm_title_for_testing)
3300 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003301 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003302 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003303 if (strval == NULL)
3304 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003305 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003306 // a blank title isn't useful, make it empty, so that "running" is
3307 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003308 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003309 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003310 // Same as blank
3311 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003312 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003313 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3314 term->tl_title = NULL;
3315 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003316 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003317 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003318#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003319 else if (!enc_utf8 && enc_codepage > 0)
3320 {
3321 WCHAR *ret = NULL;
3322 int length = 0;
3323
3324 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003325 (char*)value->string.str,
3326 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003327 if (ret != NULL)
3328 {
3329 WideCharToMultiByte_alloc(enc_codepage, 0,
3330 ret, length, (char**)&term->tl_title,
3331 &length, 0, 0);
3332 vim_free(ret);
3333 }
3334 }
3335#endif
3336 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003337 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003338 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003339 strval = NULL;
3340 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003341 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003342 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003343 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003344 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003345 curwin->w_redr_status = TRUE;
3346 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003347 break;
3348
3349 case VTERM_PROP_CURSORVISIBLE:
3350 term->tl_cursor_visible = value->boolean;
3351 may_toggle_cursor(term);
3352 out_flush();
3353 break;
3354
3355 case VTERM_PROP_CURSORBLINK:
3356 term->tl_cursor_blink = value->boolean;
3357 may_set_cursor_props(term);
3358 break;
3359
3360 case VTERM_PROP_CURSORSHAPE:
3361 term->tl_cursor_shape = value->number;
3362 may_set_cursor_props(term);
3363 break;
3364
3365 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003366 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003367 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003368 if (strval == NULL)
3369 break;
3370 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003371 may_set_cursor_props(term);
3372 break;
3373
3374 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003375 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003376 term->tl_using_altscreen = value->boolean;
3377 break;
3378
3379 default:
3380 break;
3381 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003382 vim_free(strval);
3383
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003384 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003385 return 1;
3386}
3387
3388/*
3389 * The job running in the terminal resized the terminal.
3390 */
3391 static int
3392handle_resize(int rows, int cols, void *user)
3393{
3394 term_T *term = (term_T *)user;
3395 win_T *wp;
3396
3397 term->tl_rows = rows;
3398 term->tl_cols = cols;
3399 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003400 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003401 term->tl_vterm_size_changed = FALSE;
3402 else
3403 {
3404 FOR_ALL_WINDOWS(wp)
3405 {
3406 if (wp->w_buffer == term->tl_buffer)
3407 {
3408 win_setheight_win(rows, wp);
3409 win_setwidth_win(cols, wp);
3410 }
3411 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003412 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003413 }
3414 return 1;
3415}
3416
3417/*
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003418 * If the number of lines that are stored goes over 'termwinscroll' then
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003419 * delete the first 10%.
3420 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3421 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003422 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003423 static void
3424limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003425{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003426 if (gap->ga_len < term->tl_buffer->b_p_twsl)
3427 return;
3428
3429 int todo = term->tl_buffer->b_p_twsl / 10;
3430 int i;
3431
3432 curbuf = term->tl_buffer;
3433 for (i = 0; i < todo; ++i)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003434 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003435 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003436 if (update_buffer)
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003437 ml_delete(1);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003438 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003439 curbuf = curwin->w_buffer;
3440
3441 gap->ga_len -= todo;
3442 mch_memmove(gap->ga_data,
3443 (sb_line_T *)gap->ga_data + todo,
3444 sizeof(sb_line_T) * gap->ga_len);
3445 if (update_buffer)
3446 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003447}
3448
3449/*
3450 * Handle a line that is pushed off the top of the screen.
3451 */
3452 static int
3453handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3454{
3455 term_T *term = (term_T *)user;
3456 garray_T *gap;
3457 int update_buffer;
3458
3459 if (term->tl_normal_mode)
3460 {
3461 // In Terminal-Normal mode the user interacts with the buffer, thus we
3462 // must not change it. Postpone adding the scrollback lines.
3463 gap = &term->tl_scrollback_postponed;
3464 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003465 }
3466 else
3467 {
3468 // First remove the lines that were appended before, the pushed line
3469 // goes above it.
3470 cleanup_scrollback(term);
3471 gap = &term->tl_scrollback;
3472 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003473 }
3474
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003475 limit_scrollback(term, gap, update_buffer);
3476
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003477 if (ga_grow(gap, 1) == FAIL)
3478 return 0;
3479
3480 cellattr_T *p = NULL;
3481 int len = 0;
3482 int i;
3483 int c;
3484 int col;
3485 int text_len;
3486 char_u *text;
3487 sb_line_T *line;
3488 garray_T ga;
3489 cellattr_T fill_attr = term->tl_default_color;
3490
3491 // do not store empty cells at the end
3492 for (i = 0; i < cols; ++i)
3493 if (cells[i].chars[0] != 0)
3494 len = i + 1;
3495 else
3496 cell2cellattr(&cells[i], &fill_attr);
3497
3498 ga_init2(&ga, 1, 100);
3499 if (len > 0)
3500 p = ALLOC_MULT(cellattr_T, len);
3501 if (p != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003502 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003503 for (col = 0; col < len; col += cells[col].width)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003504 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003505 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003506 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003507 ga.ga_len = 0;
3508 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003509 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003510 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3511 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3512 (char_u *)ga.ga_data + ga.ga_len);
3513 cell2cellattr(&cells[col], &p[col]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003514 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003515 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003516 if (ga_grow(&ga, 1) == FAIL)
3517 {
3518 if (update_buffer)
3519 text = (char_u *)"";
3520 else
3521 text = vim_strsave((char_u *)"");
3522 text_len = 0;
3523 }
3524 else
3525 {
3526 text = ga.ga_data;
3527 text_len = ga.ga_len;
3528 *(text + text_len) = NUL;
3529 }
3530 if (update_buffer)
3531 add_scrollback_line_to_buffer(term, text, text_len);
3532
3533 line = (sb_line_T *)gap->ga_data + gap->ga_len;
3534 line->sb_cols = len;
3535 line->sb_cells = p;
3536 line->sb_fill_attr = fill_attr;
3537 if (update_buffer)
3538 {
3539 line->sb_text = NULL;
3540 ++term->tl_scrollback_scrolled;
3541 ga_clear(&ga); // free the text
3542 }
3543 else
3544 {
3545 line->sb_text = text;
3546 ga_init(&ga); // text is kept in tl_scrollback_postponed
3547 }
3548 ++gap->ga_len;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003549 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003550}
3551
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003552/*
3553 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3554 * received and stored in tl_scrollback_postponed.
3555 */
3556 static void
3557handle_postponed_scrollback(term_T *term)
3558{
3559 int i;
3560
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003561 if (term->tl_scrollback_postponed.ga_len == 0)
3562 return;
3563 ch_log(NULL, "Moving postponed scrollback to scrollback");
3564
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003565 // First remove the lines that were appended before, the pushed lines go
3566 // above it.
3567 cleanup_scrollback(term);
3568
3569 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3570 {
3571 char_u *text;
3572 sb_line_T *pp_line;
3573 sb_line_T *line;
3574
3575 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3576 break;
3577 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3578
3579 text = pp_line->sb_text;
3580 if (text == NULL)
3581 text = (char_u *)"";
3582 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3583 vim_free(pp_line->sb_text);
3584
3585 line = (sb_line_T *)term->tl_scrollback.ga_data
3586 + term->tl_scrollback.ga_len;
3587 line->sb_cols = pp_line->sb_cols;
3588 line->sb_cells = pp_line->sb_cells;
3589 line->sb_fill_attr = pp_line->sb_fill_attr;
3590 line->sb_text = NULL;
3591 ++term->tl_scrollback_scrolled;
3592 ++term->tl_scrollback.ga_len;
3593 }
3594
3595 ga_clear(&term->tl_scrollback_postponed);
3596 limit_scrollback(term, &term->tl_scrollback, TRUE);
3597}
3598
LemonBoy77771d32022-04-13 11:47:25 +01003599/*
3600 * Called when the terminal wants to ring the system bell.
3601 */
3602 static int
3603handle_bell(void *user UNUSED)
3604{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003605 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003606 return 0;
3607}
3608
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003609static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003610 handle_damage, // damage
3611 handle_moverect, // moverect
3612 handle_movecursor, // movecursor
3613 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003614 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003615 handle_resize, // resize
3616 handle_pushline, // sb_pushline
Bram Moolenaar6a12d262022-10-16 19:26:52 +01003617 NULL, // sb_popline
3618 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003619};
3620
3621/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003622 * Do the work after the channel of a terminal was closed.
3623 * Must be called only when updating_screen is FALSE.
3624 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3625 */
3626 static int
3627term_after_channel_closed(term_T *term)
3628{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003629 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003630 if (!term->tl_normal_mode)
3631 {
3632 int fnum = term->tl_buffer->b_fnum;
3633
3634 cleanup_vterm(term);
3635
3636 if (term->tl_finish == TL_FINISH_CLOSE)
3637 {
3638 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003639 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003640#ifdef FEAT_PROP_POPUP
3641 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003642
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003643 // If this was a terminal in a popup window, go back to the
3644 // previous window.
3645 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3646 {
3647 pwin = curwin;
3648 if (win_valid(prevwin))
3649 win_enter(prevwin, FALSE);
3650 }
3651 else
3652#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003653 // If this is the last normal window: exit Vim.
3654 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3655 {
3656 exarg_T ea;
3657
Bram Moolenaara80faa82020-04-12 19:37:17 +02003658 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003659 ex_quit(&ea);
3660 return TRUE;
3661 }
3662
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003663 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003664 ch_log(NULL, "terminal job finished, closing window");
3665 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaare76062c2022-11-28 18:51:43 +00003666 if (curbuf == term->tl_buffer)
3667 {
3668 // Avoid closing the window if we temporarily use it.
3669 if (is_aucmd_win(curwin))
3670 do_set_w_closing = TRUE;
3671 if (do_set_w_closing)
3672 curwin->w_closing = TRUE;
3673 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
3674 if (do_set_w_closing)
3675 curwin->w_closing = FALSE;
3676 aucmd_restbuf(&aco);
3677 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003678#ifdef FEAT_PROP_POPUP
3679 if (pwin != NULL)
3680 popup_close_with_retval(pwin, 0);
3681#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003682 return TRUE;
3683 }
3684 if (term->tl_finish == TL_FINISH_OPEN
3685 && term->tl_buffer->b_nwindows == 0)
3686 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003687 char *cmd = term->tl_opencmd == NULL
3688 ? "botright sbuf %d"
3689 : (char *)term->tl_opencmd;
3690 size_t len = strlen(cmd) + 50;
3691 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003692
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003693 if (buf != NULL)
3694 {
3695 ch_log(NULL, "terminal job finished, opening window");
3696 vim_snprintf(buf, len, cmd, fnum);
3697 do_cmdline_cmd((char_u *)buf);
3698 vim_free(buf);
3699 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003700 }
3701 else
3702 ch_log(NULL, "terminal job finished");
3703 }
3704
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003705 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003706 return FALSE;
3707}
3708
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003709#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3710/*
3711 * If the current window is a terminal in a popup window and the job has
3712 * finished, close the popup window and to back to the previous window.
3713 * Otherwise return FAIL.
3714 */
3715 int
3716may_close_term_popup(void)
3717{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003718 if (!popup_is_popup(curwin) || curbuf->b_term == NULL
3719 || term_job_running_not_none(curbuf->b_term))
3720 return FAIL;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003721
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003722 win_T *pwin = curwin;
3723
3724 if (win_valid(prevwin))
3725 win_enter(prevwin, FALSE);
3726 popup_close_with_retval(pwin, 0);
3727 return OK;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003728}
3729#endif
3730
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003731/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003732 * Called when a channel is going to be closed, before invoking the close
3733 * callback.
3734 */
3735 void
3736term_channel_closing(channel_T *ch)
3737{
3738 term_T *term;
3739
3740 for (term = first_term; term != NULL; term = term->tl_next)
3741 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3742 term->tl_channel_closing = TRUE;
3743}
3744
3745/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003746 * Called when a channel has been closed.
3747 * If this was a channel for a terminal window then finish it up.
3748 */
3749 void
3750term_channel_closed(channel_T *ch)
3751{
3752 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003753 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003754 int did_one = FALSE;
3755
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003756 for (term = first_term; term != NULL; term = next_term)
3757 {
3758 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003759 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003760 {
3761 term->tl_channel_closed = TRUE;
3762 did_one = TRUE;
3763
Bram Moolenaard23a8232018-02-10 18:45:26 +01003764 VIM_CLEAR(term->tl_title);
3765 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003766#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003767 if (term->tl_out_fd != NULL)
3768 {
3769 fclose(term->tl_out_fd);
3770 term->tl_out_fd = NULL;
3771 }
3772#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003773
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003774 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003775 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003776 // Cannot open or close windows now. Can happen when
3777 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003778 term->tl_channel_recently_closed = TRUE;
3779 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003780 }
3781
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003782 if (term_after_channel_closed(term))
3783 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003784 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003785 }
3786
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003787 if (did_one)
3788 {
3789 redraw_statuslines();
3790
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003791 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003792 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003793 typebuf_was_filled = TRUE;
3794
3795 term = curbuf->b_term;
3796 if (term != NULL)
3797 {
3798 if (term->tl_job == ch->ch_job)
3799 maketitle();
3800 update_cursor(term, term->tl_cursor_visible);
3801 }
3802 }
3803}
3804
3805/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003806 * To be called after resetting updating_screen: handle any terminal where the
3807 * channel was closed.
3808 */
3809 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003810term_check_channel_closed_recently(void)
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003811{
3812 term_T *term;
3813 term_T *next_term;
3814
3815 for (term = first_term; term != NULL; term = next_term)
3816 {
3817 next_term = term->tl_next;
3818 if (term->tl_channel_recently_closed)
3819 {
3820 term->tl_channel_recently_closed = FALSE;
3821 if (term_after_channel_closed(term))
3822 // start over, the list may have changed
3823 next_term = first_term;
3824 }
3825 }
3826}
3827
3828/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003829 * Fill one screen line from a line of the terminal.
3830 * Advances "pos" to past the last column.
3831 */
3832 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003833term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003834 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003835 win_T *wp,
3836 VTermScreen *screen,
3837 VTermPos *pos,
3838 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003839{
3840 int off = screen_get_current_line_off();
3841
3842 for (pos->col = 0; pos->col < max_col; )
3843 {
3844 VTermScreenCell cell;
3845 int c;
3846
3847 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003848 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003849
3850 c = cell.chars[0];
3851 if (c == NUL)
3852 {
3853 ScreenLines[off] = ' ';
3854 if (enc_utf8)
3855 ScreenLinesUC[off] = NUL;
3856 }
3857 else
3858 {
3859 if (enc_utf8)
3860 {
3861 int i;
3862
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003863 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003864 for (i = 0; i < Screen_mco
3865 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3866 {
3867 ScreenLinesC[i][off] = cell.chars[i + 1];
3868 if (cell.chars[i + 1] == 0)
3869 break;
3870 }
3871 if (c >= 0x80 || (Screen_mco > 0
3872 && ScreenLinesC[0][off] != 0))
3873 {
3874 ScreenLines[off] = ' ';
3875 ScreenLinesUC[off] = c;
3876 }
3877 else
3878 {
3879 ScreenLines[off] = c;
3880 ScreenLinesUC[off] = NUL;
3881 }
3882 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003883#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003884 else if (has_mbyte && c >= 0x80)
3885 {
3886 char_u mb[MB_MAXBYTES+1];
3887 WCHAR wc = c;
3888
3889 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3890 (char*)mb, 2, 0, 0) > 1)
3891 {
3892 ScreenLines[off] = mb[0];
3893 ScreenLines[off + 1] = mb[1];
3894 cell.width = mb_ptr2cells(mb);
3895 }
3896 else
3897 ScreenLines[off] = c;
3898 }
3899#endif
3900 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003901 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003902 ScreenLines[off] = c;
3903 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003904 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3905 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003906
3907 ++pos->col;
3908 ++off;
3909 if (cell.width == 2)
3910 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003911 // don't set the second byte to NUL for a DBCS encoding, it
3912 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003913 if (enc_utf8)
3914 {
3915 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003916 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003917 }
3918 else if (!has_mbyte)
3919 {
3920 // Can't show a double-width character with a single-byte
3921 // 'encoding', just use a space.
3922 ScreenLines[off] = ' ';
3923 ScreenAttrs[off] = ScreenAttrs[off - 1];
3924 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003925
3926 ++pos->col;
3927 ++off;
3928 }
3929 }
3930}
3931
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003932#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003933 static void
3934update_system_term(term_T *term)
3935{
3936 VTermPos pos;
3937 VTermScreen *screen;
3938
3939 if (term->tl_vterm == NULL)
3940 return;
3941 screen = vterm_obtain_screen(term->tl_vterm);
3942
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003943 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003944 while (term->tl_toprow > 0
3945 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3946 {
3947 int save_p_more = p_more;
3948
3949 p_more = FALSE;
3950 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003951 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003952 p_more = save_p_more;
3953 --term->tl_toprow;
3954 }
3955
3956 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3957 && pos.row < Rows; ++pos.row)
3958 {
3959 if (pos.row < term->tl_rows)
3960 {
3961 int max_col = MIN(Columns, term->tl_cols);
3962
Bram Moolenaar83d47902020-03-26 20:34:00 +01003963 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003964 }
3965 else
3966 pos.col = 0;
3967
zeertzjqd0c1b772024-03-16 15:03:33 +01003968 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, -1,
3969 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003970 }
3971
3972 term->tl_dirty_row_start = MAX_ROW;
3973 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003974}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003975#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003976
3977/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003978 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3979 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003980 * Terminal-Normal mode.
3981 */
3982 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003983term_do_update_window(win_T *wp)
3984{
3985 term_T *term = wp->w_buffer->b_term;
3986
3987 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3988}
3989
3990/*
3991 * Called to update a window that contains an active terminal.
3992 */
3993 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003994term_update_window(win_T *wp)
3995{
3996 term_T *term = wp->w_buffer->b_term;
3997 VTerm *vterm;
3998 VTermScreen *screen;
3999 VTermState *state;
4000 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004001 int rows, cols;
4002 int newrows, newcols;
4003 int minsize;
4004 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004005
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004006 vterm = term->tl_vterm;
4007 screen = vterm_obtain_screen(vterm);
4008 state = vterm_obtain_state(vterm);
4009
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004010 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
4011 // With UPD_SOME_VALID only redraw what was marked dirty.
4012 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004013 {
4014 term->tl_dirty_row_start = 0;
4015 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004016
4017 if (term->tl_postponed_scroll > 0
4018 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004019 // Scrolling is usually faster than redrawing, when there are only
4020 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004021 term_scroll_up(term, 0, term->tl_postponed_scroll);
4022 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004023 }
4024
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004025 /*
4026 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004027 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004028 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004029 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004030
Bram Moolenaar498c2562018-04-15 23:45:15 +02004031 newrows = 99999;
4032 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004033 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02004034 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004035 // Always use curwin, it may be a popup window.
4036 win_T *wwp = twp == NULL ? curwin : twp;
4037
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004038 // When more than one window shows the same terminal, use the
4039 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004040 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004041 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004042 newrows = MIN(newrows, wwp->w_height);
4043 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004044 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004045 if (twp == NULL)
4046 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004047 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02004048 if (newrows == 99999 || newcols == 99999)
4049 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02004050 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
4051 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
4052
Bram Moolenaareba13e42021-02-23 17:47:23 +01004053 // If no cell is visible there is no point in resizing. Also, vterm can't
4054 // handle a zero height.
4055 if (newrows == 0 || newcols == 0)
4056 return;
4057
Bram Moolenaar498c2562018-04-15 23:45:15 +02004058 if (term->tl_rows != newrows || term->tl_cols != newcols)
4059 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004060 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004061 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004062 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02004063 newrows);
4064 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02004065
4066 // Updating the terminal size will cause the snapshot to be cleared.
4067 // When not in terminal_loop() we need to restore it.
4068 if (term != in_terminal_loop)
4069 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004070 }
4071
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004072 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004073 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01004074 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004075
Bram Moolenaar3a497e12017-09-30 20:40:27 +02004076 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
4077 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004078 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004079 if (pos.row < term->tl_rows)
4080 {
Bram Moolenaar13568252018-03-16 20:46:58 +01004081 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004082
Bram Moolenaar83d47902020-03-26 20:34:00 +01004083 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004084 }
4085 else
4086 pos.col = 0;
4087
Bram Moolenaar510f0372022-07-04 17:46:22 +01004088 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01004089#ifdef FEAT_MENU
4090 + winbar_height(wp)
4091#endif
zeertzjqd0c1b772024-03-16 15:03:33 +01004092 , wp->w_wincol, pos.col, wp->w_width, -1,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004093#ifdef FEAT_PROP_POPUP
4094 popup_is_popup(wp) ? SLF_POPUP :
4095#endif
4096 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004097 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00004098}
4099
4100/*
4101 * Called after updating all windows: may reset dirty rows.
4102 */
4103 void
4104term_did_update_window(win_T *wp)
4105{
4106 term_T *term = wp->w_buffer->b_term;
4107
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004108 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode
4109 || wp->w_redr_type != 0)
4110 return;
4111
4112 term->tl_dirty_row_start = MAX_ROW;
4113 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004114}
4115
4116/*
4117 * Return TRUE if "wp" is a terminal window where the job has finished.
4118 */
4119 int
4120term_is_finished(buf_T *buf)
4121{
4122 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
4123}
4124
4125/*
4126 * Return TRUE if "wp" is a terminal window where the job has finished or we
4127 * are in Terminal-Normal mode, thus we show the buffer contents.
4128 */
4129 int
4130term_show_buffer(buf_T *buf)
4131{
4132 term_T *term = buf->b_term;
4133
4134 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4135}
4136
4137/*
4138 * The current buffer is going to be changed. If there is terminal
4139 * highlighting remove it now.
4140 */
4141 void
4142term_change_in_curbuf(void)
4143{
4144 term_T *term = curbuf->b_term;
4145
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004146 if (!term_is_finished(curbuf) || term->tl_scrollback.ga_len <= 0)
4147 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004148
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004149 free_scrollback(term);
4150 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
4151
4152 // The buffer is now like a normal buffer, it cannot be easily
4153 // abandoned when changed.
4154 set_string_option_direct((char_u *)"buftype", -1,
4155 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004156}
4157
4158/*
4159 * Get the screen attribute for a position in the buffer.
4160 * Use a negative "col" to get the filler background color.
4161 */
4162 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004163term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004164{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004165 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004166 term_T *term = buf->b_term;
4167 sb_line_T *line;
4168 cellattr_T *cellattr;
4169
4170 if (lnum > term->tl_scrollback.ga_len)
4171 cellattr = &term->tl_default_color;
4172 else
4173 {
4174 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4175 if (col < 0 || col >= line->sb_cols)
4176 cellattr = &line->sb_fill_attr;
4177 else
4178 cellattr = line->sb_cells + col;
4179 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004180 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004181}
4182
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004183/*
4184 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004185 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004186 */
4187 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004188cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004189{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004190 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4191 if (rgb->index == 0)
4192 rgb->type = VTERM_COLOR_RGB;
4193 else
4194 {
4195 rgb->type = VTERM_COLOR_INDEXED;
4196 --rgb->index;
4197 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004198}
4199
4200/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004201 * Initialize vterm color from the synID.
4202 * Returns TRUE if color is set to "fg" and "bg".
4203 * Otherwise returns FALSE.
4204 */
4205 static int
4206get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4207{
4208#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4209 // Use the actual color for the GUI and when 'termguicolors' is set.
4210 if (0
4211# ifdef FEAT_GUI
4212 || gui.in_use
4213# endif
4214# ifdef FEAT_TERMGUICOLORS
4215 || p_tgc
4216# ifdef FEAT_VTP
4217 // Finally get INVALCOLOR on this execution path
4218 || (!p_tgc && t_colors >= 256)
4219# endif
4220# endif
4221 )
4222 {
4223 guicolor_T fg_rgb = INVALCOLOR;
4224 guicolor_T bg_rgb = INVALCOLOR;
4225
4226 if (id > 0)
4227 syn_id2colors(id, &fg_rgb, &bg_rgb);
4228
4229 if (fg_rgb != INVALCOLOR)
4230 {
4231 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4232 fg->red = (unsigned)(rgb >> 16);
4233 fg->green = (unsigned)(rgb >> 8) & 255;
4234 fg->blue = (unsigned)rgb & 255;
4235 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4236 }
4237 else
4238 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4239
4240 if (bg_rgb != INVALCOLOR)
4241 {
4242 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4243 bg->red = (unsigned)(rgb >> 16);
4244 bg->green = (unsigned)(rgb >> 8) & 255;
4245 bg->blue = (unsigned)rgb & 255;
4246 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4247 }
4248 else
4249 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4250
4251 return TRUE;
4252 }
4253 else
4254#endif
4255 if (t_colors >= 16)
4256 {
4257 int cterm_fg = -1;
4258 int cterm_bg = -1;
4259
4260 if (id > 0)
4261 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4262
4263 if (cterm_fg >= 0)
4264 {
4265 cterm_color2vterm(cterm_fg, fg);
4266 fg->type |= VTERM_COLOR_DEFAULT_FG;
4267 }
4268 else
4269 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4270
4271 if (cterm_bg >= 0)
4272 {
4273 cterm_color2vterm(cterm_bg, bg);
4274 bg->type |= VTERM_COLOR_DEFAULT_BG;
4275 }
4276 else
4277 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4278
4279 return TRUE;
4280 }
4281
4282 return FALSE;
4283}
4284
4285 void
4286term_reset_wincolor(win_T *wp)
4287{
4288 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4289 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4290}
4291
4292/*
4293 * Cache the color of 'wincolor'.
4294 */
4295 void
4296term_update_wincolor(win_T *wp)
4297{
4298 int id = 0;
4299
4300 if (*wp->w_p_wcr != NUL)
4301 id = syn_name2id(wp->w_p_wcr);
4302 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4303 &wp->w_term_wincolor.bg))
4304 term_reset_wincolor(wp);
4305}
4306
4307/*
4308 * Called when option 'termguicolors' was set,
4309 * or when any highlight is changed.
4310 */
4311 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004312term_update_wincolor_all(void)
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004313{
4314 win_T *wp = NULL;
4315 int did_curwin = FALSE;
4316
4317 while (for_all_windows_and_curwin(&wp, &did_curwin))
4318 term_update_wincolor(wp);
4319}
4320
4321/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004322 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004323 */
4324 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004325init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004326{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004327 VTermColor *fg, *bg;
4328 int fgval, bgval;
4329 int id;
4330
Bram Moolenaara80faa82020-04-12 19:37:17 +02004331 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004332 term->tl_default_color.width = 1;
4333 fg = &term->tl_default_color.fg;
4334 bg = &term->tl_default_color.bg;
4335
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004336 // Vterm uses a default black background. Set it to white when
4337 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004338 if (*p_bg == 'l')
4339 {
4340 fgval = 0;
4341 bgval = 255;
4342 }
4343 else
4344 {
4345 fgval = 255;
4346 bgval = 0;
4347 }
4348 fg->red = fg->green = fg->blue = fgval;
4349 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004350 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4351 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004352
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004353 // The highlight group overrules the defaults.
4354 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004355
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004356 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004357 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004358#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004359 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004360#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004361
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004362 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004363 if (cterm_normal_fg_color > 0)
4364 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004365 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004366# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4367# ifdef VIMDLL
4368 if (!gui.in_use)
4369# endif
4370 {
4371 tmp = fg->red;
4372 fg->red = fg->blue;
4373 fg->blue = tmp;
4374 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004375# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004376 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004377# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004378 else
4379 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004380# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004381
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004382 if (cterm_normal_bg_color > 0)
4383 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004384 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004385# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4386# ifdef VIMDLL
4387 if (!gui.in_use)
4388# endif
4389 {
4390 tmp = fg->red;
4391 fg->red = fg->blue;
4392 fg->blue = tmp;
4393 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004394# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004395 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004396# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004397 else
4398 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004399# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004400 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004401}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004402
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004403#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4404/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004405 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4406 * "ansi_colors" argument in term_start()) shall be applied.
4407 */
4408 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004409term_use_palette(void)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004410{
4411 if (0
4412#ifdef FEAT_GUI
4413 || gui.in_use
4414#endif
4415#ifdef FEAT_TERMGUICOLORS
4416 || p_tgc
4417#endif
4418 )
4419 return TRUE;
4420 return FALSE;
4421}
4422
4423/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004424 * Set the 16 ANSI colors from array of RGB values
4425 */
4426 static void
4427set_vterm_palette(VTerm *vterm, long_u *rgb)
4428{
4429 int index = 0;
4430 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004431
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004432 for (; index < 16; index++)
4433 {
4434 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004435
Millyb771b6b2021-11-23 12:07:25 +00004436 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004437 color.red = (unsigned)(rgb[index] >> 16);
4438 color.green = (unsigned)(rgb[index] >> 8) & 255;
4439 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004440 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004441 vterm_state_set_palette_color(state, index, &color);
4442 }
4443}
4444
4445/*
4446 * Set the ANSI color palette from a list of colors
4447 */
4448 static int
4449set_ansi_colors_list(VTerm *vterm, list_T *list)
4450{
4451 int n = 0;
4452 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004453 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004454
Bram Moolenaarb0992022020-01-30 14:55:42 +01004455 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004456 {
4457 char_u *color_name;
4458 guicolor_T guicolor;
4459
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004460 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004461 if (color_name == NULL)
4462 return FAIL;
4463
4464 guicolor = GUI_GET_COLOR(color_name);
4465 if (guicolor == INVALCOLOR)
4466 return FAIL;
4467
4468 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4469 }
4470
4471 if (n != 16 || li != NULL)
4472 return FAIL;
4473
4474 set_vterm_palette(vterm, rgb);
4475
4476 return OK;
4477}
4478
4479/*
4480 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4481 */
4482 static void
4483init_vterm_ansi_colors(VTerm *vterm)
4484{
4485 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4486
LemonBoyb2b3acb2022-05-20 10:10:34 +01004487 if (var == NULL)
4488 return;
4489
4490 if (var->di_tv.v_type != VAR_LIST
4491 || var->di_tv.vval.v_list == NULL
4492 || var->di_tv.vval.v_list->lv_first == &range_list_item
4493 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004494 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004495}
4496#endif
4497
Bram Moolenaar52acb112018-03-18 19:20:22 +01004498/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004499 * Handles a "drop" command from the job in the terminal.
4500 * "item" is the file name, "item->li_next" may have options.
4501 */
4502 static void
4503handle_drop_command(listitem_T *item)
4504{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004505 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004506 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004507 int bufnr;
4508 win_T *wp;
4509 tabpage_T *tp;
4510 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004511 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004512
4513 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4514 FOR_ALL_TAB_WINDOWS(tp, wp)
4515 {
4516 if (wp->w_buffer->b_fnum == bufnr)
4517 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004518 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004519 goto_tabpage_win(tp, wp);
4520 return;
4521 }
4522 }
4523
Bram Moolenaara80faa82020-04-12 19:37:17 +02004524 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004525
4526 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4527 && opt_item->li_tv.vval.v_dict != NULL)
4528 {
4529 dict_T *dict = opt_item->li_tv.vval.v_dict;
4530 char_u *p;
4531
Bram Moolenaard61efa52022-07-23 09:52:04 +01004532 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004533 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004534 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004535 if (p != NULL)
4536 {
4537 if (check_ff_value(p) == FAIL)
4538 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4539 else
4540 ea.force_ff = *p;
4541 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004542 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004543 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004544 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004545 if (p != NULL)
4546 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004547 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004548 if (ea.cmd != NULL)
4549 {
4550 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4551 ea.force_enc = 11;
4552 tofree = ea.cmd;
4553 }
4554 }
4555
Bram Moolenaard61efa52022-07-23 09:52:04 +01004556 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004557 if (p != NULL)
4558 get_bad_opt(p, &ea);
4559
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004560 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004561 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004562 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004563 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004564 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004565 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004566 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004567 ea.force_bin = FORCE_NOBIN;
4568 }
4569
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004570 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004571 if (ea.cmd == NULL)
4572 ea.cmd = (char_u *)"split";
4573 ea.arg = fname;
4574 ea.cmdidx = CMD_split;
4575 ex_splitview(&ea);
4576
4577 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004578}
4579
4580/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004581 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4582 */
4583 static int
4584is_permitted_term_api(char_u *func, char_u *pat)
4585{
4586 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4587}
4588
4589/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004590 * Handles a function call from the job running in a terminal.
4591 * "item" is the function name, "item->li_next" has the arguments.
4592 */
4593 static void
4594handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4595{
4596 char_u *func;
4597 typval_T argvars[2];
4598 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004599 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004600
4601 if (item->li_next == NULL)
4602 {
4603 ch_log(channel, "Missing function arguments for call");
4604 return;
4605 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004606 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004607
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004608 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004609 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004610 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004611 return;
4612 }
4613
4614 argvars[0].v_type = VAR_NUMBER;
4615 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4616 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004617 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004618 funcexe.fe_firstline = 1L;
4619 funcexe.fe_lastline = 1L;
4620 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004621 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004622 {
4623 clear_tv(&rettv);
4624 ch_log(channel, "Function %s called", func);
4625 }
4626 else
4627 ch_log(channel, "Calling function %s failed", func);
4628}
4629
4630/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004631 * URL decoding (also know as Percent-encoding).
4632 *
4633 * Note this function currently is only used for decoding shell's
4634 * OSC 7 escape sequence which we can assume all bytes are valid
4635 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4636 * encoding bytes like 0xfe, 0xff.
4637 */
4638 static size_t
4639url_decode(const char *src, const size_t len, char_u *dst)
4640{
4641 size_t i = 0, j = 0;
4642
4643 while (i < len)
4644 {
4645 if (src[i] == '%' && i + 2 < len)
4646 {
4647 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4648 j++;
4649 i += 3;
4650 }
4651 else
4652 {
4653 dst[j] = src[i];
4654 i++;
4655 j++;
4656 }
4657 }
4658 dst[j] = '\0';
4659 return j;
4660}
4661
4662/*
4663 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4664 *
4665 * The OSC 7 sequence has the format of
4666 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4667 * and what VTerm provides via VTermStringFragment is
4668 * "file://HOSTNAME/CURRENT/DIR"
4669 */
4670 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004671sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004672{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004673 int offset = 7; // len of "file://" is 7
4674 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004675 char_u *new_dir;
4676
4677 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004678 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004679 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004680 ++offset;
4681 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004682 }
4683
Bram Moolenaar474ad392022-08-21 11:37:17 +01004684 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004685 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004686 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004687 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004688 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004689 }
4690
Bram Moolenaar474ad392022-08-21 11:37:17 +01004691 new_dir = alloc(gap->ga_len - offset + 1);
4692 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004693 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4694 vim_free(new_dir);
4695}
4696
4697/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004698 * Called by libvterm when it cannot recognize an OSC sequence.
4699 * We recognize a terminal API command.
4700 */
4701 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004702parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004703{
4704 term_T *term = (term_T *)user;
4705 js_read_T reader;
4706 typval_T tv;
4707 channel_T *channel = term->tl_job == NULL ? NULL
4708 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004709 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004710
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004711 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004712 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004713 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004714
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004715 // Concatenate what was received until the final piece is found.
4716 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4717 {
4718 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004719 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004720 }
4721 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004722 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004723 if (!frag.final)
4724 return 1;
4725
4726 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004727
4728 if (command == 7)
4729 {
4730 sync_shell_dir(gap);
4731 ga_clear(gap);
4732 return 1;
4733 }
4734
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004735 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004736 reader.js_fill = NULL;
4737 reader.js_used = 0;
4738 if (json_decode(&reader, &tv, 0) == OK
4739 && tv.v_type == VAR_LIST
4740 && tv.vval.v_list != NULL)
4741 {
4742 listitem_T *item = tv.vval.v_list->lv_first;
4743
4744 if (item == NULL)
4745 ch_log(channel, "Missing command");
4746 else
4747 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004748 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004749
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004750 // Make sure an invoked command doesn't delete the buffer (and the
4751 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004752 ++term->tl_buffer->b_locked;
4753
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004754 item = item->li_next;
4755 if (item == NULL)
4756 ch_log(channel, "Missing argument for %s", cmd);
4757 else if (STRCMP(cmd, "drop") == 0)
4758 handle_drop_command(item);
4759 else if (STRCMP(cmd, "call") == 0)
4760 handle_call_command(term, channel, item);
4761 else
4762 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004763 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004764 }
4765 }
4766 else
4767 ch_log(channel, "Invalid JSON received");
4768
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004769 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004770 clear_tv(&tv);
4771 return 1;
4772}
4773
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004774/*
4775 * Called by libvterm when it cannot recognize a CSI sequence.
4776 * We recognize the window position report.
4777 */
4778 static int
4779parse_csi(
4780 const char *leader UNUSED,
4781 const long args[],
4782 int argcount,
4783 const char *intermed UNUSED,
4784 char command,
4785 void *user)
4786{
4787 term_T *term = (term_T *)user;
4788 char buf[100];
4789 int len;
4790 int x = 0;
4791 int y = 0;
4792 win_T *wp;
4793
4794 // We recognize only CSI 13 t
4795 if (command != 't' || argcount != 1 || args[0] != 13)
4796 return 0; // not handled
4797
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004798 // When getting the window position is not possible or it fails it results
4799 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004800#if defined(FEAT_GUI) \
4801 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4802 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004803 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004804#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004805
4806 FOR_ALL_WINDOWS(wp)
4807 if (wp->w_buffer == term->tl_buffer)
4808 break;
4809 if (wp != NULL)
4810 {
4811#ifdef FEAT_GUI
4812 if (gui.in_use)
4813 {
4814 x += wp->w_wincol * gui.char_width;
4815 y += W_WINROW(wp) * gui.char_height;
4816 }
4817 else
4818#endif
4819 {
4820 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004821 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004822 x += wp->w_wincol * 7;
4823 y += W_WINROW(wp) * 10;
4824 }
4825 }
4826
4827 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4828 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4829 (char_u *)buf, len, NULL);
4830 return 1;
4831}
4832
Bram Moolenaard8637282020-05-20 18:41:41 +02004833static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004834 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004835 parse_csi, // csi
4836 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004837 NULL, // dcs
4838 NULL, // apc
4839 NULL, // pm
4840 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004841};
4842
4843/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004844 * Use Vim's allocation functions for vterm so profiling works.
4845 */
4846 static void *
4847vterm_malloc(size_t size, void *data UNUSED)
4848{
Bram Moolenaar88137392021-11-12 16:01:15 +00004849 // make sure that the length is not zero
4850 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004851}
4852
4853 static void
4854vterm_memfree(void *ptr, void *data UNUSED)
4855{
4856 vim_free(ptr);
4857}
4858
4859static VTermAllocatorFunctions vterm_allocator = {
4860 &vterm_malloc,
4861 &vterm_memfree
4862};
4863
4864/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004865 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004866 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004867 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004868 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004869create_vterm(term_T *term, int rows, int cols)
4870{
4871 VTerm *vterm;
4872 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004873 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004874 VTermValue value;
4875
Bram Moolenaar756ef112018-04-10 12:04:27 +02004876 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004877 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004878 if (vterm == NULL)
4879 return FAIL;
4880
4881 // Allocate screen and state here, so we can bail out if that fails.
4882 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004883 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004884 if (state == NULL || screen == NULL)
4885 {
4886 vterm_free(vterm);
4887 return FAIL;
4888 }
4889
Bram Moolenaar52acb112018-03-18 19:20:22 +01004890 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004891 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004892 vterm_set_utf8(vterm, 1);
4893
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004894 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004895
4896 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004897 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004898 &term->tl_default_color.fg,
4899 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004900
Bram Moolenaar9e587872019-05-13 20:27:23 +02004901 if (t_colors < 16)
4902 // Less than 16 colors: assume that bold means using a bright color for
4903 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004904 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4905
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004906 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004907 vterm_screen_reset(screen, 1 /* hard */);
4908
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004909 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004910 vterm_screen_enable_altscreen(screen, 1);
4911
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004912 // For unix do not use a blinking cursor. In an xterm this causes the
4913 // cursor to blink if it's blinking in the xterm.
4914 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004915#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004916 if (GetCaretBlinkTime() == INFINITE)
4917 value.boolean = 0;
4918 else
4919 value.boolean = 1;
4920#else
4921 value.boolean = 0;
4922#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004923 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004924 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004925
4926 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004927}
4928
4929/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004930 * Reset the terminal palette to its default value.
4931 */
4932 static void
4933term_reset_palette(VTerm *vterm)
4934{
4935 VTermState *state = vterm_obtain_state(vterm);
4936 int index;
4937
4938 for (index = 0; index < 16; index++)
4939 {
4940 VTermColor color;
4941
4942 color.type = VTERM_COLOR_INDEXED;
4943 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4944 &color.index);
4945 // The first valid index starts at 1.
4946 color.index -= 1;
4947
4948 vterm_state_set_palette_color(state, index, &color);
4949 }
4950}
4951
4952 static void
4953term_update_palette(term_T *term)
4954{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004955#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004956 if (term_use_palette()
4957 && (term->tl_palette != NULL
4958 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004959 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004960 {
4961 if (term->tl_palette != NULL)
4962 set_vterm_palette(term->tl_vterm, term->tl_palette);
4963 else
4964 init_vterm_ansi_colors(term->tl_vterm);
4965 }
4966 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004967#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004968 term_reset_palette(term->tl_vterm);
4969}
4970
4971/*
4972 * Called when option 'termguicolors' is changed.
4973 */
4974 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004975term_update_palette_all(void)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004976{
4977 term_T *term;
4978
4979 FOR_ALL_TERMS(term)
4980 {
4981 if (term->tl_vterm == NULL)
4982 continue;
4983 term_update_palette(term);
4984 }
4985}
4986
4987/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004988 * Called when option 'background' or 'termguicolors' was set,
4989 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02004990 */
4991 void
4992term_update_colors_all(void)
4993{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004994 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02004995
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004996 FOR_ALL_TERMS(term)
4997 {
4998 if (term->tl_vterm == NULL)
4999 continue;
5000 init_default_colors(term);
5001 vterm_state_set_default_colors(
5002 vterm_obtain_state(term->tl_vterm),
5003 &term->tl_default_color.fg,
5004 &term->tl_default_color.bg);
5005 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005006}
5007
5008/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005009 * Return the text to show for the buffer name and status.
5010 */
5011 char_u *
5012term_get_status_text(term_T *term)
5013{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005014 if (term->tl_status_text != NULL)
5015 return term->tl_status_text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005016
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005017 char_u *txt;
5018 size_t len;
5019 char_u *fname;
5020
5021 if (term->tl_normal_mode)
5022 {
5023 if (term_job_running(term))
5024 txt = (char_u *)_("Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005025 else
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005026 txt = (char_u *)_("Terminal-finished");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005027 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005028 else if (term->tl_title != NULL)
5029 txt = term->tl_title;
5030 else if (term_none_open(term))
5031 txt = (char_u *)_("active");
5032 else if (term_job_running(term))
5033 txt = (char_u *)_("running");
5034 else
5035 txt = (char_u *)_("finished");
5036 fname = buf_get_fname(term->tl_buffer);
5037 len = 9 + STRLEN(fname) + STRLEN(txt);
5038 term->tl_status_text = alloc(len);
5039 if (term->tl_status_text != NULL)
5040 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
5041 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005042 return term->tl_status_text;
5043}
5044
5045/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00005046 * Clear the cached value of the status text.
5047 */
5048 void
5049term_clear_status_text(term_T *term)
5050{
5051 VIM_CLEAR(term->tl_status_text);
5052}
5053
5054/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005055 * Mark references in jobs of terminals.
5056 */
5057 int
5058set_ref_in_term(int copyID)
5059{
5060 int abort = FALSE;
5061 term_T *term;
5062 typval_T tv;
5063
Bram Moolenaar75a1a942019-06-20 03:45:36 +02005064 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005065 if (term->tl_job != NULL)
5066 {
5067 tv.v_type = VAR_JOB;
5068 tv.vval.v_job = term->tl_job;
5069 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
5070 }
5071 return abort;
5072}
5073
5074/*
5075 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005076 * Returns NULL when the buffer is not for a terminal window and logs a message
5077 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005078 */
5079 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005080term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005081{
5082 buf_T *buf;
5083
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005084 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01005085 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005086 --emsg_off;
5087 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005088 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01005089 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005090 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005091 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005092 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005093 return buf;
5094}
5095
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005096 static void
5097clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005098{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005099 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005100 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
5101 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005102}
5103
5104 static void
5105dump_term_color(FILE *fd, VTermColor *color)
5106{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005107 int index;
5108
5109 if (VTERM_COLOR_IS_INDEXED(color))
5110 index = color->index + 1;
5111 else if (color->type == 0)
5112 // use RGB values
5113 index = 255;
5114 else
5115 // default color
5116 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005117 fprintf(fd, "%02x%02x%02x%d",
5118 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005119 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005120}
5121
5122/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005123 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01005124 *
5125 * Each screen cell in full is:
5126 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5127 * {characters} is a space for an empty cell
5128 * For a double-width character "+" is changed to "*" and the next cell is
5129 * skipped.
5130 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5131 * when "&" use the same as the previous cell.
5132 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5133 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5134 * {color-idx} is a number from 0 to 255
5135 *
5136 * Screen cell with same width, attributes and color as the previous one:
5137 * |{characters}
5138 *
5139 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5140 *
5141 * Repeating the previous screen cell:
5142 * @{count}
5143 */
5144 void
5145f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5146{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005147 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005148 term_T *term;
5149 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005150 int max_height = 0;
5151 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005152 stat_T st;
5153 FILE *fd;
5154 VTermPos pos;
5155 VTermScreen *screen;
5156 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005157 VTermState *state;
5158 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005159
5160 if (check_restricted() || check_secure())
5161 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005162
5163 if (in_vim9script()
5164 && (check_for_buffer_arg(argvars, 0) == FAIL
5165 || check_for_string_arg(argvars, 1) == FAIL
5166 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5167 return;
5168
5169 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005170 if (buf == NULL)
5171 return;
5172 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005173 if (term->tl_vterm == NULL)
5174 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005175 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005176 return;
5177 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005178
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005179 if (argvars[2].v_type != VAR_UNKNOWN)
5180 {
5181 dict_T *d;
5182
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005183 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005184 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005185 d = argvars[2].vval.v_dict;
5186 if (d != NULL)
5187 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005188 max_height = dict_get_number(d, "rows");
5189 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005190 }
5191 }
5192
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005193 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005194 if (fname == NULL)
5195 return;
5196 if (mch_stat((char *)fname, &st) >= 0)
5197 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005198 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005199 return;
5200 }
5201
Bram Moolenaard96ff162018-02-18 22:13:29 +01005202 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5203 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005204 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005205 return;
5206 }
5207
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005208 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005209
5210 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005211 state = vterm_obtain_state(term->tl_vterm);
5212 vterm_state_get_cursorpos(state, &cursor_pos);
5213
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005214 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5215 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005216 {
5217 int repeat = 0;
5218
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005219 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5220 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005221 {
5222 VTermScreenCell cell;
5223 int same_attr;
5224 int same_chars = TRUE;
5225 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005226 int is_cursor_pos = (pos.col == cursor_pos.col
5227 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005228
5229 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005230 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005231
5232 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5233 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005234 int c = cell.chars[i];
5235 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005236 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005237
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005238 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005239 if (i == 0)
5240 {
5241 c = (c == NUL) ? ' ' : c;
5242 pc = (pc == NUL) ? ' ' : pc;
5243 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005244 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005245 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005246 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005247 break;
5248 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005249 same_attr = vtermAttr2hl(&cell.attrs)
5250 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005251 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5252 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005253 if (same_chars && cell.width == prev_cell.width && same_attr
5254 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005255 {
5256 ++repeat;
5257 }
5258 else
5259 {
5260 if (repeat > 0)
5261 {
5262 fprintf(fd, "@%d", repeat);
5263 repeat = 0;
5264 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005265 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005266
5267 if (cell.chars[0] == NUL)
5268 fputs(" ", fd);
5269 else
5270 {
5271 char_u charbuf[10];
5272 int len;
5273
5274 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5275 && cell.chars[i] != NUL; ++i)
5276 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005277 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005278 fwrite(charbuf, len, 1, fd);
5279 }
5280 }
5281
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005282 // When only the characters differ we don't write anything, the
5283 // following "|", "@" or NL will indicate using the same
5284 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005285 if (cell.width != prev_cell.width || !same_attr)
5286 {
5287 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005288 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005289 else
5290 fputs("+", fd);
5291
5292 if (same_attr)
5293 {
5294 fputs("&", fd);
5295 }
5296 else
5297 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005298 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005299 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005300 fputs("&", fd);
5301 else
5302 {
5303 fputs("#", fd);
5304 dump_term_color(fd, &cell.fg);
5305 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005306 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005307 fputs("&", fd);
5308 else
5309 {
5310 fputs("#", fd);
5311 dump_term_color(fd, &cell.bg);
5312 }
5313 }
5314 }
5315
5316 prev_cell = cell;
5317 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005318
5319 if (cell.width == 2)
5320 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005321 }
5322 if (repeat > 0)
5323 fprintf(fd, "@%d", repeat);
5324 fputs("\n", fd);
5325 }
5326
5327 fclose(fd);
5328}
5329
5330/*
5331 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5332 */
5333 static void
5334dump_is_corrupt(garray_T *gap)
5335{
5336 ga_concat(gap, (char_u *)"CORRUPT");
5337}
5338
5339 static void
5340append_cell(garray_T *gap, cellattr_T *cell)
5341{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005342 if (ga_grow(gap, 1) == FAIL)
5343 return;
5344
5345 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5346 ++gap->ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005347}
5348
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005349 static void
5350clear_cellattr(cellattr_T *cell)
5351{
5352 CLEAR_FIELD(*cell);
5353 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5354 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5355}
5356
Bram Moolenaard96ff162018-02-18 22:13:29 +01005357/*
5358 * Read the dump file from "fd" and append lines to the current buffer.
5359 * Return the cell width of the longest line.
5360 */
5361 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005362read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005363{
5364 int c;
5365 garray_T ga_text;
5366 garray_T ga_cell;
5367 char_u *prev_char = NULL;
5368 int attr = 0;
5369 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005370 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005371 term_T *term = curbuf->b_term;
5372 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005373 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005374
5375 ga_init2(&ga_text, 1, 90);
5376 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005377 clear_cellattr(&cell);
5378 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005379 cursor_pos->row = -1;
5380 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005381
5382 c = fgetc(fd);
5383 for (;;)
5384 {
5385 if (c == EOF)
5386 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005387 if (c == '\r')
5388 {
5389 // DOS line endings? Ignore.
5390 c = fgetc(fd);
5391 }
5392 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005393 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005394 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005395 if (ga_text.ga_data == NULL)
5396 dump_is_corrupt(&ga_text);
5397 if (ga_grow(&term->tl_scrollback, 1) == OK)
5398 {
5399 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5400 + term->tl_scrollback.ga_len;
5401
5402 if (max_cells < ga_cell.ga_len)
5403 max_cells = ga_cell.ga_len;
5404 line->sb_cols = ga_cell.ga_len;
5405 line->sb_cells = ga_cell.ga_data;
5406 line->sb_fill_attr = term->tl_default_color;
5407 ++term->tl_scrollback.ga_len;
5408 ga_init(&ga_cell);
5409
5410 ga_append(&ga_text, NUL);
5411 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5412 ga_text.ga_len, FALSE);
5413 }
5414 else
5415 ga_clear(&ga_cell);
5416 ga_text.ga_len = 0;
5417
5418 c = fgetc(fd);
5419 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005420 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005421 {
5422 int prev_len = ga_text.ga_len;
5423
Bram Moolenaar9271d052018-02-25 21:39:46 +01005424 if (c == '>')
5425 {
5426 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005427 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005428 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5429 cursor_pos->col = ga_cell.ga_len;
5430 }
5431
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005432 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005433 c = fgetc(fd);
5434 if (c != EOF)
5435 ga_append(&ga_text, c);
5436 for (;;)
5437 {
5438 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005439 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005440 || c == EOF || c == '\n')
5441 break;
5442 ga_append(&ga_text, c);
5443 }
5444
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005445 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005446 vim_free(prev_char);
5447 if (ga_text.ga_data != NULL)
5448 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5449 ga_text.ga_len - prev_len);
5450
Bram Moolenaar9271d052018-02-25 21:39:46 +01005451 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005452 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005453 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005454 }
5455 else if (c == '+' || c == '*')
5456 {
5457 int is_bg;
5458
5459 cell.width = c == '+' ? 1 : 2;
5460
5461 c = fgetc(fd);
5462 if (c == '&')
5463 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005464 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005465 c = fgetc(fd);
5466 }
Keith Thompson184f71c2024-01-04 21:19:04 +01005467 else if (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005468 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005469 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005470 attr = 0;
Keith Thompson184f71c2024-01-04 21:19:04 +01005471 while (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005472 {
5473 attr = attr * 10 + (c - '0');
5474 c = fgetc(fd);
5475 }
5476 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005477
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005478 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005479 for (is_bg = 0; is_bg <= 1; ++is_bg)
5480 {
5481 if (c == '&')
5482 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005483 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005484 c = fgetc(fd);
5485 }
5486 else if (c == '#')
5487 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005488 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005489
5490 c = fgetc(fd);
5491 red = hex2nr(c);
5492 c = fgetc(fd);
5493 red = (red << 4) + hex2nr(c);
5494 c = fgetc(fd);
5495 green = hex2nr(c);
5496 c = fgetc(fd);
5497 green = (green << 4) + hex2nr(c);
5498 c = fgetc(fd);
5499 blue = hex2nr(c);
5500 c = fgetc(fd);
5501 blue = (blue << 4) + hex2nr(c);
5502 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005503 if (!SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005504 dump_is_corrupt(&ga_text);
Keith Thompson184f71c2024-01-04 21:19:04 +01005505 while (SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005506 {
5507 index = index * 10 + (c - '0');
5508 c = fgetc(fd);
5509 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005510 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005511 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005512 type = VTERM_COLOR_RGB;
5513 if (index == 0)
5514 {
5515 if (is_bg)
5516 type |= VTERM_COLOR_DEFAULT_BG;
5517 else
5518 type |= VTERM_COLOR_DEFAULT_FG;
5519 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005520 }
5521 else
5522 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005523 type = VTERM_COLOR_INDEXED;
5524 index -= 1;
5525 }
5526 if (is_bg)
5527 {
5528 cell.bg.type = type;
5529 cell.bg.red = red;
5530 cell.bg.green = green;
5531 cell.bg.blue = blue;
5532 cell.bg.index = index;
5533 }
5534 else
5535 {
5536 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005537 cell.fg.red = red;
5538 cell.fg.green = green;
5539 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005540 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005541 }
5542 }
5543 else
5544 dump_is_corrupt(&ga_text);
5545 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005546 }
5547 else
5548 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005549 }
5550 else
5551 dump_is_corrupt(&ga_text);
5552
5553 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005554 if (cell.width == 2)
5555 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005556 }
5557 else if (c == '@')
5558 {
5559 if (prev_char == NULL)
5560 dump_is_corrupt(&ga_text);
5561 else
5562 {
5563 int count = 0;
5564
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005565 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005566 for (;;)
5567 {
5568 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005569 if (!SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005570 break;
5571 count = count * 10 + (c - '0');
5572 }
5573
5574 while (count-- > 0)
5575 {
5576 ga_concat(&ga_text, prev_char);
5577 append_cell(&ga_cell, &cell);
5578 }
5579 }
5580 }
5581 else
5582 {
5583 dump_is_corrupt(&ga_text);
5584 c = fgetc(fd);
5585 }
5586 }
5587
5588 if (ga_text.ga_len > 0)
5589 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005590 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005591 dump_is_corrupt(&ga_text);
5592 ga_append(&ga_text, NUL);
5593 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5594 ga_text.ga_len, FALSE);
5595 }
5596
5597 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005598 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005599 vim_free(prev_char);
5600
5601 return max_cells;
5602}
5603
5604/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005605 * Return an allocated string with at least "text_width" "=" characters and
5606 * "fname" inserted in the middle.
5607 */
5608 static char_u *
5609get_separator(int text_width, char_u *fname)
5610{
5611 int width = MAX(text_width, curwin->w_width);
5612 char_u *textline;
5613 int fname_size;
5614 char_u *p = fname;
5615 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005616 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005617
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005618 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005619 if (textline == NULL)
5620 return NULL;
5621
5622 fname_size = vim_strsize(fname);
5623 if (fname_size < width - 8)
5624 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005625 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005626 width = MAX(text_width, fname_size + 8);
5627 }
5628 else if (fname_size > width - 8)
5629 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005630 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005631 p = gettail(fname);
5632 fname_size = vim_strsize(p);
5633 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005634 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005635 while (fname_size > width - 8)
5636 {
5637 p += (*mb_ptr2len)(p);
5638 fname_size = vim_strsize(p);
5639 }
5640
5641 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5642 textline[i] = '=';
5643 textline[i++] = ' ';
5644
5645 STRCPY(textline + i, p);
5646 off = STRLEN(textline);
5647 textline[off] = ' ';
5648 for (i = 1; i < (width - fname_size) / 2; ++i)
5649 textline[off + i] = '=';
5650 textline[off + i] = NUL;
5651
5652 return textline;
5653}
5654
5655/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005656 * Common for "term_dumpdiff()" and "term_dumpload()".
5657 */
5658 static void
5659term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5660{
5661 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005662 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005663 char_u buf1[NUMBUFLEN];
5664 char_u buf2[NUMBUFLEN];
5665 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005666 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005667 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005668 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005669 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005670 char_u *textline = NULL;
5671
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005672 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005673 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005674 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005675 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005676 if (fname1 == NULL || (do_diff && fname2 == NULL))
5677 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005678 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005679 return;
5680 }
5681 fd1 = mch_fopen((char *)fname1, READBIN);
5682 if (fd1 == NULL)
5683 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005684 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005685 return;
5686 }
5687 if (do_diff)
5688 {
5689 fd2 = mch_fopen((char *)fname2, READBIN);
5690 if (fd2 == NULL)
5691 {
5692 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005693 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005694 return;
5695 }
5696 }
5697
5698 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005699 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5700 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5701 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5702 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5703 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005704
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005705 if (opt.jo_term_name == NULL)
5706 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005707 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005708
Bram Moolenaar51e14382019-05-25 20:21:28 +02005709 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005710 if (fname_tofree != NULL)
5711 {
5712 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5713 opt.jo_term_name = fname_tofree;
5714 }
5715 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005716
Bram Moolenaar87abab92019-06-03 21:14:59 +02005717 if (opt.jo_bufnr_buf != NULL)
5718 {
5719 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5720
5721 // With "bufnr" argument: enter the window with this buffer and make it
5722 // empty.
5723 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005724 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005725 else
5726 {
5727 buf = curbuf;
5728 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005729 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005730 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005731 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005732 }
5733 }
5734 else
5735 // Create a new terminal window.
5736 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5737
Bram Moolenaard96ff162018-02-18 22:13:29 +01005738 if (buf != NULL && buf->b_term != NULL)
5739 {
5740 int i;
5741 linenr_T bot_lnum;
5742 linenr_T lnum;
5743 term_T *term = buf->b_term;
5744 int width;
5745 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005746 VTermPos cursor_pos1;
5747 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005748
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005749 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005750
Bram Moolenaard96ff162018-02-18 22:13:29 +01005751 rettv->vval.v_number = buf->b_fnum;
5752
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005753 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005754 width = read_dump_file(fd1, &cursor_pos1);
5755
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005756 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005757 if (cursor_pos1.row >= 0)
5758 {
5759 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5760 coladvance(cursor_pos1.col);
5761 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005762
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005763 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005764 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005765
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005766 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005767 if (!do_diff)
5768 goto theend;
5769
5770 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5771
Bram Moolenaar4a696342018-04-05 18:45:26 +02005772 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005773 if (textline == NULL)
5774 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005775 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5776 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5777 vim_free(textline);
5778
5779 textline = get_separator(width, fname2);
5780 if (textline == NULL)
5781 goto theend;
5782 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5783 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005784 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005785
5786 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005787 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005788 if (width2 > width)
5789 {
5790 vim_free(textline);
5791 textline = alloc(width2 + 1);
5792 if (textline == NULL)
5793 goto theend;
5794 width = width2;
5795 textline[width] = NUL;
5796 }
5797 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5798
5799 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5800 {
5801 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5802 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005803 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005804 for (i = 0; i < width; ++i)
5805 textline[i] = '-';
5806 }
5807 else
5808 {
5809 char_u *line1;
5810 char_u *line2;
5811 char_u *p1;
5812 char_u *p2;
5813 int col;
5814 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5815 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5816 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5817 ->sb_cells;
5818
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005819 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005820 line1 = vim_strsave(ml_get(lnum));
5821 if (line1 == NULL)
5822 break;
5823 p1 = line1;
5824
5825 line2 = ml_get(lnum + bot_lnum);
5826 p2 = line2;
5827 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5828 {
5829 int len1 = utfc_ptr2len(p1);
5830 int len2 = utfc_ptr2len(p2);
5831
5832 textline[col] = ' ';
5833 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005834 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005835 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005836 else if (lnum == cursor_pos1.row + 1
5837 && col == cursor_pos1.col
5838 && (cursor_pos1.row != cursor_pos2.row
5839 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005840 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005841 textline[col] = '>';
5842 else if (lnum == cursor_pos2.row + 1
5843 && col == cursor_pos2.col
5844 && (cursor_pos1.row != cursor_pos2.row
5845 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005846 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005847 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005848 else if (cellattr1 != NULL && cellattr2 != NULL)
5849 {
5850 if ((cellattr1 + col)->width
5851 != (cellattr2 + col)->width)
5852 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005853 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005854 &(cellattr2 + col)->fg))
5855 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005856 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005857 &(cellattr2 + col)->bg))
5858 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005859 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5860 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005861 textline[col] = 'a';
5862 }
5863 p1 += len1;
5864 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005865 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005866 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005867
5868 while (col < width)
5869 {
5870 if (*p1 == NUL && *p2 == NUL)
5871 textline[col] = '?';
5872 else if (*p1 == NUL)
5873 {
5874 textline[col] = '+';
5875 p2 += utfc_ptr2len(p2);
5876 }
5877 else
5878 {
5879 textline[col] = '-';
5880 p1 += utfc_ptr2len(p1);
5881 }
5882 ++col;
5883 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005884
5885 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005886 }
5887 if (add_empty_scrollback(term, &term->tl_default_color,
5888 term->tl_top_diff_rows) == OK)
5889 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5890 ++bot_lnum;
5891 }
5892
5893 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5894 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005895 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005896 for (i = 0; i < width; ++i)
5897 textline[i] = '+';
5898 if (add_empty_scrollback(term, &term->tl_default_color,
5899 term->tl_top_diff_rows) == OK)
5900 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5901 ++lnum;
5902 ++bot_lnum;
5903 }
5904
5905 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005906
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005907 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005908 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005909 }
5910
5911theend:
5912 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005913 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005914 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005915 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005916 fclose(fd2);
5917}
5918
5919/*
5920 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5921 * bottom files.
5922 * Return FAIL when this is not possible.
5923 */
5924 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005925term_swap_diff(void)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005926{
5927 term_T *term = curbuf->b_term;
5928 linenr_T line_count;
5929 linenr_T top_rows;
5930 linenr_T bot_rows;
5931 linenr_T bot_start;
5932 linenr_T lnum;
5933 char_u *p;
5934 sb_line_T *sb_line;
5935
5936 if (term == NULL
5937 || !term_is_finished(curbuf)
5938 || term->tl_top_diff_rows == 0
5939 || term->tl_scrollback.ga_len == 0)
5940 return FAIL;
5941
5942 line_count = curbuf->b_ml.ml_line_count;
5943 top_rows = term->tl_top_diff_rows;
5944 bot_rows = term->tl_bot_diff_rows;
5945 bot_start = line_count - bot_rows;
5946 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5947
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005948 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005949 for (lnum = 1; lnum <= top_rows; ++lnum)
5950 {
5951 p = vim_strsave(ml_get(1));
5952 if (p == NULL)
5953 return OK;
5954 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005955 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005956 vim_free(p);
5957 }
5958
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005959 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005960 for (lnum = 1; lnum <= bot_rows; ++lnum)
5961 {
5962 p = vim_strsave(ml_get(bot_start + lnum));
5963 if (p == NULL)
5964 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005965 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005966 ml_append(lnum - 1, p, 0, FALSE);
5967 vim_free(p);
5968 }
5969
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005970 // move top title to bottom
5971 p = vim_strsave(ml_get(bot_rows + 1));
5972 if (p == NULL)
5973 return OK;
5974 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005975 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005976 vim_free(p);
5977
5978 // move bottom title to top
5979 p = vim_strsave(ml_get(line_count - top_rows));
5980 if (p == NULL)
5981 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005982 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005983 ml_append(bot_rows, p, 0, FALSE);
5984 vim_free(p);
5985
Bram Moolenaard96ff162018-02-18 22:13:29 +01005986 if (top_rows == bot_rows)
5987 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005988 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005989 for (lnum = 0; lnum < top_rows; ++lnum)
5990 {
5991 sb_line_T temp;
5992
5993 temp = *(sb_line + lnum);
5994 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5995 *(sb_line + bot_start + lnum) = temp;
5996 }
5997 }
5998 else
5999 {
6000 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006001 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006002
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006003 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01006004 if (temp != NULL)
6005 {
6006 mch_memmove(temp, term->tl_scrollback.ga_data, size);
6007 mch_memmove(term->tl_scrollback.ga_data,
6008 temp + bot_start,
6009 sizeof(sb_line_T) * bot_rows);
6010 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
6011 temp + top_rows,
6012 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
6013 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
6014 + line_count - top_rows,
6015 temp,
6016 sizeof(sb_line_T) * top_rows);
6017 vim_free(temp);
6018 }
6019 }
6020
6021 term->tl_top_diff_rows = bot_rows;
6022 term->tl_bot_diff_rows = top_rows;
6023
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006024 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006025 return OK;
6026}
6027
6028/*
6029 * "term_dumpdiff(filename, filename, options)" function
6030 */
6031 void
6032f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
6033{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02006034 if (in_vim9script()
6035 && (check_for_string_arg(argvars, 0) == FAIL
6036 || check_for_string_arg(argvars, 1) == FAIL
6037 || check_for_opt_dict_arg(argvars, 2) == FAIL))
6038 return;
6039
Bram Moolenaard96ff162018-02-18 22:13:29 +01006040 term_load_dump(argvars, rettv, TRUE);
6041}
6042
6043/*
6044 * "term_dumpload(filename, options)" function
6045 */
6046 void
6047f_term_dumpload(typval_T *argvars, typval_T *rettv)
6048{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006049 if (in_vim9script()
6050 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02006051 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006052 return;
6053
Bram Moolenaard96ff162018-02-18 22:13:29 +01006054 term_load_dump(argvars, rettv, FALSE);
6055}
6056
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006057/*
6058 * "term_getaltscreen(buf)" function
6059 */
6060 void
6061f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
6062{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006063 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006064
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006065 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6066 return;
6067
6068 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006069 if (buf == NULL)
6070 return;
6071 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
6072}
6073
6074/*
6075 * "term_getattr(attr, name)" function
6076 */
6077 void
6078f_term_getattr(typval_T *argvars, typval_T *rettv)
6079{
6080 int attr;
6081 size_t i;
6082 char_u *name;
6083
6084 static struct {
6085 char *name;
6086 int attr;
6087 } attrs[] = {
6088 {"bold", HL_BOLD},
6089 {"italic", HL_ITALIC},
6090 {"underline", HL_UNDERLINE},
6091 {"strike", HL_STRIKETHROUGH},
6092 {"reverse", HL_INVERSE},
6093 };
6094
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02006095 if (in_vim9script()
6096 && (check_for_number_arg(argvars, 0) == FAIL
6097 || check_for_string_arg(argvars, 1) == FAIL))
6098 return;
6099
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006100 attr = tv_get_number(&argvars[0]);
6101 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006102 if (name == NULL)
6103 return;
6104
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02006105 if (attr > HL_ALL)
6106 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02006107 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006108 if (STRCMP(name, attrs[i].name) == 0)
6109 {
6110 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
6111 break;
6112 }
6113}
6114
6115/*
6116 * "term_getcursor(buf)" function
6117 */
6118 void
6119f_term_getcursor(typval_T *argvars, typval_T *rettv)
6120{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006121 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006122 term_T *term;
6123 list_T *l;
6124 dict_T *d;
6125
6126 if (rettv_list_alloc(rettv) == FAIL)
6127 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006128
6129 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6130 return;
6131
6132 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006133 if (buf == NULL)
6134 return;
6135 term = buf->b_term;
6136
6137 l = rettv->vval.v_list;
6138 list_append_number(l, term->tl_cursor_pos.row + 1);
6139 list_append_number(l, term->tl_cursor_pos.col + 1);
6140
6141 d = dict_alloc();
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00006142 if (d == NULL)
6143 return;
6144
6145 dict_add_number(d, "visible", term->tl_cursor_visible);
6146 dict_add_number(d, "blink", blink_state_is_inverted()
6147 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6148 dict_add_number(d, "shape", term->tl_cursor_shape);
6149 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
6150 list_append_dict(l, d);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006151}
6152
6153/*
6154 * "term_getjob(buf)" function
6155 */
6156 void
6157f_term_getjob(typval_T *argvars, typval_T *rettv)
6158{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006159 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006160
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006161 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6162 return;
6163
6164 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006165 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006166 {
6167 rettv->v_type = VAR_SPECIAL;
6168 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006169 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006170 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006171
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006172 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006173 rettv->vval.v_job = buf->b_term->tl_job;
6174 if (rettv->vval.v_job != NULL)
6175 ++rettv->vval.v_job->jv_refcount;
6176}
6177
6178 static int
6179get_row_number(typval_T *tv, term_T *term)
6180{
6181 if (tv->v_type == VAR_STRING
6182 && tv->vval.v_string != NULL
6183 && STRCMP(tv->vval.v_string, ".") == 0)
6184 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006185 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006186}
6187
6188/*
6189 * "term_getline(buf, row)" function
6190 */
6191 void
6192f_term_getline(typval_T *argvars, typval_T *rettv)
6193{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006194 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006195 term_T *term;
6196 int row;
6197
6198 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006199
6200 if (in_vim9script()
6201 && (check_for_buffer_arg(argvars, 0) == FAIL
6202 || check_for_lnum_arg(argvars, 1) == FAIL))
6203 return;
6204
6205 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006206 if (buf == NULL)
6207 return;
6208 term = buf->b_term;
6209 row = get_row_number(&argvars[1], term);
6210
6211 if (term->tl_vterm == NULL)
6212 {
6213 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6214
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006215 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006216 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6217 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6218 }
6219 else
6220 {
6221 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6222 VTermRect rect;
6223 int len;
6224 char_u *p;
6225
6226 if (row < 0 || row >= term->tl_rows)
6227 return;
6228 len = term->tl_cols * MB_MAXBYTES + 1;
6229 p = alloc(len);
6230 if (p == NULL)
6231 return;
6232 rettv->vval.v_string = p;
6233
6234 rect.start_col = 0;
6235 rect.end_col = term->tl_cols;
6236 rect.start_row = row;
6237 rect.end_row = row + 1;
6238 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6239 }
6240}
6241
6242/*
6243 * "term_getscrolled(buf)" function
6244 */
6245 void
6246f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6247{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006248 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006249
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006250 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6251 return;
6252
6253 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006254 if (buf == NULL)
6255 return;
6256 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6257}
6258
6259/*
6260 * "term_getsize(buf)" function
6261 */
6262 void
6263f_term_getsize(typval_T *argvars, typval_T *rettv)
6264{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006265 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006266 list_T *l;
6267
6268 if (rettv_list_alloc(rettv) == FAIL)
6269 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006270
6271 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6272 return;
6273
6274 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006275 if (buf == NULL)
6276 return;
6277
6278 l = rettv->vval.v_list;
6279 list_append_number(l, buf->b_term->tl_rows);
6280 list_append_number(l, buf->b_term->tl_cols);
6281}
6282
6283/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006284 * "term_setsize(buf, rows, cols)" function
6285 */
6286 void
6287f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6288{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006289 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006290 term_T *term;
6291 varnumber_T rows, cols;
6292
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006293 if (in_vim9script()
6294 && (check_for_buffer_arg(argvars, 0) == FAIL
6295 || check_for_number_arg(argvars, 1) == FAIL
6296 || check_for_number_arg(argvars, 2) == FAIL))
6297 return;
6298
6299 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006300 if (buf == NULL)
6301 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006302 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006303 return;
6304 }
6305 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006306 return;
6307 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006308 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006309 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006310 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006311 cols = cols <= 0 ? term->tl_cols : cols;
6312 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006313 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006314
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006315 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006316 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6317 term_report_winsize(term, term->tl_rows, term->tl_cols);
6318}
6319
6320/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006321 * "term_getstatus(buf)" function
6322 */
6323 void
6324f_term_getstatus(typval_T *argvars, typval_T *rettv)
6325{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006326 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006327 term_T *term;
6328 char_u val[100];
6329
6330 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006331
6332 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6333 return;
6334
6335 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006336 if (buf == NULL)
6337 return;
6338 term = buf->b_term;
6339
6340 if (term_job_running(term))
6341 STRCPY(val, "running");
6342 else
6343 STRCPY(val, "finished");
6344 if (term->tl_normal_mode)
6345 STRCAT(val, ",normal");
6346 rettv->vval.v_string = vim_strsave(val);
6347}
6348
6349/*
6350 * "term_gettitle(buf)" function
6351 */
6352 void
6353f_term_gettitle(typval_T *argvars, typval_T *rettv)
6354{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006355 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006356
6357 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006358
6359 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6360 return;
6361
6362 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006363 if (buf == NULL)
6364 return;
6365
6366 if (buf->b_term->tl_title != NULL)
6367 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6368}
6369
6370/*
6371 * "term_gettty(buf)" function
6372 */
6373 void
6374f_term_gettty(typval_T *argvars, typval_T *rettv)
6375{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006376 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006377 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006378 int num = 0;
6379
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006380 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006381 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006382 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6383 return;
6384
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006385 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006386 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006387 if (buf == NULL)
6388 return;
6389 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006390 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006391
6392 switch (num)
6393 {
6394 case 0:
6395 if (buf->b_term->tl_job != NULL)
6396 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006397 break;
6398 case 1:
6399 if (buf->b_term->tl_job != NULL)
6400 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006401 break;
6402 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006403 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006404 return;
6405 }
6406 if (p != NULL)
6407 rettv->vval.v_string = vim_strsave(p);
6408}
6409
6410/*
6411 * "term_list()" function
6412 */
6413 void
6414f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6415{
6416 term_T *tp;
6417 list_T *l;
6418
6419 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6420 return;
6421
6422 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006423 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006424 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006425 if (list_append_number(l,
6426 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6427 return;
6428}
6429
6430/*
6431 * "term_scrape(buf, row)" function
6432 */
6433 void
6434f_term_scrape(typval_T *argvars, typval_T *rettv)
6435{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006436 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006437 VTermScreen *screen = NULL;
6438 VTermPos pos;
6439 list_T *l;
6440 term_T *term;
6441 char_u *p;
6442 sb_line_T *line;
6443
6444 if (rettv_list_alloc(rettv) == FAIL)
6445 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006446
6447 if (in_vim9script()
6448 && (check_for_buffer_arg(argvars, 0) == FAIL
6449 || check_for_lnum_arg(argvars, 1) == FAIL))
6450 return;
6451
6452 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006453 if (buf == NULL)
6454 return;
6455 term = buf->b_term;
6456
6457 l = rettv->vval.v_list;
6458 pos.row = get_row_number(&argvars[1], term);
6459
6460 if (term->tl_vterm != NULL)
6461 {
6462 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006463 if (screen == NULL) // can't really happen
6464 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006465 p = NULL;
6466 line = NULL;
6467 }
6468 else
6469 {
6470 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6471
6472 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6473 return;
6474 p = ml_get_buf(buf, lnum + 1, FALSE);
6475 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6476 }
6477
6478 for (pos.col = 0; pos.col < term->tl_cols; )
6479 {
6480 dict_T *dcell;
6481 int width;
6482 VTermScreenCellAttrs attrs;
6483 VTermColor fg, bg;
6484 char_u rgb[8];
6485 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6486 int off = 0;
6487 int i;
6488
6489 if (screen == NULL)
6490 {
6491 cellattr_T *cellattr;
6492 int len;
6493
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006494 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006495 if (pos.col >= line->sb_cols)
6496 break;
6497 cellattr = line->sb_cells + pos.col;
6498 width = cellattr->width;
6499 attrs = cellattr->attrs;
6500 fg = cellattr->fg;
6501 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006502 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006503 mch_memmove(mbs, p, len);
6504 mbs[len] = NUL;
6505 p += len;
6506 }
6507 else
6508 {
6509 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006510
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006511 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6512 break;
6513 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6514 {
6515 if (cell.chars[i] == 0)
6516 break;
6517 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6518 }
6519 mbs[off] = NUL;
6520 width = cell.width;
6521 attrs = cell.attrs;
6522 fg = cell.fg;
6523 bg = cell.bg;
6524 }
6525 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006526 if (dcell == NULL)
6527 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006528 list_append_dict(l, dcell);
6529
Bram Moolenaare0be1672018-07-08 16:50:37 +02006530 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006531
6532 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6533 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006534 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006535 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6536 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006537 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006538
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006539 dict_add_number(dcell, "attr",
6540 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006541 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006542
6543 ++pos.col;
6544 if (width == 2)
6545 ++pos.col;
6546 }
6547}
6548
6549/*
6550 * "term_sendkeys(buf, keys)" function
6551 */
6552 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006553f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006554{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006555 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006556 char_u *msg;
6557 term_T *term;
6558
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006559 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006560 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006561 || check_for_string_arg(argvars, 1) == FAIL))
6562 return;
6563
6564 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006565 if (buf == NULL)
6566 return;
6567
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006568 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006569 if (msg == NULL)
6570 return;
6571 term = buf->b_term;
6572 if (term->tl_vterm == NULL)
6573 return;
6574
6575 while (*msg != NUL)
6576 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006577 int c;
6578
6579 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6580 {
6581 c = TO_SPECIAL(msg[1], msg[2]);
6582 msg += 3;
6583 }
6584 else
6585 {
6586 c = PTR2CHAR(msg);
6587 msg += MB_CPTR2LEN(msg);
6588 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006589 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006590 }
6591}
6592
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006593#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6594/*
6595 * "term_getansicolors(buf)" function
6596 */
6597 void
6598f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6599{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006600 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006601 term_T *term;
6602 VTermState *state;
6603 VTermColor color;
6604 char_u hexbuf[10];
6605 int index;
6606 list_T *list;
6607
6608 if (rettv_list_alloc(rettv) == FAIL)
6609 return;
6610
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006611 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6612 return;
6613
6614 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006615 if (buf == NULL)
6616 return;
6617 term = buf->b_term;
6618 if (term->tl_vterm == NULL)
6619 return;
6620
6621 list = rettv->vval.v_list;
6622 state = vterm_obtain_state(term->tl_vterm);
6623 for (index = 0; index < 16; index++)
6624 {
6625 vterm_state_get_palette_color(state, index, &color);
6626 sprintf((char *)hexbuf, "#%02x%02x%02x",
6627 color.red, color.green, color.blue);
6628 if (list_append_string(list, hexbuf, 7) == FAIL)
6629 return;
6630 }
6631}
6632
6633/*
6634 * "term_setansicolors(buf, list)" function
6635 */
6636 void
6637f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6638{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006639 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006640 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006641 listitem_T *li;
6642 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006643
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006644 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006645 && (check_for_buffer_arg(argvars, 0) == FAIL
6646 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006647 return;
6648
6649 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006650 if (buf == NULL)
6651 return;
6652 term = buf->b_term;
6653 if (term->tl_vterm == NULL)
6654 return;
6655
Bram Moolenaard83392a2022-09-01 12:22:46 +01006656 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006657 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006658
LemonBoyb2b3acb2022-05-20 10:10:34 +01006659 if (argvars[1].vval.v_list->lv_first == &range_list_item
6660 || argvars[1].vval.v_list->lv_len != 16)
6661 {
Bram Moolenaar23919542023-05-05 22:12:22 +01006662 semsg(_(e_invalid_value_for_argument_str), "\"colors\"");
LemonBoyb2b3acb2022-05-20 10:10:34 +01006663 return;
6664 }
6665
6666 if (term->tl_palette == NULL)
6667 term->tl_palette = ALLOC_MULT(long_u, 16);
6668 if (term->tl_palette == NULL)
6669 return;
6670
6671 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6672 {
6673 char_u *color_name;
6674 guicolor_T guicolor;
6675
6676 color_name = tv_get_string_chk(&li->li_tv);
6677 if (color_name == NULL)
6678 return;
6679
6680 guicolor = GUI_GET_COLOR(color_name);
6681 if (guicolor == INVALCOLOR)
6682 {
6683 semsg(_(e_cannot_allocate_color_str), color_name);
6684 return;
6685 }
6686
6687 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6688 }
6689
6690 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006691}
6692#endif
6693
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006694/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006695 * "term_setapi(buf, api)" function
6696 */
6697 void
6698f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6699{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006700 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006701 term_T *term;
6702 char_u *api;
6703
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006704 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006705 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006706 || check_for_string_arg(argvars, 1) == FAIL))
6707 return;
6708
6709 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006710 if (buf == NULL)
6711 return;
6712 term = buf->b_term;
6713 vim_free(term->tl_api);
6714 api = tv_get_string_chk(&argvars[1]);
6715 if (api != NULL)
6716 term->tl_api = vim_strsave(api);
6717 else
6718 term->tl_api = NULL;
6719}
6720
6721/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006722 * "term_setrestore(buf, command)" function
6723 */
6724 void
6725f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6726{
6727#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006728 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006729 term_T *term;
6730 char_u *cmd;
6731
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006732 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006733 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006734 || check_for_string_arg(argvars, 1) == FAIL))
6735 return;
6736
6737 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006738 if (buf == NULL)
6739 return;
6740 term = buf->b_term;
6741 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006742 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006743 if (cmd != NULL)
6744 term->tl_command = vim_strsave(cmd);
6745 else
6746 term->tl_command = NULL;
6747#endif
6748}
6749
6750/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006751 * "term_setkill(buf, how)" function
6752 */
6753 void
6754f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6755{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006756 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006757 term_T *term;
6758 char_u *how;
6759
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006760 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006761 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006762 || check_for_string_arg(argvars, 1) == FAIL))
6763 return;
6764
6765 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006766 if (buf == NULL)
6767 return;
6768 term = buf->b_term;
6769 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006770 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006771 if (how != NULL)
6772 term->tl_kill = vim_strsave(how);
6773 else
6774 term->tl_kill = NULL;
6775}
6776
6777/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006778 * "term_start(command, options)" function
6779 */
6780 void
6781f_term_start(typval_T *argvars, typval_T *rettv)
6782{
6783 jobopt_T opt;
6784 buf_T *buf;
6785
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006786 if (in_vim9script()
6787 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6788 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6789 return;
6790
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006791 init_job_options(&opt);
6792 if (argvars[1].v_type != VAR_UNKNOWN
6793 && get_job_options(&argvars[1], &opt,
6794 JO_TIMEOUT_ALL + JO_STOPONEXIT
6795 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6796 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6797 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6798 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006799 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006800 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006801 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006802 return;
6803
Bram Moolenaar13568252018-03-16 20:46:58 +01006804 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006805
6806 if (buf != NULL && buf->b_term != NULL)
6807 rettv->vval.v_number = buf->b_fnum;
6808}
6809
6810/*
6811 * "term_wait" function
6812 */
6813 void
6814f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6815{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006816 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006817
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006818 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006819 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006820 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006821 return;
6822
6823 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006824 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006825 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006826 if (buf->b_term->tl_job == NULL)
6827 {
6828 ch_log(NULL, "term_wait(): no job to wait for");
6829 return;
6830 }
6831 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006832 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006833 return;
6834
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006835 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006836 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006837 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6838 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006839 // The job is dead, keep reading channel I/O until the channel is
6840 // closed. buf->b_term may become NULL if the terminal was closed while
6841 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006842 ch_log(NULL, "term_wait(): waiting for channel to close");
6843 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6844 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006845 term_flush_messages();
6846
Bram Moolenaard45aa552018-05-21 22:50:29 +02006847 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006848 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006849 // If the terminal is closed when the channel is closed the
6850 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006851 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006852 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6853 // came here from a close callback, only wait one time
6854 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006855 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006856
6857 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006858 }
6859 else
6860 {
6861 long wait = 10L;
6862
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006863 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006864
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006865 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006866 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006867 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006868 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006869
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006870 // Flushing messages on channels is hopefully sufficient.
6871 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006872 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006873 }
6874}
6875
6876/*
6877 * Called when a channel has sent all the lines to a terminal.
6878 * Send a CTRL-D to mark the end of the text.
6879 */
6880 void
6881term_send_eof(channel_T *ch)
6882{
6883 term_T *term;
6884
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006885 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006886 if (term->tl_job == ch->ch_job)
6887 {
6888 if (term->tl_eof_chars != NULL)
6889 {
6890 channel_send(ch, PART_IN, term->tl_eof_chars,
6891 (int)STRLEN(term->tl_eof_chars), NULL);
6892 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6893 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006894# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006895 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006896 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006897 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6898# endif
6899 }
6900}
6901
Bram Moolenaar113e1072019-01-20 15:30:40 +01006902#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006903 job_T *
6904term_getjob(term_T *term)
6905{
6906 return term != NULL ? term->tl_job : NULL;
6907}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006908#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006909
Bram Moolenaar4f974752019-02-17 17:44:42 +01006910# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006911
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006912///////////////////////////////////////
6913// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006914#ifdef PROTO
6915typedef int COORD;
6916typedef int DWORD;
6917typedef int HANDLE;
6918typedef int *DWORD_PTR;
6919typedef int HPCON;
6920typedef int HRESULT;
6921typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006922typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006923typedef int PSIZE_T;
6924typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006925typedef int BOOL;
6926# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006927#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006928
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006929HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6930HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6931HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006932BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6933BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6934void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006935
6936 static int
6937dyn_conpty_init(int verbose)
6938{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006939 static HMODULE hKerneldll = NULL;
6940 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006941 static struct
6942 {
6943 char *name;
6944 FARPROC *ptr;
6945 } conpty_entry[] =
6946 {
6947 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6948 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6949 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6950 {"InitializeProcThreadAttributeList",
6951 (FARPROC*)&pInitializeProcThreadAttributeList},
6952 {"UpdateProcThreadAttribute",
6953 (FARPROC*)&pUpdateProcThreadAttribute},
6954 {"DeleteProcThreadAttributeList",
6955 (FARPROC*)&pDeleteProcThreadAttributeList},
6956 {NULL, NULL}
6957 };
6958
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006959 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006960 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006961 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006962 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006963 return FAIL;
6964 }
6965
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006966 // No need to initialize twice.
6967 if (hKerneldll)
6968 return OK;
6969
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006970 hKerneldll = vimLoadLib("kernel32.dll");
6971 for (i = 0; conpty_entry[i].name != NULL
6972 && conpty_entry[i].ptr != NULL; ++i)
6973 {
6974 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6975 conpty_entry[i].name)) == NULL)
6976 {
6977 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006978 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006979 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006980 return FAIL;
6981 }
6982 }
6983
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006984 return OK;
6985}
6986
6987 static int
6988conpty_term_and_job_init(
6989 term_T *term,
6990 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006991 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006992 jobopt_T *opt,
6993 jobopt_T *orig_opt)
6994{
6995 WCHAR *cmd_wchar = NULL;
6996 WCHAR *cmd_wchar_copy = NULL;
6997 WCHAR *cwd_wchar = NULL;
6998 WCHAR *env_wchar = NULL;
6999 channel_T *channel = NULL;
7000 job_T *job = NULL;
7001 HANDLE jo = NULL;
7002 garray_T ga_cmd, ga_env;
7003 char_u *cmd = NULL;
7004 HRESULT hr;
7005 COORD consize;
7006 SIZE_T breq;
7007 PROCESS_INFORMATION proc_info;
7008 HANDLE i_theirs = NULL;
7009 HANDLE o_theirs = NULL;
7010 HANDLE i_ours = NULL;
7011 HANDLE o_ours = NULL;
7012
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007013 ga_init2(&ga_cmd, sizeof(char*), 20);
7014 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007015
7016 if (argvar->v_type == VAR_STRING)
7017 {
7018 cmd = argvar->vval.v_string;
7019 }
7020 else if (argvar->v_type == VAR_LIST)
7021 {
7022 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
7023 goto failed;
7024 cmd = ga_cmd.ga_data;
7025 }
7026 if (cmd == NULL || *cmd == NUL)
7027 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007028 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007029 goto failed;
7030 }
7031
7032 term->tl_arg0_cmd = vim_strsave(cmd);
7033
7034 cmd_wchar = enc_to_utf16(cmd, NULL);
7035
7036 if (cmd_wchar != NULL)
7037 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007038 // Request by CreateProcessW
7039 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007040 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007041 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
7042 }
7043
7044 ga_clear(&ga_cmd);
7045 if (cmd_wchar == NULL)
7046 goto failed;
7047 if (opt->jo_cwd != NULL)
7048 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
7049
7050 win32_build_env(opt->jo_env, &ga_env, TRUE);
7051 env_wchar = ga_env.ga_data;
7052
7053 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
7054 goto failed;
7055 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
7056 goto failed;
7057
7058 consize.X = term->tl_cols;
7059 consize.Y = term->tl_rows;
7060 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
7061 &term->tl_conpty);
7062 if (FAILED(hr))
7063 goto failed;
7064
7065 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
7066
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007067 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007068 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007069 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007070 if (!term->tl_siex.lpAttributeList)
7071 goto failed;
7072 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
7073 0, &breq))
7074 goto failed;
7075 if (!pUpdateProcThreadAttribute(
7076 term->tl_siex.lpAttributeList, 0,
7077 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
7078 sizeof(HPCON), NULL, NULL))
7079 goto failed;
7080
7081 channel = add_channel();
7082 if (channel == NULL)
7083 goto failed;
7084
7085 job = job_alloc();
7086 if (job == NULL)
7087 goto failed;
7088 if (argvar->v_type == VAR_STRING)
7089 {
7090 int argc;
7091
7092 build_argv_from_string(cmd, &job->jv_argv, &argc);
7093 }
7094 else
7095 {
7096 int argc;
7097
7098 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7099 }
7100
7101 if (opt->jo_set & JO_IN_BUF)
7102 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7103
7104 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
7105 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02007106 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007107 env_wchar, cwd_wchar,
7108 &term->tl_siex.StartupInfo, &proc_info))
7109 goto failed;
7110
7111 CloseHandle(i_theirs);
7112 CloseHandle(o_theirs);
7113
7114 channel_set_pipes(channel,
7115 (sock_T)i_ours,
7116 (sock_T)o_ours,
7117 (sock_T)o_ours);
7118
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007119 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007120 channel->ch_write_text_mode = TRUE;
7121
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007122 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007123 channel->ch_anonymous_pipe = TRUE;
7124
7125 jo = CreateJobObject(NULL, NULL);
7126 if (jo == NULL)
7127 goto failed;
7128
7129 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7130 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007131 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007132 CloseHandle(jo);
7133 jo = NULL;
7134 }
7135
7136 ResumeThread(proc_info.hThread);
7137 CloseHandle(proc_info.hThread);
7138
7139 vim_free(cmd_wchar);
7140 vim_free(cmd_wchar_copy);
7141 vim_free(cwd_wchar);
7142 vim_free(env_wchar);
7143
7144 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7145 goto failed;
7146
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007147#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007148 if (term_use_palette())
7149 {
7150 if (term->tl_palette != NULL)
7151 set_vterm_palette(term->tl_vterm, term->tl_palette);
7152 else
7153 init_vterm_ansi_colors(term->tl_vterm);
7154 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007155#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007156
7157 channel_set_job(channel, job, opt);
7158 job_set_options(job, opt);
7159
7160 job->jv_channel = channel;
7161 job->jv_proc_info = proc_info;
7162 job->jv_job_object = jo;
7163 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007164 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007165 ++job->jv_refcount;
7166 term->tl_job = job;
7167
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007168 // Redirecting stdout and stderr doesn't work at the job level. Instead
7169 // open the file here and handle it in. opt->jo_io was changed in
7170 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007171 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7172 {
7173 char_u *fname = opt->jo_io_name[PART_OUT];
7174
7175 ch_log(channel, "Opening output file %s", fname);
7176 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7177 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007178 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007179 }
7180
7181 return OK;
7182
7183failed:
7184 ga_clear(&ga_cmd);
7185 ga_clear(&ga_env);
7186 vim_free(cmd_wchar);
7187 vim_free(cmd_wchar_copy);
7188 vim_free(cwd_wchar);
7189 if (channel != NULL)
7190 channel_clear(channel);
7191 if (job != NULL)
7192 {
7193 job->jv_channel = NULL;
7194 job_cleanup(job);
7195 }
7196 term->tl_job = NULL;
7197 if (jo != NULL)
7198 CloseHandle(jo);
7199
7200 if (term->tl_siex.lpAttributeList != NULL)
7201 {
7202 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7203 vim_free(term->tl_siex.lpAttributeList);
7204 }
7205 term->tl_siex.lpAttributeList = NULL;
7206 if (o_theirs != NULL)
7207 CloseHandle(o_theirs);
7208 if (o_ours != NULL)
7209 CloseHandle(o_ours);
7210 if (i_ours != NULL)
7211 CloseHandle(i_ours);
7212 if (i_theirs != NULL)
7213 CloseHandle(i_theirs);
7214 if (term->tl_conpty != NULL)
7215 pClosePseudoConsole(term->tl_conpty);
7216 term->tl_conpty = NULL;
7217 return FAIL;
7218}
7219
7220 static void
7221conpty_term_report_winsize(term_T *term, int rows, int cols)
7222{
7223 COORD consize;
7224
7225 consize.X = cols;
7226 consize.Y = rows;
7227 pResizePseudoConsole(term->tl_conpty, consize);
7228}
7229
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007230 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007231term_free_conpty(term_T *term)
7232{
7233 if (term->tl_siex.lpAttributeList != NULL)
7234 {
7235 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7236 vim_free(term->tl_siex.lpAttributeList);
7237 }
7238 term->tl_siex.lpAttributeList = NULL;
7239 if (term->tl_conpty != NULL)
7240 pClosePseudoConsole(term->tl_conpty);
7241 term->tl_conpty = NULL;
7242}
7243
7244 int
7245use_conpty(void)
7246{
7247 return has_conpty;
7248}
7249
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007250# ifndef PROTO
7251
7252#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7253#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007254#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007255
7256void* (*winpty_config_new)(UINT64, void*);
7257void* (*winpty_open)(void*, void*);
7258void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7259BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7260void (*winpty_config_set_mouse_mode)(void*, int);
7261void (*winpty_config_set_initial_size)(void*, int, int);
7262LPCWSTR (*winpty_conin_name)(void*);
7263LPCWSTR (*winpty_conout_name)(void*);
7264LPCWSTR (*winpty_conerr_name)(void*);
7265void (*winpty_free)(void*);
7266void (*winpty_config_free)(void*);
7267void (*winpty_spawn_config_free)(void*);
7268void (*winpty_error_free)(void*);
7269LPCWSTR (*winpty_error_msg)(void*);
7270BOOL (*winpty_set_size)(void*, int, int, void*);
7271HANDLE (*winpty_agent_process)(void*);
7272
7273#define WINPTY_DLL "winpty.dll"
7274
7275static HINSTANCE hWinPtyDLL = NULL;
7276# endif
7277
7278 static int
7279dyn_winpty_init(int verbose)
7280{
7281 int i;
7282 static struct
7283 {
7284 char *name;
7285 FARPROC *ptr;
7286 } winpty_entry[] =
7287 {
7288 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7289 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7290 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7291 {"winpty_config_set_mouse_mode",
7292 (FARPROC*)&winpty_config_set_mouse_mode},
7293 {"winpty_config_set_initial_size",
7294 (FARPROC*)&winpty_config_set_initial_size},
7295 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7296 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7297 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7298 {"winpty_free", (FARPROC*)&winpty_free},
7299 {"winpty_open", (FARPROC*)&winpty_open},
7300 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7301 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7302 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7303 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7304 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7305 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7306 {NULL, NULL}
7307 };
7308
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007309 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007310 if (hWinPtyDLL)
7311 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007312 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7313 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007314 if (*p_winptydll != NUL)
7315 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7316 if (!hWinPtyDLL)
7317 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7318 if (!hWinPtyDLL)
7319 {
7320 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007321 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007322 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7323 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007324 return FAIL;
7325 }
7326 for (i = 0; winpty_entry[i].name != NULL
7327 && winpty_entry[i].ptr != NULL; ++i)
7328 {
7329 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7330 winpty_entry[i].name)) == NULL)
7331 {
7332 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007333 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007334 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007335 return FAIL;
7336 }
7337 }
7338
7339 return OK;
7340}
7341
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007342 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007343winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007344 term_T *term,
7345 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007346 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007347 jobopt_T *opt,
7348 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007349{
7350 WCHAR *cmd_wchar = NULL;
7351 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007352 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007353 channel_T *channel = NULL;
7354 job_T *job = NULL;
7355 DWORD error;
7356 HANDLE jo = NULL;
7357 HANDLE child_process_handle;
7358 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007359 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007360 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007361 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007362 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007363
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007364 ga_init2(&ga_cmd, sizeof(char*), 20);
7365 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007366
7367 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007368 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007369 cmd = argvar->vval.v_string;
7370 }
7371 else if (argvar->v_type == VAR_LIST)
7372 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007373 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007374 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007375 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007376 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007377 if (cmd == NULL || *cmd == NUL)
7378 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007379 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007380 goto failed;
7381 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007382
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007383 term->tl_arg0_cmd = vim_strsave(cmd);
7384
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007385 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007386 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007387 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007388 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007389 if (opt->jo_cwd != NULL)
7390 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007391
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007392 win32_build_env(opt->jo_env, &ga_env, TRUE);
7393 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007394
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007395 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7396 if (term->tl_winpty_config == NULL)
7397 goto failed;
7398
7399 winpty_config_set_mouse_mode(term->tl_winpty_config,
7400 WINPTY_MOUSE_MODE_FORCE);
7401 winpty_config_set_initial_size(term->tl_winpty_config,
7402 term->tl_cols, term->tl_rows);
7403 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7404 if (term->tl_winpty == NULL)
7405 goto failed;
7406
7407 spawn_config = winpty_spawn_config_new(
7408 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7409 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7410 NULL,
7411 cmd_wchar,
7412 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007413 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007414 &winpty_err);
7415 if (spawn_config == NULL)
7416 goto failed;
7417
7418 channel = add_channel();
7419 if (channel == NULL)
7420 goto failed;
7421
7422 job = job_alloc();
7423 if (job == NULL)
7424 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007425 if (argvar->v_type == VAR_STRING)
7426 {
7427 int argc;
7428
7429 build_argv_from_string(cmd, &job->jv_argv, &argc);
7430 }
7431 else
7432 {
7433 int argc;
7434
7435 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7436 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007437
7438 if (opt->jo_set & JO_IN_BUF)
7439 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7440
7441 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7442 &child_thread_handle, &error, &winpty_err))
7443 goto failed;
7444
7445 channel_set_pipes(channel,
7446 (sock_T)CreateFileW(
7447 winpty_conin_name(term->tl_winpty),
7448 GENERIC_WRITE, 0, NULL,
7449 OPEN_EXISTING, 0, NULL),
7450 (sock_T)CreateFileW(
7451 winpty_conout_name(term->tl_winpty),
7452 GENERIC_READ, 0, NULL,
7453 OPEN_EXISTING, 0, NULL),
7454 (sock_T)CreateFileW(
7455 winpty_conerr_name(term->tl_winpty),
7456 GENERIC_READ, 0, NULL,
7457 OPEN_EXISTING, 0, NULL));
7458
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007459 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007460 channel->ch_write_text_mode = TRUE;
7461
7462 jo = CreateJobObject(NULL, NULL);
7463 if (jo == NULL)
7464 goto failed;
7465
7466 if (!AssignProcessToJobObject(jo, child_process_handle))
7467 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007468 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007469 CloseHandle(jo);
7470 jo = NULL;
7471 }
7472
7473 winpty_spawn_config_free(spawn_config);
7474 vim_free(cmd_wchar);
7475 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007476 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007477
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007478 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7479 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007480
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007481#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007482 if (term_use_palette())
7483 {
7484 if (term->tl_palette != NULL)
7485 set_vterm_palette(term->tl_vterm, term->tl_palette);
7486 else
7487 init_vterm_ansi_colors(term->tl_vterm);
7488 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007489#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007490
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007491 channel_set_job(channel, job, opt);
7492 job_set_options(job, opt);
7493
7494 job->jv_channel = channel;
7495 job->jv_proc_info.hProcess = child_process_handle;
7496 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7497 job->jv_job_object = jo;
7498 job->jv_status = JOB_STARTED;
7499 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007500 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007501 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007502 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007503 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007504 ++job->jv_refcount;
7505 term->tl_job = job;
7506
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007507 // Redirecting stdout and stderr doesn't work at the job level. Instead
7508 // open the file here and handle it in. opt->jo_io was changed in
7509 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007510 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7511 {
7512 char_u *fname = opt->jo_io_name[PART_OUT];
7513
7514 ch_log(channel, "Opening output file %s", fname);
7515 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7516 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007517 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007518 }
7519
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007520 return OK;
7521
7522failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007523 ga_clear(&ga_cmd);
7524 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007525 vim_free(cmd_wchar);
7526 vim_free(cwd_wchar);
7527 if (spawn_config != NULL)
7528 winpty_spawn_config_free(spawn_config);
7529 if (channel != NULL)
7530 channel_clear(channel);
7531 if (job != NULL)
7532 {
7533 job->jv_channel = NULL;
7534 job_cleanup(job);
7535 }
7536 term->tl_job = NULL;
7537 if (jo != NULL)
7538 CloseHandle(jo);
7539 if (term->tl_winpty != NULL)
7540 winpty_free(term->tl_winpty);
7541 term->tl_winpty = NULL;
7542 if (term->tl_winpty_config != NULL)
7543 winpty_config_free(term->tl_winpty_config);
7544 term->tl_winpty_config = NULL;
7545 if (winpty_err != NULL)
7546 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007547 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007548 (short_u *)winpty_error_msg(winpty_err), NULL);
7549
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007550 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007551 winpty_error_free(winpty_err);
7552 }
7553 return FAIL;
7554}
7555
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007556/*
7557 * Create a new terminal of "rows" by "cols" cells.
7558 * Store a reference in "term".
7559 * Return OK or FAIL.
7560 */
7561 static int
7562term_and_job_init(
7563 term_T *term,
7564 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007565 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007566 jobopt_T *opt,
7567 jobopt_T *orig_opt)
7568{
7569 int use_winpty = FALSE;
7570 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007571 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007572
7573 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7574 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7575
7576 if (!has_winpty && !has_conpty)
7577 // If neither is available give the errors for winpty, since when
7578 // conpty is not available it can't be installed either.
7579 return dyn_winpty_init(TRUE);
7580
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007581 if (opt->jo_tty_type != NUL)
7582 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007583
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007584 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007585 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007586 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007587 use_conpty = TRUE;
7588 else if (has_winpty)
7589 use_winpty = TRUE;
7590 // else: error
7591 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007592 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007593 {
7594 if (has_winpty)
7595 use_winpty = TRUE;
7596 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007597 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007598 {
7599 if (has_conpty)
7600 use_conpty = TRUE;
7601 else
7602 return dyn_conpty_init(TRUE);
7603 }
7604
7605 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007606 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007607
7608 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007609 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007610
7611 // error
7612 return dyn_winpty_init(TRUE);
7613}
7614
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007615 static int
7616create_pty_only(term_T *term, jobopt_T *options)
7617{
7618 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7619 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7620 char in_name[80], out_name[80];
7621 channel_T *channel = NULL;
7622
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007623 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7624 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007625
7626 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7627 GetCurrentProcessId(),
7628 curbuf->b_fnum);
7629 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7630 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7631 PIPE_UNLIMITED_INSTANCES,
7632 0, 0, NMPWAIT_NOWAIT, NULL);
7633 if (hPipeIn == INVALID_HANDLE_VALUE)
7634 goto failed;
7635
7636 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7637 GetCurrentProcessId(),
7638 curbuf->b_fnum);
7639 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7640 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7641 PIPE_UNLIMITED_INSTANCES,
7642 0, 0, 0, NULL);
7643 if (hPipeOut == INVALID_HANDLE_VALUE)
7644 goto failed;
7645
7646 ConnectNamedPipe(hPipeIn, NULL);
7647 ConnectNamedPipe(hPipeOut, NULL);
7648
7649 term->tl_job = job_alloc();
7650 if (term->tl_job == NULL)
7651 goto failed;
7652 ++term->tl_job->jv_refcount;
7653
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007654 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007655 term->tl_job->jv_status = JOB_FINISHED;
7656
7657 channel = add_channel();
7658 if (channel == NULL)
7659 goto failed;
7660 term->tl_job->jv_channel = channel;
7661 channel->ch_keep_open = TRUE;
7662 channel->ch_named_pipe = TRUE;
7663
7664 channel_set_pipes(channel,
7665 (sock_T)hPipeIn,
7666 (sock_T)hPipeOut,
7667 (sock_T)hPipeOut);
7668 channel_set_job(channel, term->tl_job, options);
7669 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7670 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7671
7672 return OK;
7673
7674failed:
7675 if (hPipeIn != NULL)
7676 CloseHandle(hPipeIn);
7677 if (hPipeOut != NULL)
7678 CloseHandle(hPipeOut);
7679 return FAIL;
7680}
7681
7682/*
7683 * Free the terminal emulator part of "term".
7684 */
7685 static void
7686term_free_vterm(term_T *term)
7687{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007688 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007689 if (term->tl_winpty != NULL)
7690 winpty_free(term->tl_winpty);
7691 term->tl_winpty = NULL;
7692 if (term->tl_winpty_config != NULL)
7693 winpty_config_free(term->tl_winpty_config);
7694 term->tl_winpty_config = NULL;
7695 if (term->tl_vterm != NULL)
7696 vterm_free(term->tl_vterm);
7697 term->tl_vterm = NULL;
7698}
7699
7700/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007701 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007702 */
7703 static void
7704term_report_winsize(term_T *term, int rows, int cols)
7705{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007706 if (term->tl_conpty)
7707 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007708 if (term->tl_winpty)
7709 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7710}
7711
7712 int
7713terminal_enabled(void)
7714{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007715 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007716}
7717
7718# else
7719
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007720///////////////////////////////////////
7721// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007722
7723/*
7724 * Create a new terminal of "rows" by "cols" cells.
7725 * Start job for "cmd".
7726 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007727 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007728 * Return OK or FAIL.
7729 */
7730 static int
7731term_and_job_init(
7732 term_T *term,
7733 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007734 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007735 jobopt_T *opt,
7736 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007737{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007738 term->tl_arg0_cmd = NULL;
7739
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007740 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7741 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007742
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007743#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007744 if (term_use_palette())
7745 {
7746 if (term->tl_palette != NULL)
7747 set_vterm_palette(term->tl_vterm, term->tl_palette);
7748 else
7749 init_vterm_ansi_colors(term->tl_vterm);
7750 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007751#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007752
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007753 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007754 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007755 if (term->tl_job != NULL)
7756 ++term->tl_job->jv_refcount;
7757
7758 return term->tl_job != NULL
7759 && term->tl_job->jv_channel != NULL
7760 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7761}
7762
7763 static int
7764create_pty_only(term_T *term, jobopt_T *opt)
7765{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007766 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7767 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007768
7769 term->tl_job = job_alloc();
7770 if (term->tl_job == NULL)
7771 return FAIL;
7772 ++term->tl_job->jv_refcount;
7773
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007774 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007775 term->tl_job->jv_status = JOB_FINISHED;
7776
7777 return mch_create_pty_channel(term->tl_job, opt);
7778}
7779
7780/*
7781 * Free the terminal emulator part of "term".
7782 */
7783 static void
7784term_free_vterm(term_T *term)
7785{
7786 if (term->tl_vterm != NULL)
7787 vterm_free(term->tl_vterm);
7788 term->tl_vterm = NULL;
7789}
7790
7791/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007792 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007793 */
7794 static void
7795term_report_winsize(term_T *term, int rows, int cols)
7796{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007797 // Use an ioctl() to report the new window size to the job.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007798 if (term->tl_job == NULL || term->tl_job->jv_channel == NULL)
7799 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007800
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007801 int fd = -1;
7802 int part;
7803
7804 for (part = PART_OUT; part < PART_COUNT; ++part)
7805 {
7806 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
7807 if (mch_isatty(fd))
7808 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007809 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007810 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7811 mch_signal_job(term->tl_job, (char_u *)"winch");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007812}
7813
7814# endif
7815
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007816#endif // FEAT_TERMINAL