blob: 1fc0ef96881f9516fe67b6b7e46efea94b3f8d83 [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
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200541 int cmod_split_modified = FALSE;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100542 if (vertical)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200543 {
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200544 if (!(cmdmod.cmod_split & WSP_VERT))
545 cmod_split_modified = TRUE;
Bram Moolenaare1004402020-10-24 20:49:43 +0200546 cmdmod.cmod_split |= WSP_VERT;
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200547 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200548 ex_splitview(&split_ea);
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200549 if (cmod_split_modified)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200550 cmdmod.cmod_split &= ~WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200551 if (curwin == old_curwin)
552 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100553 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200554 vim_free(term);
555 return NULL;
556 }
557 }
558 term->tl_buffer = curbuf;
559 curbuf->b_term = term;
560
561 if (!opt->jo_hidden)
562 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100563 // Only one size was taken care of with :new, do the other one. With
564 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100565 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200566 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100567 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 win_setwidth(opt->jo_term_cols);
569 }
570
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100571 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200572 term->tl_next = first_term;
573 first_term = term;
574
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100575 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
576
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200577 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100578 {
579 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200580 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100581 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100582 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100583 {
584 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100585 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100586 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200587 else
588 {
589 int i;
590 size_t len;
591 char_u *cmd, *p;
592
593 if (argvar->v_type == VAR_STRING)
594 {
595 cmd = argvar->vval.v_string;
596 if (cmd == NULL)
597 cmd = (char_u *)"";
598 else if (STRCMP(cmd, "NONE") == 0)
599 cmd = (char_u *)"pty";
600 }
601 else if (argvar->v_type != VAR_LIST
602 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100603 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100604 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200605 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
606 cmd = (char_u*)"";
607
608 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200609 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200610
611 for (i = 0; p != NULL; ++i)
612 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100613 // Prepend a ! to the command name to avoid the buffer name equals
614 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200615 if (i == 0)
616 vim_snprintf((char *)p, len, "!%s", cmd);
617 else
618 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
619 if (buflist_findname(p) == NULL)
620 {
621 vim_free(curbuf->b_ffname);
622 curbuf->b_ffname = p;
623 break;
624 }
625 }
626 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100627 vim_free(curbuf->b_sfname);
628 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200629 curbuf->b_fname = curbuf->b_ffname;
630
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100631 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
632
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200633 if (opt->jo_term_opencmd != NULL)
634 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
635
636 if (opt->jo_eof_chars != NULL)
637 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
638
639 set_string_option_direct((char_u *)"buftype", -1,
640 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200641 // Avoid that 'buftype' is reset when this buffer is entered.
642 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200643
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100644 // Mark the buffer as not modifiable. It can only be made modifiable after
645 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200646 curbuf->b_p_ma = FALSE;
647
Bram Moolenaarb936b792020-09-04 18:34:09 +0200648 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100649#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200650 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
651#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200652 setup_job_options(opt, term->tl_rows, term->tl_cols);
653
Bram Moolenaar13568252018-03-16 20:46:58 +0100654 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100655 return curbuf;
656
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100657#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100658 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100659 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100660 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100661 else if (argvar->v_type == VAR_STRING)
662 {
663 char_u *cmd = argvar->vval.v_string;
664
665 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
666 term->tl_command = vim_strsave(cmd);
667 }
668 else if (argvar->v_type == VAR_LIST
669 && argvar->vval.v_list != NULL
670 && argvar->vval.v_list->lv_len > 0)
671 {
672 garray_T ga;
673 listitem_T *item;
674
675 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200676 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100677 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100678 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100679 char_u *p;
680
681 if (s == NULL)
682 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100683 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100684 if (p == NULL)
685 break;
686 ga_concat(&ga, p);
687 vim_free(p);
688 ga_append(&ga, ' ');
689 }
690 if (item == NULL)
691 {
692 ga_append(&ga, NUL);
693 term->tl_command = ga.ga_data;
694 }
695 else
696 ga_clear(&ga);
697 }
698#endif
699
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100700 if (opt->jo_term_kill != NULL)
701 {
702 char_u *p = skiptowhite(opt->jo_term_kill);
703
704 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
705 }
706
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200707 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100708 {
709 char_u *p = skiptowhite(opt->jo_term_api);
710
711 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
712 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200713 else
714 term->tl_api = vim_strsave((char_u *)"Tapi_");
715
Bram Moolenaar83d47902020-03-26 20:34:00 +0100716 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
717 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
718
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100719#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100720 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
721 if (opt->jo_set2 & JO2_ANSI_COLORS)
722 {
723 term->tl_palette = ALLOC_MULT(long_u, 16);
724 if (term->tl_palette == NULL)
725 {
726 vim_free(term);
727 return NULL;
728 }
729 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
730 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100731#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100732
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100733 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100734 if (argv == NULL
735 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200736 && argvar->vval.v_string != NULL
737 && STRCMP(argvar->vval.v_string, "NONE") == 0)
738 res = create_pty_only(term, opt);
739 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200740 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200741
742 newbuf = curbuf;
743 if (res == OK)
744 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100745 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200746 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
747 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100748#ifdef FEAT_GUI
749 if (term->tl_system)
750 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100751 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100752 term->tl_toprow = msg_row + 1;
753 term->tl_dirty_row_end = 0;
754 }
755#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200756
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100757 // Make sure we don't get stuck on sending keys to the job, it leads to
758 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200759 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
760
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200761 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200762 {
763 --curbuf->b_nwindows;
764 curbuf = old_curbuf;
765 curwin->w_buffer = curbuf;
766 ++curbuf->b_nwindows;
767 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000768 else if (vgetc_busy
769#ifdef FEAT_TIMERS
770 || timer_busy
771#endif
772 || input_busy)
773 {
774 char_u ignore[4];
775
776 // When waiting for input need to return and possibly end up in
777 // terminal_loop() instead.
778 ignore[0] = K_SPECIAL;
779 ignore[1] = KS_EXTRA;
780 ignore[2] = KE_IGNORE;
781 ignore[3] = NUL;
782 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
783 typebuf_was_filled = TRUE;
784 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200785 }
786 else
787 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100788 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200789 return NULL;
790 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100791
Bram Moolenaar13568252018-03-16 20:46:58 +0100792 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200793 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
794 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200795 return newbuf;
796}
797
798/*
799 * ":terminal": open a terminal window and execute a job in it.
800 */
801 void
802ex_terminal(exarg_T *eap)
803{
804 typval_T argvar[2];
805 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100806 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200807 char_u *cmd;
808 char_u *tofree = NULL;
809
810 init_job_options(&opt);
811
812 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100813 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200814 {
815 char_u *p, *ep;
816
817 cmd += 2;
818 p = skiptowhite(cmd);
819 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200820 if (ep != NULL)
821 {
822 if (ep < p)
823 p = ep;
824 else
825 ep = NULL;
826 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200827
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200828 // Note: Keep this in sync with get_terminalopt_name.
829
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200830# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
831 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
832 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200833 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200834 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100835 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200836 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200837 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200838 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200839 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200840 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200841 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200842 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100843 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100844 else if (OPTARG_HAS("shell"))
845 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200846 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100847 {
848 opt.jo_set2 |= JO2_TERM_KILL;
849 opt.jo_term_kill = ep + 1;
850 p = skiptowhite(cmd);
851 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200852 else if (OPTARG_HAS("api"))
853 {
854 opt.jo_set2 |= JO2_TERM_API;
855 if (ep != NULL)
856 {
857 opt.jo_term_api = ep + 1;
858 p = skiptowhite(cmd);
859 }
860 else
861 opt.jo_term_api = NULL;
862 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100863 else if (OPTARG_HAS("rows") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200864 {
865 opt.jo_set2 |= JO2_TERM_ROWS;
866 opt.jo_term_rows = atoi((char *)ep + 1);
867 p = skiptowhite(cmd);
868 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100869 else if (OPTARG_HAS("cols") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200870 {
871 opt.jo_set2 |= JO2_TERM_COLS;
872 opt.jo_term_cols = atoi((char *)ep + 1);
873 p = skiptowhite(cmd);
874 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200875 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200876 {
877 char_u *buf = NULL;
878 char_u *keys;
879
Bram Moolenaar21109272020-01-30 16:27:20 +0100880 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200881 p = skiptowhite(cmd);
882 *p = NUL;
zeertzjq7e0bae02023-08-11 23:15:38 +0200883 keys = replace_termcodes(ep + 1, &buf, 0,
Bram Moolenaar459fd782019-10-13 16:43:39 +0200884 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200885 opt.jo_set2 |= JO2_EOF_CHARS;
886 opt.jo_eof_chars = vim_strsave(keys);
887 vim_free(buf);
888 *p = ' ';
889 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100890#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100891 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
892 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100893 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100894 int tty_type = NUL;
895
896 p = skiptowhite(cmd);
897 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
898 tty_type = 'w';
899 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
900 tty_type = 'c';
901 else
902 {
Bram Moolenaar50809a42023-05-20 16:39:07 +0100903 semsg(_(e_invalid_value_for_argument_str), "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100904 goto theend;
905 }
906 opt.jo_set2 |= JO2_TTY_TYPE;
907 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100908 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100909#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200910 else
911 {
912 if (*p)
913 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000914 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100915 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200916 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200917# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200918 cmd = skipwhite(p);
919 }
920 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100921 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100922 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200923 tofree = cmd = vim_strsave(p_sh);
924
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100925 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100926 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200927 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100928 }
929
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200930 if (eap->addr_count > 0)
931 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100932 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200933 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
934 opt.jo_io[PART_IN] = JIO_BUFFER;
935 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
936 opt.jo_in_top = eap->line1;
937 opt.jo_in_bot = eap->line2;
938 }
939
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100940 if (opt_shell && tofree == NULL)
941 {
942#ifdef UNIX
943 char **argv = NULL;
944 char_u *tofree1 = NULL;
945 char_u *tofree2 = NULL;
946
947 // :term ++shell command
948 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
949 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100950 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100951 vim_free(tofree1);
952 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100953 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100954#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100955# ifdef MSWIN
956 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
957 char_u *newcmd;
958
959 newcmd = alloc(cmdlen);
960 if (newcmd == NULL)
961 goto theend;
962 tofree = newcmd;
963 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
964 cmd = newcmd;
965# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000966 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100967 goto theend;
968# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100969#endif
970 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100971 argvar[0].v_type = VAR_STRING;
972 argvar[0].vval.v_string = cmd;
973 argvar[1].v_type = VAR_UNKNOWN;
974 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100975
976theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100977 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200978 vim_free(opt.jo_eof_chars);
979}
980
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200981 static char_u *
982get_terminalopt_name(expand_T *xp UNUSED, int idx)
983{
984 // Note: Keep this in sync with ex_terminal.
985 static char *(p_termopt_values[]) =
986 {
987 "close",
988 "noclose",
989 "open",
990 "curwin",
991 "hidden",
992 "norestore",
993 "shell",
994 "kill=",
995 "rows=",
996 "cols=",
997 "eof=",
998 "type=",
999 "api=",
1000 };
1001
1002 if (idx < (int)ARRAY_LENGTH(p_termopt_values))
1003 return (char_u*)p_termopt_values[idx];
1004 return NULL;
1005}
1006
1007 static char_u *
1008get_termkill_name(expand_T *xp UNUSED, int idx)
1009{
1010 // These are platform-specific values used for job_stop(). They are defined
1011 // in each platform's mch_signal_job(). Just use a unified auto-complete
1012 // list for simplicity.
1013 static char *(p_termkill_values[]) =
1014 {
1015 "term",
1016 "hup",
1017 "quit",
1018 "int",
1019 "kill",
1020 "winch",
1021 };
1022
1023 if (idx < (int)ARRAY_LENGTH(p_termkill_values))
1024 return (char_u*)p_termkill_values[idx];
1025 return NULL;
1026}
1027
1028/*
1029 * Command-line expansion for :terminal [options]
1030 */
1031 int
1032expand_terminal_opt(
1033 char_u *pat,
1034 expand_T *xp,
1035 regmatch_T *rmp,
1036 char_u ***matches,
1037 int *numMatches)
1038{
1039 if (xp->xp_pattern > xp->xp_line && *(xp->xp_pattern-1) == '=')
1040 {
1041 char_u *(*cb)(expand_T *, int) = NULL;
1042
1043 char_u *name_end = xp->xp_pattern - 1;
1044 if (name_end - xp->xp_line >= 4
1045 && STRNCMP(name_end - 4, "kill", 4) == 0)
1046 cb = get_termkill_name;
1047
1048 if (cb != NULL)
1049 {
1050 return ExpandGeneric(
1051 pat,
1052 xp,
1053 rmp,
1054 matches,
1055 numMatches,
1056 cb,
1057 FALSE);
1058 }
1059 return FAIL;
1060 }
1061 return ExpandGeneric(
1062 pat,
1063 xp,
1064 rmp,
1065 matches,
1066 numMatches,
1067 get_terminalopt_name,
1068 FALSE);
1069}
1070
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001071#if defined(FEAT_SESSION) || defined(PROTO)
1072/*
1073 * Write a :terminal command to the session file to restore the terminal in
1074 * window "wp".
1075 * Return FAIL if writing fails.
1076 */
1077 int
Bram Moolenaar0e655112020-09-11 20:36:36 +02001078term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001079{
Bram Moolenaar0e655112020-09-11 20:36:36 +02001080 const int bufnr = wp->w_buffer->b_fnum;
1081 term_T *term = wp->w_buffer->b_term;
1082
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001083 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001084 {
1085 // There are multiple views into this terminal buffer. We don't want to
1086 // create the terminal multiple times. If it's the first time, create,
1087 // otherwise link to the first buffer.
1088 char id_as_str[NUMBUFLEN];
1089 hashitem_T *entry;
1090
1091 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
1092
1093 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
1094 if (!HASHITEM_EMPTY(entry))
1095 {
1096 // we've already opened this terminal buffer
1097 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
1098 return FAIL;
1099 return put_eol(fd);
1100 }
1101 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001102
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001103 // Create the terminal and run the command. This is not without
1104 // risk, but let's assume the user only creates a session when this
1105 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001106 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1107 term->tl_cols, term->tl_rows) < 0)
1108 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001109#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001110 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1111 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001112#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001113 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1114 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001115 if (put_eol(fd) != OK)
1116 return FAIL;
1117
1118 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1119 return FAIL;
1120
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001121 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001122 {
1123 char *hash_key = alloc(NUMBUFLEN);
1124
1125 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00001126 hash_add(terminal_bufs, (char_u *)hash_key, "terminal session");
Bram Moolenaar0e655112020-09-11 20:36:36 +02001127 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001128
1129 return put_eol(fd);
1130}
1131
1132/*
1133 * Return TRUE if "buf" has a terminal that should be restored.
1134 */
1135 int
1136term_should_restore(buf_T *buf)
1137{
1138 term_T *term = buf->b_term;
1139
1140 return term != NULL && (term->tl_command == NULL
1141 || STRCMP(term->tl_command, "NONE") != 0);
1142}
1143#endif
1144
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001145/*
1146 * Free the scrollback buffer for "term".
1147 */
1148 static void
1149free_scrollback(term_T *term)
1150{
1151 int i;
1152
1153 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1154 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1155 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001156 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1157 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1158 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001159}
1160
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001161
1162// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001163static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001164
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001165/*
1166 * Free a terminal and everything it refers to.
1167 * Kills the job if there is one.
1168 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001169 * The actual terminal structure is freed later in free_unused_terminals(),
1170 * because callbacks may wipe out a buffer while the terminal is still
1171 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001172 */
1173 void
1174free_terminal(buf_T *buf)
1175{
1176 term_T *term = buf->b_term;
1177 term_T *tp;
1178
1179 if (term == NULL)
1180 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001181
1182 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001183 if (first_term == term)
1184 first_term = term->tl_next;
1185 else
1186 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1187 if (tp->tl_next == term)
1188 {
1189 tp->tl_next = term->tl_next;
1190 break;
1191 }
1192
1193 if (term->tl_job != NULL)
1194 {
1195 if (term->tl_job->jv_status != JOB_ENDED
1196 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001197 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001198 job_stop(term->tl_job, NULL, "kill");
1199 job_unref(term->tl_job);
1200 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001201 term->tl_next = terminals_to_free;
1202 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001203
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001204 buf->b_term = NULL;
1205 if (in_terminal_loop == term)
1206 in_terminal_loop = NULL;
1207}
1208
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001209 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00001210free_unused_terminals(void)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001211{
1212 while (terminals_to_free != NULL)
1213 {
1214 term_T *term = terminals_to_free;
1215
1216 terminals_to_free = term->tl_next;
1217
1218 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001219 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001220
1221 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001222 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001223 vim_free(term->tl_title);
1224#ifdef FEAT_SESSION
1225 vim_free(term->tl_command);
1226#endif
1227 vim_free(term->tl_kill);
1228 vim_free(term->tl_status_text);
1229 vim_free(term->tl_opencmd);
1230 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001231 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001232#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001233 if (term->tl_out_fd != NULL)
1234 fclose(term->tl_out_fd);
1235#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001236 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001237 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001238 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001239 vim_free(term);
1240 }
1241}
1242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001243/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001244 * Get the part that is connected to the tty. Normally this is PART_IN, but
1245 * when writing buffer lines to the job it can be another. This makes it
1246 * possible to do "1,5term vim -".
1247 */
1248 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001249get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001250{
1251#ifdef UNIX
1252 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1253 int i;
1254
1255 for (i = 0; i < 3; ++i)
1256 {
1257 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1258
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001259 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001260 return parts[i];
1261 }
1262#endif
1263 return PART_IN;
1264}
1265
1266/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001267 * Read any vterm output and send it on the channel.
1268 */
1269 static void
1270term_forward_output(term_T *term)
1271{
1272 VTerm *vterm = term->tl_vterm;
1273 char buf[KEY_BUF_LEN];
1274 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1275
1276 if (curlen > 0)
1277 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1278 (char_u *)buf, (int)curlen, NULL);
1279}
1280
1281/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001282 * Write job output "msg[len]" to the vterm.
1283 */
1284 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001285term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001286{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001287 char_u *msg = msg_arg;
1288 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001289 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001290 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001291 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1292
1293 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1294 // the end.
1295 if (len > limit)
1296 {
1297 char_u *p = msg + len - limit;
1298
1299 p -= (*mb_head_off)(msg, p);
1300 len -= p - msg;
1301 msg = p;
1302 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001303
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001304 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001305
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001306 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001307 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001308 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001309
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001310 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001311 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1312}
1313
1314 static void
Bram Moolenaar58806c12023-04-29 14:26:02 +01001315position_cursor(win_T *wp, VTermPos *pos)
1316{
1317 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1318 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1319#ifdef FEAT_PROP_POPUP
1320 if (popup_is_popup(wp))
1321 {
1322 wp->w_wrow += popup_top_extra(wp);
1323 wp->w_wcol += popup_left_extra(wp);
1324 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
1325 }
1326 else
1327 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
1328#endif
1329 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1330}
1331
1332 static void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001333update_cursor(term_T *term, int redraw)
1334{
1335 if (term->tl_normal_mode)
1336 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001337#ifdef FEAT_GUI
1338 if (term->tl_system)
1339 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1340 term->tl_cursor_pos.col);
1341 else
1342#endif
Bram Moolenaar58806c12023-04-29 14:26:02 +01001343 if (!term_job_running(term))
1344 // avoid the cursor positioned below the last used line
Bram Moolenaar13568252018-03-16 20:46:58 +01001345 setcursor();
Bram Moolenaar58806c12023-04-29 14:26:02 +01001346 else
1347 {
1348 // do not use the window cursor position
1349 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1350 windgoto(W_WINROW(curwin) + curwin->w_wrow,
1351 curwin->w_wincol + curwin->w_wcol);
1352 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001353 if (redraw)
1354 {
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001355 aco_save_T aco;
1356
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001357 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1358 cursor_on();
1359 out_flush();
1360#ifdef FEAT_GUI
1361 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001362 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001363 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001364 gui_mch_flush();
1365 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001366#endif
Bram Moolenaar24fe33a2022-11-24 00:09:02 +00001367 // Make sure an invoked autocmd doesn't delete the buffer (and the
1368 // terminal) under our fingers.
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001369 ++term->tl_buffer->b_locked;
1370
1371 // save and restore curwin and curbuf, in case the autocmd changes them
1372 aucmd_prepbuf(&aco, curbuf);
1373 apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, FALSE, term->tl_buffer);
1374 aucmd_restbuf(&aco);
1375
1376 --term->tl_buffer->b_locked;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001377 }
1378}
1379
1380/*
1381 * Invoked when "msg" output from a job was received. Write it to the terminal
1382 * of "buffer".
1383 */
1384 void
1385write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1386{
1387 size_t len = STRLEN(msg);
1388 term_T *term = buffer->b_term;
1389
Bram Moolenaar4f974752019-02-17 17:44:42 +01001390#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001391 // Win32: Cannot redirect output of the job, intercept it here and write to
1392 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001393 if (term->tl_out_fd != NULL)
1394 {
1395 ch_log(channel, "Writing %d bytes to output file", (int)len);
1396 fwrite(msg, len, 1, term->tl_out_fd);
1397 return;
1398 }
1399#endif
1400
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001401 if (term->tl_vterm == NULL)
1402 {
1403 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1404 return;
1405 }
1406 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001407 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001408 term_write_job_output(term, msg, len);
1409
Bram Moolenaar13568252018-03-16 20:46:58 +01001410#ifdef FEAT_GUI
1411 if (term->tl_system)
1412 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001413 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001414 update_system_term(term);
1415 update_cursor(term, TRUE);
1416 }
1417 else
1418#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001419 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1420 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001421 if (!term->tl_normal_mode)
1422 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001423 // Don't use update_screen() when editing the command line, it gets
1424 // cleared.
1425 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001426 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001427 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001428 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001429 update_screen(UPD_VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001430 // update_screen() can be slow, check the terminal wasn't closed
1431 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001432 if (buffer == curbuf && curbuf->b_term != NULL)
1433 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001434 }
1435 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001436 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001437 }
1438}
1439
1440/*
1441 * Send a mouse position and click to the vterm
1442 */
1443 static int
1444term_send_mouse(VTerm *vterm, int button, int pressed)
1445{
1446 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001447 int row = mouse_row - W_WINROW(curwin);
1448 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001449
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001450#ifdef FEAT_PROP_POPUP
1451 if (popup_is_popup(curwin))
1452 {
1453 row -= popup_top_extra(curwin);
1454 col -= popup_left_extra(curwin);
1455 }
1456#endif
1457 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001458 if (button != 0)
1459 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001460 return TRUE;
1461}
1462
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001463static int enter_mouse_col = -1;
1464static int enter_mouse_row = -1;
1465
1466/*
1467 * Handle a mouse click, drag or release.
1468 * Return TRUE when a mouse event is sent to the terminal.
1469 */
1470 static int
1471term_mouse_click(VTerm *vterm, int key)
1472{
1473#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001474 // For modeless selection mouse drag and release events are ignored, unless
1475 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001476 static int ignore_drag_release = TRUE;
1477 VTermMouseState mouse_state;
1478
1479 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1480 if (mouse_state.flags == 0)
1481 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001482 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001483 switch (key)
1484 {
1485 case K_LEFTDRAG:
1486 case K_LEFTRELEASE:
1487 case K_RIGHTDRAG:
1488 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001489 // Ignore drag and release events when the button-down wasn't
1490 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001491 if (ignore_drag_release)
1492 {
1493 int save_mouse_col, save_mouse_row;
1494
1495 if (enter_mouse_col < 0)
1496 break;
1497
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001498 // mouse click in the window gave us focus, handle that
1499 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001500 save_mouse_col = mouse_col;
1501 save_mouse_row = mouse_row;
1502 mouse_col = enter_mouse_col;
1503 mouse_row = enter_mouse_row;
1504 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1505 mouse_col = save_mouse_col;
1506 mouse_row = save_mouse_row;
1507 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001508 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001509 case K_LEFTMOUSE:
1510 case K_RIGHTMOUSE:
1511 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1512 ignore_drag_release = TRUE;
1513 else
1514 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001515 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001516 if (clip_star.available)
1517 {
1518 int button, is_click, is_drag;
1519
1520 button = get_mouse_button(KEY2TERMCAP1(key),
1521 &is_click, &is_drag);
1522 if (mouse_model_popup() && button == MOUSE_LEFT
1523 && (mod_mask & MOD_MASK_SHIFT))
1524 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001525 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001526 button = MOUSE_RIGHT;
1527 mod_mask &= ~MOD_MASK_SHIFT;
1528 }
1529 clip_modeless(button, is_click, is_drag);
1530 }
1531 break;
1532
1533 case K_MIDDLEMOUSE:
1534 if (clip_star.available)
1535 insert_reg('*', TRUE);
1536 break;
1537 }
1538 enter_mouse_col = -1;
1539 return FALSE;
1540 }
1541#endif
1542 enter_mouse_col = -1;
1543
1544 switch (key)
1545 {
1546 case K_LEFTMOUSE:
1547 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1548 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1549 case K_LEFTRELEASE:
1550 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1551 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1552 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1553 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1554 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1555 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1556 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1557 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1558 }
1559 return TRUE;
1560}
1561
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001562/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001563 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1564 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001565 * Return the number of bytes in "buf".
1566 */
1567 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001568term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001569{
1570 VTerm *vterm = term->tl_vterm;
1571 VTermKey key = VTERM_KEY_NONE;
1572 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001573 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001574
1575 switch (c)
1576 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001577 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001578
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001579 // don't use VTERM_KEY_BACKSPACE, it always
1580 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001581 case K_BS: c = term_backspace_char; break;
1582
1583 case ESC: key = VTERM_KEY_ESCAPE; break;
1584 case K_DEL: key = VTERM_KEY_DEL; break;
1585 case K_DOWN: key = VTERM_KEY_DOWN; break;
1586 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1587 key = VTERM_KEY_DOWN; break;
1588 case K_END: key = VTERM_KEY_END; break;
1589 case K_S_END: mod = VTERM_MOD_SHIFT;
1590 key = VTERM_KEY_END; break;
1591 case K_C_END: mod = VTERM_MOD_CTRL;
1592 key = VTERM_KEY_END; break;
1593 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1594 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1595 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1596 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1597 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1598 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1599 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1600 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1601 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1602 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1603 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1604 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1605 case K_HOME: key = VTERM_KEY_HOME; break;
1606 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1607 key = VTERM_KEY_HOME; break;
1608 case K_C_HOME: mod = VTERM_MOD_CTRL;
1609 key = VTERM_KEY_HOME; break;
1610 case K_INS: key = VTERM_KEY_INS; break;
1611 case K_K0: key = VTERM_KEY_KP_0; break;
1612 case K_K1: key = VTERM_KEY_KP_1; break;
1613 case K_K2: key = VTERM_KEY_KP_2; break;
1614 case K_K3: key = VTERM_KEY_KP_3; break;
1615 case K_K4: key = VTERM_KEY_KP_4; break;
1616 case K_K5: key = VTERM_KEY_KP_5; break;
1617 case K_K6: key = VTERM_KEY_KP_6; break;
1618 case K_K7: key = VTERM_KEY_KP_7; break;
1619 case K_K8: key = VTERM_KEY_KP_8; break;
1620 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001621 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001622 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001623 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001624 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001625 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1626 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1628 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001629 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1630 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001631 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1632 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1633 case K_LEFT: key = VTERM_KEY_LEFT; break;
1634 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1635 key = VTERM_KEY_LEFT; break;
1636 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1637 key = VTERM_KEY_LEFT; break;
1638 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1639 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1640 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1641 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1642 key = VTERM_KEY_RIGHT; break;
1643 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1644 key = VTERM_KEY_RIGHT; break;
1645 case K_UP: key = VTERM_KEY_UP; break;
1646 case K_S_UP: mod = VTERM_MOD_SHIFT;
1647 key = VTERM_KEY_UP; break;
1648 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001649 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1650 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001651
Bram Moolenaara42ad572017-11-16 13:08:04 +01001652 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1653 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001654 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1655 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001656
1657 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001658 case K_LEFTMOUSE_NM:
1659 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001660 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001661 case K_LEFTRELEASE_NM:
1662 case K_MOUSEMOVE:
1663 case K_MIDDLEMOUSE:
1664 case K_MIDDLEDRAG:
1665 case K_MIDDLERELEASE:
1666 case K_RIGHTMOUSE:
1667 case K_RIGHTDRAG:
1668 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1669 return 0;
1670 other = TRUE;
1671 break;
1672
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001673 case K_X1MOUSE: /* TODO */ return 0;
1674 case K_X1DRAG: /* TODO */ return 0;
1675 case K_X1RELEASE: /* TODO */ return 0;
1676 case K_X2MOUSE: /* TODO */ return 0;
1677 case K_X2DRAG: /* TODO */ return 0;
1678 case K_X2RELEASE: /* TODO */ return 0;
1679
1680 case K_IGNORE: return 0;
1681 case K_NOP: return 0;
1682 case K_UNDO: return 0;
1683 case K_HELP: return 0;
1684 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1685 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1686 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1687 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1688 case K_SELECT: return 0;
1689#ifdef FEAT_GUI
1690 case K_VER_SCROLLBAR: return 0;
1691 case K_HOR_SCROLLBAR: return 0;
1692#endif
1693#ifdef FEAT_GUI_TABLINE
1694 case K_TABLINE: return 0;
1695 case K_TABMENU: return 0;
1696#endif
1697#ifdef FEAT_NETBEANS_INTG
1698 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1699#endif
1700#ifdef FEAT_DND
1701 case K_DROP: return 0;
1702#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001703 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001704 case K_PS: vterm_keyboard_start_paste(vterm);
1705 other = TRUE;
1706 break;
1707 case K_PE: vterm_keyboard_end_paste(vterm);
1708 other = TRUE;
1709 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001710 }
1711
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001712 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001713 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001714 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001715 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001716 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001717 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001718 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001719
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001720 // Ctrl-Shift-i may have the key "I" instead of "i", but for the kitty
1721 // keyboard protocol should use "i". Applies to all ascii letters.
1722 if (ASCII_ISUPPER(c)
Bram Moolenaarebed1b02022-11-24 14:05:19 +00001723 && vterm_is_kitty_keyboard(vterm)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001724 && mod == (VTERM_MOD_CTRL | VTERM_MOD_SHIFT))
1725 c = TOLOWER_ASC(c);
1726
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001727 /*
1728 * Convert special keys to vterm keys:
1729 * - Write keys to vterm: vterm_keyboard_key()
1730 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001731 */
1732 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001733 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001735 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001736 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001737 vterm_keyboard_unichar(vterm, c, mod);
1738
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001739 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001740 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1741}
1742
1743/*
1744 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001745 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001746 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001747 */
1748 static int
1749term_job_running_check(term_T *term, int check_job_status)
1750{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001751 // Also consider the job finished when the channel is closed, to avoid a
1752 // race condition when updating the title.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001753 if (term == NULL
1754 || term->tl_job == NULL
1755 || !channel_is_open(term->tl_job->jv_channel))
1756 return FALSE;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001757
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001758 job_T *job = term->tl_job;
1759
1760 // Careful: Checking the job status may invoke callbacks, which close
1761 // the buffer and terminate "term". However, "job" will not be freed
1762 // yet.
1763 if (check_job_status)
1764 job_status(job);
1765 return (job->jv_status == JOB_STARTED
1766 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001767}
1768
1769/*
1770 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001771 */
1772 int
1773term_job_running(term_T *term)
1774{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001775 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001776}
1777
1778/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001779 * Return TRUE if the job for "term" is still running, ignoring the job was
1780 * "NONE".
1781 */
1782 int
1783term_job_running_not_none(term_T *term)
1784{
1785 return term_job_running(term) && !term_none_open(term);
1786}
1787
1788/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001789 * Return TRUE if "term" has an active channel and used ":term NONE".
1790 */
1791 int
1792term_none_open(term_T *term)
1793{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001794 // Also consider the job finished when the channel is closed, to avoid a
1795 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001796 return term != NULL
1797 && term->tl_job != NULL
1798 && channel_is_open(term->tl_job->jv_channel)
1799 && term->tl_job->jv_channel->ch_keep_open;
1800}
1801
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001802//
1803// Used to confirm whether we would like to kill a terminal.
1804// Return OK when the user confirms to kill it.
1805// Return FAIL if the user selects otherwise.
1806//
1807 int
1808term_confirm_stop(buf_T *buf)
1809{
1810 char_u buff[DIALOG_MSG_SIZE];
1811 int ret;
1812
1813 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1814 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1815 if (ret == VIM_YES)
1816 return OK;
1817 else
1818 return FAIL;
1819}
1820
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001821/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001822 * Used when exiting: kill the job in "buf" if so desired.
1823 * Return OK when the job finished.
1824 * Return FAIL when the job is still running.
1825 */
1826 int
1827term_try_stop_job(buf_T *buf)
1828{
1829 int count;
1830 char *how = (char *)buf->b_term->tl_kill;
1831
1832#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001833 if ((how == NULL || *how == NUL)
1834 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001835 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001836 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001837 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001838 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001839 return FAIL;
1840 }
1841#endif
1842 if (how == NULL || *how == NUL)
1843 return FAIL;
1844
1845 job_stop(buf->b_term->tl_job, NULL, how);
1846
Bram Moolenaar9172d232019-01-29 23:06:54 +01001847 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001848 for (count = 0; count < 100; ++count)
1849 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001850 job_T *job;
1851
1852 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001853 if (!buf_valid(buf)
1854 || buf->b_term == NULL
1855 || buf->b_term->tl_job == NULL)
1856 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001857 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001858
Bram Moolenaar9172d232019-01-29 23:06:54 +01001859 // Call job_status() to update jv_status. It may cause the job to be
1860 // cleaned up but it won't be freed.
1861 job_status(job);
1862 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001863 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001864
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001865 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001866 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001867 }
1868 return FAIL;
1869}
1870
1871/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001872 * Add the last line of the scrollback buffer to the buffer in the window.
1873 */
1874 static void
1875add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1876{
1877 buf_T *buf = term->tl_buffer;
1878 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1879 linenr_T lnum = buf->b_ml.ml_line_count;
1880
Bram Moolenaar4f974752019-02-17 17:44:42 +01001881#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001882 if (!enc_utf8 && enc_codepage > 0)
1883 {
1884 WCHAR *ret = NULL;
1885 int length = 0;
1886
1887 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1888 &ret, &length);
1889 if (ret != NULL)
1890 {
1891 WideCharToMultiByte_alloc(enc_codepage, 0,
1892 ret, length, (char **)&text, &len, 0, 0);
1893 vim_free(ret);
1894 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1895 vim_free(text);
1896 }
1897 }
1898 else
1899#endif
1900 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1901 if (empty)
1902 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001903 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001904 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001905 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001906 curbuf = curwin->w_buffer;
1907 }
1908}
1909
1910 static void
1911cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1912{
1913 attr->width = cell->width;
1914 attr->attrs = cell->attrs;
1915 attr->fg = cell->fg;
1916 attr->bg = cell->bg;
1917}
1918
1919 static int
1920equal_celattr(cellattr_T *a, cellattr_T *b)
1921{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001922 // We only compare the RGB colors, ignoring the ANSI index and type.
1923 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001924 return a->fg.red == b->fg.red
1925 && a->fg.green == b->fg.green
1926 && a->fg.blue == b->fg.blue
1927 && a->bg.red == b->bg.red
1928 && a->bg.green == b->bg.green
1929 && a->bg.blue == b->bg.blue;
1930}
1931
Bram Moolenaard96ff162018-02-18 22:13:29 +01001932/*
1933 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1934 * line at this position. Otherwise at the end.
1935 */
1936 static int
1937add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1938{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001939 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
1940 return FALSE;
1941
1942 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1943 + term->tl_scrollback.ga_len;
1944
1945 if (lnum > 0)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001946 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001947 int i;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001948
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001949 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001950 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001951 *line = *(line - 1);
1952 --line;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001953 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01001954 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001955 line->sb_cols = 0;
1956 line->sb_cells = NULL;
1957 line->sb_fill_attr = *fill_attr;
1958 ++term->tl_scrollback.ga_len;
1959 return OK;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001960}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001961
1962/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001963 * Remove the terminal contents from the scrollback and the buffer.
1964 * Used before adding a new scrollback line or updating the buffer for lines
1965 * displayed in the terminal.
1966 */
1967 static void
1968cleanup_scrollback(term_T *term)
1969{
1970 sb_line_T *line;
1971 garray_T *gap;
1972
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001973 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001974 gap = &term->tl_scrollback;
1975 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1976 && gap->ga_len > 0)
1977 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001978 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001979 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1980 vim_free(line->sb_cells);
1981 --gap->ga_len;
1982 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001983 curbuf = curwin->w_buffer;
1984 if (curbuf == term->tl_buffer)
1985 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001986}
1987
1988/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001989 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001990 */
1991 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001992update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001994 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001995 int len;
1996 int lines_skipped = 0;
1997 VTermPos pos;
1998 VTermScreenCell cell;
1999 cellattr_T fill_attr, new_fill_attr;
2000 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002001
2002 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
2003 "Adding terminal window snapshot to buffer");
2004
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002005 // First remove the lines that were appended before, they might be
2006 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002007 cleanup_scrollback(term);
2008
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002009 screen = vterm_obtain_screen(term->tl_vterm);
2010 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
2012 {
2013 len = 0;
2014 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
2015 if (vterm_screen_get_cell(screen, pos, &cell) != 0
2016 && cell.chars[0] != NUL)
2017 {
2018 len = pos.col + 1;
2019 new_fill_attr = term->tl_default_color;
2020 }
2021 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002022 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002023 cell2cellattr(&cell, &new_fill_attr);
2024
2025 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
2026 ++lines_skipped;
2027 else
2028 {
2029 while (lines_skipped > 0)
2030 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002031 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002032 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002033 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002034 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002035 }
2036
2037 if (len == 0)
2038 p = NULL;
2039 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002040 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002041 if ((p != NULL || len == 0)
2042 && ga_grow(&term->tl_scrollback, 1) == OK)
2043 {
2044 garray_T ga;
2045 int width;
2046 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
2047 + term->tl_scrollback.ga_len;
2048
2049 ga_init2(&ga, 1, 100);
2050 for (pos.col = 0; pos.col < len; pos.col += width)
2051 {
2052 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2053 {
2054 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02002055 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002056 if (ga_grow(&ga, 1) == OK)
2057 ga.ga_len += utf_char2bytes(' ',
2058 (char_u *)ga.ga_data + ga.ga_len);
2059 }
2060 else
2061 {
2062 width = cell.width;
2063
2064 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01002065 if (width == 2)
2066 // second cell of double-width character has the
2067 // same attributes.
2068 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002069
Bram Moolenaara79fd562018-12-20 20:47:32 +01002070 // Each character can be up to 6 bytes.
2071 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002072 {
2073 int i;
2074 int c;
2075
2076 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
2077 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2078 (char_u *)ga.ga_data + ga.ga_len);
2079 }
2080 }
2081 }
2082 line->sb_cols = len;
2083 line->sb_cells = p;
2084 line->sb_fill_attr = new_fill_attr;
2085 fill_attr = new_fill_attr;
2086 ++term->tl_scrollback.ga_len;
2087
2088 if (ga_grow(&ga, 1) == FAIL)
2089 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2090 else
2091 {
2092 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2093 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2094 }
2095 ga_clear(&ga);
2096 }
2097 else
2098 vim_free(p);
2099 }
2100 }
2101
Bram Moolenaarf3aea592018-11-11 22:18:21 +01002102 // Add trailing empty lines.
2103 for (pos.row = term->tl_scrollback.ga_len;
2104 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
2105 ++pos.row)
2106 {
2107 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
2108 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2109 }
2110
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002111 term->tl_dirty_snapshot = FALSE;
2112#ifdef FEAT_TIMERS
2113 term->tl_timer_set = FALSE;
2114#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002115}
2116
2117/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002118 * Loop over all windows in the current tab, and also curwin, which is not
2119 * encountered when using a terminal in a popup window.
2120 * Return TRUE if "*wp" was set to the next window.
2121 */
2122 static int
2123for_all_windows_and_curwin(win_T **wp, int *did_curwin)
2124{
2125 if (*wp == NULL)
2126 *wp = firstwin;
2127 else if ((*wp)->w_next != NULL)
2128 *wp = (*wp)->w_next;
2129 else if (!*did_curwin)
2130 *wp = curwin;
2131 else
2132 return FALSE;
2133 if (*wp == curwin)
2134 *did_curwin = TRUE;
2135 return TRUE;
2136}
2137
2138/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002139 * If needed, add the current lines of the terminal to scrollback and to the
2140 * buffer. Called after the job has ended and when switching to
2141 * Terminal-Normal mode.
2142 * When "redraw" is TRUE redraw the windows that show the terminal.
2143 */
2144 static void
2145may_move_terminal_to_buffer(term_T *term, int redraw)
2146{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002147 if (term->tl_vterm == NULL)
2148 return;
2149
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002150 // Update the snapshot only if something changes or the buffer does not
2151 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002152 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2153 <= term->tl_scrollback_scrolled)
2154 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002155
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002156 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002157 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2158 &term->tl_default_color.fg, &term->tl_default_color.bg);
2159
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002160 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002161 {
2162 win_T *wp = NULL;
2163 int did_curwin = FALSE;
2164
2165 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002167 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002168 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002169 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2170 wp->w_cursor.col = 0;
2171 wp->w_valid = 0;
2172 if (wp->w_cursor.lnum >= wp->w_height)
2173 {
2174 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002176 if (wp->w_topline < min_topline)
2177 wp->w_topline = min_topline;
2178 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002179 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002180 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002181 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002182 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002183}
2184
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002185#if defined(FEAT_TIMERS) || defined(PROTO)
2186/*
2187 * Check if any terminal timer expired. If so, copy text from the terminal to
2188 * the buffer.
2189 * Return the time until the next timer will expire.
2190 */
2191 int
2192term_check_timers(int next_due_arg, proftime_T *now)
2193{
2194 term_T *term;
2195 int next_due = next_due_arg;
2196
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002197 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002198 {
2199 if (term->tl_timer_set && !term->tl_normal_mode)
2200 {
2201 long this_due = proftime_time_left(&term->tl_timer_due, now);
2202
2203 if (this_due <= 1)
2204 {
2205 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002206 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002207 }
2208 else if (next_due == -1 || next_due > this_due)
2209 next_due = this_due;
2210 }
2211 }
2212
2213 return next_due;
2214}
2215#endif
2216
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002217/*
2218 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2219 * otherwise end it.
2220 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002221 static void
2222set_terminal_mode(term_T *term, int normal_mode)
2223{
2224 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002225 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002226 if (!normal_mode)
2227 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002228 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002229 if (term->tl_buffer == curbuf)
2230 maketitle();
2231}
2232
2233/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002234 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002235 * Move the vterm contents into the scrollback buffer and free the vterm.
2236 */
2237 static void
2238cleanup_vterm(term_T *term)
2239{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002240 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002241 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002242 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002243 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002244}
2245
2246/*
2247 * Switch from Terminal-Job mode to Terminal-Normal mode.
2248 * Suspends updating the terminal window.
2249 */
2250 static void
2251term_enter_normal_mode(void)
2252{
2253 term_T *term = curbuf->b_term;
2254
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002255 set_terminal_mode(term, TRUE);
2256
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002257 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002258 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002259
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002260 // Move the window cursor to the position of the cursor in the
2261 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2263 + term->tl_cursor_pos.row + 1;
2264 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002265 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2266 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002267 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002268
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002269 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002270 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2271}
2272
2273/*
2274 * Returns TRUE if the current window contains a terminal and we are in
2275 * Terminal-Normal mode.
2276 */
2277 int
2278term_in_normal_mode(void)
2279{
2280 term_T *term = curbuf->b_term;
2281
2282 return term != NULL && term->tl_normal_mode;
2283}
2284
2285/*
2286 * Switch from Terminal-Normal mode to Terminal-Job mode.
2287 * Restores updating the terminal window.
2288 */
2289 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002290term_enter_job_mode(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002291{
2292 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002293
2294 set_terminal_mode(term, FALSE);
2295
2296 if (term->tl_channel_closed)
2297 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002298 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002299#ifdef FEAT_PROP_POPUP
2300 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002301 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002302#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002303}
2304
2305/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002306 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2307 * modifiers into a basic key. However, we may only find out after calling
2308 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2309 * "no_reduce_keys" before using it.
2310 */
2311typedef enum {
2312 NRKS_NONE, // initial value
2313 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2314 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2315 // check_no_reduce_keys(), must be decremented.
2316} reduce_key_state_T;
2317
2318static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2319
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002320/*
2321 * Return TRUE if the term is using modifyOtherKeys level 2 or the kitty
2322 * keyboard protocol.
2323 */
2324 static int
2325vterm_using_key_protocol(void)
2326{
2327 return curbuf->b_term != NULL
2328 && curbuf->b_term->tl_vterm != NULL
2329 && (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm)
2330 || vterm_is_kitty_keyboard(curbuf->b_term->tl_vterm));
2331}
2332
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002333 void
2334check_no_reduce_keys(void)
2335{
2336 if (no_reduce_key_state != NRKS_CHECK
2337 || no_reduce_keys >= 1
2338 || curbuf->b_term == NULL
2339 || curbuf->b_term->tl_vterm == NULL)
2340 return;
2341
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002342 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002343 {
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002344 // "modify_other_keys" or kitty keyboard protocol was enabled while
2345 // waiting.
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002346 no_reduce_key_state = NRKS_SET;
2347 ++no_reduce_keys;
2348 }
2349}
2350
2351/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002352 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002353 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002354 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002355 */
2356 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002357term_vgetc(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358{
2359 int c;
2360 int save_State = State;
2361
Bram Moolenaar24959102022-05-07 20:01:16 +01002362 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002363 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002364#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002365 ctrl_break_was_pressed = FALSE;
2366#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002367
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002368 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002369 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002370 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002371 no_reduce_key_state = NRKS_SET;
2372 }
2373 else
2374 {
2375 no_reduce_key_state = NRKS_CHECK;
2376 }
2377
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002378 c = vgetc();
2379 got_int = FALSE;
2380 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002381
2382 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002383 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002384 no_reduce_key_state = NRKS_NONE;
2385
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002386 return c;
2387}
2388
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002389static int mouse_was_outside = FALSE;
2390
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002391/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002392 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002393 * Return FAIL when the key needs to be handled in Normal mode.
2394 * Return OK when the key was dropped or sent to the terminal.
2395 */
2396 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002397send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002398{
2399 char msg[KEY_BUF_LEN];
2400 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002401 int dragging_outside = FALSE;
2402
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002403 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002404 switch (c)
2405 {
2406 case NUL:
2407 case K_ZERO:
2408 if (typed)
2409 stuffcharReadbuff(c);
2410 return FAIL;
2411
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002412 case K_TABLINE:
2413 stuffcharReadbuff(c);
2414 return FAIL;
2415
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002416 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002417 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002418 return FAIL;
2419
2420 case K_LEFTDRAG:
2421 case K_MIDDLEDRAG:
2422 case K_RIGHTDRAG:
2423 case K_X1DRAG:
2424 case K_X2DRAG:
2425 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002426 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002427 case K_LEFTMOUSE:
2428 case K_LEFTMOUSE_NM:
2429 case K_LEFTRELEASE:
2430 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002431 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002432 case K_MIDDLEMOUSE:
2433 case K_MIDDLERELEASE:
2434 case K_RIGHTMOUSE:
2435 case K_RIGHTRELEASE:
2436 case K_X1MOUSE:
2437 case K_X1RELEASE:
2438 case K_X2MOUSE:
2439 case K_X2RELEASE:
2440
2441 case K_MOUSEUP:
2442 case K_MOUSEDOWN:
2443 case K_MOUSELEFT:
2444 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002445 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002446 int row = mouse_row;
2447 int col = mouse_col;
2448
2449#ifdef FEAT_PROP_POPUP
2450 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002451 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002452 row -= popup_top_extra(curwin);
2453 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002454 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002455#endif
2456 if (row < W_WINROW(curwin)
2457 || row >= (W_WINROW(curwin) + curwin->w_height)
2458 || col < curwin->w_wincol
2459 || col >= W_ENDCOL(curwin)
2460 || dragging_outside)
2461 {
2462 // click or scroll outside the current window or on status
2463 // line or vertical separator
2464 if (typed)
2465 {
2466 stuffcharReadbuff(c);
2467 mouse_was_outside = TRUE;
2468 }
2469 return FAIL;
2470 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002471 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002472 break;
2473
2474 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002475 case K_SCRIPT_COMMAND:
2476 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002477 }
2478 if (typed)
2479 mouse_was_outside = FALSE;
2480
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002481 // Convert the typed key to a sequence of bytes for the job.
2482 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002483 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002484 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002485 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2486 (char_u *)msg, (int)len, NULL);
2487
2488 return OK;
2489}
2490
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002491/*
2492 * Handle CTRL-W "": send register contents to the job.
2493 */
2494 static void
2495term_paste_register(int prev_c UNUSED)
2496{
2497 int c;
2498 list_T *l;
2499 listitem_T *item;
2500 long reglen = 0;
2501 int type;
2502
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 if (add_to_showcmd(prev_c))
2504 if (add_to_showcmd('"'))
2505 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002506
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002507 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002508 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002509
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002510 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
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002514 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002515 if (c == '=' && get_expr_register() != '=')
2516 return;
2517 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002518 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002519 return;
2520
2521 l = (list_T *)get_reg_contents(c, GREG_LIST);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002522 if (l == NULL)
2523 return;
2524
2525 type = get_reg_type(c, &reglen);
2526 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002527 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002528 char_u *s = tv_get_string(&item->li_tv);
2529#ifdef MSWIN
2530 char_u *tmp = s;
2531
2532 if (!enc_utf8 && enc_codepage > 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002533 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002534 WCHAR *ret = NULL;
2535 int length = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002536
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002537 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2538 (int)STRLEN(s), &ret, &length);
2539 if (ret != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002540 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002541 WideCharToMultiByte_alloc(CP_UTF8, 0,
2542 ret, length, (char **)&s, &length, 0, 0);
2543 vim_free(ret);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002544 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002545 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002546#endif
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002547 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2548 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002549#ifdef MSWIN
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002550 if (tmp != s)
2551 vim_free(s);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002552#endif
2553
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002554 if (item->li_next != NULL || type == MLINE)
2555 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2556 (char_u *)"\r", 1, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002557 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002558 list_free(l);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002559}
2560
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002561/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002562 * Return TRUE when waiting for a character in the terminal, the cursor of the
2563 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002564 */
2565 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002566terminal_is_active(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002567{
2568 return in_terminal_loop != NULL;
2569}
2570
Bram Moolenaar83d47902020-03-26 20:34:00 +01002571/*
dundargocc57b5bc2022-11-02 13:30:51 +00002572 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002573 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002574 static int
2575term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002576{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002577 char_u *name;
2578
2579 if (wp != NULL && *wp->w_p_wcr != NUL)
2580 name = wp->w_p_wcr;
2581 else if (term->tl_highlight_name != NULL)
2582 name = term->tl_highlight_name;
2583 else
2584 name = (char_u*)"Terminal";
2585
2586 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002587}
2588
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002589#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002590 cursorentry_T *
2591term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2592{
2593 term_T *term = in_terminal_loop;
2594 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002595 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002596 guicolor_T term_fg = INVALCOLOR;
2597 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002598
Bram Moolenaara80faa82020-04-12 19:37:17 +02002599 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002600 entry.shape = entry.mshape =
2601 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2602 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2603 SHAPE_BLOCK;
2604 entry.percentage = 20;
2605 if (term->tl_cursor_blink)
2606 {
2607 entry.blinkwait = 700;
2608 entry.blinkon = 400;
2609 entry.blinkoff = 250;
2610 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002611
Bram Moolenaar83d47902020-03-26 20:34:00 +01002612 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002613 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002614 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002615 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002616 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002617 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002618 else
2619 *fg = gui.back_pixel;
2620
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002621 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002622 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002623 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002624 *bg = term_fg;
2625 else
2626 *bg = gui.norm_pixel;
2627 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002628 else
2629 *bg = color_name2handle(term->tl_cursor_color);
2630 entry.name = "n";
2631 entry.used_for = SHAPE_CURSOR;
2632
2633 return &entry;
2634}
2635#endif
2636
Bram Moolenaard317b382018-02-08 22:33:31 +01002637 static void
2638may_output_cursor_props(void)
2639{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002640 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002641 || last_set_cursor_shape != desired_cursor_shape
2642 || last_set_cursor_blink != desired_cursor_blink)
2643 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002644 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002645 last_set_cursor_shape = desired_cursor_shape;
2646 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002647 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002648 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002649 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002650 ui_cursor_shape_forced(TRUE);
2651 else
2652 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2653 }
2654}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002655
Bram Moolenaard317b382018-02-08 22:33:31 +01002656/*
2657 * Set the cursor color and shape, if not last set to these.
2658 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002659 static void
2660may_set_cursor_props(term_T *term)
2661{
2662#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002663 // For the GUI the cursor properties are obtained with
2664 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002665 if (gui.in_use)
2666 return;
2667#endif
2668 if (in_terminal_loop == term)
2669 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002670 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002671 desired_cursor_shape = term->tl_cursor_shape;
2672 desired_cursor_blink = term->tl_cursor_blink;
2673 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002674 }
2675}
2676
Bram Moolenaard317b382018-02-08 22:33:31 +01002677/*
2678 * Reset the desired cursor properties and restore them when needed.
2679 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002680 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002681prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002682{
2683#ifdef FEAT_GUI
2684 if (gui.in_use)
2685 return;
2686#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002687 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002688 desired_cursor_shape = -1;
2689 desired_cursor_blink = -1;
2690 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002691}
2692
2693/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002694 * Returns TRUE if the current window contains a terminal and we are sending
2695 * keys to the job.
2696 * If "check_job_status" is TRUE update the job status.
2697 */
2698 static int
2699term_use_loop_check(int check_job_status)
2700{
2701 term_T *term = curbuf->b_term;
2702
2703 return term != NULL
2704 && !term->tl_normal_mode
2705 && term->tl_vterm != NULL
2706 && term_job_running_check(term, check_job_status);
2707}
2708
2709/*
2710 * Returns TRUE if the current window contains a terminal and we are sending
2711 * keys to the job.
2712 */
2713 int
2714term_use_loop(void)
2715{
2716 return term_use_loop_check(FALSE);
2717}
2718
2719/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002720 * Called when entering a window with the mouse. If this is a terminal window
2721 * we may want to change state.
2722 */
2723 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002724term_win_entered(void)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002725{
2726 term_T *term = curbuf->b_term;
2727
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002728 if (term == NULL)
2729 return;
2730
2731 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002732 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002733 reset_VIsual_and_resel();
2734 if (State & MODE_INSERT)
2735 stop_insert_mode = TRUE;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002736 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002737 mouse_was_outside = FALSE;
2738 enter_mouse_col = mouse_col;
2739 enter_mouse_row = mouse_row;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002740}
2741
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002742 void
2743term_focus_change(int in_focus)
2744{
2745 term_T *term = curbuf->b_term;
2746
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002747 if (term == NULL || term->tl_vterm == NULL)
2748 return;
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002749
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002750 VTermState *state = vterm_obtain_state(term->tl_vterm);
2751
2752 if (in_focus)
2753 vterm_state_focus_in(state);
2754 else
2755 vterm_state_focus_out(state);
2756 term_forward_output(term);
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002757}
2758
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002759/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002760 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2761 * Return the Ctrl-key value in that case.
2762 */
2763 static int
2764raw_c_to_ctrl(int c)
2765{
2766 if ((mod_mask & MOD_MASK_CTRL)
2767 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2768 return c & 0x1f;
2769 return c;
2770}
2771
2772/*
2773 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002774 * Also when the Kitty keyboard protocol is used.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002775 * May set "mod_mask".
2776 */
2777 static int
2778ctrl_to_raw_c(int c)
2779{
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002780 if (c < 0x20 && vterm_using_key_protocol())
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002781 {
2782 mod_mask |= MOD_MASK_CTRL;
2783 return c + '@';
2784 }
2785 return c;
2786}
2787
2788/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002789 * Wait for input and send it to the job.
2790 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2791 * when there is no more typahead.
2792 * Return when the start of a CTRL-W command is typed or anything else that
2793 * should be handled as a Normal mode command.
2794 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2795 * the terminal was closed.
2796 */
2797 int
2798terminal_loop(int blocking)
2799{
2800 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002801 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002802 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002803 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002804#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002805 int tty_fd = curbuf->b_term->tl_job->jv_channel
2806 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002807#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002808 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002809
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002810 // Remember the terminal we are sending keys to. However, the terminal
2811 // might be closed while waiting for a character, e.g. typing "exit" in a
2812 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2813 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002814 in_terminal_loop = curbuf->b_term;
2815
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002816 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002817 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002818 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002819 if (termwinkey == Ctrl_W)
2820 termwinkey = 0;
2821 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002822 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002823 may_set_cursor_props(curbuf->b_term);
2824
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002825 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002826 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002827#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002828 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002829#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002830 // TODO: skip screen update when handling a sequence of keys.
2831 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002832 while (must_redraw != 0)
2833 if (update_screen(0) == FAIL)
2834 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002835 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002836 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002837 break;
2838
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002839 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002840 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002841
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002842 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002843 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002844 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002845 // Job finished while waiting for a character. Push back the
2846 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002847 if (raw_c != K_IGNORE)
2848 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002849 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002850 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002851 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002852 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002853 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002854
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002855#ifdef UNIX
2856 /*
2857 * The shell or another program may change the tty settings. Getting
2858 * them for every typed character is a bit of overhead, but it's needed
2859 * for the first character typed, e.g. when Vim starts in a shell.
2860 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002861 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002862 {
2863 ttyinfo_T info;
2864
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002865 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002866 if (get_tty_info(tty_fd, &info) == OK)
2867 term_backspace_char = info.backspace;
2868 }
2869#endif
2870
Bram Moolenaar4f974752019-02-17 17:44:42 +01002871#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002872 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2873 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002874 if (ctrl_break_was_pressed)
2875 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2876#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002877 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2878 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002879 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002880#ifdef FEAT_GUI
2881 && !curbuf->b_term->tl_system
2882#endif
2883 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002884 {
2885 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002886 int prev_raw_c = raw_c;
2887 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002889 if (add_to_showcmd(c))
2890 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002891
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002892 raw_c = term_vgetc();
2893 c = raw_c_to_ctrl(raw_c);
2894
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002895 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002896
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002897 if (!term_use_loop_check(TRUE)
2898 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002899 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002900 break;
2901
2902 if (prev_c == Ctrl_BSL)
2903 {
2904 if (c == Ctrl_N)
2905 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002906 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002907 term_enter_normal_mode();
2908 ret = FAIL;
2909 goto theend;
2910 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002911 // Send both keys to the terminal, first one here, second one
2912 // below.
2913 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2914 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002915 }
2916 else if (c == Ctrl_C)
2917 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002918 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002919 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2920 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002921 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002923 // "CTRL-W .": send CTRL-W to the job
2924 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002925 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002926 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002927 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002928 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002929 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002930 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002931 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002932 else if (c == 'N')
2933 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002934 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002935 term_enter_normal_mode();
2936 ret = FAIL;
2937 goto theend;
2938 }
2939 else if (c == '"')
2940 {
2941 term_paste_register(prev_c);
2942 continue;
2943 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002944 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002945 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002946 // space for CTRL-W, modifier, multi-byte char and NUL
2947 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002948
2949 // Put the command into the typeahead buffer, when using the
2950 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2951 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002952 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002953 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002954 ret = OK;
2955 goto theend;
2956 }
2957 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002958# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002959 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002960 {
2961 WCHAR wc;
2962 char_u mb[3];
2963
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002964 mb[0] = (unsigned)raw_c >> 8;
2965 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002966 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002967 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002968 }
2969# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002970 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002971 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002972 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002973 // We are sure to come back here, don't reset the cursor color
2974 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002975 restore_cursor = FALSE;
2976
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002977 ret = OK;
2978 goto theend;
2979 }
2980 }
2981 ret = FAIL;
2982
2983theend:
2984 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002985 if (restore_cursor)
2986 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002987
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002988 // Move a snapshot of the screen contents to the buffer, so that completion
2989 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002990 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2991 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002992
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002993 return ret;
2994}
2995
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002996 static void
2997may_toggle_cursor(term_T *term)
2998{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002999 if (in_terminal_loop != term)
3000 return;
3001
3002 if (term->tl_cursor_visible)
3003 cursor_on();
3004 else
3005 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003006}
3007
3008/*
3009 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01003010 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003011 */
3012 static int
3013color2index(VTermColor *color, int fg, int *boldp)
3014{
3015 int red = color->red;
3016 int blue = color->blue;
3017 int green = color->green;
3018
LemonBoyb2b3acb2022-05-20 10:10:34 +01003019 *boldp = FALSE;
3020
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003021 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003022 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01003023
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003024 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003025 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003026 // Use the color as-is if possible, give up otherwise.
3027 if (color->index < t_colors)
3028 return color->index + 1;
3029 // 8-color terminals can actually display twice as many colors by
3030 // setting the high-intensity/bold bit.
3031 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003032 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003033 *boldp = TRUE;
3034 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003035 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01003036 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003037 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01003038
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003039 if (t_colors >= 256)
3040 {
3041 if (red == blue && red == green)
3042 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003043 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003044 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003045 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
3046 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
3047 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003048 int i;
3049
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003050 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003051 return 17; // 00/00/00
3052 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003053 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003054 for (i = 0; i < 23; ++i)
3055 if (red < cutoff[i])
3056 return i + 233;
3057 return 256;
3058 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003059 {
3060 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
3061 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003062
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003063 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003064 for (ri = 0; ri < 5; ++ri)
3065 if (red < cutoff[ri])
3066 break;
3067 for (gi = 0; gi < 5; ++gi)
3068 if (green < cutoff[gi])
3069 break;
3070 for (bi = 0; bi < 5; ++bi)
3071 if (blue < cutoff[bi])
3072 break;
3073 return 17 + ri * 36 + gi * 6 + bi;
3074 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003075 }
3076 return 0;
3077}
3078
3079/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01003080 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003081 */
3082 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003083vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003084{
3085 int attr = 0;
3086
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003087 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003088 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003089 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003090 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003091 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003092 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003093 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003094 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003095 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003096 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003097 return attr;
3098}
3099
3100/*
3101 * Store Vterm attributes in "cell" from highlight flags.
3102 */
3103 static void
3104hl2vtermAttr(int attr, cellattr_T *cell)
3105{
Bram Moolenaara80faa82020-04-12 19:37:17 +02003106 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003107 if (attr & HL_BOLD)
3108 cell->attrs.bold = 1;
3109 if (attr & HL_UNDERLINE)
3110 cell->attrs.underline = 1;
3111 if (attr & HL_ITALIC)
3112 cell->attrs.italic = 1;
3113 if (attr & HL_STRIKETHROUGH)
3114 cell->attrs.strike = 1;
3115 if (attr & HL_INVERSE)
3116 cell->attrs.reverse = 1;
3117}
3118
3119/*
3120 * Convert the attributes of a vterm cell into an attribute index.
3121 */
3122 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003123cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003124 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003125 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003126 VTermScreenCellAttrs *cellattrs,
3127 VTermColor *cellfg,
3128 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003129{
3130 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003131 VTermColor *fg = cellfg;
3132 VTermColor *bg = cellbg;
3133 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3134 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3135
3136 if (is_default_fg || is_default_bg)
3137 {
3138 if (wp != NULL && *wp->w_p_wcr != NUL)
3139 {
3140 if (is_default_fg)
3141 fg = &wp->w_term_wincolor.fg;
3142 if (is_default_bg)
3143 bg = &wp->w_term_wincolor.bg;
3144 }
3145 else
3146 {
3147 if (is_default_fg)
3148 fg = &term->tl_default_color.fg;
3149 if (is_default_bg)
3150 bg = &term->tl_default_color.bg;
3151 }
3152 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153
3154#ifdef FEAT_GUI
3155 if (gui.in_use)
3156 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003157 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3158 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3159 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003160 }
3161 else
3162#endif
3163#ifdef FEAT_TERMGUICOLORS
3164 if (p_tgc)
3165 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003166 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3167 ? INVALCOLOR
3168 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3169 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3170 ? INVALCOLOR
3171 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3172 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003173 }
3174 else
3175#endif
3176 {
3177 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003178 int ctermfg = color2index(fg, TRUE, &bold);
3179 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003180
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003181 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003182 if (bold == TRUE)
3183 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003184
3185 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003186 }
3187 return 0;
3188}
3189
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003190 static void
3191set_dirty_snapshot(term_T *term)
3192{
3193 term->tl_dirty_snapshot = TRUE;
3194#ifdef FEAT_TIMERS
3195 if (!term->tl_normal_mode)
3196 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003197 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003198 profile_setlimit(100L, &term->tl_timer_due);
3199 term->tl_timer_set = TRUE;
3200 }
3201#endif
3202}
3203
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003204 static int
3205handle_damage(VTermRect rect, void *user)
3206{
3207 term_T *term = (term_T *)user;
3208
3209 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3210 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003211 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003212 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003213 return 1;
3214}
3215
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003216 static void
3217term_scroll_up(term_T *term, int start_row, int count)
3218{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003219 win_T *wp = NULL;
3220 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003221 VTermColor fg, bg;
3222 VTermScreenCellAttrs attr;
3223 int clear_attr;
3224
Bram Moolenaara80faa82020-04-12 19:37:17 +02003225 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003226
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003227 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003228 {
3229 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003230 {
3231 // Set the color to clear lines with.
3232 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3233 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003234 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003235 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003236 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003237 }
3238}
3239
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003240 static int
3241handle_moverect(VTermRect dest, VTermRect src, void *user)
3242{
3243 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003244 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003245
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003246 // Scrolling up is done much more efficiently by deleting lines instead of
3247 // redrawing the text. But avoid doing this multiple times, postpone until
3248 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003249 if (dest.start_col == src.start_col
3250 && dest.end_col == src.end_col
3251 && dest.start_row < src.start_row)
3252 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003253 if (dest.start_row == 0)
3254 term->tl_postponed_scroll += count;
3255 else
3256 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003257 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003258
3259 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3260 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003261 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003262
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003263 // Note sure if the scrolling will work correctly, let's do a complete
3264 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003265 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003266 return 1;
3267}
3268
3269 static int
3270handle_movecursor(
3271 VTermPos pos,
3272 VTermPos oldpos UNUSED,
3273 int visible,
3274 void *user)
3275{
3276 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003277 win_T *wp = NULL;
3278 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003279
3280 term->tl_cursor_pos = pos;
3281 term->tl_cursor_visible = visible;
3282
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003283 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003284 {
3285 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003286 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003287 }
3288 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003289 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003290
3291 return 1;
3292}
3293
3294 static int
3295handle_settermprop(
3296 VTermProp prop,
3297 VTermValue *value,
3298 void *user)
3299{
3300 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003301 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003302
3303 switch (prop)
3304 {
3305 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003306 if (disable_vterm_title_for_testing)
3307 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003308 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003309 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003310 if (strval == NULL)
3311 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003312 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003313 // a blank title isn't useful, make it empty, so that "running" is
3314 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003315 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003316 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003317 // Same as blank
3318 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003319 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003320 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3321 term->tl_title = NULL;
3322 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003323 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003324 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003325#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003326 else if (!enc_utf8 && enc_codepage > 0)
3327 {
3328 WCHAR *ret = NULL;
3329 int length = 0;
3330
3331 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003332 (char*)value->string.str,
3333 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003334 if (ret != NULL)
3335 {
3336 WideCharToMultiByte_alloc(enc_codepage, 0,
3337 ret, length, (char**)&term->tl_title,
3338 &length, 0, 0);
3339 vim_free(ret);
3340 }
3341 }
3342#endif
3343 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003344 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003345 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003346 strval = NULL;
3347 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003348 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003349 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003350 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003351 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003352 curwin->w_redr_status = TRUE;
3353 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003354 break;
3355
3356 case VTERM_PROP_CURSORVISIBLE:
3357 term->tl_cursor_visible = value->boolean;
3358 may_toggle_cursor(term);
3359 out_flush();
3360 break;
3361
3362 case VTERM_PROP_CURSORBLINK:
3363 term->tl_cursor_blink = value->boolean;
3364 may_set_cursor_props(term);
3365 break;
3366
3367 case VTERM_PROP_CURSORSHAPE:
3368 term->tl_cursor_shape = value->number;
3369 may_set_cursor_props(term);
3370 break;
3371
3372 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003373 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003374 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003375 if (strval == NULL)
3376 break;
3377 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003378 may_set_cursor_props(term);
3379 break;
3380
3381 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003382 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003383 term->tl_using_altscreen = value->boolean;
3384 break;
3385
3386 default:
3387 break;
3388 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003389 vim_free(strval);
3390
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003391 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003392 return 1;
3393}
3394
3395/*
3396 * The job running in the terminal resized the terminal.
3397 */
3398 static int
3399handle_resize(int rows, int cols, void *user)
3400{
3401 term_T *term = (term_T *)user;
3402 win_T *wp;
3403
3404 term->tl_rows = rows;
3405 term->tl_cols = cols;
3406 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003407 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003408 term->tl_vterm_size_changed = FALSE;
3409 else
3410 {
3411 FOR_ALL_WINDOWS(wp)
3412 {
3413 if (wp->w_buffer == term->tl_buffer)
3414 {
3415 win_setheight_win(rows, wp);
3416 win_setwidth_win(cols, wp);
3417 }
3418 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003419 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003420 }
3421 return 1;
3422}
3423
3424/*
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003425 * If the number of lines that are stored goes over 'termwinscroll' then
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003426 * delete the first 10%.
3427 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3428 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003429 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003430 static void
3431limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003432{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003433 if (gap->ga_len < term->tl_buffer->b_p_twsl)
3434 return;
3435
3436 int todo = term->tl_buffer->b_p_twsl / 10;
3437 int i;
3438
3439 curbuf = term->tl_buffer;
3440 for (i = 0; i < todo; ++i)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003441 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003442 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003443 if (update_buffer)
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003444 ml_delete(1);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003445 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003446 curbuf = curwin->w_buffer;
3447
3448 gap->ga_len -= todo;
3449 mch_memmove(gap->ga_data,
3450 (sb_line_T *)gap->ga_data + todo,
3451 sizeof(sb_line_T) * gap->ga_len);
3452 if (update_buffer)
3453 term->tl_scrollback_scrolled -= todo;
Christian Brabandt1254e6d2024-07-29 21:19:51 +02003454
3455 // make sure cursor is on a valid line
3456 if (curbuf == term->tl_buffer)
3457 check_cursor();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003458}
3459
3460/*
3461 * Handle a line that is pushed off the top of the screen.
3462 */
3463 static int
3464handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3465{
3466 term_T *term = (term_T *)user;
3467 garray_T *gap;
3468 int update_buffer;
3469
3470 if (term->tl_normal_mode)
3471 {
3472 // In Terminal-Normal mode the user interacts with the buffer, thus we
3473 // must not change it. Postpone adding the scrollback lines.
3474 gap = &term->tl_scrollback_postponed;
3475 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003476 }
3477 else
3478 {
3479 // First remove the lines that were appended before, the pushed line
3480 // goes above it.
3481 cleanup_scrollback(term);
3482 gap = &term->tl_scrollback;
3483 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003484 }
3485
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003486 limit_scrollback(term, gap, update_buffer);
3487
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003488 if (ga_grow(gap, 1) == FAIL)
3489 return 0;
3490
3491 cellattr_T *p = NULL;
3492 int len = 0;
3493 int i;
3494 int c;
3495 int col;
3496 int text_len;
3497 char_u *text;
3498 sb_line_T *line;
3499 garray_T ga;
3500 cellattr_T fill_attr = term->tl_default_color;
3501
3502 // do not store empty cells at the end
3503 for (i = 0; i < cols; ++i)
3504 if (cells[i].chars[0] != 0)
3505 len = i + 1;
3506 else
3507 cell2cellattr(&cells[i], &fill_attr);
3508
3509 ga_init2(&ga, 1, 100);
3510 if (len > 0)
3511 p = ALLOC_MULT(cellattr_T, len);
3512 if (p != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003513 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003514 for (col = 0; col < len; col += cells[col].width)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003515 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003516 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003517 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003518 ga.ga_len = 0;
3519 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003520 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003521 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3522 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3523 (char_u *)ga.ga_data + ga.ga_len);
3524 cell2cellattr(&cells[col], &p[col]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003525 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003526 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003527 if (ga_grow(&ga, 1) == FAIL)
3528 {
3529 if (update_buffer)
3530 text = (char_u *)"";
3531 else
3532 text = vim_strsave((char_u *)"");
3533 text_len = 0;
3534 }
3535 else
3536 {
3537 text = ga.ga_data;
3538 text_len = ga.ga_len;
3539 *(text + text_len) = NUL;
3540 }
3541 if (update_buffer)
3542 add_scrollback_line_to_buffer(term, text, text_len);
3543
3544 line = (sb_line_T *)gap->ga_data + gap->ga_len;
3545 line->sb_cols = len;
3546 line->sb_cells = p;
3547 line->sb_fill_attr = fill_attr;
3548 if (update_buffer)
3549 {
3550 line->sb_text = NULL;
3551 ++term->tl_scrollback_scrolled;
3552 ga_clear(&ga); // free the text
3553 }
3554 else
3555 {
3556 line->sb_text = text;
3557 ga_init(&ga); // text is kept in tl_scrollback_postponed
3558 }
3559 ++gap->ga_len;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003560 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003561}
3562
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003563/*
3564 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3565 * received and stored in tl_scrollback_postponed.
3566 */
3567 static void
3568handle_postponed_scrollback(term_T *term)
3569{
3570 int i;
3571
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003572 if (term->tl_scrollback_postponed.ga_len == 0)
3573 return;
3574 ch_log(NULL, "Moving postponed scrollback to scrollback");
3575
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003576 // First remove the lines that were appended before, the pushed lines go
3577 // above it.
3578 cleanup_scrollback(term);
3579
3580 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3581 {
3582 char_u *text;
3583 sb_line_T *pp_line;
3584 sb_line_T *line;
3585
3586 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3587 break;
3588 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3589
3590 text = pp_line->sb_text;
3591 if (text == NULL)
3592 text = (char_u *)"";
3593 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3594 vim_free(pp_line->sb_text);
3595
3596 line = (sb_line_T *)term->tl_scrollback.ga_data
3597 + term->tl_scrollback.ga_len;
3598 line->sb_cols = pp_line->sb_cols;
3599 line->sb_cells = pp_line->sb_cells;
3600 line->sb_fill_attr = pp_line->sb_fill_attr;
3601 line->sb_text = NULL;
3602 ++term->tl_scrollback_scrolled;
3603 ++term->tl_scrollback.ga_len;
3604 }
3605
3606 ga_clear(&term->tl_scrollback_postponed);
3607 limit_scrollback(term, &term->tl_scrollback, TRUE);
3608}
3609
LemonBoy77771d32022-04-13 11:47:25 +01003610/*
3611 * Called when the terminal wants to ring the system bell.
3612 */
3613 static int
3614handle_bell(void *user UNUSED)
3615{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003616 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003617 return 0;
3618}
3619
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003620static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003621 handle_damage, // damage
3622 handle_moverect, // moverect
3623 handle_movecursor, // movecursor
3624 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003625 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003626 handle_resize, // resize
3627 handle_pushline, // sb_pushline
Bram Moolenaar6a12d262022-10-16 19:26:52 +01003628 NULL, // sb_popline
3629 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003630};
3631
3632/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003633 * Do the work after the channel of a terminal was closed.
3634 * Must be called only when updating_screen is FALSE.
3635 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3636 */
3637 static int
3638term_after_channel_closed(term_T *term)
3639{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003640 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003641 if (!term->tl_normal_mode)
3642 {
3643 int fnum = term->tl_buffer->b_fnum;
3644
3645 cleanup_vterm(term);
3646
3647 if (term->tl_finish == TL_FINISH_CLOSE)
3648 {
3649 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003650 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003651#ifdef FEAT_PROP_POPUP
3652 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003653
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003654 // If this was a terminal in a popup window, go back to the
3655 // previous window.
3656 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3657 {
3658 pwin = curwin;
3659 if (win_valid(prevwin))
3660 win_enter(prevwin, FALSE);
3661 }
3662 else
3663#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003664 // If this is the last normal window: exit Vim.
3665 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3666 {
3667 exarg_T ea;
3668
Bram Moolenaara80faa82020-04-12 19:37:17 +02003669 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003670 ex_quit(&ea);
3671 return TRUE;
3672 }
3673
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003674 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003675 ch_log(NULL, "terminal job finished, closing window");
3676 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaare76062c2022-11-28 18:51:43 +00003677 if (curbuf == term->tl_buffer)
3678 {
3679 // Avoid closing the window if we temporarily use it.
3680 if (is_aucmd_win(curwin))
3681 do_set_w_closing = TRUE;
3682 if (do_set_w_closing)
3683 curwin->w_closing = TRUE;
3684 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
3685 if (do_set_w_closing)
3686 curwin->w_closing = FALSE;
3687 aucmd_restbuf(&aco);
3688 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003689#ifdef FEAT_PROP_POPUP
3690 if (pwin != NULL)
3691 popup_close_with_retval(pwin, 0);
3692#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003693 return TRUE;
3694 }
3695 if (term->tl_finish == TL_FINISH_OPEN
3696 && term->tl_buffer->b_nwindows == 0)
3697 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003698 char *cmd = term->tl_opencmd == NULL
3699 ? "botright sbuf %d"
3700 : (char *)term->tl_opencmd;
3701 size_t len = strlen(cmd) + 50;
3702 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003703
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003704 if (buf != NULL)
3705 {
3706 ch_log(NULL, "terminal job finished, opening window");
3707 vim_snprintf(buf, len, cmd, fnum);
3708 do_cmdline_cmd((char_u *)buf);
3709 vim_free(buf);
3710 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003711 }
3712 else
3713 ch_log(NULL, "terminal job finished");
3714 }
3715
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003716 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003717 return FALSE;
3718}
3719
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003720#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3721/*
3722 * If the current window is a terminal in a popup window and the job has
3723 * finished, close the popup window and to back to the previous window.
3724 * Otherwise return FAIL.
3725 */
3726 int
3727may_close_term_popup(void)
3728{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003729 if (!popup_is_popup(curwin) || curbuf->b_term == NULL
3730 || term_job_running_not_none(curbuf->b_term))
3731 return FAIL;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003732
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003733 win_T *pwin = curwin;
3734
3735 if (win_valid(prevwin))
3736 win_enter(prevwin, FALSE);
3737 popup_close_with_retval(pwin, 0);
3738 return OK;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003739}
3740#endif
3741
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003742/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003743 * Called when a channel is going to be closed, before invoking the close
3744 * callback.
3745 */
3746 void
3747term_channel_closing(channel_T *ch)
3748{
3749 term_T *term;
3750
3751 for (term = first_term; term != NULL; term = term->tl_next)
3752 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3753 term->tl_channel_closing = TRUE;
3754}
3755
3756/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003757 * Called when a channel has been closed.
3758 * If this was a channel for a terminal window then finish it up.
3759 */
3760 void
3761term_channel_closed(channel_T *ch)
3762{
3763 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003764 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003765 int did_one = FALSE;
3766
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003767 for (term = first_term; term != NULL; term = next_term)
3768 {
3769 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003770 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003771 {
3772 term->tl_channel_closed = TRUE;
3773 did_one = TRUE;
3774
Bram Moolenaard23a8232018-02-10 18:45:26 +01003775 VIM_CLEAR(term->tl_title);
3776 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003777#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003778 if (term->tl_out_fd != NULL)
3779 {
3780 fclose(term->tl_out_fd);
3781 term->tl_out_fd = NULL;
3782 }
3783#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003784
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003785 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003786 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003787 // Cannot open or close windows now. Can happen when
3788 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003789 term->tl_channel_recently_closed = TRUE;
3790 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003791 }
3792
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003793 if (term_after_channel_closed(term))
3794 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003795 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003796 }
3797
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003798 if (did_one)
3799 {
3800 redraw_statuslines();
3801
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003802 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003803 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003804 typebuf_was_filled = TRUE;
3805
3806 term = curbuf->b_term;
3807 if (term != NULL)
3808 {
3809 if (term->tl_job == ch->ch_job)
3810 maketitle();
3811 update_cursor(term, term->tl_cursor_visible);
3812 }
3813 }
3814}
3815
3816/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003817 * To be called after resetting updating_screen: handle any terminal where the
3818 * channel was closed.
3819 */
3820 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003821term_check_channel_closed_recently(void)
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003822{
3823 term_T *term;
3824 term_T *next_term;
3825
3826 for (term = first_term; term != NULL; term = next_term)
3827 {
3828 next_term = term->tl_next;
3829 if (term->tl_channel_recently_closed)
3830 {
3831 term->tl_channel_recently_closed = FALSE;
3832 if (term_after_channel_closed(term))
3833 // start over, the list may have changed
3834 next_term = first_term;
3835 }
3836 }
3837}
3838
3839/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003840 * Fill one screen line from a line of the terminal.
3841 * Advances "pos" to past the last column.
3842 */
3843 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003844term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003845 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003846 win_T *wp,
3847 VTermScreen *screen,
3848 VTermPos *pos,
3849 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003850{
3851 int off = screen_get_current_line_off();
3852
3853 for (pos->col = 0; pos->col < max_col; )
3854 {
3855 VTermScreenCell cell;
3856 int c;
3857
3858 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003859 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003860
3861 c = cell.chars[0];
3862 if (c == NUL)
3863 {
3864 ScreenLines[off] = ' ';
3865 if (enc_utf8)
3866 ScreenLinesUC[off] = NUL;
3867 }
3868 else
3869 {
3870 if (enc_utf8)
3871 {
3872 int i;
3873
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003874 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003875 for (i = 0; i < Screen_mco
3876 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3877 {
3878 ScreenLinesC[i][off] = cell.chars[i + 1];
3879 if (cell.chars[i + 1] == 0)
3880 break;
3881 }
3882 if (c >= 0x80 || (Screen_mco > 0
3883 && ScreenLinesC[0][off] != 0))
3884 {
3885 ScreenLines[off] = ' ';
3886 ScreenLinesUC[off] = c;
3887 }
3888 else
3889 {
3890 ScreenLines[off] = c;
3891 ScreenLinesUC[off] = NUL;
3892 }
3893 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003894#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003895 else if (has_mbyte && c >= 0x80)
3896 {
3897 char_u mb[MB_MAXBYTES+1];
3898 WCHAR wc = c;
3899
3900 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3901 (char*)mb, 2, 0, 0) > 1)
3902 {
3903 ScreenLines[off] = mb[0];
3904 ScreenLines[off + 1] = mb[1];
3905 cell.width = mb_ptr2cells(mb);
3906 }
3907 else
3908 ScreenLines[off] = c;
3909 }
3910#endif
3911 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003912 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003913 ScreenLines[off] = c;
3914 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003915 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3916 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003917
3918 ++pos->col;
3919 ++off;
3920 if (cell.width == 2)
3921 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003922 // don't set the second byte to NUL for a DBCS encoding, it
3923 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003924 if (enc_utf8)
3925 {
3926 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003927 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003928 }
3929 else if (!has_mbyte)
3930 {
3931 // Can't show a double-width character with a single-byte
3932 // 'encoding', just use a space.
3933 ScreenLines[off] = ' ';
3934 ScreenAttrs[off] = ScreenAttrs[off - 1];
3935 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003936
3937 ++pos->col;
3938 ++off;
3939 }
3940 }
3941}
3942
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003943#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003944 static void
3945update_system_term(term_T *term)
3946{
3947 VTermPos pos;
3948 VTermScreen *screen;
3949
3950 if (term->tl_vterm == NULL)
3951 return;
3952 screen = vterm_obtain_screen(term->tl_vterm);
3953
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003954 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003955 while (term->tl_toprow > 0
3956 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3957 {
3958 int save_p_more = p_more;
3959
3960 p_more = FALSE;
3961 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003962 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003963 p_more = save_p_more;
3964 --term->tl_toprow;
3965 }
3966
3967 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3968 && pos.row < Rows; ++pos.row)
3969 {
3970 if (pos.row < term->tl_rows)
3971 {
3972 int max_col = MIN(Columns, term->tl_cols);
3973
Bram Moolenaar83d47902020-03-26 20:34:00 +01003974 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003975 }
3976 else
3977 pos.col = 0;
3978
zeertzjqd0c1b772024-03-16 15:03:33 +01003979 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, -1,
3980 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003981 }
3982
3983 term->tl_dirty_row_start = MAX_ROW;
3984 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003985}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003986#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003987
3988/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003989 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3990 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003991 * Terminal-Normal mode.
3992 */
3993 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003994term_do_update_window(win_T *wp)
3995{
3996 term_T *term = wp->w_buffer->b_term;
3997
3998 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3999}
4000
4001/*
4002 * Called to update a window that contains an active terminal.
4003 */
4004 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004005term_update_window(win_T *wp)
4006{
4007 term_T *term = wp->w_buffer->b_term;
4008 VTerm *vterm;
4009 VTermScreen *screen;
4010 VTermState *state;
4011 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004012 int rows, cols;
4013 int newrows, newcols;
4014 int minsize;
4015 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004016
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004017 vterm = term->tl_vterm;
4018 screen = vterm_obtain_screen(vterm);
4019 state = vterm_obtain_state(vterm);
4020
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004021 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
4022 // With UPD_SOME_VALID only redraw what was marked dirty.
4023 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004024 {
4025 term->tl_dirty_row_start = 0;
4026 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004027
4028 if (term->tl_postponed_scroll > 0
4029 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004030 // Scrolling is usually faster than redrawing, when there are only
4031 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004032 term_scroll_up(term, 0, term->tl_postponed_scroll);
4033 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004034 }
4035
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004036 /*
4037 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004038 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004039 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004040 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004041
Bram Moolenaar498c2562018-04-15 23:45:15 +02004042 newrows = 99999;
4043 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004044 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02004045 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004046 // Always use curwin, it may be a popup window.
4047 win_T *wwp = twp == NULL ? curwin : twp;
4048
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004049 // When more than one window shows the same terminal, use the
4050 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004051 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004052 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004053 newrows = MIN(newrows, wwp->w_height);
4054 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004055 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004056 if (twp == NULL)
4057 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004058 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02004059 if (newrows == 99999 || newcols == 99999)
4060 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02004061 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
4062 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
4063
Bram Moolenaareba13e42021-02-23 17:47:23 +01004064 // If no cell is visible there is no point in resizing. Also, vterm can't
4065 // handle a zero height.
4066 if (newrows == 0 || newcols == 0)
4067 return;
4068
Bram Moolenaar498c2562018-04-15 23:45:15 +02004069 if (term->tl_rows != newrows || term->tl_cols != newcols)
4070 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004071 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004072 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004073 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02004074 newrows);
4075 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02004076
4077 // Updating the terminal size will cause the snapshot to be cleared.
4078 // When not in terminal_loop() we need to restore it.
4079 if (term != in_terminal_loop)
4080 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004081 }
4082
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004083 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004084 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01004085 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004086
Bram Moolenaar3a497e12017-09-30 20:40:27 +02004087 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
4088 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004089 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004090 if (pos.row < term->tl_rows)
4091 {
Bram Moolenaar13568252018-03-16 20:46:58 +01004092 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004093
Bram Moolenaar83d47902020-03-26 20:34:00 +01004094 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004095 }
4096 else
4097 pos.col = 0;
4098
Bram Moolenaar510f0372022-07-04 17:46:22 +01004099 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01004100#ifdef FEAT_MENU
4101 + winbar_height(wp)
4102#endif
zeertzjqd0c1b772024-03-16 15:03:33 +01004103 , wp->w_wincol, pos.col, wp->w_width, -1,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004104#ifdef FEAT_PROP_POPUP
4105 popup_is_popup(wp) ? SLF_POPUP :
4106#endif
4107 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004108 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00004109}
4110
4111/*
4112 * Called after updating all windows: may reset dirty rows.
4113 */
4114 void
4115term_did_update_window(win_T *wp)
4116{
4117 term_T *term = wp->w_buffer->b_term;
4118
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004119 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode
4120 || wp->w_redr_type != 0)
4121 return;
4122
4123 term->tl_dirty_row_start = MAX_ROW;
4124 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004125}
4126
4127/*
4128 * Return TRUE if "wp" is a terminal window where the job has finished.
4129 */
4130 int
4131term_is_finished(buf_T *buf)
4132{
4133 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
4134}
4135
4136/*
4137 * Return TRUE if "wp" is a terminal window where the job has finished or we
4138 * are in Terminal-Normal mode, thus we show the buffer contents.
4139 */
4140 int
4141term_show_buffer(buf_T *buf)
4142{
4143 term_T *term = buf->b_term;
4144
4145 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4146}
4147
4148/*
4149 * The current buffer is going to be changed. If there is terminal
4150 * highlighting remove it now.
4151 */
4152 void
4153term_change_in_curbuf(void)
4154{
4155 term_T *term = curbuf->b_term;
4156
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004157 if (!term_is_finished(curbuf) || term->tl_scrollback.ga_len <= 0)
4158 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004159
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004160 free_scrollback(term);
4161 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
4162
4163 // The buffer is now like a normal buffer, it cannot be easily
4164 // abandoned when changed.
4165 set_string_option_direct((char_u *)"buftype", -1,
4166 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004167}
4168
4169/*
4170 * Get the screen attribute for a position in the buffer.
4171 * Use a negative "col" to get the filler background color.
4172 */
4173 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004174term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004175{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004176 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004177 term_T *term = buf->b_term;
4178 sb_line_T *line;
4179 cellattr_T *cellattr;
4180
4181 if (lnum > term->tl_scrollback.ga_len)
4182 cellattr = &term->tl_default_color;
4183 else
4184 {
4185 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4186 if (col < 0 || col >= line->sb_cols)
4187 cellattr = &line->sb_fill_attr;
4188 else
4189 cellattr = line->sb_cells + col;
4190 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004191 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004192}
4193
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004194/*
4195 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004196 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004197 */
4198 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004199cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004200{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004201 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4202 if (rgb->index == 0)
4203 rgb->type = VTERM_COLOR_RGB;
4204 else
4205 {
4206 rgb->type = VTERM_COLOR_INDEXED;
4207 --rgb->index;
4208 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004209}
4210
4211/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004212 * Initialize vterm color from the synID.
4213 * Returns TRUE if color is set to "fg" and "bg".
4214 * Otherwise returns FALSE.
4215 */
4216 static int
4217get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4218{
4219#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4220 // Use the actual color for the GUI and when 'termguicolors' is set.
4221 if (0
4222# ifdef FEAT_GUI
4223 || gui.in_use
4224# endif
4225# ifdef FEAT_TERMGUICOLORS
4226 || p_tgc
4227# ifdef FEAT_VTP
4228 // Finally get INVALCOLOR on this execution path
4229 || (!p_tgc && t_colors >= 256)
4230# endif
4231# endif
4232 )
4233 {
4234 guicolor_T fg_rgb = INVALCOLOR;
4235 guicolor_T bg_rgb = INVALCOLOR;
4236
4237 if (id > 0)
4238 syn_id2colors(id, &fg_rgb, &bg_rgb);
4239
4240 if (fg_rgb != INVALCOLOR)
4241 {
4242 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4243 fg->red = (unsigned)(rgb >> 16);
4244 fg->green = (unsigned)(rgb >> 8) & 255;
4245 fg->blue = (unsigned)rgb & 255;
4246 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4247 }
4248 else
4249 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4250
4251 if (bg_rgb != INVALCOLOR)
4252 {
4253 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4254 bg->red = (unsigned)(rgb >> 16);
4255 bg->green = (unsigned)(rgb >> 8) & 255;
4256 bg->blue = (unsigned)rgb & 255;
4257 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4258 }
4259 else
4260 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4261
4262 return TRUE;
4263 }
4264 else
4265#endif
4266 if (t_colors >= 16)
4267 {
4268 int cterm_fg = -1;
4269 int cterm_bg = -1;
4270
4271 if (id > 0)
4272 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4273
4274 if (cterm_fg >= 0)
4275 {
4276 cterm_color2vterm(cterm_fg, fg);
4277 fg->type |= VTERM_COLOR_DEFAULT_FG;
4278 }
4279 else
4280 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4281
4282 if (cterm_bg >= 0)
4283 {
4284 cterm_color2vterm(cterm_bg, bg);
4285 bg->type |= VTERM_COLOR_DEFAULT_BG;
4286 }
4287 else
4288 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4289
4290 return TRUE;
4291 }
4292
4293 return FALSE;
4294}
4295
4296 void
4297term_reset_wincolor(win_T *wp)
4298{
4299 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4300 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4301}
4302
4303/*
4304 * Cache the color of 'wincolor'.
4305 */
4306 void
4307term_update_wincolor(win_T *wp)
4308{
4309 int id = 0;
4310
4311 if (*wp->w_p_wcr != NUL)
4312 id = syn_name2id(wp->w_p_wcr);
4313 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4314 &wp->w_term_wincolor.bg))
4315 term_reset_wincolor(wp);
4316}
4317
4318/*
4319 * Called when option 'termguicolors' was set,
4320 * or when any highlight is changed.
4321 */
4322 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004323term_update_wincolor_all(void)
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004324{
4325 win_T *wp = NULL;
4326 int did_curwin = FALSE;
4327
4328 while (for_all_windows_and_curwin(&wp, &did_curwin))
4329 term_update_wincolor(wp);
4330}
4331
4332/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004333 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004334 */
4335 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004336init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004337{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004338 VTermColor *fg, *bg;
4339 int fgval, bgval;
4340 int id;
4341
Bram Moolenaara80faa82020-04-12 19:37:17 +02004342 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004343 term->tl_default_color.width = 1;
4344 fg = &term->tl_default_color.fg;
4345 bg = &term->tl_default_color.bg;
4346
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004347 // Vterm uses a default black background. Set it to white when
4348 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004349 if (*p_bg == 'l')
4350 {
4351 fgval = 0;
4352 bgval = 255;
4353 }
4354 else
4355 {
4356 fgval = 255;
4357 bgval = 0;
4358 }
4359 fg->red = fg->green = fg->blue = fgval;
4360 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004361 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4362 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004363
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004364 // The highlight group overrules the defaults.
4365 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004366
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004367 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004368 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004369#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004370 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004371#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004372
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004373 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004374 if (cterm_normal_fg_color > 0)
4375 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004376 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004377# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4378# ifdef VIMDLL
4379 if (!gui.in_use)
4380# endif
4381 {
4382 tmp = fg->red;
4383 fg->red = fg->blue;
4384 fg->blue = tmp;
4385 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004386# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004387 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004388# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004389 else
4390 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004391# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004392
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004393 if (cterm_normal_bg_color > 0)
4394 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004395 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004396# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4397# ifdef VIMDLL
4398 if (!gui.in_use)
4399# endif
4400 {
4401 tmp = fg->red;
4402 fg->red = fg->blue;
4403 fg->blue = tmp;
4404 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004405# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004406 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004407# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004408 else
4409 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004410# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004411 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004412}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004413
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004414#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4415/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004416 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4417 * "ansi_colors" argument in term_start()) shall be applied.
4418 */
4419 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004420term_use_palette(void)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004421{
4422 if (0
4423#ifdef FEAT_GUI
4424 || gui.in_use
4425#endif
4426#ifdef FEAT_TERMGUICOLORS
4427 || p_tgc
4428#endif
4429 )
4430 return TRUE;
4431 return FALSE;
4432}
4433
4434/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004435 * Set the 16 ANSI colors from array of RGB values
4436 */
4437 static void
4438set_vterm_palette(VTerm *vterm, long_u *rgb)
4439{
4440 int index = 0;
4441 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004442
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004443 for (; index < 16; index++)
4444 {
4445 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004446
Millyb771b6b2021-11-23 12:07:25 +00004447 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004448 color.red = (unsigned)(rgb[index] >> 16);
4449 color.green = (unsigned)(rgb[index] >> 8) & 255;
4450 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004451 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004452 vterm_state_set_palette_color(state, index, &color);
4453 }
4454}
4455
4456/*
4457 * Set the ANSI color palette from a list of colors
4458 */
4459 static int
4460set_ansi_colors_list(VTerm *vterm, list_T *list)
4461{
4462 int n = 0;
4463 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004464 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004465
Bram Moolenaarb0992022020-01-30 14:55:42 +01004466 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004467 {
4468 char_u *color_name;
4469 guicolor_T guicolor;
4470
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004471 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004472 if (color_name == NULL)
4473 return FAIL;
4474
4475 guicolor = GUI_GET_COLOR(color_name);
4476 if (guicolor == INVALCOLOR)
4477 return FAIL;
4478
4479 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4480 }
4481
4482 if (n != 16 || li != NULL)
4483 return FAIL;
4484
4485 set_vterm_palette(vterm, rgb);
4486
4487 return OK;
4488}
4489
4490/*
4491 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4492 */
4493 static void
4494init_vterm_ansi_colors(VTerm *vterm)
4495{
4496 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4497
LemonBoyb2b3acb2022-05-20 10:10:34 +01004498 if (var == NULL)
4499 return;
4500
4501 if (var->di_tv.v_type != VAR_LIST
4502 || var->di_tv.vval.v_list == NULL
4503 || var->di_tv.vval.v_list->lv_first == &range_list_item
4504 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004505 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004506}
4507#endif
4508
Bram Moolenaar52acb112018-03-18 19:20:22 +01004509/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004510 * Handles a "drop" command from the job in the terminal.
4511 * "item" is the file name, "item->li_next" may have options.
4512 */
4513 static void
4514handle_drop_command(listitem_T *item)
4515{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004516 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004517 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004518 int bufnr;
4519 win_T *wp;
4520 tabpage_T *tp;
4521 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004522 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004523
4524 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4525 FOR_ALL_TAB_WINDOWS(tp, wp)
4526 {
4527 if (wp->w_buffer->b_fnum == bufnr)
4528 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004529 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004530 goto_tabpage_win(tp, wp);
4531 return;
4532 }
4533 }
4534
Bram Moolenaara80faa82020-04-12 19:37:17 +02004535 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004536
4537 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4538 && opt_item->li_tv.vval.v_dict != NULL)
4539 {
4540 dict_T *dict = opt_item->li_tv.vval.v_dict;
4541 char_u *p;
4542
Bram Moolenaard61efa52022-07-23 09:52:04 +01004543 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004544 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004545 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004546 if (p != NULL)
4547 {
4548 if (check_ff_value(p) == FAIL)
4549 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4550 else
4551 ea.force_ff = *p;
4552 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004553 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004554 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004555 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004556 if (p != NULL)
4557 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004558 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004559 if (ea.cmd != NULL)
4560 {
4561 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4562 ea.force_enc = 11;
4563 tofree = ea.cmd;
4564 }
4565 }
4566
Bram Moolenaard61efa52022-07-23 09:52:04 +01004567 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004568 if (p != NULL)
4569 get_bad_opt(p, &ea);
4570
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004571 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004572 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004573 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004574 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004575 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004576 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004577 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004578 ea.force_bin = FORCE_NOBIN;
4579 }
4580
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004581 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004582 if (ea.cmd == NULL)
4583 ea.cmd = (char_u *)"split";
4584 ea.arg = fname;
4585 ea.cmdidx = CMD_split;
4586 ex_splitview(&ea);
4587
4588 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004589}
4590
4591/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004592 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4593 */
4594 static int
4595is_permitted_term_api(char_u *func, char_u *pat)
4596{
4597 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4598}
4599
4600/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004601 * Handles a function call from the job running in a terminal.
4602 * "item" is the function name, "item->li_next" has the arguments.
4603 */
4604 static void
4605handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4606{
4607 char_u *func;
4608 typval_T argvars[2];
4609 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004610 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004611
4612 if (item->li_next == NULL)
4613 {
4614 ch_log(channel, "Missing function arguments for call");
4615 return;
4616 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004617 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004618
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004619 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004620 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004621 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004622 return;
4623 }
4624
4625 argvars[0].v_type = VAR_NUMBER;
4626 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4627 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004628 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004629 funcexe.fe_firstline = 1L;
4630 funcexe.fe_lastline = 1L;
4631 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004632 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004633 {
4634 clear_tv(&rettv);
4635 ch_log(channel, "Function %s called", func);
4636 }
4637 else
4638 ch_log(channel, "Calling function %s failed", func);
4639}
4640
4641/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004642 * URL decoding (also know as Percent-encoding).
4643 *
4644 * Note this function currently is only used for decoding shell's
4645 * OSC 7 escape sequence which we can assume all bytes are valid
4646 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4647 * encoding bytes like 0xfe, 0xff.
4648 */
4649 static size_t
4650url_decode(const char *src, const size_t len, char_u *dst)
4651{
4652 size_t i = 0, j = 0;
4653
4654 while (i < len)
4655 {
4656 if (src[i] == '%' && i + 2 < len)
4657 {
4658 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4659 j++;
4660 i += 3;
4661 }
4662 else
4663 {
4664 dst[j] = src[i];
4665 i++;
4666 j++;
4667 }
4668 }
4669 dst[j] = '\0';
4670 return j;
4671}
4672
4673/*
4674 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4675 *
4676 * The OSC 7 sequence has the format of
4677 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4678 * and what VTerm provides via VTermStringFragment is
4679 * "file://HOSTNAME/CURRENT/DIR"
4680 */
4681 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004682sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004683{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004684 int offset = 7; // len of "file://" is 7
4685 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004686 char_u *new_dir;
4687
4688 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004689 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004690 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004691 ++offset;
4692 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004693 }
4694
Bram Moolenaar474ad392022-08-21 11:37:17 +01004695 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004696 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004697 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004698 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004699 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004700 }
4701
Bram Moolenaar474ad392022-08-21 11:37:17 +01004702 new_dir = alloc(gap->ga_len - offset + 1);
4703 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004704 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4705 vim_free(new_dir);
4706}
4707
4708/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004709 * Called by libvterm when it cannot recognize an OSC sequence.
4710 * We recognize a terminal API command.
4711 */
4712 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004713parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004714{
4715 term_T *term = (term_T *)user;
4716 js_read_T reader;
4717 typval_T tv;
4718 channel_T *channel = term->tl_job == NULL ? NULL
4719 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004720 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004721
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004722 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004723 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004724 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004725
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004726 // Concatenate what was received until the final piece is found.
4727 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4728 {
4729 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004730 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004731 }
4732 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004733 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004734 if (!frag.final)
4735 return 1;
4736
4737 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004738
4739 if (command == 7)
4740 {
4741 sync_shell_dir(gap);
4742 ga_clear(gap);
4743 return 1;
4744 }
4745
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004746 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004747 reader.js_fill = NULL;
4748 reader.js_used = 0;
4749 if (json_decode(&reader, &tv, 0) == OK
4750 && tv.v_type == VAR_LIST
4751 && tv.vval.v_list != NULL)
4752 {
4753 listitem_T *item = tv.vval.v_list->lv_first;
4754
4755 if (item == NULL)
4756 ch_log(channel, "Missing command");
4757 else
4758 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004759 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004760
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004761 // Make sure an invoked command doesn't delete the buffer (and the
4762 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004763 ++term->tl_buffer->b_locked;
4764
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004765 item = item->li_next;
4766 if (item == NULL)
4767 ch_log(channel, "Missing argument for %s", cmd);
4768 else if (STRCMP(cmd, "drop") == 0)
4769 handle_drop_command(item);
4770 else if (STRCMP(cmd, "call") == 0)
4771 handle_call_command(term, channel, item);
4772 else
4773 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004774 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004775 }
4776 }
4777 else
4778 ch_log(channel, "Invalid JSON received");
4779
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004780 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004781 clear_tv(&tv);
4782 return 1;
4783}
4784
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004785/*
4786 * Called by libvterm when it cannot recognize a CSI sequence.
4787 * We recognize the window position report.
4788 */
4789 static int
4790parse_csi(
4791 const char *leader UNUSED,
4792 const long args[],
4793 int argcount,
4794 const char *intermed UNUSED,
4795 char command,
4796 void *user)
4797{
4798 term_T *term = (term_T *)user;
4799 char buf[100];
4800 int len;
4801 int x = 0;
4802 int y = 0;
4803 win_T *wp;
4804
4805 // We recognize only CSI 13 t
4806 if (command != 't' || argcount != 1 || args[0] != 13)
4807 return 0; // not handled
4808
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004809 // When getting the window position is not possible or it fails it results
4810 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004811#if defined(FEAT_GUI) \
4812 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4813 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004814 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004815#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004816
4817 FOR_ALL_WINDOWS(wp)
4818 if (wp->w_buffer == term->tl_buffer)
4819 break;
4820 if (wp != NULL)
4821 {
4822#ifdef FEAT_GUI
4823 if (gui.in_use)
4824 {
4825 x += wp->w_wincol * gui.char_width;
4826 y += W_WINROW(wp) * gui.char_height;
4827 }
4828 else
4829#endif
4830 {
4831 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004832 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004833 x += wp->w_wincol * 7;
4834 y += W_WINROW(wp) * 10;
4835 }
4836 }
4837
4838 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4839 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4840 (char_u *)buf, len, NULL);
4841 return 1;
4842}
4843
Bram Moolenaard8637282020-05-20 18:41:41 +02004844static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004845 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004846 parse_csi, // csi
4847 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004848 NULL, // dcs
4849 NULL, // apc
4850 NULL, // pm
4851 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004852};
4853
4854/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004855 * Use Vim's allocation functions for vterm so profiling works.
4856 */
4857 static void *
4858vterm_malloc(size_t size, void *data UNUSED)
4859{
Bram Moolenaar88137392021-11-12 16:01:15 +00004860 // make sure that the length is not zero
4861 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004862}
4863
4864 static void
4865vterm_memfree(void *ptr, void *data UNUSED)
4866{
4867 vim_free(ptr);
4868}
4869
4870static VTermAllocatorFunctions vterm_allocator = {
4871 &vterm_malloc,
4872 &vterm_memfree
4873};
4874
4875/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004876 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004877 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004878 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004879 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004880create_vterm(term_T *term, int rows, int cols)
4881{
4882 VTerm *vterm;
4883 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004884 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004885 VTermValue value;
4886
Bram Moolenaar756ef112018-04-10 12:04:27 +02004887 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004888 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004889 if (vterm == NULL)
4890 return FAIL;
4891
4892 // Allocate screen and state here, so we can bail out if that fails.
4893 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004894 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004895 if (state == NULL || screen == NULL)
4896 {
4897 vterm_free(vterm);
4898 return FAIL;
4899 }
4900
Bram Moolenaar52acb112018-03-18 19:20:22 +01004901 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004902 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004903 vterm_set_utf8(vterm, 1);
4904
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004905 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004906
4907 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004908 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004909 &term->tl_default_color.fg,
4910 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004911
Bram Moolenaar9e587872019-05-13 20:27:23 +02004912 if (t_colors < 16)
4913 // Less than 16 colors: assume that bold means using a bright color for
4914 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004915 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4916
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004917 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004918 vterm_screen_reset(screen, 1 /* hard */);
4919
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004920 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004921 vterm_screen_enable_altscreen(screen, 1);
4922
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004923 // For unix do not use a blinking cursor. In an xterm this causes the
4924 // cursor to blink if it's blinking in the xterm.
4925 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004926#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004927 if (GetCaretBlinkTime() == INFINITE)
4928 value.boolean = 0;
4929 else
4930 value.boolean = 1;
4931#else
4932 value.boolean = 0;
4933#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004934 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004935 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004936
4937 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004938}
4939
4940/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004941 * Reset the terminal palette to its default value.
4942 */
4943 static void
4944term_reset_palette(VTerm *vterm)
4945{
4946 VTermState *state = vterm_obtain_state(vterm);
4947 int index;
4948
4949 for (index = 0; index < 16; index++)
4950 {
4951 VTermColor color;
4952
4953 color.type = VTERM_COLOR_INDEXED;
4954 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4955 &color.index);
4956 // The first valid index starts at 1.
4957 color.index -= 1;
4958
4959 vterm_state_set_palette_color(state, index, &color);
4960 }
4961}
4962
4963 static void
4964term_update_palette(term_T *term)
4965{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004966#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004967 if (term_use_palette()
4968 && (term->tl_palette != NULL
4969 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004970 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004971 {
4972 if (term->tl_palette != NULL)
4973 set_vterm_palette(term->tl_vterm, term->tl_palette);
4974 else
4975 init_vterm_ansi_colors(term->tl_vterm);
4976 }
4977 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004978#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004979 term_reset_palette(term->tl_vterm);
4980}
4981
4982/*
4983 * Called when option 'termguicolors' is changed.
4984 */
4985 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004986term_update_palette_all(void)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004987{
4988 term_T *term;
4989
4990 FOR_ALL_TERMS(term)
4991 {
4992 if (term->tl_vterm == NULL)
4993 continue;
4994 term_update_palette(term);
4995 }
4996}
4997
4998/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004999 * Called when option 'background' or 'termguicolors' was set,
5000 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02005001 */
5002 void
5003term_update_colors_all(void)
5004{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005005 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02005006
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005007 FOR_ALL_TERMS(term)
5008 {
5009 if (term->tl_vterm == NULL)
5010 continue;
5011 init_default_colors(term);
5012 vterm_state_set_default_colors(
5013 vterm_obtain_state(term->tl_vterm),
5014 &term->tl_default_color.fg,
5015 &term->tl_default_color.bg);
5016 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005017}
5018
5019/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005020 * Return the text to show for the buffer name and status.
5021 */
5022 char_u *
5023term_get_status_text(term_T *term)
5024{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005025 if (term->tl_status_text != NULL)
5026 return term->tl_status_text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005027
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005028 char_u *txt;
5029 size_t len;
5030 char_u *fname;
5031
5032 if (term->tl_normal_mode)
5033 {
5034 if (term_job_running(term))
5035 txt = (char_u *)_("Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005036 else
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005037 txt = (char_u *)_("Terminal-finished");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005038 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005039 else if (term->tl_title != NULL)
5040 txt = term->tl_title;
5041 else if (term_none_open(term))
5042 txt = (char_u *)_("active");
5043 else if (term_job_running(term))
5044 txt = (char_u *)_("running");
5045 else
5046 txt = (char_u *)_("finished");
5047 fname = buf_get_fname(term->tl_buffer);
5048 len = 9 + STRLEN(fname) + STRLEN(txt);
5049 term->tl_status_text = alloc(len);
5050 if (term->tl_status_text != NULL)
5051 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
5052 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005053 return term->tl_status_text;
5054}
5055
5056/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00005057 * Clear the cached value of the status text.
5058 */
5059 void
5060term_clear_status_text(term_T *term)
5061{
5062 VIM_CLEAR(term->tl_status_text);
5063}
5064
5065/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005066 * Mark references in jobs of terminals.
5067 */
5068 int
5069set_ref_in_term(int copyID)
5070{
5071 int abort = FALSE;
5072 term_T *term;
5073 typval_T tv;
5074
Bram Moolenaar75a1a942019-06-20 03:45:36 +02005075 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005076 if (term->tl_job != NULL)
5077 {
5078 tv.v_type = VAR_JOB;
5079 tv.vval.v_job = term->tl_job;
5080 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
5081 }
5082 return abort;
5083}
5084
5085/*
5086 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005087 * Returns NULL when the buffer is not for a terminal window and logs a message
5088 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005089 */
5090 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005091term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005092{
5093 buf_T *buf;
5094
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005095 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01005096 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005097 --emsg_off;
5098 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005099 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01005100 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005101 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005102 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005103 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005104 return buf;
5105}
5106
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005107 static void
5108clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005109{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005110 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005111 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
5112 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005113}
5114
5115 static void
5116dump_term_color(FILE *fd, VTermColor *color)
5117{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005118 int index;
5119
5120 if (VTERM_COLOR_IS_INDEXED(color))
5121 index = color->index + 1;
5122 else if (color->type == 0)
5123 // use RGB values
5124 index = 255;
5125 else
5126 // default color
5127 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005128 fprintf(fd, "%02x%02x%02x%d",
5129 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005130 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005131}
5132
5133/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005134 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01005135 *
5136 * Each screen cell in full is:
5137 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5138 * {characters} is a space for an empty cell
5139 * For a double-width character "+" is changed to "*" and the next cell is
5140 * skipped.
5141 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5142 * when "&" use the same as the previous cell.
5143 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5144 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5145 * {color-idx} is a number from 0 to 255
5146 *
5147 * Screen cell with same width, attributes and color as the previous one:
5148 * |{characters}
5149 *
5150 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5151 *
5152 * Repeating the previous screen cell:
5153 * @{count}
5154 */
5155 void
5156f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5157{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005158 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005159 term_T *term;
5160 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005161 int max_height = 0;
5162 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005163 stat_T st;
5164 FILE *fd;
5165 VTermPos pos;
5166 VTermScreen *screen;
5167 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005168 VTermState *state;
5169 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005170
5171 if (check_restricted() || check_secure())
5172 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005173
5174 if (in_vim9script()
5175 && (check_for_buffer_arg(argvars, 0) == FAIL
5176 || check_for_string_arg(argvars, 1) == FAIL
5177 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5178 return;
5179
5180 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005181 if (buf == NULL)
5182 return;
5183 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005184 if (term->tl_vterm == NULL)
5185 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005186 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005187 return;
5188 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005189
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005190 if (argvars[2].v_type != VAR_UNKNOWN)
5191 {
5192 dict_T *d;
5193
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005194 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005195 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005196 d = argvars[2].vval.v_dict;
5197 if (d != NULL)
5198 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005199 max_height = dict_get_number(d, "rows");
5200 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005201 }
5202 }
5203
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005204 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005205 if (fname == NULL)
5206 return;
5207 if (mch_stat((char *)fname, &st) >= 0)
5208 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005209 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005210 return;
5211 }
5212
Bram Moolenaard96ff162018-02-18 22:13:29 +01005213 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5214 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005215 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005216 return;
5217 }
5218
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005219 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005220
5221 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005222 state = vterm_obtain_state(term->tl_vterm);
5223 vterm_state_get_cursorpos(state, &cursor_pos);
5224
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005225 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5226 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005227 {
5228 int repeat = 0;
5229
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005230 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5231 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005232 {
5233 VTermScreenCell cell;
5234 int same_attr;
5235 int same_chars = TRUE;
5236 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005237 int is_cursor_pos = (pos.col == cursor_pos.col
5238 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005239
5240 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005241 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005242
5243 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5244 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005245 int c = cell.chars[i];
5246 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005247 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005248
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005249 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005250 if (i == 0)
5251 {
5252 c = (c == NUL) ? ' ' : c;
5253 pc = (pc == NUL) ? ' ' : pc;
5254 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005255 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005256 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005257 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005258 break;
5259 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005260 same_attr = vtermAttr2hl(&cell.attrs)
5261 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005262 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5263 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005264 if (same_chars && cell.width == prev_cell.width && same_attr
5265 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005266 {
5267 ++repeat;
5268 }
5269 else
5270 {
5271 if (repeat > 0)
5272 {
5273 fprintf(fd, "@%d", repeat);
5274 repeat = 0;
5275 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005276 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005277
5278 if (cell.chars[0] == NUL)
5279 fputs(" ", fd);
5280 else
5281 {
5282 char_u charbuf[10];
5283 int len;
5284
5285 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5286 && cell.chars[i] != NUL; ++i)
5287 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005288 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005289 fwrite(charbuf, len, 1, fd);
5290 }
5291 }
5292
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005293 // When only the characters differ we don't write anything, the
5294 // following "|", "@" or NL will indicate using the same
5295 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005296 if (cell.width != prev_cell.width || !same_attr)
5297 {
5298 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005299 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005300 else
5301 fputs("+", fd);
5302
5303 if (same_attr)
5304 {
5305 fputs("&", fd);
5306 }
5307 else
5308 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005309 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005310 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005311 fputs("&", fd);
5312 else
5313 {
5314 fputs("#", fd);
5315 dump_term_color(fd, &cell.fg);
5316 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005317 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005318 fputs("&", fd);
5319 else
5320 {
5321 fputs("#", fd);
5322 dump_term_color(fd, &cell.bg);
5323 }
5324 }
5325 }
5326
5327 prev_cell = cell;
5328 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005329
5330 if (cell.width == 2)
5331 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005332 }
5333 if (repeat > 0)
5334 fprintf(fd, "@%d", repeat);
5335 fputs("\n", fd);
5336 }
5337
5338 fclose(fd);
5339}
5340
5341/*
5342 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5343 */
5344 static void
5345dump_is_corrupt(garray_T *gap)
5346{
5347 ga_concat(gap, (char_u *)"CORRUPT");
5348}
5349
5350 static void
5351append_cell(garray_T *gap, cellattr_T *cell)
5352{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005353 if (ga_grow(gap, 1) == FAIL)
5354 return;
5355
5356 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5357 ++gap->ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005358}
5359
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005360 static void
5361clear_cellattr(cellattr_T *cell)
5362{
5363 CLEAR_FIELD(*cell);
5364 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5365 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5366}
5367
Bram Moolenaard96ff162018-02-18 22:13:29 +01005368/*
5369 * Read the dump file from "fd" and append lines to the current buffer.
5370 * Return the cell width of the longest line.
5371 */
5372 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005373read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005374{
5375 int c;
5376 garray_T ga_text;
5377 garray_T ga_cell;
5378 char_u *prev_char = NULL;
5379 int attr = 0;
5380 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005381 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005382 term_T *term = curbuf->b_term;
5383 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005384 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005385
5386 ga_init2(&ga_text, 1, 90);
5387 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005388 clear_cellattr(&cell);
5389 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005390 cursor_pos->row = -1;
5391 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005392
5393 c = fgetc(fd);
5394 for (;;)
5395 {
5396 if (c == EOF)
5397 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005398 if (c == '\r')
5399 {
5400 // DOS line endings? Ignore.
5401 c = fgetc(fd);
5402 }
5403 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005404 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005405 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005406 if (ga_text.ga_data == NULL)
5407 dump_is_corrupt(&ga_text);
5408 if (ga_grow(&term->tl_scrollback, 1) == OK)
5409 {
5410 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5411 + term->tl_scrollback.ga_len;
5412
5413 if (max_cells < ga_cell.ga_len)
5414 max_cells = ga_cell.ga_len;
5415 line->sb_cols = ga_cell.ga_len;
5416 line->sb_cells = ga_cell.ga_data;
5417 line->sb_fill_attr = term->tl_default_color;
5418 ++term->tl_scrollback.ga_len;
5419 ga_init(&ga_cell);
5420
5421 ga_append(&ga_text, NUL);
5422 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5423 ga_text.ga_len, FALSE);
5424 }
5425 else
5426 ga_clear(&ga_cell);
5427 ga_text.ga_len = 0;
5428
5429 c = fgetc(fd);
5430 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005431 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005432 {
5433 int prev_len = ga_text.ga_len;
5434
Bram Moolenaar9271d052018-02-25 21:39:46 +01005435 if (c == '>')
5436 {
5437 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005438 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005439 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5440 cursor_pos->col = ga_cell.ga_len;
5441 }
5442
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005443 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005444 c = fgetc(fd);
5445 if (c != EOF)
5446 ga_append(&ga_text, c);
5447 for (;;)
5448 {
5449 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005450 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005451 || c == EOF || c == '\n')
5452 break;
5453 ga_append(&ga_text, c);
5454 }
5455
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005456 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005457 vim_free(prev_char);
5458 if (ga_text.ga_data != NULL)
5459 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5460 ga_text.ga_len - prev_len);
5461
Bram Moolenaar9271d052018-02-25 21:39:46 +01005462 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005463 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005464 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005465 }
5466 else if (c == '+' || c == '*')
5467 {
5468 int is_bg;
5469
5470 cell.width = c == '+' ? 1 : 2;
5471
5472 c = fgetc(fd);
5473 if (c == '&')
5474 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005475 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005476 c = fgetc(fd);
5477 }
Keith Thompson184f71c2024-01-04 21:19:04 +01005478 else if (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005479 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005480 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005481 attr = 0;
Keith Thompson184f71c2024-01-04 21:19:04 +01005482 while (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005483 {
5484 attr = attr * 10 + (c - '0');
5485 c = fgetc(fd);
5486 }
5487 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005488
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005489 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005490 for (is_bg = 0; is_bg <= 1; ++is_bg)
5491 {
5492 if (c == '&')
5493 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005494 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005495 c = fgetc(fd);
5496 }
5497 else if (c == '#')
5498 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005499 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005500
5501 c = fgetc(fd);
5502 red = hex2nr(c);
5503 c = fgetc(fd);
5504 red = (red << 4) + hex2nr(c);
5505 c = fgetc(fd);
5506 green = hex2nr(c);
5507 c = fgetc(fd);
5508 green = (green << 4) + hex2nr(c);
5509 c = fgetc(fd);
5510 blue = hex2nr(c);
5511 c = fgetc(fd);
5512 blue = (blue << 4) + hex2nr(c);
5513 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005514 if (!SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005515 dump_is_corrupt(&ga_text);
Keith Thompson184f71c2024-01-04 21:19:04 +01005516 while (SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005517 {
5518 index = index * 10 + (c - '0');
5519 c = fgetc(fd);
5520 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005521 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005522 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005523 type = VTERM_COLOR_RGB;
5524 if (index == 0)
5525 {
5526 if (is_bg)
5527 type |= VTERM_COLOR_DEFAULT_BG;
5528 else
5529 type |= VTERM_COLOR_DEFAULT_FG;
5530 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005531 }
5532 else
5533 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005534 type = VTERM_COLOR_INDEXED;
5535 index -= 1;
5536 }
5537 if (is_bg)
5538 {
5539 cell.bg.type = type;
5540 cell.bg.red = red;
5541 cell.bg.green = green;
5542 cell.bg.blue = blue;
5543 cell.bg.index = index;
5544 }
5545 else
5546 {
5547 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005548 cell.fg.red = red;
5549 cell.fg.green = green;
5550 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005551 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005552 }
5553 }
5554 else
5555 dump_is_corrupt(&ga_text);
5556 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005557 }
5558 else
5559 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005560 }
5561 else
5562 dump_is_corrupt(&ga_text);
5563
5564 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005565 if (cell.width == 2)
5566 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005567 }
5568 else if (c == '@')
5569 {
5570 if (prev_char == NULL)
5571 dump_is_corrupt(&ga_text);
5572 else
5573 {
5574 int count = 0;
5575
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005576 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005577 for (;;)
5578 {
5579 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005580 if (!SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005581 break;
5582 count = count * 10 + (c - '0');
5583 }
5584
5585 while (count-- > 0)
5586 {
5587 ga_concat(&ga_text, prev_char);
5588 append_cell(&ga_cell, &cell);
5589 }
5590 }
5591 }
5592 else
5593 {
5594 dump_is_corrupt(&ga_text);
5595 c = fgetc(fd);
5596 }
5597 }
5598
5599 if (ga_text.ga_len > 0)
5600 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005601 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005602 dump_is_corrupt(&ga_text);
5603 ga_append(&ga_text, NUL);
5604 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5605 ga_text.ga_len, FALSE);
5606 }
5607
5608 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005609 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005610 vim_free(prev_char);
5611
5612 return max_cells;
5613}
5614
5615/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005616 * Return an allocated string with at least "text_width" "=" characters and
5617 * "fname" inserted in the middle.
5618 */
5619 static char_u *
5620get_separator(int text_width, char_u *fname)
5621{
5622 int width = MAX(text_width, curwin->w_width);
5623 char_u *textline;
5624 int fname_size;
5625 char_u *p = fname;
5626 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005627 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005628
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005629 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005630 if (textline == NULL)
5631 return NULL;
5632
5633 fname_size = vim_strsize(fname);
5634 if (fname_size < width - 8)
5635 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005636 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005637 width = MAX(text_width, fname_size + 8);
5638 }
5639 else if (fname_size > width - 8)
5640 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005641 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005642 p = gettail(fname);
5643 fname_size = vim_strsize(p);
5644 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005645 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005646 while (fname_size > width - 8)
5647 {
5648 p += (*mb_ptr2len)(p);
5649 fname_size = vim_strsize(p);
5650 }
5651
5652 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5653 textline[i] = '=';
5654 textline[i++] = ' ';
5655
5656 STRCPY(textline + i, p);
5657 off = STRLEN(textline);
5658 textline[off] = ' ';
5659 for (i = 1; i < (width - fname_size) / 2; ++i)
5660 textline[off + i] = '=';
5661 textline[off + i] = NUL;
5662
5663 return textline;
5664}
5665
5666/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005667 * Common for "term_dumpdiff()" and "term_dumpload()".
5668 */
5669 static void
5670term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5671{
5672 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005673 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005674 char_u buf1[NUMBUFLEN];
5675 char_u buf2[NUMBUFLEN];
5676 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005677 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005678 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005679 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005680 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005681 char_u *textline = NULL;
5682
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005683 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005684 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005685 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005686 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005687 if (fname1 == NULL || (do_diff && fname2 == NULL))
5688 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005689 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005690 return;
5691 }
5692 fd1 = mch_fopen((char *)fname1, READBIN);
5693 if (fd1 == NULL)
5694 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005695 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005696 return;
5697 }
5698 if (do_diff)
5699 {
5700 fd2 = mch_fopen((char *)fname2, READBIN);
5701 if (fd2 == NULL)
5702 {
5703 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005704 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005705 return;
5706 }
5707 }
5708
5709 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005710 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5711 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5712 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5713 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5714 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005715
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005716 if (opt.jo_term_name == NULL)
5717 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005718 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005719
Bram Moolenaar51e14382019-05-25 20:21:28 +02005720 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005721 if (fname_tofree != NULL)
5722 {
5723 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5724 opt.jo_term_name = fname_tofree;
5725 }
5726 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005727
Bram Moolenaar87abab92019-06-03 21:14:59 +02005728 if (opt.jo_bufnr_buf != NULL)
5729 {
5730 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5731
5732 // With "bufnr" argument: enter the window with this buffer and make it
5733 // empty.
5734 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005735 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005736 else
5737 {
5738 buf = curbuf;
5739 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005740 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005741 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005742 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005743 }
5744 }
5745 else
5746 // Create a new terminal window.
5747 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5748
Bram Moolenaard96ff162018-02-18 22:13:29 +01005749 if (buf != NULL && buf->b_term != NULL)
5750 {
5751 int i;
5752 linenr_T bot_lnum;
5753 linenr_T lnum;
5754 term_T *term = buf->b_term;
5755 int width;
5756 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005757 VTermPos cursor_pos1;
5758 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005759
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005760 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005761
Bram Moolenaard96ff162018-02-18 22:13:29 +01005762 rettv->vval.v_number = buf->b_fnum;
5763
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005764 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005765 width = read_dump_file(fd1, &cursor_pos1);
5766
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005767 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005768 if (cursor_pos1.row >= 0)
5769 {
5770 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5771 coladvance(cursor_pos1.col);
5772 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005773
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005774 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005775 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005776
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005777 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005778 if (!do_diff)
5779 goto theend;
5780
5781 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5782
Bram Moolenaar4a696342018-04-05 18:45:26 +02005783 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005784 if (textline == NULL)
5785 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005786 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5787 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5788 vim_free(textline);
5789
5790 textline = get_separator(width, fname2);
5791 if (textline == NULL)
5792 goto theend;
5793 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5794 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005795 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005796
5797 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005798 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005799 if (width2 > width)
5800 {
5801 vim_free(textline);
5802 textline = alloc(width2 + 1);
5803 if (textline == NULL)
5804 goto theend;
5805 width = width2;
5806 textline[width] = NUL;
5807 }
5808 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5809
5810 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5811 {
5812 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5813 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005814 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005815 for (i = 0; i < width; ++i)
5816 textline[i] = '-';
5817 }
5818 else
5819 {
5820 char_u *line1;
5821 char_u *line2;
5822 char_u *p1;
5823 char_u *p2;
5824 int col;
5825 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5826 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5827 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5828 ->sb_cells;
5829
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005830 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005831 line1 = vim_strsave(ml_get(lnum));
5832 if (line1 == NULL)
5833 break;
5834 p1 = line1;
5835
5836 line2 = ml_get(lnum + bot_lnum);
5837 p2 = line2;
5838 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5839 {
5840 int len1 = utfc_ptr2len(p1);
5841 int len2 = utfc_ptr2len(p2);
5842
5843 textline[col] = ' ';
5844 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005845 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005846 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005847 else if (lnum == cursor_pos1.row + 1
5848 && col == cursor_pos1.col
5849 && (cursor_pos1.row != cursor_pos2.row
5850 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005851 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005852 textline[col] = '>';
5853 else if (lnum == cursor_pos2.row + 1
5854 && col == cursor_pos2.col
5855 && (cursor_pos1.row != cursor_pos2.row
5856 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005857 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005858 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005859 else if (cellattr1 != NULL && cellattr2 != NULL)
5860 {
5861 if ((cellattr1 + col)->width
5862 != (cellattr2 + col)->width)
5863 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005864 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005865 &(cellattr2 + col)->fg))
5866 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005867 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005868 &(cellattr2 + col)->bg))
5869 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005870 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5871 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005872 textline[col] = 'a';
5873 }
5874 p1 += len1;
5875 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005876 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005877 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005878
5879 while (col < width)
5880 {
5881 if (*p1 == NUL && *p2 == NUL)
5882 textline[col] = '?';
5883 else if (*p1 == NUL)
5884 {
5885 textline[col] = '+';
5886 p2 += utfc_ptr2len(p2);
5887 }
5888 else
5889 {
5890 textline[col] = '-';
5891 p1 += utfc_ptr2len(p1);
5892 }
5893 ++col;
5894 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005895
5896 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005897 }
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 ++bot_lnum;
5902 }
5903
5904 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5905 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005906 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005907 for (i = 0; i < width; ++i)
5908 textline[i] = '+';
5909 if (add_empty_scrollback(term, &term->tl_default_color,
5910 term->tl_top_diff_rows) == OK)
5911 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5912 ++lnum;
5913 ++bot_lnum;
5914 }
5915
5916 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005917
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005918 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005919 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005920 }
5921
5922theend:
5923 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005924 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005925 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005926 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005927 fclose(fd2);
5928}
5929
5930/*
5931 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5932 * bottom files.
5933 * Return FAIL when this is not possible.
5934 */
5935 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005936term_swap_diff(void)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005937{
5938 term_T *term = curbuf->b_term;
5939 linenr_T line_count;
5940 linenr_T top_rows;
5941 linenr_T bot_rows;
5942 linenr_T bot_start;
5943 linenr_T lnum;
5944 char_u *p;
5945 sb_line_T *sb_line;
5946
5947 if (term == NULL
5948 || !term_is_finished(curbuf)
5949 || term->tl_top_diff_rows == 0
5950 || term->tl_scrollback.ga_len == 0)
5951 return FAIL;
5952
5953 line_count = curbuf->b_ml.ml_line_count;
5954 top_rows = term->tl_top_diff_rows;
5955 bot_rows = term->tl_bot_diff_rows;
5956 bot_start = line_count - bot_rows;
5957 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5958
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005959 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005960 for (lnum = 1; lnum <= top_rows; ++lnum)
5961 {
5962 p = vim_strsave(ml_get(1));
5963 if (p == NULL)
5964 return OK;
5965 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005966 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005967 vim_free(p);
5968 }
5969
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005970 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005971 for (lnum = 1; lnum <= bot_rows; ++lnum)
5972 {
5973 p = vim_strsave(ml_get(bot_start + lnum));
5974 if (p == NULL)
5975 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005976 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005977 ml_append(lnum - 1, p, 0, FALSE);
5978 vim_free(p);
5979 }
5980
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005981 // move top title to bottom
5982 p = vim_strsave(ml_get(bot_rows + 1));
5983 if (p == NULL)
5984 return OK;
5985 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005986 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005987 vim_free(p);
5988
5989 // move bottom title to top
5990 p = vim_strsave(ml_get(line_count - top_rows));
5991 if (p == NULL)
5992 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005993 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005994 ml_append(bot_rows, p, 0, FALSE);
5995 vim_free(p);
5996
Bram Moolenaard96ff162018-02-18 22:13:29 +01005997 if (top_rows == bot_rows)
5998 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005999 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01006000 for (lnum = 0; lnum < top_rows; ++lnum)
6001 {
6002 sb_line_T temp;
6003
6004 temp = *(sb_line + lnum);
6005 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
6006 *(sb_line + bot_start + lnum) = temp;
6007 }
6008 }
6009 else
6010 {
6011 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006012 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006013
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006014 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01006015 if (temp != NULL)
6016 {
6017 mch_memmove(temp, term->tl_scrollback.ga_data, size);
6018 mch_memmove(term->tl_scrollback.ga_data,
6019 temp + bot_start,
6020 sizeof(sb_line_T) * bot_rows);
6021 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
6022 temp + top_rows,
6023 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
6024 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
6025 + line_count - top_rows,
6026 temp,
6027 sizeof(sb_line_T) * top_rows);
6028 vim_free(temp);
6029 }
6030 }
6031
6032 term->tl_top_diff_rows = bot_rows;
6033 term->tl_bot_diff_rows = top_rows;
6034
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006035 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006036 return OK;
6037}
6038
6039/*
6040 * "term_dumpdiff(filename, filename, options)" function
6041 */
6042 void
6043f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
6044{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02006045 if (in_vim9script()
6046 && (check_for_string_arg(argvars, 0) == FAIL
6047 || check_for_string_arg(argvars, 1) == FAIL
6048 || check_for_opt_dict_arg(argvars, 2) == FAIL))
6049 return;
6050
Bram Moolenaard96ff162018-02-18 22:13:29 +01006051 term_load_dump(argvars, rettv, TRUE);
6052}
6053
6054/*
6055 * "term_dumpload(filename, options)" function
6056 */
6057 void
6058f_term_dumpload(typval_T *argvars, typval_T *rettv)
6059{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006060 if (in_vim9script()
6061 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02006062 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006063 return;
6064
Bram Moolenaard96ff162018-02-18 22:13:29 +01006065 term_load_dump(argvars, rettv, FALSE);
6066}
6067
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006068/*
6069 * "term_getaltscreen(buf)" function
6070 */
6071 void
6072f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
6073{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006074 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006075
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006076 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6077 return;
6078
6079 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006080 if (buf == NULL)
6081 return;
6082 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
6083}
6084
6085/*
6086 * "term_getattr(attr, name)" function
6087 */
6088 void
6089f_term_getattr(typval_T *argvars, typval_T *rettv)
6090{
6091 int attr;
6092 size_t i;
6093 char_u *name;
6094
6095 static struct {
6096 char *name;
6097 int attr;
6098 } attrs[] = {
6099 {"bold", HL_BOLD},
6100 {"italic", HL_ITALIC},
6101 {"underline", HL_UNDERLINE},
6102 {"strike", HL_STRIKETHROUGH},
6103 {"reverse", HL_INVERSE},
6104 };
6105
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02006106 if (in_vim9script()
6107 && (check_for_number_arg(argvars, 0) == FAIL
6108 || check_for_string_arg(argvars, 1) == FAIL))
6109 return;
6110
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006111 attr = tv_get_number(&argvars[0]);
6112 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006113 if (name == NULL)
6114 return;
6115
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02006116 if (attr > HL_ALL)
6117 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02006118 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006119 if (STRCMP(name, attrs[i].name) == 0)
6120 {
6121 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
6122 break;
6123 }
6124}
6125
6126/*
6127 * "term_getcursor(buf)" function
6128 */
6129 void
6130f_term_getcursor(typval_T *argvars, typval_T *rettv)
6131{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006132 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006133 term_T *term;
6134 list_T *l;
6135 dict_T *d;
6136
6137 if (rettv_list_alloc(rettv) == FAIL)
6138 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006139
6140 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6141 return;
6142
6143 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006144 if (buf == NULL)
6145 return;
6146 term = buf->b_term;
6147
6148 l = rettv->vval.v_list;
6149 list_append_number(l, term->tl_cursor_pos.row + 1);
6150 list_append_number(l, term->tl_cursor_pos.col + 1);
6151
6152 d = dict_alloc();
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00006153 if (d == NULL)
6154 return;
6155
6156 dict_add_number(d, "visible", term->tl_cursor_visible);
6157 dict_add_number(d, "blink", blink_state_is_inverted()
6158 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6159 dict_add_number(d, "shape", term->tl_cursor_shape);
6160 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
6161 list_append_dict(l, d);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006162}
6163
6164/*
6165 * "term_getjob(buf)" function
6166 */
6167 void
6168f_term_getjob(typval_T *argvars, typval_T *rettv)
6169{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006170 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006171
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006172 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6173 return;
6174
6175 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006176 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006177 {
Ernie Raela78eb252024-06-13 17:24:54 +02006178 if (in_vim9script())
6179 {
6180 rettv->v_type = VAR_JOB;
6181 rettv->vval.v_job = NULL;
6182 }
6183 else
6184 {
6185 rettv->v_type = VAR_SPECIAL;
6186 rettv->vval.v_number = VVAL_NULL;
6187 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006188 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006189 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006190
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006191 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006192 rettv->vval.v_job = buf->b_term->tl_job;
6193 if (rettv->vval.v_job != NULL)
6194 ++rettv->vval.v_job->jv_refcount;
6195}
6196
6197 static int
6198get_row_number(typval_T *tv, term_T *term)
6199{
6200 if (tv->v_type == VAR_STRING
6201 && tv->vval.v_string != NULL
6202 && STRCMP(tv->vval.v_string, ".") == 0)
6203 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006204 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006205}
6206
6207/*
6208 * "term_getline(buf, row)" function
6209 */
6210 void
6211f_term_getline(typval_T *argvars, typval_T *rettv)
6212{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006213 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006214 term_T *term;
6215 int row;
6216
6217 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006218
6219 if (in_vim9script()
6220 && (check_for_buffer_arg(argvars, 0) == FAIL
6221 || check_for_lnum_arg(argvars, 1) == FAIL))
6222 return;
6223
6224 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006225 if (buf == NULL)
6226 return;
6227 term = buf->b_term;
6228 row = get_row_number(&argvars[1], term);
6229
6230 if (term->tl_vterm == NULL)
6231 {
6232 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6233
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006234 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006235 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6236 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6237 }
6238 else
6239 {
6240 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6241 VTermRect rect;
6242 int len;
6243 char_u *p;
6244
6245 if (row < 0 || row >= term->tl_rows)
6246 return;
6247 len = term->tl_cols * MB_MAXBYTES + 1;
6248 p = alloc(len);
6249 if (p == NULL)
6250 return;
6251 rettv->vval.v_string = p;
6252
6253 rect.start_col = 0;
6254 rect.end_col = term->tl_cols;
6255 rect.start_row = row;
6256 rect.end_row = row + 1;
6257 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6258 }
6259}
6260
6261/*
6262 * "term_getscrolled(buf)" function
6263 */
6264 void
6265f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6266{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006267 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006268
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006269 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6270 return;
6271
6272 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006273 if (buf == NULL)
6274 return;
6275 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6276}
6277
6278/*
6279 * "term_getsize(buf)" function
6280 */
6281 void
6282f_term_getsize(typval_T *argvars, typval_T *rettv)
6283{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006284 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006285 list_T *l;
6286
6287 if (rettv_list_alloc(rettv) == FAIL)
6288 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006289
6290 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6291 return;
6292
6293 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006294 if (buf == NULL)
6295 return;
6296
6297 l = rettv->vval.v_list;
6298 list_append_number(l, buf->b_term->tl_rows);
6299 list_append_number(l, buf->b_term->tl_cols);
6300}
6301
6302/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006303 * "term_setsize(buf, rows, cols)" function
6304 */
6305 void
Dominique Pellé0268ff32024-07-28 21:12:20 +02006306f_term_setsize(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006307{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006308 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006309 term_T *term;
6310 varnumber_T rows, cols;
6311
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006312 if (in_vim9script()
6313 && (check_for_buffer_arg(argvars, 0) == FAIL
6314 || check_for_number_arg(argvars, 1) == FAIL
6315 || check_for_number_arg(argvars, 2) == FAIL))
6316 return;
6317
6318 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006319 if (buf == NULL)
6320 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006321 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006322 return;
6323 }
6324 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006325 return;
6326 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006327 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006328 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006329 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006330 cols = cols <= 0 ? term->tl_cols : cols;
6331 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006332 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006333
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006334 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006335 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6336 term_report_winsize(term, term->tl_rows, term->tl_cols);
6337}
6338
6339/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006340 * "term_getstatus(buf)" function
6341 */
6342 void
6343f_term_getstatus(typval_T *argvars, typval_T *rettv)
6344{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006345 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006346 term_T *term;
6347 char_u val[100];
6348
6349 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006350
6351 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6352 return;
6353
6354 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006355 if (buf == NULL)
6356 return;
6357 term = buf->b_term;
6358
6359 if (term_job_running(term))
6360 STRCPY(val, "running");
6361 else
6362 STRCPY(val, "finished");
6363 if (term->tl_normal_mode)
6364 STRCAT(val, ",normal");
6365 rettv->vval.v_string = vim_strsave(val);
6366}
6367
6368/*
6369 * "term_gettitle(buf)" function
6370 */
6371 void
6372f_term_gettitle(typval_T *argvars, typval_T *rettv)
6373{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006374 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006375
6376 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006377
6378 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6379 return;
6380
6381 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006382 if (buf == NULL)
6383 return;
6384
6385 if (buf->b_term->tl_title != NULL)
6386 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6387}
6388
6389/*
6390 * "term_gettty(buf)" function
6391 */
6392 void
6393f_term_gettty(typval_T *argvars, typval_T *rettv)
6394{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006395 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006396 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006397 int num = 0;
6398
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006399 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006400 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006401 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6402 return;
6403
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006404 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006405 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006406 if (buf == NULL)
6407 return;
6408 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006409 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006410
6411 switch (num)
6412 {
6413 case 0:
6414 if (buf->b_term->tl_job != NULL)
6415 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006416 break;
6417 case 1:
6418 if (buf->b_term->tl_job != NULL)
6419 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006420 break;
6421 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006422 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006423 return;
6424 }
6425 if (p != NULL)
6426 rettv->vval.v_string = vim_strsave(p);
6427}
6428
6429/*
6430 * "term_list()" function
6431 */
6432 void
6433f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6434{
6435 term_T *tp;
6436 list_T *l;
6437
6438 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6439 return;
6440
6441 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006442 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006443 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006444 if (list_append_number(l,
6445 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6446 return;
6447}
6448
6449/*
6450 * "term_scrape(buf, row)" function
6451 */
6452 void
6453f_term_scrape(typval_T *argvars, typval_T *rettv)
6454{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006455 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006456 VTermScreen *screen = NULL;
6457 VTermPos pos;
6458 list_T *l;
6459 term_T *term;
6460 char_u *p;
6461 sb_line_T *line;
6462
6463 if (rettv_list_alloc(rettv) == FAIL)
6464 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006465
6466 if (in_vim9script()
6467 && (check_for_buffer_arg(argvars, 0) == FAIL
6468 || check_for_lnum_arg(argvars, 1) == FAIL))
6469 return;
6470
6471 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006472 if (buf == NULL)
6473 return;
6474 term = buf->b_term;
6475
6476 l = rettv->vval.v_list;
6477 pos.row = get_row_number(&argvars[1], term);
6478
6479 if (term->tl_vterm != NULL)
6480 {
6481 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006482 if (screen == NULL) // can't really happen
6483 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006484 p = NULL;
6485 line = NULL;
6486 }
6487 else
6488 {
6489 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6490
6491 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6492 return;
6493 p = ml_get_buf(buf, lnum + 1, FALSE);
6494 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6495 }
6496
6497 for (pos.col = 0; pos.col < term->tl_cols; )
6498 {
6499 dict_T *dcell;
6500 int width;
6501 VTermScreenCellAttrs attrs;
6502 VTermColor fg, bg;
6503 char_u rgb[8];
6504 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6505 int off = 0;
6506 int i;
6507
6508 if (screen == NULL)
6509 {
6510 cellattr_T *cellattr;
6511 int len;
6512
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006513 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006514 if (pos.col >= line->sb_cols)
6515 break;
6516 cellattr = line->sb_cells + pos.col;
6517 width = cellattr->width;
6518 attrs = cellattr->attrs;
6519 fg = cellattr->fg;
6520 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006521 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006522 mch_memmove(mbs, p, len);
6523 mbs[len] = NUL;
6524 p += len;
6525 }
6526 else
6527 {
6528 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006529
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006530 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6531 break;
6532 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6533 {
6534 if (cell.chars[i] == 0)
6535 break;
6536 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6537 }
6538 mbs[off] = NUL;
6539 width = cell.width;
6540 attrs = cell.attrs;
6541 fg = cell.fg;
6542 bg = cell.bg;
6543 }
6544 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006545 if (dcell == NULL)
6546 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006547 list_append_dict(l, dcell);
6548
Bram Moolenaare0be1672018-07-08 16:50:37 +02006549 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006550
6551 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6552 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006553 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006554 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6555 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006556 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006557
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006558 dict_add_number(dcell, "attr",
6559 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006560 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006561
6562 ++pos.col;
6563 if (width == 2)
6564 ++pos.col;
6565 }
6566}
6567
6568/*
6569 * "term_sendkeys(buf, keys)" function
6570 */
6571 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006572f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006573{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006574 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006575 char_u *msg;
6576 term_T *term;
6577
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006578 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006579 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006580 || check_for_string_arg(argvars, 1) == FAIL))
6581 return;
6582
6583 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006584 if (buf == NULL)
6585 return;
6586
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006587 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006588 if (msg == NULL)
6589 return;
6590 term = buf->b_term;
6591 if (term->tl_vterm == NULL)
6592 return;
6593
6594 while (*msg != NUL)
6595 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006596 int c;
6597
6598 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6599 {
6600 c = TO_SPECIAL(msg[1], msg[2]);
6601 msg += 3;
6602 }
6603 else
6604 {
6605 c = PTR2CHAR(msg);
6606 msg += MB_CPTR2LEN(msg);
6607 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006608 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006609 }
6610}
6611
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006612#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6613/*
6614 * "term_getansicolors(buf)" function
6615 */
6616 void
6617f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6618{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006619 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006620 term_T *term;
6621 VTermState *state;
6622 VTermColor color;
6623 char_u hexbuf[10];
6624 int index;
6625 list_T *list;
6626
6627 if (rettv_list_alloc(rettv) == FAIL)
6628 return;
6629
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006630 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6631 return;
6632
6633 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006634 if (buf == NULL)
6635 return;
6636 term = buf->b_term;
6637 if (term->tl_vterm == NULL)
6638 return;
6639
6640 list = rettv->vval.v_list;
6641 state = vterm_obtain_state(term->tl_vterm);
6642 for (index = 0; index < 16; index++)
6643 {
6644 vterm_state_get_palette_color(state, index, &color);
6645 sprintf((char *)hexbuf, "#%02x%02x%02x",
6646 color.red, color.green, color.blue);
6647 if (list_append_string(list, hexbuf, 7) == FAIL)
6648 return;
6649 }
6650}
6651
6652/*
6653 * "term_setansicolors(buf, list)" function
6654 */
6655 void
6656f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6657{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006658 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006659 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006660 listitem_T *li;
6661 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006662
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006663 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006664 && (check_for_buffer_arg(argvars, 0) == FAIL
6665 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006666 return;
6667
6668 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006669 if (buf == NULL)
6670 return;
6671 term = buf->b_term;
6672 if (term->tl_vterm == NULL)
6673 return;
6674
Bram Moolenaard83392a2022-09-01 12:22:46 +01006675 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006676 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006677
LemonBoyb2b3acb2022-05-20 10:10:34 +01006678 if (argvars[1].vval.v_list->lv_first == &range_list_item
6679 || argvars[1].vval.v_list->lv_len != 16)
6680 {
Bram Moolenaar23919542023-05-05 22:12:22 +01006681 semsg(_(e_invalid_value_for_argument_str), "\"colors\"");
LemonBoyb2b3acb2022-05-20 10:10:34 +01006682 return;
6683 }
6684
6685 if (term->tl_palette == NULL)
6686 term->tl_palette = ALLOC_MULT(long_u, 16);
6687 if (term->tl_palette == NULL)
6688 return;
6689
6690 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6691 {
6692 char_u *color_name;
6693 guicolor_T guicolor;
6694
6695 color_name = tv_get_string_chk(&li->li_tv);
6696 if (color_name == NULL)
6697 return;
6698
6699 guicolor = GUI_GET_COLOR(color_name);
6700 if (guicolor == INVALCOLOR)
6701 {
6702 semsg(_(e_cannot_allocate_color_str), color_name);
6703 return;
6704 }
6705
6706 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6707 }
6708
6709 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006710}
6711#endif
6712
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006713/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006714 * "term_setapi(buf, api)" function
6715 */
6716 void
6717f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6718{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006719 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006720 term_T *term;
6721 char_u *api;
6722
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006723 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006724 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006725 || check_for_string_arg(argvars, 1) == FAIL))
6726 return;
6727
6728 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006729 if (buf == NULL)
6730 return;
6731 term = buf->b_term;
6732 vim_free(term->tl_api);
6733 api = tv_get_string_chk(&argvars[1]);
6734 if (api != NULL)
6735 term->tl_api = vim_strsave(api);
6736 else
6737 term->tl_api = NULL;
6738}
6739
6740/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006741 * "term_setrestore(buf, command)" function
6742 */
6743 void
6744f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6745{
6746#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006747 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006748 term_T *term;
6749 char_u *cmd;
6750
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006751 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006752 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006753 || check_for_string_arg(argvars, 1) == FAIL))
6754 return;
6755
6756 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006757 if (buf == NULL)
6758 return;
6759 term = buf->b_term;
6760 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006761 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006762 if (cmd != NULL)
6763 term->tl_command = vim_strsave(cmd);
6764 else
6765 term->tl_command = NULL;
6766#endif
6767}
6768
6769/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006770 * "term_setkill(buf, how)" function
6771 */
6772 void
6773f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6774{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006775 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006776 term_T *term;
6777 char_u *how;
6778
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006779 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006780 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006781 || check_for_string_arg(argvars, 1) == FAIL))
6782 return;
6783
6784 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006785 if (buf == NULL)
6786 return;
6787 term = buf->b_term;
6788 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006789 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006790 if (how != NULL)
6791 term->tl_kill = vim_strsave(how);
6792 else
6793 term->tl_kill = NULL;
6794}
6795
6796/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006797 * "term_start(command, options)" function
6798 */
6799 void
6800f_term_start(typval_T *argvars, typval_T *rettv)
6801{
6802 jobopt_T opt;
6803 buf_T *buf;
6804
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006805 if (in_vim9script()
6806 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6807 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6808 return;
6809
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006810 init_job_options(&opt);
6811 if (argvars[1].v_type != VAR_UNKNOWN
6812 && get_job_options(&argvars[1], &opt,
6813 JO_TIMEOUT_ALL + JO_STOPONEXIT
6814 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6815 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6816 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6817 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006818 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006819 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006820 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006821 return;
6822
Bram Moolenaar13568252018-03-16 20:46:58 +01006823 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006824
6825 if (buf != NULL && buf->b_term != NULL)
6826 rettv->vval.v_number = buf->b_fnum;
6827}
6828
6829/*
6830 * "term_wait" function
6831 */
6832 void
6833f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6834{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006835 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006836
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006837 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006838 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006839 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006840 return;
6841
6842 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006843 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006844 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006845 if (buf->b_term->tl_job == NULL)
6846 {
6847 ch_log(NULL, "term_wait(): no job to wait for");
6848 return;
6849 }
6850 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006851 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006852 return;
6853
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006854 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006855 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006856 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6857 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006858 // The job is dead, keep reading channel I/O until the channel is
6859 // closed. buf->b_term may become NULL if the terminal was closed while
6860 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006861 ch_log(NULL, "term_wait(): waiting for channel to close");
6862 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6863 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006864 term_flush_messages();
6865
Bram Moolenaard45aa552018-05-21 22:50:29 +02006866 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006867 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006868 // If the terminal is closed when the channel is closed the
6869 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006870 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006871 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6872 // came here from a close callback, only wait one time
6873 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006874 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006875
6876 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006877 }
6878 else
6879 {
6880 long wait = 10L;
6881
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006882 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006883
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006884 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006885 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006886 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006887 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006888
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006889 // Flushing messages on channels is hopefully sufficient.
6890 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006891 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006892 }
6893}
6894
6895/*
6896 * Called when a channel has sent all the lines to a terminal.
6897 * Send a CTRL-D to mark the end of the text.
6898 */
6899 void
6900term_send_eof(channel_T *ch)
6901{
6902 term_T *term;
6903
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006904 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006905 if (term->tl_job == ch->ch_job)
6906 {
6907 if (term->tl_eof_chars != NULL)
6908 {
6909 channel_send(ch, PART_IN, term->tl_eof_chars,
6910 (int)STRLEN(term->tl_eof_chars), NULL);
6911 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6912 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006913# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006914 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006915 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006916 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6917# endif
6918 }
6919}
6920
Bram Moolenaar113e1072019-01-20 15:30:40 +01006921#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006922 job_T *
6923term_getjob(term_T *term)
6924{
6925 return term != NULL ? term->tl_job : NULL;
6926}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006927#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006928
Bram Moolenaar4f974752019-02-17 17:44:42 +01006929# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006930
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006931///////////////////////////////////////
6932// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006933#ifdef PROTO
6934typedef int COORD;
6935typedef int DWORD;
6936typedef int HANDLE;
6937typedef int *DWORD_PTR;
6938typedef int HPCON;
6939typedef int HRESULT;
6940typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006941typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006942typedef int PSIZE_T;
6943typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006944typedef int BOOL;
6945# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006946#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006947
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006948HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6949HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6950HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006951BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6952BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6953void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006954
6955 static int
6956dyn_conpty_init(int verbose)
6957{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006958 static HMODULE hKerneldll = NULL;
6959 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006960 static struct
6961 {
6962 char *name;
6963 FARPROC *ptr;
6964 } conpty_entry[] =
6965 {
6966 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6967 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6968 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6969 {"InitializeProcThreadAttributeList",
6970 (FARPROC*)&pInitializeProcThreadAttributeList},
6971 {"UpdateProcThreadAttribute",
6972 (FARPROC*)&pUpdateProcThreadAttribute},
6973 {"DeleteProcThreadAttributeList",
6974 (FARPROC*)&pDeleteProcThreadAttributeList},
6975 {NULL, NULL}
6976 };
6977
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006978 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006979 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006980 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006981 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006982 return FAIL;
6983 }
6984
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006985 // No need to initialize twice.
6986 if (hKerneldll)
6987 return OK;
6988
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006989 hKerneldll = vimLoadLib("kernel32.dll");
6990 for (i = 0; conpty_entry[i].name != NULL
6991 && conpty_entry[i].ptr != NULL; ++i)
6992 {
6993 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6994 conpty_entry[i].name)) == NULL)
6995 {
6996 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006997 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006998 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006999 return FAIL;
7000 }
7001 }
7002
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007003 return OK;
7004}
7005
7006 static int
7007conpty_term_and_job_init(
7008 term_T *term,
7009 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007010 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007011 jobopt_T *opt,
7012 jobopt_T *orig_opt)
7013{
7014 WCHAR *cmd_wchar = NULL;
7015 WCHAR *cmd_wchar_copy = NULL;
7016 WCHAR *cwd_wchar = NULL;
7017 WCHAR *env_wchar = NULL;
7018 channel_T *channel = NULL;
7019 job_T *job = NULL;
7020 HANDLE jo = NULL;
7021 garray_T ga_cmd, ga_env;
7022 char_u *cmd = NULL;
7023 HRESULT hr;
7024 COORD consize;
7025 SIZE_T breq;
7026 PROCESS_INFORMATION proc_info;
7027 HANDLE i_theirs = NULL;
7028 HANDLE o_theirs = NULL;
7029 HANDLE i_ours = NULL;
7030 HANDLE o_ours = NULL;
7031
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007032 ga_init2(&ga_cmd, sizeof(char*), 20);
7033 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007034
7035 if (argvar->v_type == VAR_STRING)
7036 {
7037 cmd = argvar->vval.v_string;
7038 }
7039 else if (argvar->v_type == VAR_LIST)
7040 {
7041 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
7042 goto failed;
7043 cmd = ga_cmd.ga_data;
7044 }
7045 if (cmd == NULL || *cmd == NUL)
7046 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007047 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007048 goto failed;
7049 }
7050
7051 term->tl_arg0_cmd = vim_strsave(cmd);
7052
7053 cmd_wchar = enc_to_utf16(cmd, NULL);
7054
7055 if (cmd_wchar != NULL)
7056 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007057 // Request by CreateProcessW
7058 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007059 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007060 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
7061 }
7062
7063 ga_clear(&ga_cmd);
7064 if (cmd_wchar == NULL)
7065 goto failed;
7066 if (opt->jo_cwd != NULL)
7067 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
7068
7069 win32_build_env(opt->jo_env, &ga_env, TRUE);
7070 env_wchar = ga_env.ga_data;
7071
7072 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
7073 goto failed;
7074 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
7075 goto failed;
7076
7077 consize.X = term->tl_cols;
7078 consize.Y = term->tl_rows;
7079 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
7080 &term->tl_conpty);
7081 if (FAILED(hr))
7082 goto failed;
7083
7084 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
7085
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007086 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007087 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007088 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007089 if (!term->tl_siex.lpAttributeList)
7090 goto failed;
7091 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
7092 0, &breq))
7093 goto failed;
7094 if (!pUpdateProcThreadAttribute(
7095 term->tl_siex.lpAttributeList, 0,
7096 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
7097 sizeof(HPCON), NULL, NULL))
7098 goto failed;
7099
7100 channel = add_channel();
7101 if (channel == NULL)
7102 goto failed;
7103
7104 job = job_alloc();
7105 if (job == NULL)
7106 goto failed;
7107 if (argvar->v_type == VAR_STRING)
7108 {
7109 int argc;
7110
7111 build_argv_from_string(cmd, &job->jv_argv, &argc);
7112 }
7113 else
7114 {
7115 int argc;
7116
7117 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7118 }
7119
7120 if (opt->jo_set & JO_IN_BUF)
7121 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7122
7123 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
7124 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02007125 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007126 env_wchar, cwd_wchar,
7127 &term->tl_siex.StartupInfo, &proc_info))
7128 goto failed;
7129
7130 CloseHandle(i_theirs);
7131 CloseHandle(o_theirs);
7132
7133 channel_set_pipes(channel,
7134 (sock_T)i_ours,
7135 (sock_T)o_ours,
7136 (sock_T)o_ours);
7137
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007138 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007139 channel->ch_write_text_mode = TRUE;
7140
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007141 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007142 channel->ch_anonymous_pipe = TRUE;
7143
7144 jo = CreateJobObject(NULL, NULL);
7145 if (jo == NULL)
7146 goto failed;
7147
7148 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7149 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007150 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007151 CloseHandle(jo);
7152 jo = NULL;
7153 }
7154
7155 ResumeThread(proc_info.hThread);
7156 CloseHandle(proc_info.hThread);
7157
7158 vim_free(cmd_wchar);
7159 vim_free(cmd_wchar_copy);
7160 vim_free(cwd_wchar);
7161 vim_free(env_wchar);
7162
7163 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7164 goto failed;
7165
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007166#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007167 if (term_use_palette())
7168 {
7169 if (term->tl_palette != NULL)
7170 set_vterm_palette(term->tl_vterm, term->tl_palette);
7171 else
7172 init_vterm_ansi_colors(term->tl_vterm);
7173 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007174#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007175
7176 channel_set_job(channel, job, opt);
7177 job_set_options(job, opt);
7178
7179 job->jv_channel = channel;
7180 job->jv_proc_info = proc_info;
7181 job->jv_job_object = jo;
7182 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007183 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007184 ++job->jv_refcount;
7185 term->tl_job = job;
7186
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007187 // Redirecting stdout and stderr doesn't work at the job level. Instead
7188 // open the file here and handle it in. opt->jo_io was changed in
7189 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007190 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7191 {
7192 char_u *fname = opt->jo_io_name[PART_OUT];
7193
7194 ch_log(channel, "Opening output file %s", fname);
7195 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7196 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007197 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007198 }
7199
7200 return OK;
7201
7202failed:
7203 ga_clear(&ga_cmd);
7204 ga_clear(&ga_env);
7205 vim_free(cmd_wchar);
7206 vim_free(cmd_wchar_copy);
7207 vim_free(cwd_wchar);
7208 if (channel != NULL)
7209 channel_clear(channel);
7210 if (job != NULL)
7211 {
7212 job->jv_channel = NULL;
7213 job_cleanup(job);
7214 }
7215 term->tl_job = NULL;
7216 if (jo != NULL)
7217 CloseHandle(jo);
7218
7219 if (term->tl_siex.lpAttributeList != NULL)
7220 {
7221 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7222 vim_free(term->tl_siex.lpAttributeList);
7223 }
7224 term->tl_siex.lpAttributeList = NULL;
7225 if (o_theirs != NULL)
7226 CloseHandle(o_theirs);
7227 if (o_ours != NULL)
7228 CloseHandle(o_ours);
7229 if (i_ours != NULL)
7230 CloseHandle(i_ours);
7231 if (i_theirs != NULL)
7232 CloseHandle(i_theirs);
7233 if (term->tl_conpty != NULL)
7234 pClosePseudoConsole(term->tl_conpty);
7235 term->tl_conpty = NULL;
7236 return FAIL;
7237}
7238
7239 static void
7240conpty_term_report_winsize(term_T *term, int rows, int cols)
7241{
7242 COORD consize;
7243
7244 consize.X = cols;
7245 consize.Y = rows;
7246 pResizePseudoConsole(term->tl_conpty, consize);
7247}
7248
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007249 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007250term_free_conpty(term_T *term)
7251{
7252 if (term->tl_siex.lpAttributeList != NULL)
7253 {
7254 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7255 vim_free(term->tl_siex.lpAttributeList);
7256 }
7257 term->tl_siex.lpAttributeList = NULL;
7258 if (term->tl_conpty != NULL)
7259 pClosePseudoConsole(term->tl_conpty);
7260 term->tl_conpty = NULL;
7261}
7262
7263 int
7264use_conpty(void)
7265{
7266 return has_conpty;
7267}
7268
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007269# ifndef PROTO
7270
7271#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7272#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007273#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007274
7275void* (*winpty_config_new)(UINT64, void*);
7276void* (*winpty_open)(void*, void*);
7277void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7278BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7279void (*winpty_config_set_mouse_mode)(void*, int);
7280void (*winpty_config_set_initial_size)(void*, int, int);
7281LPCWSTR (*winpty_conin_name)(void*);
7282LPCWSTR (*winpty_conout_name)(void*);
7283LPCWSTR (*winpty_conerr_name)(void*);
7284void (*winpty_free)(void*);
7285void (*winpty_config_free)(void*);
7286void (*winpty_spawn_config_free)(void*);
7287void (*winpty_error_free)(void*);
7288LPCWSTR (*winpty_error_msg)(void*);
7289BOOL (*winpty_set_size)(void*, int, int, void*);
7290HANDLE (*winpty_agent_process)(void*);
7291
7292#define WINPTY_DLL "winpty.dll"
7293
7294static HINSTANCE hWinPtyDLL = NULL;
7295# endif
7296
7297 static int
7298dyn_winpty_init(int verbose)
7299{
7300 int i;
7301 static struct
7302 {
7303 char *name;
7304 FARPROC *ptr;
7305 } winpty_entry[] =
7306 {
7307 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7308 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7309 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7310 {"winpty_config_set_mouse_mode",
7311 (FARPROC*)&winpty_config_set_mouse_mode},
7312 {"winpty_config_set_initial_size",
7313 (FARPROC*)&winpty_config_set_initial_size},
7314 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7315 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7316 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7317 {"winpty_free", (FARPROC*)&winpty_free},
7318 {"winpty_open", (FARPROC*)&winpty_open},
7319 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7320 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7321 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7322 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7323 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7324 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7325 {NULL, NULL}
7326 };
7327
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007328 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007329 if (hWinPtyDLL)
7330 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007331 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7332 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007333 if (*p_winptydll != NUL)
7334 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7335 if (!hWinPtyDLL)
7336 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7337 if (!hWinPtyDLL)
7338 {
7339 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007340 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007341 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7342 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007343 return FAIL;
7344 }
7345 for (i = 0; winpty_entry[i].name != NULL
7346 && winpty_entry[i].ptr != NULL; ++i)
7347 {
7348 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7349 winpty_entry[i].name)) == NULL)
7350 {
7351 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007352 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007353 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007354 return FAIL;
7355 }
7356 }
7357
7358 return OK;
7359}
7360
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007361 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007362winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007363 term_T *term,
7364 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007365 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007366 jobopt_T *opt,
7367 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007368{
7369 WCHAR *cmd_wchar = NULL;
7370 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007371 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007372 channel_T *channel = NULL;
7373 job_T *job = NULL;
7374 DWORD error;
7375 HANDLE jo = NULL;
7376 HANDLE child_process_handle;
7377 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007378 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007379 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007380 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007381 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007382
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007383 ga_init2(&ga_cmd, sizeof(char*), 20);
7384 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007385
7386 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007387 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007388 cmd = argvar->vval.v_string;
7389 }
7390 else if (argvar->v_type == VAR_LIST)
7391 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007392 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007393 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007394 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007395 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007396 if (cmd == NULL || *cmd == NUL)
7397 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007398 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007399 goto failed;
7400 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007401
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007402 term->tl_arg0_cmd = vim_strsave(cmd);
7403
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007404 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007405 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007406 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007407 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007408 if (opt->jo_cwd != NULL)
7409 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007410
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007411 win32_build_env(opt->jo_env, &ga_env, TRUE);
7412 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007413
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007414 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7415 if (term->tl_winpty_config == NULL)
7416 goto failed;
7417
7418 winpty_config_set_mouse_mode(term->tl_winpty_config,
7419 WINPTY_MOUSE_MODE_FORCE);
7420 winpty_config_set_initial_size(term->tl_winpty_config,
7421 term->tl_cols, term->tl_rows);
7422 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7423 if (term->tl_winpty == NULL)
7424 goto failed;
7425
7426 spawn_config = winpty_spawn_config_new(
7427 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7428 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7429 NULL,
7430 cmd_wchar,
7431 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007432 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007433 &winpty_err);
7434 if (spawn_config == NULL)
7435 goto failed;
7436
7437 channel = add_channel();
7438 if (channel == NULL)
7439 goto failed;
7440
7441 job = job_alloc();
7442 if (job == NULL)
7443 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007444 if (argvar->v_type == VAR_STRING)
7445 {
7446 int argc;
7447
7448 build_argv_from_string(cmd, &job->jv_argv, &argc);
7449 }
7450 else
7451 {
7452 int argc;
7453
7454 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7455 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007456
7457 if (opt->jo_set & JO_IN_BUF)
7458 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7459
7460 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7461 &child_thread_handle, &error, &winpty_err))
7462 goto failed;
7463
7464 channel_set_pipes(channel,
7465 (sock_T)CreateFileW(
7466 winpty_conin_name(term->tl_winpty),
7467 GENERIC_WRITE, 0, NULL,
7468 OPEN_EXISTING, 0, NULL),
7469 (sock_T)CreateFileW(
7470 winpty_conout_name(term->tl_winpty),
7471 GENERIC_READ, 0, NULL,
7472 OPEN_EXISTING, 0, NULL),
7473 (sock_T)CreateFileW(
7474 winpty_conerr_name(term->tl_winpty),
7475 GENERIC_READ, 0, NULL,
7476 OPEN_EXISTING, 0, NULL));
7477
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007478 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007479 channel->ch_write_text_mode = TRUE;
7480
7481 jo = CreateJobObject(NULL, NULL);
7482 if (jo == NULL)
7483 goto failed;
7484
7485 if (!AssignProcessToJobObject(jo, child_process_handle))
7486 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007487 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007488 CloseHandle(jo);
7489 jo = NULL;
7490 }
7491
7492 winpty_spawn_config_free(spawn_config);
7493 vim_free(cmd_wchar);
7494 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007495 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007496
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007497 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7498 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007499
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007500#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007501 if (term_use_palette())
7502 {
7503 if (term->tl_palette != NULL)
7504 set_vterm_palette(term->tl_vterm, term->tl_palette);
7505 else
7506 init_vterm_ansi_colors(term->tl_vterm);
7507 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007508#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007509
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007510 channel_set_job(channel, job, opt);
7511 job_set_options(job, opt);
7512
7513 job->jv_channel = channel;
7514 job->jv_proc_info.hProcess = child_process_handle;
7515 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7516 job->jv_job_object = jo;
7517 job->jv_status = JOB_STARTED;
7518 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007519 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007520 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007521 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007522 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007523 ++job->jv_refcount;
7524 term->tl_job = job;
7525
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007526 // Redirecting stdout and stderr doesn't work at the job level. Instead
7527 // open the file here and handle it in. opt->jo_io was changed in
7528 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007529 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7530 {
7531 char_u *fname = opt->jo_io_name[PART_OUT];
7532
7533 ch_log(channel, "Opening output file %s", fname);
7534 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7535 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007536 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007537 }
7538
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007539 return OK;
7540
7541failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007542 ga_clear(&ga_cmd);
7543 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007544 vim_free(cmd_wchar);
7545 vim_free(cwd_wchar);
7546 if (spawn_config != NULL)
7547 winpty_spawn_config_free(spawn_config);
7548 if (channel != NULL)
7549 channel_clear(channel);
7550 if (job != NULL)
7551 {
7552 job->jv_channel = NULL;
7553 job_cleanup(job);
7554 }
7555 term->tl_job = NULL;
7556 if (jo != NULL)
7557 CloseHandle(jo);
7558 if (term->tl_winpty != NULL)
7559 winpty_free(term->tl_winpty);
7560 term->tl_winpty = NULL;
7561 if (term->tl_winpty_config != NULL)
7562 winpty_config_free(term->tl_winpty_config);
7563 term->tl_winpty_config = NULL;
7564 if (winpty_err != NULL)
7565 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007566 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007567 (short_u *)winpty_error_msg(winpty_err), NULL);
7568
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007569 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007570 winpty_error_free(winpty_err);
7571 }
7572 return FAIL;
7573}
7574
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007575/*
7576 * Create a new terminal of "rows" by "cols" cells.
7577 * Store a reference in "term".
7578 * Return OK or FAIL.
7579 */
7580 static int
7581term_and_job_init(
7582 term_T *term,
7583 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007584 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007585 jobopt_T *opt,
7586 jobopt_T *orig_opt)
7587{
7588 int use_winpty = FALSE;
7589 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007590 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007591
7592 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7593 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7594
7595 if (!has_winpty && !has_conpty)
7596 // If neither is available give the errors for winpty, since when
7597 // conpty is not available it can't be installed either.
7598 return dyn_winpty_init(TRUE);
7599
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007600 if (opt->jo_tty_type != NUL)
7601 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007602
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007603 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007604 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007605 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007606 use_conpty = TRUE;
7607 else if (has_winpty)
7608 use_winpty = TRUE;
7609 // else: error
7610 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007611 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007612 {
7613 if (has_winpty)
7614 use_winpty = TRUE;
7615 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007616 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007617 {
7618 if (has_conpty)
7619 use_conpty = TRUE;
7620 else
7621 return dyn_conpty_init(TRUE);
7622 }
7623
7624 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007625 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007626
7627 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007628 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007629
7630 // error
7631 return dyn_winpty_init(TRUE);
7632}
7633
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007634 static int
7635create_pty_only(term_T *term, jobopt_T *options)
7636{
7637 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7638 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7639 char in_name[80], out_name[80];
7640 channel_T *channel = NULL;
7641
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007642 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7643 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007644
7645 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7646 GetCurrentProcessId(),
7647 curbuf->b_fnum);
7648 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7649 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7650 PIPE_UNLIMITED_INSTANCES,
7651 0, 0, NMPWAIT_NOWAIT, NULL);
7652 if (hPipeIn == INVALID_HANDLE_VALUE)
7653 goto failed;
7654
7655 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7656 GetCurrentProcessId(),
7657 curbuf->b_fnum);
7658 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7659 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7660 PIPE_UNLIMITED_INSTANCES,
7661 0, 0, 0, NULL);
7662 if (hPipeOut == INVALID_HANDLE_VALUE)
7663 goto failed;
7664
7665 ConnectNamedPipe(hPipeIn, NULL);
7666 ConnectNamedPipe(hPipeOut, NULL);
7667
7668 term->tl_job = job_alloc();
7669 if (term->tl_job == NULL)
7670 goto failed;
7671 ++term->tl_job->jv_refcount;
7672
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007673 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007674 term->tl_job->jv_status = JOB_FINISHED;
7675
7676 channel = add_channel();
7677 if (channel == NULL)
7678 goto failed;
7679 term->tl_job->jv_channel = channel;
7680 channel->ch_keep_open = TRUE;
7681 channel->ch_named_pipe = TRUE;
7682
7683 channel_set_pipes(channel,
7684 (sock_T)hPipeIn,
7685 (sock_T)hPipeOut,
7686 (sock_T)hPipeOut);
7687 channel_set_job(channel, term->tl_job, options);
7688 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7689 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7690
7691 return OK;
7692
7693failed:
7694 if (hPipeIn != NULL)
7695 CloseHandle(hPipeIn);
7696 if (hPipeOut != NULL)
7697 CloseHandle(hPipeOut);
7698 return FAIL;
7699}
7700
7701/*
7702 * Free the terminal emulator part of "term".
7703 */
7704 static void
7705term_free_vterm(term_T *term)
7706{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007707 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007708 if (term->tl_winpty != NULL)
7709 winpty_free(term->tl_winpty);
7710 term->tl_winpty = NULL;
7711 if (term->tl_winpty_config != NULL)
7712 winpty_config_free(term->tl_winpty_config);
7713 term->tl_winpty_config = NULL;
7714 if (term->tl_vterm != NULL)
7715 vterm_free(term->tl_vterm);
7716 term->tl_vterm = NULL;
7717}
7718
7719/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007720 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007721 */
7722 static void
7723term_report_winsize(term_T *term, int rows, int cols)
7724{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007725 if (term->tl_conpty)
7726 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007727 if (term->tl_winpty)
7728 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7729}
7730
7731 int
7732terminal_enabled(void)
7733{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007734 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007735}
7736
7737# else
7738
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007739///////////////////////////////////////
7740// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007741
7742/*
7743 * Create a new terminal of "rows" by "cols" cells.
7744 * Start job for "cmd".
7745 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007746 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007747 * Return OK or FAIL.
7748 */
7749 static int
7750term_and_job_init(
7751 term_T *term,
7752 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007753 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007754 jobopt_T *opt,
7755 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007756{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007757 term->tl_arg0_cmd = NULL;
7758
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007759 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7760 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007761
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007762#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007763 if (term_use_palette())
7764 {
7765 if (term->tl_palette != NULL)
7766 set_vterm_palette(term->tl_vterm, term->tl_palette);
7767 else
7768 init_vterm_ansi_colors(term->tl_vterm);
7769 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007770#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007771
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007772 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007773 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007774 if (term->tl_job != NULL)
7775 ++term->tl_job->jv_refcount;
7776
7777 return term->tl_job != NULL
7778 && term->tl_job->jv_channel != NULL
7779 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7780}
7781
7782 static int
7783create_pty_only(term_T *term, jobopt_T *opt)
7784{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007785 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7786 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007787
7788 term->tl_job = job_alloc();
7789 if (term->tl_job == NULL)
7790 return FAIL;
7791 ++term->tl_job->jv_refcount;
7792
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007793 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007794 term->tl_job->jv_status = JOB_FINISHED;
7795
7796 return mch_create_pty_channel(term->tl_job, opt);
7797}
7798
7799/*
7800 * Free the terminal emulator part of "term".
7801 */
7802 static void
7803term_free_vterm(term_T *term)
7804{
7805 if (term->tl_vterm != NULL)
7806 vterm_free(term->tl_vterm);
7807 term->tl_vterm = NULL;
7808}
7809
7810/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007811 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007812 */
7813 static void
7814term_report_winsize(term_T *term, int rows, int cols)
7815{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007816 // Use an ioctl() to report the new window size to the job.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007817 if (term->tl_job == NULL || term->tl_job->jv_channel == NULL)
7818 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007819
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007820 int fd = -1;
7821 int part;
7822
7823 for (part = PART_OUT; part < PART_COUNT; ++part)
7824 {
7825 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
7826 if (mch_isatty(fd))
7827 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007828 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007829 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7830 mch_signal_job(term->tl_job, (char_u *)"winch");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007831}
7832
7833# endif
7834
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007835#endif // FEAT_TERMINAL