blob: 921b234de557528b973fbc2ba48f0ed0474971ea [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 {
Yegappan Lakshmanan562610c2025-05-04 21:05:51 +020056 VTermScreenCellAttrs attrs;
57 char width;
58 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
Christian Brabandt991657e2024-10-15 20:31:14 +0200449 pos_T save_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200450
451 if (check_restricted() || check_secure())
452 return NULL;
Bram Moolenaare5b44862021-05-30 13:54:03 +0200453 if (cmdwin_type != 0)
454 {
455 emsg(_(e_cannot_open_terminal_from_command_line_window));
456 return NULL;
457 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200458
459 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
460 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
461 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100462 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
463 || (argvar != NULL
464 && argvar->v_type == VAR_LIST
465 && argvar->vval.v_list != NULL
466 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200467 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000468 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200469 return NULL;
470 }
471
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200472 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200473 if (term == NULL)
474 return NULL;
475 term->tl_dirty_row_end = MAX_ROW;
476 term->tl_cursor_visible = TRUE;
477 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
478 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100479#ifdef FEAT_GUI
480 term->tl_system = (flags & TERM_START_SYSTEM);
481#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200482 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100483 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200484 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200485
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200486 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200487 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200488 if (opt->jo_curwin)
489 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100490 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100491 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200492 {
493 no_write_message();
494 vim_free(term);
495 return NULL;
496 }
497 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200498 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
499 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
500 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200501 {
502 vim_free(term);
503 return NULL;
504 }
505 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100506 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200507 {
508 buf_T *buf;
509
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100510 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100511 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200512 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
513 BLN_NEW | BLN_LISTED);
514 if (buf == NULL || ml_open(buf) == FAIL)
515 {
516 vim_free(term);
517 return NULL;
518 }
519 old_curbuf = curbuf;
520 --curbuf->b_nwindows;
521 curbuf = buf;
Christian Brabandt991657e2024-10-15 20:31:14 +0200522 save_cursor = curwin->w_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200523 curwin->w_buffer = buf;
524 ++curbuf->b_nwindows;
525 }
526 else
527 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100528 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200529 split_ea.cmdidx = CMD_new;
530 split_ea.cmd = (char_u *)"new";
531 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100532 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200533 {
534 split_ea.line2 = opt->jo_term_rows;
535 split_ea.addr_count = 1;
536 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100537 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200538 {
539 split_ea.line2 = opt->jo_term_cols;
540 split_ea.addr_count = 1;
541 }
542
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200543 int cmod_split_modified = FALSE;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100544 if (vertical)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200545 {
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200546 if (!(cmdmod.cmod_split & WSP_VERT))
547 cmod_split_modified = TRUE;
Bram Moolenaare1004402020-10-24 20:49:43 +0200548 cmdmod.cmod_split |= WSP_VERT;
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200549 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200550 ex_splitview(&split_ea);
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200551 if (cmod_split_modified)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200552 cmdmod.cmod_split &= ~WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200553 if (curwin == old_curwin)
554 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100555 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200556 vim_free(term);
557 return NULL;
558 }
559 }
560 term->tl_buffer = curbuf;
561 curbuf->b_term = term;
562
563 if (!opt->jo_hidden)
564 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100565 // Only one size was taken care of with :new, do the other one. With
566 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100567 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100569 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200570 win_setwidth(opt->jo_term_cols);
571 }
572
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100573 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200574 term->tl_next = first_term;
575 first_term = term;
576
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100577 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
578
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200579 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100580 {
581 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200582 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100583 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100584 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100585 {
586 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100587 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100588 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200589 else
590 {
591 int i;
592 size_t len;
593 char_u *cmd, *p;
594
595 if (argvar->v_type == VAR_STRING)
596 {
597 cmd = argvar->vval.v_string;
598 if (cmd == NULL)
599 cmd = (char_u *)"";
600 else if (STRCMP(cmd, "NONE") == 0)
601 cmd = (char_u *)"pty";
602 }
603 else if (argvar->v_type != VAR_LIST
604 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100605 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100606 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200607 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
608 cmd = (char_u*)"";
609
610 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200611 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200612
613 for (i = 0; p != NULL; ++i)
614 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100615 // Prepend a ! to the command name to avoid the buffer name equals
616 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200617 if (i == 0)
618 vim_snprintf((char *)p, len, "!%s", cmd);
619 else
620 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
621 if (buflist_findname(p) == NULL)
622 {
623 vim_free(curbuf->b_ffname);
624 curbuf->b_ffname = p;
625 break;
626 }
627 }
628 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100629 vim_free(curbuf->b_sfname);
630 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200631 curbuf->b_fname = curbuf->b_ffname;
632
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100633 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
634
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200635 if (opt->jo_term_opencmd != NULL)
636 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
637
638 if (opt->jo_eof_chars != NULL)
639 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
640
641 set_string_option_direct((char_u *)"buftype", -1,
642 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200643 // Avoid that 'buftype' is reset when this buffer is entered.
644 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200645
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100646 // Mark the buffer as not modifiable. It can only be made modifiable after
647 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200648 curbuf->b_p_ma = FALSE;
649
Bram Moolenaarb936b792020-09-04 18:34:09 +0200650 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100651#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200652 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
653#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200654 setup_job_options(opt, term->tl_rows, term->tl_cols);
655
Bram Moolenaar13568252018-03-16 20:46:58 +0100656 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100657 return curbuf;
658
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100659#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100660 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100661 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100662 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100663 else if (argvar->v_type == VAR_STRING)
664 {
665 char_u *cmd = argvar->vval.v_string;
666
667 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
668 term->tl_command = vim_strsave(cmd);
669 }
670 else if (argvar->v_type == VAR_LIST
671 && argvar->vval.v_list != NULL
672 && argvar->vval.v_list->lv_len > 0)
673 {
674 garray_T ga;
675 listitem_T *item;
676
677 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200678 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100679 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100680 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100681 char_u *p;
682
683 if (s == NULL)
684 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100685 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100686 if (p == NULL)
687 break;
688 ga_concat(&ga, p);
689 vim_free(p);
690 ga_append(&ga, ' ');
691 }
692 if (item == NULL)
693 {
694 ga_append(&ga, NUL);
695 term->tl_command = ga.ga_data;
696 }
697 else
698 ga_clear(&ga);
699 }
700#endif
701
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100702 if (opt->jo_term_kill != NULL)
703 {
704 char_u *p = skiptowhite(opt->jo_term_kill);
705
706 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
707 }
708
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200709 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100710 {
711 char_u *p = skiptowhite(opt->jo_term_api);
712
713 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
714 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200715 else
716 term->tl_api = vim_strsave((char_u *)"Tapi_");
717
Bram Moolenaar83d47902020-03-26 20:34:00 +0100718 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
719 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
720
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100721#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100722 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
723 if (opt->jo_set2 & JO2_ANSI_COLORS)
724 {
725 term->tl_palette = ALLOC_MULT(long_u, 16);
726 if (term->tl_palette == NULL)
727 {
728 vim_free(term);
729 return NULL;
730 }
731 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
732 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100733#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100734
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100735 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100736 if (argv == NULL
737 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200738 && argvar->vval.v_string != NULL
739 && STRCMP(argvar->vval.v_string, "NONE") == 0)
740 res = create_pty_only(term, opt);
741 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200742 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200743
744 newbuf = curbuf;
745 if (res == OK)
746 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100747 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200748 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
749 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100750#ifdef FEAT_GUI
751 if (term->tl_system)
752 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100753 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100754 term->tl_toprow = msg_row + 1;
755 term->tl_dirty_row_end = 0;
756 }
757#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200758
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100759 // Make sure we don't get stuck on sending keys to the job, it leads to
760 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200761 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
762
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200763 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200764 {
765 --curbuf->b_nwindows;
766 curbuf = old_curbuf;
767 curwin->w_buffer = curbuf;
Christian Brabandt991657e2024-10-15 20:31:14 +0200768 curwin->w_cursor = save_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200769 ++curbuf->b_nwindows;
770 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000771 else if (vgetc_busy
772#ifdef FEAT_TIMERS
773 || timer_busy
774#endif
775 || input_busy)
776 {
777 char_u ignore[4];
778
779 // When waiting for input need to return and possibly end up in
780 // terminal_loop() instead.
781 ignore[0] = K_SPECIAL;
782 ignore[1] = KS_EXTRA;
783 ignore[2] = KE_IGNORE;
784 ignore[3] = NUL;
785 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
786 typebuf_was_filled = TRUE;
787 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788 }
789 else
790 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100791 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200792 return NULL;
793 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100794
Bram Moolenaar13568252018-03-16 20:46:58 +0100795 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200796 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
797 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200798 return newbuf;
799}
800
801/*
802 * ":terminal": open a terminal window and execute a job in it.
803 */
804 void
805ex_terminal(exarg_T *eap)
806{
807 typval_T argvar[2];
808 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100809 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200810 char_u *cmd;
811 char_u *tofree = NULL;
812
813 init_job_options(&opt);
814
815 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100816 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200817 {
818 char_u *p, *ep;
819
820 cmd += 2;
821 p = skiptowhite(cmd);
822 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200823 if (ep != NULL)
824 {
825 if (ep < p)
826 p = ep;
827 else
828 ep = NULL;
829 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200830
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200831 // Note: Keep this in sync with get_terminalopt_name.
832
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200833# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
834 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
835 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200836 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200837 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100838 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200839 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200840 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200841 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200842 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200843 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200844 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200845 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100846 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100847 else if (OPTARG_HAS("shell"))
848 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200849 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100850 {
851 opt.jo_set2 |= JO2_TERM_KILL;
852 opt.jo_term_kill = ep + 1;
853 p = skiptowhite(cmd);
854 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200855 else if (OPTARG_HAS("api"))
856 {
857 opt.jo_set2 |= JO2_TERM_API;
858 if (ep != NULL)
859 {
860 opt.jo_term_api = ep + 1;
861 p = skiptowhite(cmd);
862 }
863 else
864 opt.jo_term_api = NULL;
865 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100866 else if (OPTARG_HAS("rows") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200867 {
868 opt.jo_set2 |= JO2_TERM_ROWS;
869 opt.jo_term_rows = atoi((char *)ep + 1);
870 p = skiptowhite(cmd);
871 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100872 else if (OPTARG_HAS("cols") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200873 {
874 opt.jo_set2 |= JO2_TERM_COLS;
875 opt.jo_term_cols = atoi((char *)ep + 1);
876 p = skiptowhite(cmd);
877 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200878 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200879 {
880 char_u *buf = NULL;
881 char_u *keys;
882
Bram Moolenaar21109272020-01-30 16:27:20 +0100883 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200884 p = skiptowhite(cmd);
885 *p = NUL;
zeertzjq7e0bae02023-08-11 23:15:38 +0200886 keys = replace_termcodes(ep + 1, &buf, 0,
Bram Moolenaar459fd782019-10-13 16:43:39 +0200887 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200888 opt.jo_set2 |= JO2_EOF_CHARS;
889 opt.jo_eof_chars = vim_strsave(keys);
890 vim_free(buf);
891 *p = ' ';
892 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100893#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100894 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
895 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100896 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100897 int tty_type = NUL;
898
899 p = skiptowhite(cmd);
900 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
901 tty_type = 'w';
902 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
903 tty_type = 'c';
904 else
905 {
Bram Moolenaar50809a42023-05-20 16:39:07 +0100906 semsg(_(e_invalid_value_for_argument_str), "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100907 goto theend;
908 }
909 opt.jo_set2 |= JO2_TTY_TYPE;
910 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100911 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100912#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200913 else
914 {
915 if (*p)
916 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000917 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100918 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200919 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200920# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200921 cmd = skipwhite(p);
922 }
923 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100924 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100925 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200926 tofree = cmd = vim_strsave(p_sh);
927
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100928 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100929 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200930 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100931 }
932
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200933 if (eap->addr_count > 0)
934 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100935 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200936 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
937 opt.jo_io[PART_IN] = JIO_BUFFER;
938 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
939 opt.jo_in_top = eap->line1;
940 opt.jo_in_bot = eap->line2;
941 }
942
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100943 if (opt_shell && tofree == NULL)
944 {
945#ifdef UNIX
946 char **argv = NULL;
947 char_u *tofree1 = NULL;
948 char_u *tofree2 = NULL;
949
950 // :term ++shell command
951 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
952 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100953 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100954 vim_free(tofree1);
955 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100956 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100957#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100958# ifdef MSWIN
959 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
960 char_u *newcmd;
961
962 newcmd = alloc(cmdlen);
963 if (newcmd == NULL)
964 goto theend;
965 tofree = newcmd;
966 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
967 cmd = newcmd;
968# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000969 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100970 goto theend;
971# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100972#endif
973 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100974 argvar[0].v_type = VAR_STRING;
975 argvar[0].vval.v_string = cmd;
976 argvar[1].v_type = VAR_UNKNOWN;
977 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100978
979theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100980 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200981 vim_free(opt.jo_eof_chars);
982}
983
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200984 static char_u *
985get_terminalopt_name(expand_T *xp UNUSED, int idx)
986{
987 // Note: Keep this in sync with ex_terminal.
988 static char *(p_termopt_values[]) =
989 {
990 "close",
991 "noclose",
992 "open",
993 "curwin",
994 "hidden",
995 "norestore",
996 "shell",
997 "kill=",
998 "rows=",
999 "cols=",
1000 "eof=",
1001 "type=",
1002 "api=",
1003 };
1004
1005 if (idx < (int)ARRAY_LENGTH(p_termopt_values))
1006 return (char_u*)p_termopt_values[idx];
1007 return NULL;
1008}
1009
1010 static char_u *
1011get_termkill_name(expand_T *xp UNUSED, int idx)
1012{
1013 // These are platform-specific values used for job_stop(). They are defined
1014 // in each platform's mch_signal_job(). Just use a unified auto-complete
1015 // list for simplicity.
1016 static char *(p_termkill_values[]) =
1017 {
1018 "term",
1019 "hup",
1020 "quit",
1021 "int",
1022 "kill",
1023 "winch",
1024 };
1025
1026 if (idx < (int)ARRAY_LENGTH(p_termkill_values))
1027 return (char_u*)p_termkill_values[idx];
1028 return NULL;
1029}
1030
1031/*
1032 * Command-line expansion for :terminal [options]
1033 */
1034 int
1035expand_terminal_opt(
1036 char_u *pat,
1037 expand_T *xp,
1038 regmatch_T *rmp,
1039 char_u ***matches,
1040 int *numMatches)
1041{
1042 if (xp->xp_pattern > xp->xp_line && *(xp->xp_pattern-1) == '=')
1043 {
1044 char_u *(*cb)(expand_T *, int) = NULL;
1045
1046 char_u *name_end = xp->xp_pattern - 1;
1047 if (name_end - xp->xp_line >= 4
1048 && STRNCMP(name_end - 4, "kill", 4) == 0)
1049 cb = get_termkill_name;
1050
1051 if (cb != NULL)
1052 {
1053 return ExpandGeneric(
1054 pat,
1055 xp,
1056 rmp,
1057 matches,
1058 numMatches,
1059 cb,
1060 FALSE);
1061 }
1062 return FAIL;
1063 }
1064 return ExpandGeneric(
1065 pat,
1066 xp,
1067 rmp,
1068 matches,
1069 numMatches,
1070 get_terminalopt_name,
1071 FALSE);
1072}
1073
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001074#if defined(FEAT_SESSION) || defined(PROTO)
1075/*
1076 * Write a :terminal command to the session file to restore the terminal in
1077 * window "wp".
1078 * Return FAIL if writing fails.
1079 */
1080 int
Bram Moolenaar0e655112020-09-11 20:36:36 +02001081term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001082{
Bram Moolenaar0e655112020-09-11 20:36:36 +02001083 const int bufnr = wp->w_buffer->b_fnum;
1084 term_T *term = wp->w_buffer->b_term;
1085
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001086 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001087 {
1088 // There are multiple views into this terminal buffer. We don't want to
1089 // create the terminal multiple times. If it's the first time, create,
1090 // otherwise link to the first buffer.
1091 char id_as_str[NUMBUFLEN];
1092 hashitem_T *entry;
1093
1094 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
1095
1096 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
1097 if (!HASHITEM_EMPTY(entry))
1098 {
1099 // we've already opened this terminal buffer
1100 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
1101 return FAIL;
1102 return put_eol(fd);
1103 }
1104 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001105
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001106 // Create the terminal and run the command. This is not without
1107 // risk, but let's assume the user only creates a session when this
1108 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001109 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1110 term->tl_cols, term->tl_rows) < 0)
1111 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001112#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001113 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1114 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001115#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001116 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1117 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001118 if (put_eol(fd) != OK)
1119 return FAIL;
1120
1121 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1122 return FAIL;
1123
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001124 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001125 {
1126 char *hash_key = alloc(NUMBUFLEN);
1127
1128 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00001129 hash_add(terminal_bufs, (char_u *)hash_key, "terminal session");
Bram Moolenaar0e655112020-09-11 20:36:36 +02001130 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001131
1132 return put_eol(fd);
1133}
1134
1135/*
1136 * Return TRUE if "buf" has a terminal that should be restored.
1137 */
1138 int
1139term_should_restore(buf_T *buf)
1140{
1141 term_T *term = buf->b_term;
1142
1143 return term != NULL && (term->tl_command == NULL
1144 || STRCMP(term->tl_command, "NONE") != 0);
1145}
1146#endif
1147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001148/*
1149 * Free the scrollback buffer for "term".
1150 */
1151 static void
1152free_scrollback(term_T *term)
1153{
1154 int i;
1155
1156 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1157 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1158 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001159 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1160 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1161 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001162}
1163
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001164
1165// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001166static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001167
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001168/*
1169 * Free a terminal and everything it refers to.
1170 * Kills the job if there is one.
1171 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001172 * The actual terminal structure is freed later in free_unused_terminals(),
1173 * because callbacks may wipe out a buffer while the terminal is still
1174 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001175 */
1176 void
1177free_terminal(buf_T *buf)
1178{
1179 term_T *term = buf->b_term;
1180 term_T *tp;
1181
1182 if (term == NULL)
1183 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001184
1185 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001186 if (first_term == term)
1187 first_term = term->tl_next;
1188 else
1189 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1190 if (tp->tl_next == term)
1191 {
1192 tp->tl_next = term->tl_next;
1193 break;
1194 }
1195
1196 if (term->tl_job != NULL)
1197 {
1198 if (term->tl_job->jv_status != JOB_ENDED
1199 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001200 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001201 job_stop(term->tl_job, NULL, "kill");
1202 job_unref(term->tl_job);
1203 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001204 term->tl_next = terminals_to_free;
1205 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001206
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001207 buf->b_term = NULL;
1208 if (in_terminal_loop == term)
1209 in_terminal_loop = NULL;
1210}
1211
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001212 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00001213free_unused_terminals(void)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001214{
1215 while (terminals_to_free != NULL)
1216 {
1217 term_T *term = terminals_to_free;
1218
1219 terminals_to_free = term->tl_next;
1220
1221 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001222 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001223
1224 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001225 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001226 vim_free(term->tl_title);
1227#ifdef FEAT_SESSION
1228 vim_free(term->tl_command);
1229#endif
1230 vim_free(term->tl_kill);
1231 vim_free(term->tl_status_text);
1232 vim_free(term->tl_opencmd);
1233 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001234 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001235#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001236 if (term->tl_out_fd != NULL)
1237 fclose(term->tl_out_fd);
1238#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001239 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001240 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001241 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001242 vim_free(term);
1243 }
1244}
1245
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001246/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001247 * Get the part that is connected to the tty. Normally this is PART_IN, but
1248 * when writing buffer lines to the job it can be another. This makes it
1249 * possible to do "1,5term vim -".
1250 */
1251 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001252get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001253{
1254#ifdef UNIX
1255 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1256 int i;
1257
1258 for (i = 0; i < 3; ++i)
1259 {
1260 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1261
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001262 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001263 return parts[i];
1264 }
1265#endif
1266 return PART_IN;
1267}
1268
1269/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001270 * Read any vterm output and send it on the channel.
1271 */
1272 static void
1273term_forward_output(term_T *term)
1274{
1275 VTerm *vterm = term->tl_vterm;
1276 char buf[KEY_BUF_LEN];
1277 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1278
1279 if (curlen > 0)
1280 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1281 (char_u *)buf, (int)curlen, NULL);
1282}
1283
1284/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001285 * Write job output "msg[len]" to the vterm.
1286 */
1287 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001288term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001289{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001290 char_u *msg = msg_arg;
1291 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001292 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001293 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001294 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1295
1296 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1297 // the end.
1298 if (len > limit)
1299 {
1300 char_u *p = msg + len - limit;
1301
1302 p -= (*mb_head_off)(msg, p);
1303 len -= p - msg;
1304 msg = p;
1305 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001306
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001307 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001308
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001309 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001310 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001311 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001312
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001313 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001314 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1315}
1316
1317 static void
Bram Moolenaar58806c12023-04-29 14:26:02 +01001318position_cursor(win_T *wp, VTermPos *pos)
1319{
1320 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1321 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1322#ifdef FEAT_PROP_POPUP
1323 if (popup_is_popup(wp))
1324 {
1325 wp->w_wrow += popup_top_extra(wp);
1326 wp->w_wcol += popup_left_extra(wp);
1327 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
1328 }
1329 else
1330 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
1331#endif
1332 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1333}
1334
1335 static void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001336update_cursor(term_T *term, int redraw)
1337{
1338 if (term->tl_normal_mode)
1339 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001340#ifdef FEAT_GUI
1341 if (term->tl_system)
1342 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1343 term->tl_cursor_pos.col);
1344 else
1345#endif
Bram Moolenaar58806c12023-04-29 14:26:02 +01001346 if (!term_job_running(term))
1347 // avoid the cursor positioned below the last used line
Bram Moolenaar13568252018-03-16 20:46:58 +01001348 setcursor();
Bram Moolenaar58806c12023-04-29 14:26:02 +01001349 else
1350 {
1351 // do not use the window cursor position
1352 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1353 windgoto(W_WINROW(curwin) + curwin->w_wrow,
Hirohito Higashi3b9b95d2025-06-01 20:22:55 +02001354 curwin->w_wincol + curwin->w_wcol);
Bram Moolenaar58806c12023-04-29 14:26:02 +01001355 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001356 if (redraw)
1357 {
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001358 aco_save_T aco;
1359
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001360 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1361 cursor_on();
1362 out_flush();
1363#ifdef FEAT_GUI
1364 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001365 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001366 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001367 gui_mch_flush();
1368 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001369#endif
Bram Moolenaar24fe33a2022-11-24 00:09:02 +00001370 // Make sure an invoked autocmd doesn't delete the buffer (and the
1371 // terminal) under our fingers.
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001372 ++term->tl_buffer->b_locked;
1373
1374 // save and restore curwin and curbuf, in case the autocmd changes them
1375 aucmd_prepbuf(&aco, curbuf);
1376 apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, FALSE, term->tl_buffer);
1377 aucmd_restbuf(&aco);
1378
1379 --term->tl_buffer->b_locked;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001380 }
1381}
1382
1383/*
1384 * Invoked when "msg" output from a job was received. Write it to the terminal
1385 * of "buffer".
1386 */
1387 void
1388write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1389{
1390 size_t len = STRLEN(msg);
1391 term_T *term = buffer->b_term;
1392
Bram Moolenaar4f974752019-02-17 17:44:42 +01001393#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001394 // Win32: Cannot redirect output of the job, intercept it here and write to
1395 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001396 if (term->tl_out_fd != NULL)
1397 {
1398 ch_log(channel, "Writing %d bytes to output file", (int)len);
1399 fwrite(msg, len, 1, term->tl_out_fd);
1400 return;
1401 }
1402#endif
1403
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001404 if (term->tl_vterm == NULL)
1405 {
1406 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1407 return;
1408 }
1409 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001410 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001411 term_write_job_output(term, msg, len);
1412
Bram Moolenaar13568252018-03-16 20:46:58 +01001413#ifdef FEAT_GUI
1414 if (term->tl_system)
1415 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001416 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001417 update_system_term(term);
1418 update_cursor(term, TRUE);
1419 }
1420 else
1421#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001422 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1423 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001424 if (!term->tl_normal_mode)
1425 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001426 // Don't use update_screen() when editing the command line, it gets
1427 // cleared.
1428 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001429 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001430 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001431 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001432 update_screen(UPD_VALID_NO_UPDATE);
Naruhiko Nishinobe5bd4d2025-05-14 21:20:28 +02001433#if defined(FEAT_TABPANEL)
1434 if (redraw_tabpanel)
1435 draw_tabpanel();
1436#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001437 // update_screen() can be slow, check the terminal wasn't closed
1438 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001439 if (buffer == curbuf && curbuf->b_term != NULL)
1440 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001441 }
1442 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001443 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001444 }
1445}
1446
1447/*
1448 * Send a mouse position and click to the vterm
1449 */
1450 static int
1451term_send_mouse(VTerm *vterm, int button, int pressed)
1452{
1453 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001454 int row = mouse_row - W_WINROW(curwin);
1455 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001456
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001457#ifdef FEAT_PROP_POPUP
1458 if (popup_is_popup(curwin))
1459 {
1460 row -= popup_top_extra(curwin);
1461 col -= popup_left_extra(curwin);
1462 }
1463#endif
1464 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001465 if (button != 0)
1466 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001467 return TRUE;
1468}
1469
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001470static int enter_mouse_col = -1;
1471static int enter_mouse_row = -1;
1472
1473/*
1474 * Handle a mouse click, drag or release.
1475 * Return TRUE when a mouse event is sent to the terminal.
1476 */
1477 static int
1478term_mouse_click(VTerm *vterm, int key)
1479{
1480#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001481 // For modeless selection mouse drag and release events are ignored, unless
1482 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001483 static int ignore_drag_release = TRUE;
1484 VTermMouseState mouse_state;
1485
1486 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1487 if (mouse_state.flags == 0)
1488 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001489 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001490 switch (key)
1491 {
1492 case K_LEFTDRAG:
1493 case K_LEFTRELEASE:
1494 case K_RIGHTDRAG:
1495 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001496 // Ignore drag and release events when the button-down wasn't
1497 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001498 if (ignore_drag_release)
1499 {
1500 int save_mouse_col, save_mouse_row;
1501
1502 if (enter_mouse_col < 0)
1503 break;
1504
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001505 // mouse click in the window gave us focus, handle that
1506 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001507 save_mouse_col = mouse_col;
1508 save_mouse_row = mouse_row;
1509 mouse_col = enter_mouse_col;
1510 mouse_row = enter_mouse_row;
1511 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1512 mouse_col = save_mouse_col;
1513 mouse_row = save_mouse_row;
1514 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001515 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001516 case K_LEFTMOUSE:
1517 case K_RIGHTMOUSE:
1518 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1519 ignore_drag_release = TRUE;
1520 else
1521 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001522 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001523 if (clip_star.available)
1524 {
1525 int button, is_click, is_drag;
1526
1527 button = get_mouse_button(KEY2TERMCAP1(key),
1528 &is_click, &is_drag);
1529 if (mouse_model_popup() && button == MOUSE_LEFT
1530 && (mod_mask & MOD_MASK_SHIFT))
1531 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001532 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001533 button = MOUSE_RIGHT;
1534 mod_mask &= ~MOD_MASK_SHIFT;
1535 }
1536 clip_modeless(button, is_click, is_drag);
1537 }
1538 break;
1539
1540 case K_MIDDLEMOUSE:
1541 if (clip_star.available)
1542 insert_reg('*', TRUE);
1543 break;
1544 }
1545 enter_mouse_col = -1;
1546 return FALSE;
1547 }
1548#endif
1549 enter_mouse_col = -1;
1550
1551 switch (key)
1552 {
1553 case K_LEFTMOUSE:
1554 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1555 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1556 case K_LEFTRELEASE:
1557 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1558 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1559 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1560 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1561 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1562 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1563 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1564 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1565 }
1566 return TRUE;
1567}
1568
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001569/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001570 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1571 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001572 * Return the number of bytes in "buf".
1573 */
1574 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001575term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001576{
1577 VTerm *vterm = term->tl_vterm;
1578 VTermKey key = VTERM_KEY_NONE;
1579 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001580 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001581
1582 switch (c)
1583 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001584 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001585
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001586 // don't use VTERM_KEY_BACKSPACE, it always
1587 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001588 case K_BS: c = term_backspace_char; break;
1589
1590 case ESC: key = VTERM_KEY_ESCAPE; break;
1591 case K_DEL: key = VTERM_KEY_DEL; break;
1592 case K_DOWN: key = VTERM_KEY_DOWN; break;
1593 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1594 key = VTERM_KEY_DOWN; break;
1595 case K_END: key = VTERM_KEY_END; break;
1596 case K_S_END: mod = VTERM_MOD_SHIFT;
1597 key = VTERM_KEY_END; break;
1598 case K_C_END: mod = VTERM_MOD_CTRL;
1599 key = VTERM_KEY_END; break;
1600 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1601 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1602 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1603 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1604 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1605 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1606 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1607 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1608 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1609 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1610 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1611 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1612 case K_HOME: key = VTERM_KEY_HOME; break;
1613 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1614 key = VTERM_KEY_HOME; break;
1615 case K_C_HOME: mod = VTERM_MOD_CTRL;
1616 key = VTERM_KEY_HOME; break;
1617 case K_INS: key = VTERM_KEY_INS; break;
1618 case K_K0: key = VTERM_KEY_KP_0; break;
1619 case K_K1: key = VTERM_KEY_KP_1; break;
1620 case K_K2: key = VTERM_KEY_KP_2; break;
1621 case K_K3: key = VTERM_KEY_KP_3; break;
1622 case K_K4: key = VTERM_KEY_KP_4; break;
1623 case K_K5: key = VTERM_KEY_KP_5; break;
1624 case K_K6: key = VTERM_KEY_KP_6; break;
1625 case K_K7: key = VTERM_KEY_KP_7; break;
1626 case K_K8: key = VTERM_KEY_KP_8; break;
1627 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001628 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001629 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001630 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001631 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001632 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1633 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001634 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1635 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001636 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1637 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001638 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1639 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1640 case K_LEFT: key = VTERM_KEY_LEFT; break;
1641 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1642 key = VTERM_KEY_LEFT; break;
1643 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1644 key = VTERM_KEY_LEFT; break;
1645 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1646 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1647 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1648 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1649 key = VTERM_KEY_RIGHT; break;
1650 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1651 key = VTERM_KEY_RIGHT; break;
1652 case K_UP: key = VTERM_KEY_UP; break;
1653 case K_S_UP: mod = VTERM_MOD_SHIFT;
1654 key = VTERM_KEY_UP; break;
1655 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001656 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1657 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001658
Bram Moolenaara42ad572017-11-16 13:08:04 +01001659 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1660 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001661 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1662 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001663
1664 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001665 case K_LEFTMOUSE_NM:
1666 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001667 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001668 case K_LEFTRELEASE_NM:
1669 case K_MOUSEMOVE:
1670 case K_MIDDLEMOUSE:
1671 case K_MIDDLEDRAG:
1672 case K_MIDDLERELEASE:
1673 case K_RIGHTMOUSE:
1674 case K_RIGHTDRAG:
1675 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1676 return 0;
1677 other = TRUE;
1678 break;
1679
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001680 case K_X1MOUSE: /* TODO */ return 0;
1681 case K_X1DRAG: /* TODO */ return 0;
1682 case K_X1RELEASE: /* TODO */ return 0;
1683 case K_X2MOUSE: /* TODO */ return 0;
1684 case K_X2DRAG: /* TODO */ return 0;
1685 case K_X2RELEASE: /* TODO */ return 0;
1686
1687 case K_IGNORE: return 0;
1688 case K_NOP: return 0;
1689 case K_UNDO: return 0;
1690 case K_HELP: return 0;
1691 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1692 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1693 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1694 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1695 case K_SELECT: return 0;
1696#ifdef FEAT_GUI
1697 case K_VER_SCROLLBAR: return 0;
1698 case K_HOR_SCROLLBAR: return 0;
1699#endif
1700#ifdef FEAT_GUI_TABLINE
1701 case K_TABLINE: return 0;
1702 case K_TABMENU: return 0;
1703#endif
1704#ifdef FEAT_NETBEANS_INTG
1705 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1706#endif
1707#ifdef FEAT_DND
1708 case K_DROP: return 0;
1709#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001710 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001711 case K_PS: vterm_keyboard_start_paste(vterm);
1712 other = TRUE;
1713 break;
1714 case K_PE: vterm_keyboard_end_paste(vterm);
1715 other = TRUE;
1716 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001717 }
1718
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001719 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001720 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001721 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001722 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001723 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001724 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001725 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001726
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001727 // Ctrl-Shift-i may have the key "I" instead of "i", but for the kitty
1728 // keyboard protocol should use "i". Applies to all ascii letters.
1729 if (ASCII_ISUPPER(c)
Bram Moolenaarebed1b02022-11-24 14:05:19 +00001730 && vterm_is_kitty_keyboard(vterm)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001731 && mod == (VTERM_MOD_CTRL | VTERM_MOD_SHIFT))
1732 c = TOLOWER_ASC(c);
1733
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 /*
1735 * Convert special keys to vterm keys:
1736 * - Write keys to vterm: vterm_keyboard_key()
1737 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001738 */
1739 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001740 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001741 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001742 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001743 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001744 vterm_keyboard_unichar(vterm, c, mod);
1745
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001746 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001747 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1748}
1749
1750/*
1751 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001752 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001753 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001754 */
1755 static int
1756term_job_running_check(term_T *term, int check_job_status)
1757{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001758 // Also consider the job finished when the channel is closed, to avoid a
1759 // race condition when updating the title.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001760 if (term == NULL
1761 || term->tl_job == NULL
1762 || !channel_is_open(term->tl_job->jv_channel))
1763 return FALSE;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001764
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001765 job_T *job = term->tl_job;
1766
1767 // Careful: Checking the job status may invoke callbacks, which close
1768 // the buffer and terminate "term". However, "job" will not be freed
1769 // yet.
1770 if (check_job_status)
1771 job_status(job);
1772 return (job->jv_status == JOB_STARTED
1773 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001774}
1775
1776/*
1777 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001778 */
1779 int
1780term_job_running(term_T *term)
1781{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001782 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001783}
1784
1785/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001786 * Return TRUE if the job for "term" is still running, ignoring the job was
1787 * "NONE".
1788 */
1789 int
1790term_job_running_not_none(term_T *term)
1791{
1792 return term_job_running(term) && !term_none_open(term);
1793}
1794
1795/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001796 * Return TRUE if "term" has an active channel and used ":term NONE".
1797 */
1798 int
1799term_none_open(term_T *term)
1800{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001801 // Also consider the job finished when the channel is closed, to avoid a
1802 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001803 return term != NULL
1804 && term->tl_job != NULL
1805 && channel_is_open(term->tl_job->jv_channel)
1806 && term->tl_job->jv_channel->ch_keep_open;
1807}
1808
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001809//
1810// Used to confirm whether we would like to kill a terminal.
1811// Return OK when the user confirms to kill it.
1812// Return FAIL if the user selects otherwise.
1813//
1814 int
1815term_confirm_stop(buf_T *buf)
1816{
1817 char_u buff[DIALOG_MSG_SIZE];
1818 int ret;
1819
1820 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1821 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1822 if (ret == VIM_YES)
1823 return OK;
1824 else
1825 return FAIL;
1826}
1827
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001828/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001829 * Used when exiting: kill the job in "buf" if so desired.
1830 * Return OK when the job finished.
1831 * Return FAIL when the job is still running.
1832 */
1833 int
1834term_try_stop_job(buf_T *buf)
1835{
1836 int count;
1837 char *how = (char *)buf->b_term->tl_kill;
1838
1839#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001840 if ((how == NULL || *how == NUL)
1841 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001842 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001843 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001844 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001845 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001846 return FAIL;
1847 }
1848#endif
1849 if (how == NULL || *how == NUL)
1850 return FAIL;
1851
1852 job_stop(buf->b_term->tl_job, NULL, how);
1853
Bram Moolenaar9172d232019-01-29 23:06:54 +01001854 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001855 for (count = 0; count < 100; ++count)
1856 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001857 job_T *job;
1858
1859 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001860 if (!buf_valid(buf)
1861 || buf->b_term == NULL
1862 || buf->b_term->tl_job == NULL)
1863 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001864 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001865
Bram Moolenaar9172d232019-01-29 23:06:54 +01001866 // Call job_status() to update jv_status. It may cause the job to be
1867 // cleaned up but it won't be freed.
1868 job_status(job);
1869 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001870 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001871
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001872 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001873 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001874 }
1875 return FAIL;
1876}
1877
1878/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001879 * Add the last line of the scrollback buffer to the buffer in the window.
1880 */
1881 static void
1882add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1883{
1884 buf_T *buf = term->tl_buffer;
1885 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1886 linenr_T lnum = buf->b_ml.ml_line_count;
1887
Bram Moolenaar4f974752019-02-17 17:44:42 +01001888#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001889 if (!enc_utf8 && enc_codepage > 0)
1890 {
1891 WCHAR *ret = NULL;
1892 int length = 0;
1893
1894 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1895 &ret, &length);
1896 if (ret != NULL)
1897 {
1898 WideCharToMultiByte_alloc(enc_codepage, 0,
1899 ret, length, (char **)&text, &len, 0, 0);
1900 vim_free(ret);
1901 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1902 vim_free(text);
1903 }
1904 }
1905 else
1906#endif
1907 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1908 if (empty)
1909 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001910 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001911 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001912 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913 curbuf = curwin->w_buffer;
1914 }
1915}
1916
1917 static void
1918cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1919{
1920 attr->width = cell->width;
1921 attr->attrs = cell->attrs;
1922 attr->fg = cell->fg;
1923 attr->bg = cell->bg;
1924}
1925
1926 static int
1927equal_celattr(cellattr_T *a, cellattr_T *b)
1928{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001929 // We only compare the RGB colors, ignoring the ANSI index and type.
1930 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001931 return a->fg.red == b->fg.red
1932 && a->fg.green == b->fg.green
1933 && a->fg.blue == b->fg.blue
1934 && a->bg.red == b->bg.red
1935 && a->bg.green == b->bg.green
1936 && a->bg.blue == b->bg.blue;
1937}
1938
Bram Moolenaard96ff162018-02-18 22:13:29 +01001939/*
1940 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1941 * line at this position. Otherwise at the end.
1942 */
1943 static int
1944add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1945{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001946 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
1947 return FALSE;
1948
1949 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1950 + term->tl_scrollback.ga_len;
1951
1952 if (lnum > 0)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001953 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001954 int i;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001955
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001956 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001957 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001958 *line = *(line - 1);
1959 --line;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001960 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01001961 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001962 line->sb_cols = 0;
1963 line->sb_cells = NULL;
1964 line->sb_fill_attr = *fill_attr;
1965 ++term->tl_scrollback.ga_len;
1966 return OK;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001967}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001968
1969/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001970 * Remove the terminal contents from the scrollback and the buffer.
1971 * Used before adding a new scrollback line or updating the buffer for lines
1972 * displayed in the terminal.
1973 */
1974 static void
1975cleanup_scrollback(term_T *term)
1976{
1977 sb_line_T *line;
1978 garray_T *gap;
1979
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001980 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001981 gap = &term->tl_scrollback;
1982 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1983 && gap->ga_len > 0)
1984 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001985 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001986 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1987 vim_free(line->sb_cells);
1988 --gap->ga_len;
1989 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001990 curbuf = curwin->w_buffer;
1991 if (curbuf == term->tl_buffer)
1992 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001993}
1994
1995/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001996 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001997 */
1998 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001999update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002000{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002001 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002002 int len;
2003 int lines_skipped = 0;
2004 VTermPos pos;
2005 VTermScreenCell cell;
2006 cellattr_T fill_attr, new_fill_attr;
2007 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002008
2009 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
2010 "Adding terminal window snapshot to buffer");
2011
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002012 // First remove the lines that were appended before, they might be
2013 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002014 cleanup_scrollback(term);
2015
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016 screen = vterm_obtain_screen(term->tl_vterm);
2017 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002018 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
2019 {
2020 len = 0;
2021 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
2022 if (vterm_screen_get_cell(screen, pos, &cell) != 0
2023 && cell.chars[0] != NUL)
2024 {
2025 len = pos.col + 1;
2026 new_fill_attr = term->tl_default_color;
2027 }
2028 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002029 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002030 cell2cellattr(&cell, &new_fill_attr);
2031
2032 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
2033 ++lines_skipped;
2034 else
2035 {
2036 while (lines_skipped > 0)
2037 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002038 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002039 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002040 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002041 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002042 }
2043
2044 if (len == 0)
2045 p = NULL;
2046 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002047 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002048 if ((p != NULL || len == 0)
2049 && ga_grow(&term->tl_scrollback, 1) == OK)
2050 {
2051 garray_T ga;
2052 int width;
2053 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
2054 + term->tl_scrollback.ga_len;
2055
2056 ga_init2(&ga, 1, 100);
2057 for (pos.col = 0; pos.col < len; pos.col += width)
2058 {
2059 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2060 {
2061 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02002062 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002063 if (ga_grow(&ga, 1) == OK)
2064 ga.ga_len += utf_char2bytes(' ',
2065 (char_u *)ga.ga_data + ga.ga_len);
2066 }
2067 else
2068 {
2069 width = cell.width;
2070
2071 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01002072 if (width == 2)
2073 // second cell of double-width character has the
2074 // same attributes.
2075 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002076
Bram Moolenaara79fd562018-12-20 20:47:32 +01002077 // Each character can be up to 6 bytes.
2078 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002079 {
2080 int i;
2081 int c;
2082
2083 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
2084 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2085 (char_u *)ga.ga_data + ga.ga_len);
2086 }
2087 }
2088 }
2089 line->sb_cols = len;
2090 line->sb_cells = p;
2091 line->sb_fill_attr = new_fill_attr;
2092 fill_attr = new_fill_attr;
2093 ++term->tl_scrollback.ga_len;
2094
2095 if (ga_grow(&ga, 1) == FAIL)
2096 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2097 else
2098 {
2099 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2100 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2101 }
2102 ga_clear(&ga);
2103 }
2104 else
2105 vim_free(p);
2106 }
2107 }
2108
Bram Moolenaarf3aea592018-11-11 22:18:21 +01002109 // Add trailing empty lines.
2110 for (pos.row = term->tl_scrollback.ga_len;
2111 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
2112 ++pos.row)
2113 {
2114 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
2115 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2116 }
2117
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002118 term->tl_dirty_snapshot = FALSE;
2119#ifdef FEAT_TIMERS
2120 term->tl_timer_set = FALSE;
2121#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002122}
2123
2124/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002125 * Loop over all windows in the current tab, and also curwin, which is not
2126 * encountered when using a terminal in a popup window.
2127 * Return TRUE if "*wp" was set to the next window.
2128 */
2129 static int
2130for_all_windows_and_curwin(win_T **wp, int *did_curwin)
2131{
2132 if (*wp == NULL)
2133 *wp = firstwin;
2134 else if ((*wp)->w_next != NULL)
2135 *wp = (*wp)->w_next;
2136 else if (!*did_curwin)
2137 *wp = curwin;
2138 else
2139 return FALSE;
2140 if (*wp == curwin)
2141 *did_curwin = TRUE;
2142 return TRUE;
2143}
2144
2145/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002146 * If needed, add the current lines of the terminal to scrollback and to the
2147 * buffer. Called after the job has ended and when switching to
2148 * Terminal-Normal mode.
2149 * When "redraw" is TRUE redraw the windows that show the terminal.
2150 */
2151 static void
2152may_move_terminal_to_buffer(term_T *term, int redraw)
2153{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002154 if (term->tl_vterm == NULL)
2155 return;
2156
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002157 // Update the snapshot only if something changes or the buffer does not
2158 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002159 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2160 <= term->tl_scrollback_scrolled)
2161 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002162
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002163 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002164 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2165 &term->tl_default_color.fg, &term->tl_default_color.bg);
2166
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002167 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002168 {
2169 win_T *wp = NULL;
2170 int did_curwin = FALSE;
2171
2172 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002173 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002174 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002176 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2177 wp->w_cursor.col = 0;
2178 wp->w_valid = 0;
2179 if (wp->w_cursor.lnum >= wp->w_height)
2180 {
2181 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002182
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002183 if (wp->w_topline < min_topline)
2184 wp->w_topline = min_topline;
2185 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002186 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002187 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002188 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002189 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002190}
2191
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002192#if defined(FEAT_TIMERS) || defined(PROTO)
2193/*
2194 * Check if any terminal timer expired. If so, copy text from the terminal to
2195 * the buffer.
2196 * Return the time until the next timer will expire.
2197 */
2198 int
2199term_check_timers(int next_due_arg, proftime_T *now)
2200{
2201 term_T *term;
2202 int next_due = next_due_arg;
2203
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002204 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002205 {
2206 if (term->tl_timer_set && !term->tl_normal_mode)
2207 {
2208 long this_due = proftime_time_left(&term->tl_timer_due, now);
2209
2210 if (this_due <= 1)
2211 {
2212 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002213 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002214 }
2215 else if (next_due == -1 || next_due > this_due)
2216 next_due = this_due;
2217 }
2218 }
2219
2220 return next_due;
2221}
2222#endif
2223
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002224/*
2225 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2226 * otherwise end it.
2227 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002228 static void
2229set_terminal_mode(term_T *term, int normal_mode)
2230{
2231 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002232 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002233 if (!normal_mode)
2234 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002235 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 if (term->tl_buffer == curbuf)
2237 maketitle();
2238}
2239
2240/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002241 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002242 * Move the vterm contents into the scrollback buffer and free the vterm.
2243 */
2244 static void
2245cleanup_vterm(term_T *term)
2246{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002247 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002248 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002249 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002250 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002251}
2252
2253/*
2254 * Switch from Terminal-Job mode to Terminal-Normal mode.
2255 * Suspends updating the terminal window.
2256 */
2257 static void
2258term_enter_normal_mode(void)
2259{
2260 term_T *term = curbuf->b_term;
2261
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002262 set_terminal_mode(term, TRUE);
2263
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002264 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002265 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002266
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002267 // Move the window cursor to the position of the cursor in the
2268 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002269 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2270 + term->tl_cursor_pos.row + 1;
2271 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002272 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2273 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002274 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002275
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002276 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002277 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2278}
2279
2280/*
2281 * Returns TRUE if the current window contains a terminal and we are in
2282 * Terminal-Normal mode.
2283 */
2284 int
2285term_in_normal_mode(void)
2286{
2287 term_T *term = curbuf->b_term;
2288
2289 return term != NULL && term->tl_normal_mode;
2290}
2291
2292/*
2293 * Switch from Terminal-Normal mode to Terminal-Job mode.
2294 * Restores updating the terminal window.
2295 */
2296 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002297term_enter_job_mode(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002298{
2299 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002300
2301 set_terminal_mode(term, FALSE);
2302
2303 if (term->tl_channel_closed)
2304 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002305 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002306#ifdef FEAT_PROP_POPUP
2307 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002308 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002309#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002310}
2311
2312/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002313 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2314 * modifiers into a basic key. However, we may only find out after calling
2315 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2316 * "no_reduce_keys" before using it.
2317 */
2318typedef enum {
2319 NRKS_NONE, // initial value
2320 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2321 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2322 // check_no_reduce_keys(), must be decremented.
2323} reduce_key_state_T;
2324
2325static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2326
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002327/*
2328 * Return TRUE if the term is using modifyOtherKeys level 2 or the kitty
2329 * keyboard protocol.
2330 */
2331 static int
2332vterm_using_key_protocol(void)
2333{
2334 return curbuf->b_term != NULL
2335 && curbuf->b_term->tl_vterm != NULL
2336 && (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm)
2337 || vterm_is_kitty_keyboard(curbuf->b_term->tl_vterm));
2338}
2339
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002340 void
2341check_no_reduce_keys(void)
2342{
2343 if (no_reduce_key_state != NRKS_CHECK
2344 || no_reduce_keys >= 1
2345 || curbuf->b_term == NULL
2346 || curbuf->b_term->tl_vterm == NULL)
2347 return;
2348
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002349 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002350 {
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002351 // "modify_other_keys" or kitty keyboard protocol was enabled while
2352 // waiting.
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002353 no_reduce_key_state = NRKS_SET;
2354 ++no_reduce_keys;
2355 }
2356}
2357
2358/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002359 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002360 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002361 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002362 */
2363 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002364term_vgetc(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002365{
2366 int c;
2367 int save_State = State;
2368
Bram Moolenaar24959102022-05-07 20:01:16 +01002369 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002370 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002371#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002372 ctrl_break_was_pressed = FALSE;
2373#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002374
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002375 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002376 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002377 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002378 no_reduce_key_state = NRKS_SET;
2379 }
2380 else
2381 {
2382 no_reduce_key_state = NRKS_CHECK;
2383 }
2384
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002385 c = vgetc();
2386 got_int = FALSE;
2387 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002388
2389 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002390 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002391 no_reduce_key_state = NRKS_NONE;
2392
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002393 return c;
2394}
2395
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002396static int mouse_was_outside = FALSE;
2397
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002398/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002399 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002400 * Return FAIL when the key needs to be handled in Normal mode.
2401 * Return OK when the key was dropped or sent to the terminal.
2402 */
2403 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002404send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002405{
2406 char msg[KEY_BUF_LEN];
2407 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002408 int dragging_outside = FALSE;
2409
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002410 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002411 switch (c)
2412 {
2413 case NUL:
2414 case K_ZERO:
2415 if (typed)
2416 stuffcharReadbuff(c);
2417 return FAIL;
2418
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002419 case K_TABLINE:
2420 stuffcharReadbuff(c);
2421 return FAIL;
2422
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002423 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002424 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002425 return FAIL;
2426
2427 case K_LEFTDRAG:
2428 case K_MIDDLEDRAG:
2429 case K_RIGHTDRAG:
2430 case K_X1DRAG:
2431 case K_X2DRAG:
2432 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002433 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002434 case K_LEFTMOUSE:
2435 case K_LEFTMOUSE_NM:
2436 case K_LEFTRELEASE:
2437 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002438 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002439 case K_MIDDLEMOUSE:
2440 case K_MIDDLERELEASE:
2441 case K_RIGHTMOUSE:
2442 case K_RIGHTRELEASE:
2443 case K_X1MOUSE:
2444 case K_X1RELEASE:
2445 case K_X2MOUSE:
2446 case K_X2RELEASE:
2447
2448 case K_MOUSEUP:
2449 case K_MOUSEDOWN:
2450 case K_MOUSELEFT:
2451 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002452 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002453 int row = mouse_row;
2454 int col = mouse_col;
2455
2456#ifdef FEAT_PROP_POPUP
2457 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002458 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002459 row -= popup_top_extra(curwin);
2460 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002461 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002462#endif
2463 if (row < W_WINROW(curwin)
2464 || row >= (W_WINROW(curwin) + curwin->w_height)
2465 || col < curwin->w_wincol
2466 || col >= W_ENDCOL(curwin)
2467 || dragging_outside)
2468 {
2469 // click or scroll outside the current window or on status
2470 // line or vertical separator
2471 if (typed)
2472 {
2473 stuffcharReadbuff(c);
2474 mouse_was_outside = TRUE;
2475 }
2476 return FAIL;
2477 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002478 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002479 break;
2480
2481 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002482 case K_SCRIPT_COMMAND:
2483 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002484 }
2485 if (typed)
2486 mouse_was_outside = FALSE;
2487
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002488 // Convert the typed key to a sequence of bytes for the job.
2489 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002490 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002491 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002492 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2493 (char_u *)msg, (int)len, NULL);
2494
2495 return OK;
2496}
2497
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002498/*
2499 * Handle CTRL-W "": send register contents to the job.
2500 */
2501 static void
2502term_paste_register(int prev_c UNUSED)
2503{
2504 int c;
2505 list_T *l;
2506 listitem_T *item;
2507 long reglen = 0;
2508 int type;
2509
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002510 if (add_to_showcmd(prev_c))
2511 if (add_to_showcmd('"'))
2512 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002513
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002514 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002515 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002516
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002517 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
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002521 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002522 if (c == '=' && get_expr_register() != '=')
2523 return;
2524 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002525 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002526 return;
2527
2528 l = (list_T *)get_reg_contents(c, GREG_LIST);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002529 if (l == NULL)
2530 return;
2531
2532 type = get_reg_type(c, &reglen);
2533 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002534 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002535 char_u *s = tv_get_string(&item->li_tv);
2536#ifdef MSWIN
2537 char_u *tmp = s;
2538
2539 if (!enc_utf8 && enc_codepage > 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002540 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002541 WCHAR *ret = NULL;
2542 int length = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002543
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002544 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2545 (int)STRLEN(s), &ret, &length);
2546 if (ret != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002547 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002548 WideCharToMultiByte_alloc(CP_UTF8, 0,
2549 ret, length, (char **)&s, &length, 0, 0);
2550 vim_free(ret);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002551 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002552 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002553#endif
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002554 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2555 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002556#ifdef MSWIN
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002557 if (tmp != s)
2558 vim_free(s);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002559#endif
2560
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002561 if (item->li_next != NULL || type == MLINE)
2562 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2563 (char_u *)"\r", 1, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002564 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002565 list_free(l);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002566}
2567
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002568/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002569 * Return TRUE when waiting for a character in the terminal, the cursor of the
2570 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002571 */
2572 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002573terminal_is_active(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002574{
2575 return in_terminal_loop != NULL;
2576}
2577
Bram Moolenaar83d47902020-03-26 20:34:00 +01002578/*
dundargocc57b5bc2022-11-02 13:30:51 +00002579 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002580 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002581 static int
2582term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002583{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002584 char_u *name;
2585
2586 if (wp != NULL && *wp->w_p_wcr != NUL)
2587 name = wp->w_p_wcr;
2588 else if (term->tl_highlight_name != NULL)
2589 name = term->tl_highlight_name;
2590 else
2591 name = (char_u*)"Terminal";
2592
2593 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002594}
2595
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002596#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002597 cursorentry_T *
2598term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2599{
2600 term_T *term = in_terminal_loop;
2601 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002602 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002603 guicolor_T term_fg = INVALCOLOR;
2604 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002605
Bram Moolenaara80faa82020-04-12 19:37:17 +02002606 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002607 entry.shape = entry.mshape =
2608 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2609 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2610 SHAPE_BLOCK;
2611 entry.percentage = 20;
2612 if (term->tl_cursor_blink)
2613 {
2614 entry.blinkwait = 700;
2615 entry.blinkon = 400;
2616 entry.blinkoff = 250;
2617 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002618
Bram Moolenaar83d47902020-03-26 20:34:00 +01002619 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002620 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002621 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002622 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002623 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002624 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002625 else
2626 *fg = gui.back_pixel;
2627
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002628 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002629 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002630 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002631 *bg = term_fg;
2632 else
2633 *bg = gui.norm_pixel;
2634 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002635 else
2636 *bg = color_name2handle(term->tl_cursor_color);
2637 entry.name = "n";
2638 entry.used_for = SHAPE_CURSOR;
2639
2640 return &entry;
2641}
2642#endif
2643
Bram Moolenaard317b382018-02-08 22:33:31 +01002644 static void
2645may_output_cursor_props(void)
2646{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002647 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002648 || last_set_cursor_shape != desired_cursor_shape
2649 || last_set_cursor_blink != desired_cursor_blink)
2650 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002651 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002652 last_set_cursor_shape = desired_cursor_shape;
2653 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002654 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002655 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002656 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002657 ui_cursor_shape_forced(TRUE);
2658 else
2659 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2660 }
2661}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002662
Bram Moolenaard317b382018-02-08 22:33:31 +01002663/*
2664 * Set the cursor color and shape, if not last set to these.
2665 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002666 static void
2667may_set_cursor_props(term_T *term)
2668{
2669#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002670 // For the GUI the cursor properties are obtained with
2671 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002672 if (gui.in_use)
2673 return;
2674#endif
2675 if (in_terminal_loop == term)
2676 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002677 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002678 desired_cursor_shape = term->tl_cursor_shape;
2679 desired_cursor_blink = term->tl_cursor_blink;
2680 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002681 }
2682}
2683
Bram Moolenaard317b382018-02-08 22:33:31 +01002684/*
2685 * Reset the desired cursor properties and restore them when needed.
2686 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002687 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002688prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002689{
2690#ifdef FEAT_GUI
2691 if (gui.in_use)
2692 return;
2693#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002694 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002695 desired_cursor_shape = -1;
2696 desired_cursor_blink = -1;
2697 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002698}
2699
2700/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002701 * Returns TRUE if the current window contains a terminal and we are sending
2702 * keys to the job.
2703 * If "check_job_status" is TRUE update the job status.
2704 */
2705 static int
2706term_use_loop_check(int check_job_status)
2707{
2708 term_T *term = curbuf->b_term;
2709
2710 return term != NULL
2711 && !term->tl_normal_mode
2712 && term->tl_vterm != NULL
2713 && term_job_running_check(term, check_job_status);
2714}
2715
2716/*
2717 * Returns TRUE if the current window contains a terminal and we are sending
2718 * keys to the job.
2719 */
2720 int
2721term_use_loop(void)
2722{
2723 return term_use_loop_check(FALSE);
2724}
2725
2726/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002727 * Called when entering a window with the mouse. If this is a terminal window
2728 * we may want to change state.
2729 */
2730 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002731term_win_entered(void)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002732{
2733 term_T *term = curbuf->b_term;
2734
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002735 if (term == NULL)
2736 return;
2737
2738 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002739 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002740 reset_VIsual_and_resel();
2741 if (State & MODE_INSERT)
2742 stop_insert_mode = TRUE;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002743 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002744 mouse_was_outside = FALSE;
2745 enter_mouse_col = mouse_col;
2746 enter_mouse_row = mouse_row;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002747}
2748
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002749 void
2750term_focus_change(int in_focus)
2751{
2752 term_T *term = curbuf->b_term;
2753
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002754 if (term == NULL || term->tl_vterm == NULL)
2755 return;
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002756
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002757 VTermState *state = vterm_obtain_state(term->tl_vterm);
2758
2759 if (in_focus)
2760 vterm_state_focus_in(state);
2761 else
2762 vterm_state_focus_out(state);
2763 term_forward_output(term);
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002764}
2765
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002766/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002767 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2768 * Return the Ctrl-key value in that case.
2769 */
2770 static int
2771raw_c_to_ctrl(int c)
2772{
2773 if ((mod_mask & MOD_MASK_CTRL)
2774 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2775 return c & 0x1f;
2776 return c;
2777}
2778
2779/*
2780 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002781 * Also when the Kitty keyboard protocol is used.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002782 * May set "mod_mask".
2783 */
2784 static int
2785ctrl_to_raw_c(int c)
2786{
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002787 if (c < 0x20 && vterm_using_key_protocol())
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002788 {
2789 mod_mask |= MOD_MASK_CTRL;
2790 return c + '@';
2791 }
2792 return c;
2793}
2794
2795/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002796 * Wait for input and send it to the job.
2797 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2798 * when there is no more typahead.
2799 * Return when the start of a CTRL-W command is typed or anything else that
2800 * should be handled as a Normal mode command.
2801 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2802 * the terminal was closed.
2803 */
2804 int
2805terminal_loop(int blocking)
2806{
2807 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002808 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002809 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002810 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002811#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002812 int tty_fd = curbuf->b_term->tl_job->jv_channel
2813 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002814#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002815 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002816
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002817 // Remember the terminal we are sending keys to. However, the terminal
2818 // might be closed while waiting for a character, e.g. typing "exit" in a
2819 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2820 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002821 in_terminal_loop = curbuf->b_term;
2822
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002823 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002824 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002825 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002826 if (termwinkey == Ctrl_W)
2827 termwinkey = 0;
2828 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002829 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002830 may_set_cursor_props(curbuf->b_term);
2831
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002832 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002833 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002834#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002835 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002836#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002837 // TODO: skip screen update when handling a sequence of keys.
2838 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002839 while (must_redraw != 0)
2840 if (update_screen(0) == FAIL)
2841 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002842 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002843 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002844 break;
2845
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002846 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002847 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002848
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002849 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002850 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002851 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002852 // Job finished while waiting for a character. Push back the
2853 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002854 if (raw_c != K_IGNORE)
2855 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002856 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002857 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002858 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002859 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002860 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002861
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002862#ifdef UNIX
2863 /*
2864 * The shell or another program may change the tty settings. Getting
2865 * them for every typed character is a bit of overhead, but it's needed
2866 * for the first character typed, e.g. when Vim starts in a shell.
2867 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002868 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002869 {
2870 ttyinfo_T info;
2871
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002872 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002873 if (get_tty_info(tty_fd, &info) == OK)
2874 term_backspace_char = info.backspace;
2875 }
2876#endif
2877
Bram Moolenaar4f974752019-02-17 17:44:42 +01002878#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002879 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2880 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002881 if (ctrl_break_was_pressed)
2882 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2883#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002884 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2885 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002886 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002887#ifdef FEAT_GUI
2888 && !curbuf->b_term->tl_system
2889#endif
2890 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002891 {
2892 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002893 int prev_raw_c = raw_c;
2894 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002895
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002896 if (add_to_showcmd(c))
2897 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002898
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002899 raw_c = term_vgetc();
2900 c = raw_c_to_ctrl(raw_c);
2901
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002902 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002903
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002904 if (!term_use_loop_check(TRUE)
2905 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002906 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002907 break;
2908
2909 if (prev_c == Ctrl_BSL)
2910 {
2911 if (c == Ctrl_N)
2912 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002913 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002914 term_enter_normal_mode();
2915 ret = FAIL;
2916 goto theend;
2917 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002918 // Send both keys to the terminal, first one here, second one
2919 // below.
2920 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2921 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922 }
2923 else if (c == Ctrl_C)
2924 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002925 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002926 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2927 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002928 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002929 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002930 // "CTRL-W .": send CTRL-W to the job
2931 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002932 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002933 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002934 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002935 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002936 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002937 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002938 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002939 else if (c == 'N')
2940 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002941 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002942 term_enter_normal_mode();
2943 ret = FAIL;
2944 goto theend;
2945 }
2946 else if (c == '"')
2947 {
2948 term_paste_register(prev_c);
2949 continue;
2950 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002951 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002952 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002953 // space for CTRL-W, modifier, multi-byte char and NUL
2954 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002955
2956 // Put the command into the typeahead buffer, when using the
2957 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2958 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002959 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002960 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002961 ret = OK;
2962 goto theend;
2963 }
2964 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002965# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002966 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002967 {
2968 WCHAR wc;
2969 char_u mb[3];
2970
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002971 mb[0] = (unsigned)raw_c >> 8;
2972 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002973 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002974 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002975 }
2976# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002977 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002978 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002979 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002980 // We are sure to come back here, don't reset the cursor color
2981 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002982 restore_cursor = FALSE;
2983
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002984 ret = OK;
2985 goto theend;
2986 }
2987 }
2988 ret = FAIL;
2989
2990theend:
2991 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002992 if (restore_cursor)
2993 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002994
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002995 // Move a snapshot of the screen contents to the buffer, so that completion
2996 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002997 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2998 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002999
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003000 return ret;
3001}
3002
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003003 static void
3004may_toggle_cursor(term_T *term)
3005{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003006 if (in_terminal_loop != term)
3007 return;
3008
3009 if (term->tl_cursor_visible)
3010 cursor_on();
3011 else
3012 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003013}
3014
3015/*
3016 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01003017 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003018 */
3019 static int
3020color2index(VTermColor *color, int fg, int *boldp)
3021{
3022 int red = color->red;
3023 int blue = color->blue;
3024 int green = color->green;
3025
LemonBoyb2b3acb2022-05-20 10:10:34 +01003026 *boldp = FALSE;
3027
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003028 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003029 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01003030
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003031 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003032 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003033 // Use the color as-is if possible, give up otherwise.
3034 if (color->index < t_colors)
3035 return color->index + 1;
3036 // 8-color terminals can actually display twice as many colors by
3037 // setting the high-intensity/bold bit.
3038 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003039 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003040 *boldp = TRUE;
3041 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003042 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01003043 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003044 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01003045
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003046 if (t_colors >= 256)
3047 {
3048 if (red == blue && red == green)
3049 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003050 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003051 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003052 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
3053 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
3054 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003055 int i;
3056
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003057 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003058 return 17; // 00/00/00
3059 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003060 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003061 for (i = 0; i < 23; ++i)
3062 if (red < cutoff[i])
3063 return i + 233;
3064 return 256;
3065 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003066 {
3067 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
3068 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003069
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003070 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003071 for (ri = 0; ri < 5; ++ri)
3072 if (red < cutoff[ri])
3073 break;
3074 for (gi = 0; gi < 5; ++gi)
3075 if (green < cutoff[gi])
3076 break;
3077 for (bi = 0; bi < 5; ++bi)
3078 if (blue < cutoff[bi])
3079 break;
3080 return 17 + ri * 36 + gi * 6 + bi;
3081 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003082 }
3083 return 0;
3084}
3085
3086/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01003087 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003088 */
3089 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003090vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003091{
3092 int attr = 0;
3093
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003094 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003096 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003098 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003099 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003100 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003101 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003102 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003103 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003104 return attr;
3105}
3106
3107/*
3108 * Store Vterm attributes in "cell" from highlight flags.
3109 */
3110 static void
3111hl2vtermAttr(int attr, cellattr_T *cell)
3112{
Bram Moolenaara80faa82020-04-12 19:37:17 +02003113 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003114 if (attr & HL_BOLD)
3115 cell->attrs.bold = 1;
3116 if (attr & HL_UNDERLINE)
3117 cell->attrs.underline = 1;
3118 if (attr & HL_ITALIC)
3119 cell->attrs.italic = 1;
3120 if (attr & HL_STRIKETHROUGH)
3121 cell->attrs.strike = 1;
3122 if (attr & HL_INVERSE)
3123 cell->attrs.reverse = 1;
3124}
3125
3126/*
3127 * Convert the attributes of a vterm cell into an attribute index.
3128 */
3129 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003130cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003131 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003132 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003133 VTermScreenCellAttrs *cellattrs,
3134 VTermColor *cellfg,
3135 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003136{
3137 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003138 VTermColor *fg = cellfg;
3139 VTermColor *bg = cellbg;
3140 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3141 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3142
3143 if (is_default_fg || is_default_bg)
3144 {
3145 if (wp != NULL && *wp->w_p_wcr != NUL)
3146 {
3147 if (is_default_fg)
3148 fg = &wp->w_term_wincolor.fg;
3149 if (is_default_bg)
3150 bg = &wp->w_term_wincolor.bg;
3151 }
3152 else
3153 {
3154 if (is_default_fg)
3155 fg = &term->tl_default_color.fg;
3156 if (is_default_bg)
3157 bg = &term->tl_default_color.bg;
3158 }
3159 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003160
3161#ifdef FEAT_GUI
3162 if (gui.in_use)
3163 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003164 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3165 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3166 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003167 }
3168 else
3169#endif
3170#ifdef FEAT_TERMGUICOLORS
3171 if (p_tgc)
3172 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003173 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3174 ? INVALCOLOR
3175 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3176 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3177 ? INVALCOLOR
3178 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3179 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003180 }
3181 else
3182#endif
3183 {
3184 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003185 int ctermfg = color2index(fg, TRUE, &bold);
3186 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003187
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003188 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003189 if (bold == TRUE)
3190 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003191
3192 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003193 }
3194 return 0;
3195}
3196
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003197 static void
3198set_dirty_snapshot(term_T *term)
3199{
3200 term->tl_dirty_snapshot = TRUE;
3201#ifdef FEAT_TIMERS
3202 if (!term->tl_normal_mode)
3203 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003204 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003205 profile_setlimit(100L, &term->tl_timer_due);
3206 term->tl_timer_set = TRUE;
3207 }
3208#endif
3209}
3210
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003211 static int
3212handle_damage(VTermRect rect, void *user)
3213{
3214 term_T *term = (term_T *)user;
3215
3216 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3217 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003218 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003219 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003220 return 1;
3221}
3222
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003223 static void
3224term_scroll_up(term_T *term, int start_row, int count)
3225{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003226 win_T *wp = NULL;
3227 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003228 VTermColor fg, bg;
3229 VTermScreenCellAttrs attr;
3230 int clear_attr;
3231
Bram Moolenaara80faa82020-04-12 19:37:17 +02003232 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003233
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003234 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003235 {
3236 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003237 {
3238 // Set the color to clear lines with.
3239 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3240 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003241 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003242 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003243 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003244 }
3245}
3246
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003247 static int
3248handle_moverect(VTermRect dest, VTermRect src, void *user)
3249{
3250 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003251 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003252
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003253 // Scrolling up is done much more efficiently by deleting lines instead of
3254 // redrawing the text. But avoid doing this multiple times, postpone until
3255 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003256 if (dest.start_col == src.start_col
3257 && dest.end_col == src.end_col
3258 && dest.start_row < src.start_row)
3259 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003260 if (dest.start_row == 0)
3261 term->tl_postponed_scroll += count;
3262 else
3263 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003264 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003265
3266 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3267 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003268 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003269
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003270 // Note sure if the scrolling will work correctly, let's do a complete
3271 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003272 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003273 return 1;
3274}
3275
3276 static int
3277handle_movecursor(
3278 VTermPos pos,
3279 VTermPos oldpos UNUSED,
3280 int visible,
3281 void *user)
3282{
3283 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003284 win_T *wp = NULL;
3285 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003286
3287 term->tl_cursor_pos = pos;
3288 term->tl_cursor_visible = visible;
3289
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003290 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003291 {
3292 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003293 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003294 }
3295 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003296 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003297
3298 return 1;
3299}
3300
3301 static int
3302handle_settermprop(
3303 VTermProp prop,
3304 VTermValue *value,
3305 void *user)
3306{
3307 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003308 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003309
3310 switch (prop)
3311 {
3312 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003313 if (disable_vterm_title_for_testing)
3314 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003315 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003316 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003317 if (strval == NULL)
3318 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003319 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003320 // a blank title isn't useful, make it empty, so that "running" is
3321 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003322 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003323 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003324 // Same as blank
3325 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003326 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003327 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3328 term->tl_title = NULL;
3329 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003330 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003331 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003332#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003333 else if (!enc_utf8 && enc_codepage > 0)
3334 {
3335 WCHAR *ret = NULL;
3336 int length = 0;
3337
3338 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003339 (char*)value->string.str,
3340 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003341 if (ret != NULL)
3342 {
3343 WideCharToMultiByte_alloc(enc_codepage, 0,
3344 ret, length, (char**)&term->tl_title,
3345 &length, 0, 0);
3346 vim_free(ret);
3347 }
3348 }
3349#endif
3350 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003351 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003352 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003353 strval = NULL;
3354 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003355 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003356 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003357 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003358 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003359 curwin->w_redr_status = TRUE;
3360 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003361 break;
3362
3363 case VTERM_PROP_CURSORVISIBLE:
3364 term->tl_cursor_visible = value->boolean;
3365 may_toggle_cursor(term);
3366 out_flush();
3367 break;
3368
3369 case VTERM_PROP_CURSORBLINK:
3370 term->tl_cursor_blink = value->boolean;
3371 may_set_cursor_props(term);
3372 break;
3373
3374 case VTERM_PROP_CURSORSHAPE:
3375 term->tl_cursor_shape = value->number;
3376 may_set_cursor_props(term);
3377 break;
3378
3379 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003380 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003381 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003382 if (strval == NULL)
3383 break;
3384 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003385 may_set_cursor_props(term);
3386 break;
3387
3388 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003389 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003390 term->tl_using_altscreen = value->boolean;
3391 break;
3392
3393 default:
3394 break;
3395 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003396 vim_free(strval);
3397
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003398 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003399 return 1;
3400}
3401
3402/*
3403 * The job running in the terminal resized the terminal.
3404 */
3405 static int
3406handle_resize(int rows, int cols, void *user)
3407{
3408 term_T *term = (term_T *)user;
3409 win_T *wp;
3410
3411 term->tl_rows = rows;
3412 term->tl_cols = cols;
3413 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003414 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003415 term->tl_vterm_size_changed = FALSE;
3416 else
3417 {
3418 FOR_ALL_WINDOWS(wp)
3419 {
3420 if (wp->w_buffer == term->tl_buffer)
3421 {
3422 win_setheight_win(rows, wp);
3423 win_setwidth_win(cols, wp);
3424 }
3425 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003426 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003427 }
3428 return 1;
3429}
3430
3431/*
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003432 * If the number of lines that are stored goes over 'termwinscroll' then
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003433 * delete the first 10%.
3434 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3435 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003436 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003437 static void
3438limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003439{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003440 if (gap->ga_len < term->tl_buffer->b_p_twsl)
3441 return;
3442
Milly6d5f4a02024-10-22 23:17:45 +02003443 int todo = MAX(term->tl_buffer->b_p_twsl / 10,
3444 gap->ga_len - term->tl_buffer->b_p_twsl);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003445 int i;
3446
3447 curbuf = term->tl_buffer;
3448 for (i = 0; i < todo; ++i)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003449 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003450 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003451 if (update_buffer)
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003452 ml_delete(1);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003453 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003454 curbuf = curwin->w_buffer;
3455
3456 gap->ga_len -= todo;
3457 mch_memmove(gap->ga_data,
3458 (sb_line_T *)gap->ga_data + todo,
3459 sizeof(sb_line_T) * gap->ga_len);
3460 if (update_buffer)
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003461 {
Hirohito Higashifa9753a2025-04-27 15:36:43 +02003462 win_T *curwin_save = curwin;
3463 win_T *wp = NULL;
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003464
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003465 term->tl_scrollback_scrolled -= todo;
Christian Brabandt1254e6d2024-07-29 21:19:51 +02003466
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003467 FOR_ALL_WINDOWS(wp)
3468 {
3469 if (wp->w_buffer == term->tl_buffer)
3470 {
3471 curwin = wp;
3472 check_cursor();
Hirohito Higashifa9753a2025-04-27 15:36:43 +02003473 update_topline();
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003474 }
3475 }
3476 curwin = curwin_save;
3477 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003478}
3479
3480/*
3481 * Handle a line that is pushed off the top of the screen.
3482 */
3483 static int
3484handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3485{
3486 term_T *term = (term_T *)user;
3487 garray_T *gap;
3488 int update_buffer;
3489
3490 if (term->tl_normal_mode)
3491 {
3492 // In Terminal-Normal mode the user interacts with the buffer, thus we
3493 // must not change it. Postpone adding the scrollback lines.
3494 gap = &term->tl_scrollback_postponed;
3495 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003496 }
3497 else
3498 {
3499 // First remove the lines that were appended before, the pushed line
3500 // goes above it.
3501 cleanup_scrollback(term);
3502 gap = &term->tl_scrollback;
3503 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003504 }
3505
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003506 limit_scrollback(term, gap, update_buffer);
3507
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003508 if (ga_grow(gap, 1) == FAIL)
3509 return 0;
3510
3511 cellattr_T *p = NULL;
3512 int len = 0;
3513 int i;
3514 int c;
3515 int col;
3516 int text_len;
3517 char_u *text;
3518 sb_line_T *line;
3519 garray_T ga;
3520 cellattr_T fill_attr = term->tl_default_color;
3521
3522 // do not store empty cells at the end
3523 for (i = 0; i < cols; ++i)
3524 if (cells[i].chars[0] != 0)
3525 len = i + 1;
3526 else
3527 cell2cellattr(&cells[i], &fill_attr);
3528
3529 ga_init2(&ga, 1, 100);
3530 if (len > 0)
3531 p = ALLOC_MULT(cellattr_T, len);
3532 if (p != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003533 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003534 for (col = 0; col < len; col += cells[col].width)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003535 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003536 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003537 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003538 ga.ga_len = 0;
3539 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003540 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003541 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3542 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3543 (char_u *)ga.ga_data + ga.ga_len);
3544 cell2cellattr(&cells[col], &p[col]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003545 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003546 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003547 if (ga_grow(&ga, 1) == FAIL)
3548 {
3549 if (update_buffer)
3550 text = (char_u *)"";
3551 else
3552 text = vim_strsave((char_u *)"");
3553 text_len = 0;
3554 }
3555 else
3556 {
3557 text = ga.ga_data;
3558 text_len = ga.ga_len;
3559 *(text + text_len) = NUL;
3560 }
3561 if (update_buffer)
3562 add_scrollback_line_to_buffer(term, text, text_len);
3563
3564 line = (sb_line_T *)gap->ga_data + gap->ga_len;
3565 line->sb_cols = len;
3566 line->sb_cells = p;
3567 line->sb_fill_attr = fill_attr;
3568 if (update_buffer)
3569 {
3570 line->sb_text = NULL;
3571 ++term->tl_scrollback_scrolled;
3572 ga_clear(&ga); // free the text
3573 }
3574 else
3575 {
3576 line->sb_text = text;
3577 ga_init(&ga); // text is kept in tl_scrollback_postponed
3578 }
3579 ++gap->ga_len;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003580 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003581}
3582
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003583/*
3584 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3585 * received and stored in tl_scrollback_postponed.
3586 */
3587 static void
3588handle_postponed_scrollback(term_T *term)
3589{
3590 int i;
3591
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003592 if (term->tl_scrollback_postponed.ga_len == 0)
3593 return;
3594 ch_log(NULL, "Moving postponed scrollback to scrollback");
3595
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003596 // First remove the lines that were appended before, the pushed lines go
3597 // above it.
3598 cleanup_scrollback(term);
3599
3600 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3601 {
3602 char_u *text;
3603 sb_line_T *pp_line;
3604 sb_line_T *line;
3605
3606 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3607 break;
3608 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3609
3610 text = pp_line->sb_text;
3611 if (text == NULL)
3612 text = (char_u *)"";
3613 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3614 vim_free(pp_line->sb_text);
3615
3616 line = (sb_line_T *)term->tl_scrollback.ga_data
3617 + term->tl_scrollback.ga_len;
3618 line->sb_cols = pp_line->sb_cols;
3619 line->sb_cells = pp_line->sb_cells;
3620 line->sb_fill_attr = pp_line->sb_fill_attr;
3621 line->sb_text = NULL;
3622 ++term->tl_scrollback_scrolled;
3623 ++term->tl_scrollback.ga_len;
3624 }
3625
3626 ga_clear(&term->tl_scrollback_postponed);
3627 limit_scrollback(term, &term->tl_scrollback, TRUE);
3628}
3629
LemonBoy77771d32022-04-13 11:47:25 +01003630/*
3631 * Called when the terminal wants to ring the system bell.
3632 */
3633 static int
3634handle_bell(void *user UNUSED)
3635{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003636 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003637 return 0;
3638}
3639
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003640static VTermScreenCallbacks screen_callbacks = {
Yegappan Lakshmanan562610c2025-05-04 21:05:51 +02003641 handle_damage, // damage
3642 handle_moverect, // moverect
3643 handle_movecursor, // movecursor
3644 handle_settermprop, // settermprop
3645 handle_bell, // bell
3646 handle_resize, // resize
3647 handle_pushline, // sb_pushline
3648 NULL, // sb_popline
3649 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003650};
3651
3652/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003653 * Do the work after the channel of a terminal was closed.
3654 * Must be called only when updating_screen is FALSE.
3655 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3656 */
3657 static int
3658term_after_channel_closed(term_T *term)
3659{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003660 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003661 if (!term->tl_normal_mode)
3662 {
3663 int fnum = term->tl_buffer->b_fnum;
3664
3665 cleanup_vterm(term);
3666
3667 if (term->tl_finish == TL_FINISH_CLOSE)
3668 {
3669 aco_save_T aco;
zeertzjqbc11f6d2024-08-16 21:11:31 +02003670 int do_set_w_locked = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003671#ifdef FEAT_PROP_POPUP
3672 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003673
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003674 // If this was a terminal in a popup window, go back to the
3675 // previous window.
3676 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3677 {
3678 pwin = curwin;
3679 if (win_valid(prevwin))
3680 win_enter(prevwin, FALSE);
3681 }
3682 else
3683#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003684 // If this is the last normal window: exit Vim.
3685 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3686 {
3687 exarg_T ea;
3688
Bram Moolenaara80faa82020-04-12 19:37:17 +02003689 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003690 ex_quit(&ea);
3691 return TRUE;
3692 }
3693
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003694 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003695 ch_log(NULL, "terminal job finished, closing window");
3696 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaare76062c2022-11-28 18:51:43 +00003697 if (curbuf == term->tl_buffer)
3698 {
3699 // Avoid closing the window if we temporarily use it.
3700 if (is_aucmd_win(curwin))
zeertzjqbc11f6d2024-08-16 21:11:31 +02003701 do_set_w_locked = TRUE;
3702 if (do_set_w_locked)
Christian Brabandt0a6e57b2024-08-15 22:15:28 +02003703 curwin->w_locked = TRUE;
Bram Moolenaare76062c2022-11-28 18:51:43 +00003704 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
zeertzjqbc11f6d2024-08-16 21:11:31 +02003705 if (do_set_w_locked)
Christian Brabandt0a6e57b2024-08-15 22:15:28 +02003706 curwin->w_locked = FALSE;
Bram Moolenaare76062c2022-11-28 18:51:43 +00003707 aucmd_restbuf(&aco);
3708 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003709#ifdef FEAT_PROP_POPUP
3710 if (pwin != NULL)
3711 popup_close_with_retval(pwin, 0);
3712#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003713 return TRUE;
3714 }
3715 if (term->tl_finish == TL_FINISH_OPEN
3716 && term->tl_buffer->b_nwindows == 0)
3717 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003718 char *cmd = term->tl_opencmd == NULL
3719 ? "botright sbuf %d"
3720 : (char *)term->tl_opencmd;
3721 size_t len = strlen(cmd) + 50;
3722 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003723
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003724 if (buf != NULL)
3725 {
3726 ch_log(NULL, "terminal job finished, opening window");
3727 vim_snprintf(buf, len, cmd, fnum);
3728 do_cmdline_cmd((char_u *)buf);
3729 vim_free(buf);
3730 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003731 }
3732 else
3733 ch_log(NULL, "terminal job finished");
3734 }
3735
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003736 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003737 return FALSE;
3738}
3739
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003740#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3741/*
3742 * If the current window is a terminal in a popup window and the job has
3743 * finished, close the popup window and to back to the previous window.
3744 * Otherwise return FAIL.
3745 */
3746 int
3747may_close_term_popup(void)
3748{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003749 if (!popup_is_popup(curwin) || curbuf->b_term == NULL
3750 || term_job_running_not_none(curbuf->b_term))
3751 return FAIL;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003752
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003753 win_T *pwin = curwin;
3754
3755 if (win_valid(prevwin))
3756 win_enter(prevwin, FALSE);
3757 popup_close_with_retval(pwin, 0);
3758 return OK;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003759}
3760#endif
3761
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003762/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003763 * Called when a channel is going to be closed, before invoking the close
3764 * callback.
3765 */
3766 void
3767term_channel_closing(channel_T *ch)
3768{
3769 term_T *term;
3770
3771 for (term = first_term; term != NULL; term = term->tl_next)
3772 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3773 term->tl_channel_closing = TRUE;
3774}
3775
3776/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003777 * Called when a channel has been closed.
3778 * If this was a channel for a terminal window then finish it up.
3779 */
3780 void
3781term_channel_closed(channel_T *ch)
3782{
3783 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003784 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003785 int did_one = FALSE;
3786
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003787 for (term = first_term; term != NULL; term = next_term)
3788 {
3789 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003790 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003791 {
3792 term->tl_channel_closed = TRUE;
3793 did_one = TRUE;
3794
Bram Moolenaard23a8232018-02-10 18:45:26 +01003795 VIM_CLEAR(term->tl_title);
3796 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003797#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003798 if (term->tl_out_fd != NULL)
3799 {
3800 fclose(term->tl_out_fd);
3801 term->tl_out_fd = NULL;
3802 }
3803#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003804
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003805 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003806 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003807 // Cannot open or close windows now. Can happen when
3808 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003809 term->tl_channel_recently_closed = TRUE;
3810 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003811 }
3812
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003813 if (term_after_channel_closed(term))
3814 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003815 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003816 }
3817
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003818 if (did_one)
3819 {
3820 redraw_statuslines();
3821
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003822 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003823 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003824 typebuf_was_filled = TRUE;
3825
3826 term = curbuf->b_term;
3827 if (term != NULL)
3828 {
3829 if (term->tl_job == ch->ch_job)
3830 maketitle();
3831 update_cursor(term, term->tl_cursor_visible);
3832 }
3833 }
3834}
3835
3836/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003837 * To be called after resetting updating_screen: handle any terminal where the
3838 * channel was closed.
3839 */
3840 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003841term_check_channel_closed_recently(void)
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003842{
3843 term_T *term;
3844 term_T *next_term;
3845
3846 for (term = first_term; term != NULL; term = next_term)
3847 {
3848 next_term = term->tl_next;
3849 if (term->tl_channel_recently_closed)
3850 {
3851 term->tl_channel_recently_closed = FALSE;
3852 if (term_after_channel_closed(term))
3853 // start over, the list may have changed
3854 next_term = first_term;
3855 }
3856 }
3857}
3858
3859/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003860 * Fill one screen line from a line of the terminal.
3861 * Advances "pos" to past the last column.
3862 */
3863 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003864term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003865 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003866 win_T *wp,
3867 VTermScreen *screen,
3868 VTermPos *pos,
3869 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003870{
3871 int off = screen_get_current_line_off();
3872
3873 for (pos->col = 0; pos->col < max_col; )
3874 {
3875 VTermScreenCell cell;
3876 int c;
3877
3878 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003879 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003880
3881 c = cell.chars[0];
3882 if (c == NUL)
3883 {
3884 ScreenLines[off] = ' ';
3885 if (enc_utf8)
3886 ScreenLinesUC[off] = NUL;
3887 }
3888 else
3889 {
3890 if (enc_utf8)
3891 {
3892 int i;
3893
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003894 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003895 for (i = 0; i < Screen_mco
3896 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3897 {
3898 ScreenLinesC[i][off] = cell.chars[i + 1];
3899 if (cell.chars[i + 1] == 0)
3900 break;
3901 }
3902 if (c >= 0x80 || (Screen_mco > 0
3903 && ScreenLinesC[0][off] != 0))
3904 {
3905 ScreenLines[off] = ' ';
3906 ScreenLinesUC[off] = c;
3907 }
3908 else
3909 {
3910 ScreenLines[off] = c;
3911 ScreenLinesUC[off] = NUL;
3912 }
3913 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003914#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003915 else if (has_mbyte && c >= 0x80)
3916 {
3917 char_u mb[MB_MAXBYTES+1];
3918 WCHAR wc = c;
3919
3920 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3921 (char*)mb, 2, 0, 0) > 1)
3922 {
3923 ScreenLines[off] = mb[0];
3924 ScreenLines[off + 1] = mb[1];
3925 cell.width = mb_ptr2cells(mb);
3926 }
3927 else
3928 ScreenLines[off] = c;
3929 }
3930#endif
3931 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003932 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003933 ScreenLines[off] = c;
3934 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003935 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3936 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003937
3938 ++pos->col;
3939 ++off;
3940 if (cell.width == 2)
3941 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003942 // don't set the second byte to NUL for a DBCS encoding, it
3943 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003944 if (enc_utf8)
3945 {
3946 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003947 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003948 }
3949 else if (!has_mbyte)
3950 {
3951 // Can't show a double-width character with a single-byte
3952 // 'encoding', just use a space.
3953 ScreenLines[off] = ' ';
3954 ScreenAttrs[off] = ScreenAttrs[off - 1];
3955 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003956
3957 ++pos->col;
3958 ++off;
3959 }
3960 }
3961}
3962
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003963#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003964 static void
3965update_system_term(term_T *term)
3966{
3967 VTermPos pos;
3968 VTermScreen *screen;
3969
3970 if (term->tl_vterm == NULL)
3971 return;
3972 screen = vterm_obtain_screen(term->tl_vterm);
3973
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003974 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003975 while (term->tl_toprow > 0
3976 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3977 {
3978 int save_p_more = p_more;
3979
3980 p_more = FALSE;
3981 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003982 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003983 p_more = save_p_more;
3984 --term->tl_toprow;
3985 }
3986
3987 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3988 && pos.row < Rows; ++pos.row)
3989 {
3990 if (pos.row < term->tl_rows)
3991 {
3992 int max_col = MIN(Columns, term->tl_cols);
3993
Bram Moolenaar83d47902020-03-26 20:34:00 +01003994 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003995 }
3996 else
3997 pos.col = 0;
3998
zeertzjqd0c1b772024-03-16 15:03:33 +01003999 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, -1,
4000 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01004001 }
4002
4003 term->tl_dirty_row_start = MAX_ROW;
4004 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01004005}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01004006#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01004007
4008/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004009 * Return TRUE if window "wp" is to be redrawn with term_update_window().
4010 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004011 * Terminal-Normal mode.
4012 */
4013 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004014term_do_update_window(win_T *wp)
4015{
4016 term_T *term = wp->w_buffer->b_term;
4017
4018 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
4019}
4020
4021/*
4022 * Called to update a window that contains an active terminal.
4023 */
4024 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004025term_update_window(win_T *wp)
4026{
4027 term_T *term = wp->w_buffer->b_term;
4028 VTerm *vterm;
4029 VTermScreen *screen;
4030 VTermState *state;
4031 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004032 int rows, cols;
4033 int newrows, newcols;
4034 int minsize;
4035 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004036
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004037 vterm = term->tl_vterm;
4038 screen = vterm_obtain_screen(vterm);
4039 state = vterm_obtain_state(vterm);
4040
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004041 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
4042 // With UPD_SOME_VALID only redraw what was marked dirty.
4043 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004044 {
4045 term->tl_dirty_row_start = 0;
4046 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004047
4048 if (term->tl_postponed_scroll > 0
4049 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004050 // Scrolling is usually faster than redrawing, when there are only
4051 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004052 term_scroll_up(term, 0, term->tl_postponed_scroll);
4053 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004054 }
4055
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004056 /*
4057 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004058 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004059 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004060 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004061
Bram Moolenaar498c2562018-04-15 23:45:15 +02004062 newrows = 99999;
4063 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004064 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02004065 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004066 // Always use curwin, it may be a popup window.
4067 win_T *wwp = twp == NULL ? curwin : twp;
4068
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004069 // When more than one window shows the same terminal, use the
4070 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004071 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004072 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004073 newrows = MIN(newrows, wwp->w_height);
4074 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004075 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004076 if (twp == NULL)
4077 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004078 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02004079 if (newrows == 99999 || newcols == 99999)
4080 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02004081 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
4082 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
4083
Bram Moolenaareba13e42021-02-23 17:47:23 +01004084 // If no cell is visible there is no point in resizing. Also, vterm can't
4085 // handle a zero height.
4086 if (newrows == 0 || newcols == 0)
4087 return;
4088
Bram Moolenaar498c2562018-04-15 23:45:15 +02004089 if (term->tl_rows != newrows || term->tl_cols != newcols)
4090 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004091 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004092 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004093 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02004094 newrows);
4095 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02004096
4097 // Updating the terminal size will cause the snapshot to be cleared.
4098 // When not in terminal_loop() we need to restore it.
4099 if (term != in_terminal_loop)
4100 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004101 }
4102
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004103 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004104 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01004105 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004106
Bram Moolenaar3a497e12017-09-30 20:40:27 +02004107 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
4108 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004109 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004110 if (pos.row < term->tl_rows)
4111 {
Bram Moolenaar13568252018-03-16 20:46:58 +01004112 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004113
Bram Moolenaar83d47902020-03-26 20:34:00 +01004114 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004115 }
4116 else
4117 pos.col = 0;
4118
Bram Moolenaar510f0372022-07-04 17:46:22 +01004119 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01004120#ifdef FEAT_MENU
4121 + winbar_height(wp)
4122#endif
Hirohito Higashi3b9b95d2025-06-01 20:22:55 +02004123 , wp->w_wincol, pos.col, wp->w_width, -1,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004124#ifdef FEAT_PROP_POPUP
4125 popup_is_popup(wp) ? SLF_POPUP :
4126#endif
4127 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004128 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00004129}
4130
4131/*
4132 * Called after updating all windows: may reset dirty rows.
4133 */
4134 void
4135term_did_update_window(win_T *wp)
4136{
4137 term_T *term = wp->w_buffer->b_term;
4138
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004139 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode
4140 || wp->w_redr_type != 0)
4141 return;
4142
4143 term->tl_dirty_row_start = MAX_ROW;
4144 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004145}
4146
4147/*
4148 * Return TRUE if "wp" is a terminal window where the job has finished.
4149 */
4150 int
4151term_is_finished(buf_T *buf)
4152{
4153 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
4154}
4155
4156/*
4157 * Return TRUE if "wp" is a terminal window where the job has finished or we
4158 * are in Terminal-Normal mode, thus we show the buffer contents.
4159 */
4160 int
4161term_show_buffer(buf_T *buf)
4162{
4163 term_T *term = buf->b_term;
4164
4165 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4166}
4167
4168/*
4169 * The current buffer is going to be changed. If there is terminal
4170 * highlighting remove it now.
4171 */
4172 void
4173term_change_in_curbuf(void)
4174{
4175 term_T *term = curbuf->b_term;
4176
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004177 if (!term_is_finished(curbuf) || term->tl_scrollback.ga_len <= 0)
4178 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004179
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004180 free_scrollback(term);
4181 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
4182
4183 // The buffer is now like a normal buffer, it cannot be easily
4184 // abandoned when changed.
4185 set_string_option_direct((char_u *)"buftype", -1,
4186 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004187}
4188
4189/*
4190 * Get the screen attribute for a position in the buffer.
4191 * Use a negative "col" to get the filler background color.
4192 */
4193 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004194term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004195{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004196 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004197 term_T *term = buf->b_term;
4198 sb_line_T *line;
4199 cellattr_T *cellattr;
4200
4201 if (lnum > term->tl_scrollback.ga_len)
4202 cellattr = &term->tl_default_color;
4203 else
4204 {
4205 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4206 if (col < 0 || col >= line->sb_cols)
4207 cellattr = &line->sb_fill_attr;
4208 else
4209 cellattr = line->sb_cells + col;
4210 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004211 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004212}
4213
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004214/*
4215 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004216 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004217 */
4218 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004219cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004220{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004221 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4222 if (rgb->index == 0)
4223 rgb->type = VTERM_COLOR_RGB;
4224 else
4225 {
4226 rgb->type = VTERM_COLOR_INDEXED;
4227 --rgb->index;
4228 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004229}
4230
4231/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004232 * Initialize vterm color from the synID.
4233 * Returns TRUE if color is set to "fg" and "bg".
4234 * Otherwise returns FALSE.
4235 */
4236 static int
4237get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4238{
4239#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4240 // Use the actual color for the GUI and when 'termguicolors' is set.
4241 if (0
4242# ifdef FEAT_GUI
4243 || gui.in_use
4244# endif
4245# ifdef FEAT_TERMGUICOLORS
4246 || p_tgc
4247# ifdef FEAT_VTP
4248 // Finally get INVALCOLOR on this execution path
4249 || (!p_tgc && t_colors >= 256)
4250# endif
4251# endif
4252 )
4253 {
4254 guicolor_T fg_rgb = INVALCOLOR;
4255 guicolor_T bg_rgb = INVALCOLOR;
4256
4257 if (id > 0)
4258 syn_id2colors(id, &fg_rgb, &bg_rgb);
4259
4260 if (fg_rgb != INVALCOLOR)
4261 {
4262 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4263 fg->red = (unsigned)(rgb >> 16);
4264 fg->green = (unsigned)(rgb >> 8) & 255;
4265 fg->blue = (unsigned)rgb & 255;
4266 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4267 }
4268 else
4269 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4270
4271 if (bg_rgb != INVALCOLOR)
4272 {
4273 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4274 bg->red = (unsigned)(rgb >> 16);
4275 bg->green = (unsigned)(rgb >> 8) & 255;
4276 bg->blue = (unsigned)rgb & 255;
4277 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4278 }
4279 else
4280 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4281
4282 return TRUE;
4283 }
4284 else
4285#endif
4286 if (t_colors >= 16)
4287 {
4288 int cterm_fg = -1;
4289 int cterm_bg = -1;
4290
4291 if (id > 0)
4292 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4293
4294 if (cterm_fg >= 0)
4295 {
4296 cterm_color2vterm(cterm_fg, fg);
4297 fg->type |= VTERM_COLOR_DEFAULT_FG;
4298 }
4299 else
4300 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4301
4302 if (cterm_bg >= 0)
4303 {
4304 cterm_color2vterm(cterm_bg, bg);
4305 bg->type |= VTERM_COLOR_DEFAULT_BG;
4306 }
4307 else
4308 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4309
4310 return TRUE;
4311 }
4312
4313 return FALSE;
4314}
4315
4316 void
4317term_reset_wincolor(win_T *wp)
4318{
4319 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4320 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4321}
4322
4323/*
4324 * Cache the color of 'wincolor'.
4325 */
4326 void
4327term_update_wincolor(win_T *wp)
4328{
4329 int id = 0;
4330
4331 if (*wp->w_p_wcr != NUL)
4332 id = syn_name2id(wp->w_p_wcr);
4333 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4334 &wp->w_term_wincolor.bg))
4335 term_reset_wincolor(wp);
4336}
4337
4338/*
4339 * Called when option 'termguicolors' was set,
4340 * or when any highlight is changed.
4341 */
4342 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004343term_update_wincolor_all(void)
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004344{
4345 win_T *wp = NULL;
4346 int did_curwin = FALSE;
4347
4348 while (for_all_windows_and_curwin(&wp, &did_curwin))
4349 term_update_wincolor(wp);
4350}
4351
4352/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004353 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004354 */
4355 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004356init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004357{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004358 VTermColor *fg, *bg;
4359 int fgval, bgval;
4360 int id;
4361
Bram Moolenaara80faa82020-04-12 19:37:17 +02004362 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004363 term->tl_default_color.width = 1;
4364 fg = &term->tl_default_color.fg;
4365 bg = &term->tl_default_color.bg;
4366
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004367 // Vterm uses a default black background. Set it to white when
4368 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004369 if (*p_bg == 'l')
4370 {
4371 fgval = 0;
4372 bgval = 255;
4373 }
4374 else
4375 {
4376 fgval = 255;
4377 bgval = 0;
4378 }
4379 fg->red = fg->green = fg->blue = fgval;
4380 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004381 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4382 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004383
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004384 // The highlight group overrules the defaults.
4385 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004386
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004387 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004388 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004389#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004390 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004391#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004392
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004393 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004394 if (cterm_normal_fg_color > 0)
4395 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004396 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004397# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4398# ifdef VIMDLL
4399 if (!gui.in_use)
4400# endif
4401 {
4402 tmp = fg->red;
4403 fg->red = fg->blue;
4404 fg->blue = tmp;
4405 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004406# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004407 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004408# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004409 else
4410 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004411# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004412
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004413 if (cterm_normal_bg_color > 0)
4414 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004415 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004416# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4417# ifdef VIMDLL
4418 if (!gui.in_use)
4419# endif
4420 {
4421 tmp = fg->red;
4422 fg->red = fg->blue;
4423 fg->blue = tmp;
4424 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004425# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004426 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004427# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004428 else
4429 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004430# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004431 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004432}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004433
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004434#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4435/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004436 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4437 * "ansi_colors" argument in term_start()) shall be applied.
4438 */
4439 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004440term_use_palette(void)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004441{
4442 if (0
4443#ifdef FEAT_GUI
4444 || gui.in_use
4445#endif
4446#ifdef FEAT_TERMGUICOLORS
4447 || p_tgc
4448#endif
4449 )
4450 return TRUE;
4451 return FALSE;
4452}
4453
4454/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004455 * Set the 16 ANSI colors from array of RGB values
4456 */
4457 static void
4458set_vterm_palette(VTerm *vterm, long_u *rgb)
4459{
4460 int index = 0;
4461 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004462
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004463 for (; index < 16; index++)
4464 {
4465 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004466
Millyb771b6b2021-11-23 12:07:25 +00004467 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004468 color.red = (unsigned)(rgb[index] >> 16);
4469 color.green = (unsigned)(rgb[index] >> 8) & 255;
4470 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004471 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004472 vterm_state_set_palette_color(state, index, &color);
4473 }
4474}
4475
4476/*
4477 * Set the ANSI color palette from a list of colors
4478 */
4479 static int
4480set_ansi_colors_list(VTerm *vterm, list_T *list)
4481{
4482 int n = 0;
4483 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004484 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004485
Bram Moolenaarb0992022020-01-30 14:55:42 +01004486 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004487 {
4488 char_u *color_name;
4489 guicolor_T guicolor;
4490
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004491 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004492 if (color_name == NULL)
4493 return FAIL;
4494
4495 guicolor = GUI_GET_COLOR(color_name);
4496 if (guicolor == INVALCOLOR)
4497 return FAIL;
4498
4499 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4500 }
4501
4502 if (n != 16 || li != NULL)
4503 return FAIL;
4504
4505 set_vterm_palette(vterm, rgb);
4506
4507 return OK;
4508}
4509
4510/*
4511 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4512 */
4513 static void
4514init_vterm_ansi_colors(VTerm *vterm)
4515{
4516 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4517
LemonBoyb2b3acb2022-05-20 10:10:34 +01004518 if (var == NULL)
4519 return;
4520
4521 if (var->di_tv.v_type != VAR_LIST
4522 || var->di_tv.vval.v_list == NULL
4523 || var->di_tv.vval.v_list->lv_first == &range_list_item
4524 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004525 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004526}
4527#endif
4528
Bram Moolenaar52acb112018-03-18 19:20:22 +01004529/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004530 * Handles a "drop" command from the job in the terminal.
4531 * "item" is the file name, "item->li_next" may have options.
4532 */
4533 static void
4534handle_drop_command(listitem_T *item)
4535{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004536 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004537 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004538 int bufnr;
4539 win_T *wp;
4540 tabpage_T *tp;
4541 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004542 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004543
4544 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4545 FOR_ALL_TAB_WINDOWS(tp, wp)
4546 {
4547 if (wp->w_buffer->b_fnum == bufnr)
4548 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004549 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004550 goto_tabpage_win(tp, wp);
4551 return;
4552 }
4553 }
4554
Bram Moolenaara80faa82020-04-12 19:37:17 +02004555 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004556
4557 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4558 && opt_item->li_tv.vval.v_dict != NULL)
4559 {
4560 dict_T *dict = opt_item->li_tv.vval.v_dict;
4561 char_u *p;
4562
Bram Moolenaard61efa52022-07-23 09:52:04 +01004563 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004564 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004565 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004566 if (p != NULL)
4567 {
4568 if (check_ff_value(p) == FAIL)
4569 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4570 else
4571 ea.force_ff = *p;
4572 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004573 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004574 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004575 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004576 if (p != NULL)
4577 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004578 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004579 if (ea.cmd != NULL)
4580 {
4581 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4582 ea.force_enc = 11;
4583 tofree = ea.cmd;
4584 }
4585 }
4586
Bram Moolenaard61efa52022-07-23 09:52:04 +01004587 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004588 if (p != NULL)
4589 get_bad_opt(p, &ea);
4590
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004591 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004592 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004593 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004594 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004595 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004596 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004597 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004598 ea.force_bin = FORCE_NOBIN;
4599 }
4600
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004601 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004602 if (ea.cmd == NULL)
4603 ea.cmd = (char_u *)"split";
4604 ea.arg = fname;
4605 ea.cmdidx = CMD_split;
4606 ex_splitview(&ea);
4607
4608 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004609}
4610
4611/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004612 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4613 */
4614 static int
4615is_permitted_term_api(char_u *func, char_u *pat)
4616{
4617 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4618}
4619
4620/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004621 * Handles a function call from the job running in a terminal.
4622 * "item" is the function name, "item->li_next" has the arguments.
4623 */
4624 static void
4625handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4626{
4627 char_u *func;
4628 typval_T argvars[2];
4629 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004630 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004631
4632 if (item->li_next == NULL)
4633 {
4634 ch_log(channel, "Missing function arguments for call");
4635 return;
4636 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004637 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004638
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004639 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004640 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004641 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004642 return;
4643 }
4644
4645 argvars[0].v_type = VAR_NUMBER;
4646 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4647 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004648 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004649 funcexe.fe_firstline = 1L;
4650 funcexe.fe_lastline = 1L;
4651 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004652 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004653 {
4654 clear_tv(&rettv);
4655 ch_log(channel, "Function %s called", func);
4656 }
4657 else
4658 ch_log(channel, "Calling function %s failed", func);
4659}
4660
4661/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004662 * URL decoding (also know as Percent-encoding).
4663 *
4664 * Note this function currently is only used for decoding shell's
4665 * OSC 7 escape sequence which we can assume all bytes are valid
4666 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4667 * encoding bytes like 0xfe, 0xff.
4668 */
4669 static size_t
4670url_decode(const char *src, const size_t len, char_u *dst)
4671{
4672 size_t i = 0, j = 0;
4673
4674 while (i < len)
4675 {
4676 if (src[i] == '%' && i + 2 < len)
4677 {
4678 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4679 j++;
4680 i += 3;
4681 }
4682 else
4683 {
4684 dst[j] = src[i];
4685 i++;
4686 j++;
4687 }
4688 }
4689 dst[j] = '\0';
4690 return j;
4691}
4692
4693/*
4694 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4695 *
4696 * The OSC 7 sequence has the format of
4697 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4698 * and what VTerm provides via VTermStringFragment is
4699 * "file://HOSTNAME/CURRENT/DIR"
4700 */
4701 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004702sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004703{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004704 int offset = 7; // len of "file://" is 7
4705 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004706 char_u *new_dir;
4707
4708 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004709 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004710 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004711 ++offset;
4712 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004713 }
4714
Bram Moolenaar474ad392022-08-21 11:37:17 +01004715 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004716 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004717 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004718 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004719 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004720 }
4721
Bram Moolenaar474ad392022-08-21 11:37:17 +01004722 new_dir = alloc(gap->ga_len - offset + 1);
4723 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004724 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4725 vim_free(new_dir);
4726}
4727
4728/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004729 * Called by libvterm when it cannot recognize an OSC sequence.
4730 * We recognize a terminal API command.
4731 */
4732 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004733parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004734{
4735 term_T *term = (term_T *)user;
4736 js_read_T reader;
4737 typval_T tv;
4738 channel_T *channel = term->tl_job == NULL ? NULL
4739 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004740 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004741
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004742 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004743 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004744 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004745
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004746 // Concatenate what was received until the final piece is found.
4747 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4748 {
4749 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004750 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004751 }
4752 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004753 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004754 if (!frag.final)
4755 return 1;
4756
4757 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004758
4759 if (command == 7)
4760 {
4761 sync_shell_dir(gap);
4762 ga_clear(gap);
4763 return 1;
4764 }
4765
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004766 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004767 reader.js_fill = NULL;
4768 reader.js_used = 0;
4769 if (json_decode(&reader, &tv, 0) == OK
4770 && tv.v_type == VAR_LIST
4771 && tv.vval.v_list != NULL)
4772 {
4773 listitem_T *item = tv.vval.v_list->lv_first;
4774
4775 if (item == NULL)
4776 ch_log(channel, "Missing command");
4777 else
4778 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004779 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004780
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004781 // Make sure an invoked command doesn't delete the buffer (and the
4782 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004783 ++term->tl_buffer->b_locked;
4784
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004785 item = item->li_next;
4786 if (item == NULL)
4787 ch_log(channel, "Missing argument for %s", cmd);
4788 else if (STRCMP(cmd, "drop") == 0)
4789 handle_drop_command(item);
4790 else if (STRCMP(cmd, "call") == 0)
4791 handle_call_command(term, channel, item);
4792 else
4793 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004794 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004795 }
4796 }
4797 else
4798 ch_log(channel, "Invalid JSON received");
4799
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004800 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004801 clear_tv(&tv);
4802 return 1;
4803}
4804
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004805/*
4806 * Called by libvterm when it cannot recognize a CSI sequence.
4807 * We recognize the window position report.
4808 */
4809 static int
4810parse_csi(
4811 const char *leader UNUSED,
4812 const long args[],
4813 int argcount,
4814 const char *intermed UNUSED,
4815 char command,
4816 void *user)
4817{
4818 term_T *term = (term_T *)user;
4819 char buf[100];
4820 int len;
4821 int x = 0;
4822 int y = 0;
4823 win_T *wp;
4824
4825 // We recognize only CSI 13 t
4826 if (command != 't' || argcount != 1 || args[0] != 13)
4827 return 0; // not handled
4828
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004829 // When getting the window position is not possible or it fails it results
4830 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004831#if defined(FEAT_GUI) \
4832 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4833 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004834 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004835#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004836
4837 FOR_ALL_WINDOWS(wp)
4838 if (wp->w_buffer == term->tl_buffer)
4839 break;
4840 if (wp != NULL)
4841 {
4842#ifdef FEAT_GUI
4843 if (gui.in_use)
4844 {
4845 x += wp->w_wincol * gui.char_width;
4846 y += W_WINROW(wp) * gui.char_height;
4847 }
4848 else
4849#endif
4850 {
4851 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004852 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004853 x += wp->w_wincol * 7;
4854 y += W_WINROW(wp) * 10;
4855 }
4856 }
4857
4858 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4859 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4860 (char_u *)buf, len, NULL);
4861 return 1;
4862}
4863
Bram Moolenaard8637282020-05-20 18:41:41 +02004864static VTermStateFallbacks state_fallbacks = {
Yegappan Lakshmanan562610c2025-05-04 21:05:51 +02004865 NULL, // control
4866 parse_csi, // csi
4867 parse_osc, // osc
4868 NULL, // dcs
4869 NULL, // apc
4870 NULL, // pm
4871 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004872};
4873
4874/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004875 * Use Vim's allocation functions for vterm so profiling works.
4876 */
4877 static void *
4878vterm_malloc(size_t size, void *data UNUSED)
4879{
Bram Moolenaar88137392021-11-12 16:01:15 +00004880 // make sure that the length is not zero
4881 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004882}
4883
4884 static void
4885vterm_memfree(void *ptr, void *data UNUSED)
4886{
4887 vim_free(ptr);
4888}
4889
4890static VTermAllocatorFunctions vterm_allocator = {
4891 &vterm_malloc,
4892 &vterm_memfree
4893};
4894
4895/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004896 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004897 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004898 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004899 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004900create_vterm(term_T *term, int rows, int cols)
4901{
4902 VTerm *vterm;
4903 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004904 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004905 VTermValue value;
4906
Bram Moolenaar756ef112018-04-10 12:04:27 +02004907 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004908 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004909 if (vterm == NULL)
4910 return FAIL;
4911
4912 // Allocate screen and state here, so we can bail out if that fails.
4913 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004914 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004915 if (state == NULL || screen == NULL)
4916 {
4917 vterm_free(vterm);
4918 return FAIL;
4919 }
4920
Bram Moolenaar52acb112018-03-18 19:20:22 +01004921 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004922 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004923 vterm_set_utf8(vterm, 1);
4924
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004925 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004926
4927 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004928 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004929 &term->tl_default_color.fg,
4930 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004931
Bram Moolenaar9e587872019-05-13 20:27:23 +02004932 if (t_colors < 16)
4933 // Less than 16 colors: assume that bold means using a bright color for
4934 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004935 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4936
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004937 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004938 vterm_screen_reset(screen, 1 /* hard */);
4939
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004940 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004941 vterm_screen_enable_altscreen(screen, 1);
4942
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004943 // For unix do not use a blinking cursor. In an xterm this causes the
4944 // cursor to blink if it's blinking in the xterm.
4945 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004946#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004947 if (GetCaretBlinkTime() == INFINITE)
4948 value.boolean = 0;
4949 else
4950 value.boolean = 1;
4951#else
4952 value.boolean = 0;
4953#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004954 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004955 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004956
4957 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004958}
4959
4960/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004961 * Reset the terminal palette to its default value.
4962 */
4963 static void
4964term_reset_palette(VTerm *vterm)
4965{
4966 VTermState *state = vterm_obtain_state(vterm);
4967 int index;
4968
4969 for (index = 0; index < 16; index++)
4970 {
4971 VTermColor color;
4972
4973 color.type = VTERM_COLOR_INDEXED;
4974 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4975 &color.index);
4976 // The first valid index starts at 1.
4977 color.index -= 1;
4978
4979 vterm_state_set_palette_color(state, index, &color);
4980 }
4981}
4982
4983 static void
4984term_update_palette(term_T *term)
4985{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004986#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004987 if (term_use_palette()
4988 && (term->tl_palette != NULL
4989 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004990 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004991 {
4992 if (term->tl_palette != NULL)
4993 set_vterm_palette(term->tl_vterm, term->tl_palette);
4994 else
4995 init_vterm_ansi_colors(term->tl_vterm);
4996 }
4997 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004998#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004999 term_reset_palette(term->tl_vterm);
5000}
5001
5002/*
5003 * Called when option 'termguicolors' is changed.
5004 */
5005 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005006term_update_palette_all(void)
LemonBoyb2b3acb2022-05-20 10:10:34 +01005007{
5008 term_T *term;
5009
5010 FOR_ALL_TERMS(term)
5011 {
5012 if (term->tl_vterm == NULL)
5013 continue;
5014 term_update_palette(term);
5015 }
5016}
5017
5018/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005019 * Called when option 'background' or 'termguicolors' was set,
5020 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02005021 */
5022 void
5023term_update_colors_all(void)
5024{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005025 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02005026
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005027 FOR_ALL_TERMS(term)
5028 {
5029 if (term->tl_vterm == NULL)
5030 continue;
5031 init_default_colors(term);
5032 vterm_state_set_default_colors(
5033 vterm_obtain_state(term->tl_vterm),
5034 &term->tl_default_color.fg,
5035 &term->tl_default_color.bg);
5036 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005037}
5038
5039/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005040 * Return the text to show for the buffer name and status.
5041 */
5042 char_u *
5043term_get_status_text(term_T *term)
5044{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005045 if (term->tl_status_text != NULL)
5046 return term->tl_status_text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005047
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005048 char_u *txt;
5049 size_t len;
5050 char_u *fname;
5051
5052 if (term->tl_normal_mode)
5053 {
5054 if (term_job_running(term))
5055 txt = (char_u *)_("Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005056 else
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005057 txt = (char_u *)_("Terminal-finished");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005058 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005059 else if (term->tl_title != NULL)
5060 txt = term->tl_title;
5061 else if (term_none_open(term))
5062 txt = (char_u *)_("active");
5063 else if (term_job_running(term))
5064 txt = (char_u *)_("running");
5065 else
5066 txt = (char_u *)_("finished");
5067 fname = buf_get_fname(term->tl_buffer);
5068 len = 9 + STRLEN(fname) + STRLEN(txt);
5069 term->tl_status_text = alloc(len);
5070 if (term->tl_status_text != NULL)
5071 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
5072 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005073 return term->tl_status_text;
5074}
5075
5076/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00005077 * Clear the cached value of the status text.
5078 */
5079 void
5080term_clear_status_text(term_T *term)
5081{
5082 VIM_CLEAR(term->tl_status_text);
5083}
5084
5085/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005086 * Mark references in jobs of terminals.
5087 */
5088 int
5089set_ref_in_term(int copyID)
5090{
5091 int abort = FALSE;
5092 term_T *term;
5093 typval_T tv;
5094
Bram Moolenaar75a1a942019-06-20 03:45:36 +02005095 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005096 if (term->tl_job != NULL)
5097 {
5098 tv.v_type = VAR_JOB;
5099 tv.vval.v_job = term->tl_job;
Yegappan Lakshmanan9cb865e2025-03-23 16:42:16 +01005100 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005101 }
5102 return abort;
5103}
5104
5105/*
5106 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005107 * Returns NULL when the buffer is not for a terminal window and logs a message
5108 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005109 */
5110 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005111term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005112{
5113 buf_T *buf;
5114
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005115 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01005116 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005117 --emsg_off;
5118 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005119 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01005120 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005121 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005122 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005123 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005124 return buf;
5125}
5126
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005127 static void
5128clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005129{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005130 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005131 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
5132 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005133}
5134
5135 static void
5136dump_term_color(FILE *fd, VTermColor *color)
5137{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005138 int index;
5139
5140 if (VTERM_COLOR_IS_INDEXED(color))
5141 index = color->index + 1;
5142 else if (color->type == 0)
5143 // use RGB values
5144 index = 255;
5145 else
5146 // default color
5147 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005148 fprintf(fd, "%02x%02x%02x%d",
5149 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005150 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005151}
5152
5153/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005154 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01005155 *
5156 * Each screen cell in full is:
5157 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5158 * {characters} is a space for an empty cell
5159 * For a double-width character "+" is changed to "*" and the next cell is
5160 * skipped.
5161 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5162 * when "&" use the same as the previous cell.
5163 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5164 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5165 * {color-idx} is a number from 0 to 255
5166 *
5167 * Screen cell with same width, attributes and color as the previous one:
5168 * |{characters}
5169 *
5170 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5171 *
5172 * Repeating the previous screen cell:
5173 * @{count}
5174 */
5175 void
5176f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5177{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005178 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005179 term_T *term;
5180 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005181 int max_height = 0;
5182 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005183 stat_T st;
5184 FILE *fd;
5185 VTermPos pos;
5186 VTermScreen *screen;
5187 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005188 VTermState *state;
5189 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005190
5191 if (check_restricted() || check_secure())
5192 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005193
5194 if (in_vim9script()
5195 && (check_for_buffer_arg(argvars, 0) == FAIL
5196 || check_for_string_arg(argvars, 1) == FAIL
5197 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5198 return;
5199
5200 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005201 if (buf == NULL)
5202 return;
5203 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005204 if (term->tl_vterm == NULL)
5205 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005206 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005207 return;
5208 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005209
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005210 if (argvars[2].v_type != VAR_UNKNOWN)
5211 {
5212 dict_T *d;
5213
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005214 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005215 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005216 d = argvars[2].vval.v_dict;
5217 if (d != NULL)
5218 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005219 max_height = dict_get_number(d, "rows");
5220 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005221 }
5222 }
5223
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005224 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005225 if (fname == NULL)
5226 return;
5227 if (mch_stat((char *)fname, &st) >= 0)
5228 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005229 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005230 return;
5231 }
5232
Bram Moolenaard96ff162018-02-18 22:13:29 +01005233 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5234 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005235 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005236 return;
5237 }
5238
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005239 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005240
5241 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005242 state = vterm_obtain_state(term->tl_vterm);
5243 vterm_state_get_cursorpos(state, &cursor_pos);
5244
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005245 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5246 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005247 {
5248 int repeat = 0;
5249
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005250 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5251 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005252 {
5253 VTermScreenCell cell;
5254 int same_attr;
5255 int same_chars = TRUE;
5256 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005257 int is_cursor_pos = (pos.col == cursor_pos.col
5258 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005259
5260 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005261 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005262
5263 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5264 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005265 int c = cell.chars[i];
5266 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005267 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005268
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005269 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005270 if (i == 0)
5271 {
5272 c = (c == NUL) ? ' ' : c;
5273 pc = (pc == NUL) ? ' ' : pc;
5274 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005275 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005276 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005277 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005278 break;
5279 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005280 same_attr = vtermAttr2hl(&cell.attrs)
5281 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005282 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5283 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005284 if (same_chars && cell.width == prev_cell.width && same_attr
5285 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005286 {
5287 ++repeat;
5288 }
5289 else
5290 {
5291 if (repeat > 0)
5292 {
5293 fprintf(fd, "@%d", repeat);
5294 repeat = 0;
5295 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005296 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005297
5298 if (cell.chars[0] == NUL)
5299 fputs(" ", fd);
5300 else
5301 {
5302 char_u charbuf[10];
5303 int len;
5304
5305 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5306 && cell.chars[i] != NUL; ++i)
5307 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005308 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005309 fwrite(charbuf, len, 1, fd);
5310 }
5311 }
5312
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005313 // When only the characters differ we don't write anything, the
5314 // following "|", "@" or NL will indicate using the same
5315 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005316 if (cell.width != prev_cell.width || !same_attr)
5317 {
5318 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005319 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005320 else
5321 fputs("+", fd);
5322
5323 if (same_attr)
5324 {
5325 fputs("&", fd);
5326 }
5327 else
5328 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005329 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005330 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005331 fputs("&", fd);
5332 else
5333 {
5334 fputs("#", fd);
5335 dump_term_color(fd, &cell.fg);
5336 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005337 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005338 fputs("&", fd);
5339 else
5340 {
5341 fputs("#", fd);
5342 dump_term_color(fd, &cell.bg);
5343 }
5344 }
5345 }
5346
5347 prev_cell = cell;
5348 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005349
5350 if (cell.width == 2)
5351 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005352 }
5353 if (repeat > 0)
5354 fprintf(fd, "@%d", repeat);
5355 fputs("\n", fd);
5356 }
5357
5358 fclose(fd);
5359}
5360
5361/*
5362 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5363 */
5364 static void
5365dump_is_corrupt(garray_T *gap)
5366{
5367 ga_concat(gap, (char_u *)"CORRUPT");
5368}
5369
5370 static void
5371append_cell(garray_T *gap, cellattr_T *cell)
5372{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005373 if (ga_grow(gap, 1) == FAIL)
5374 return;
5375
5376 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5377 ++gap->ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005378}
5379
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005380 static void
5381clear_cellattr(cellattr_T *cell)
5382{
5383 CLEAR_FIELD(*cell);
5384 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5385 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5386}
5387
Bram Moolenaard96ff162018-02-18 22:13:29 +01005388/*
5389 * Read the dump file from "fd" and append lines to the current buffer.
5390 * Return the cell width of the longest line.
5391 */
5392 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005393read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005394{
5395 int c;
5396 garray_T ga_text;
5397 garray_T ga_cell;
5398 char_u *prev_char = NULL;
5399 int attr = 0;
5400 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005401 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005402 term_T *term = curbuf->b_term;
5403 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005404 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005405
5406 ga_init2(&ga_text, 1, 90);
5407 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005408 clear_cellattr(&cell);
5409 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005410 cursor_pos->row = -1;
5411 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005412
5413 c = fgetc(fd);
5414 for (;;)
5415 {
5416 if (c == EOF)
5417 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005418 if (c == '\r')
5419 {
5420 // DOS line endings? Ignore.
5421 c = fgetc(fd);
5422 }
5423 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005424 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005425 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005426 if (ga_text.ga_data == NULL)
5427 dump_is_corrupt(&ga_text);
5428 if (ga_grow(&term->tl_scrollback, 1) == OK)
5429 {
5430 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5431 + term->tl_scrollback.ga_len;
5432
5433 if (max_cells < ga_cell.ga_len)
5434 max_cells = ga_cell.ga_len;
5435 line->sb_cols = ga_cell.ga_len;
5436 line->sb_cells = ga_cell.ga_data;
5437 line->sb_fill_attr = term->tl_default_color;
5438 ++term->tl_scrollback.ga_len;
5439 ga_init(&ga_cell);
5440
5441 ga_append(&ga_text, NUL);
5442 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5443 ga_text.ga_len, FALSE);
5444 }
5445 else
5446 ga_clear(&ga_cell);
5447 ga_text.ga_len = 0;
5448
5449 c = fgetc(fd);
5450 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005451 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005452 {
5453 int prev_len = ga_text.ga_len;
5454
Bram Moolenaar9271d052018-02-25 21:39:46 +01005455 if (c == '>')
5456 {
5457 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005458 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005459 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5460 cursor_pos->col = ga_cell.ga_len;
5461 }
5462
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005463 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005464 c = fgetc(fd);
5465 if (c != EOF)
5466 ga_append(&ga_text, c);
5467 for (;;)
5468 {
5469 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005470 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005471 || c == EOF || c == '\n')
5472 break;
5473 ga_append(&ga_text, c);
5474 }
5475
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005476 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005477 vim_free(prev_char);
5478 if (ga_text.ga_data != NULL)
5479 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5480 ga_text.ga_len - prev_len);
5481
Bram Moolenaar9271d052018-02-25 21:39:46 +01005482 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005483 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005484 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005485 }
5486 else if (c == '+' || c == '*')
5487 {
5488 int is_bg;
5489
5490 cell.width = c == '+' ? 1 : 2;
5491
5492 c = fgetc(fd);
5493 if (c == '&')
5494 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005495 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005496 c = fgetc(fd);
5497 }
Keith Thompson184f71c2024-01-04 21:19:04 +01005498 else if (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005499 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005500 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005501 attr = 0;
Keith Thompson184f71c2024-01-04 21:19:04 +01005502 while (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005503 {
5504 attr = attr * 10 + (c - '0');
5505 c = fgetc(fd);
5506 }
5507 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005508
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005509 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005510 for (is_bg = 0; is_bg <= 1; ++is_bg)
5511 {
5512 if (c == '&')
5513 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005514 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005515 c = fgetc(fd);
5516 }
5517 else if (c == '#')
5518 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005519 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005520
5521 c = fgetc(fd);
5522 red = hex2nr(c);
5523 c = fgetc(fd);
5524 red = (red << 4) + hex2nr(c);
5525 c = fgetc(fd);
5526 green = hex2nr(c);
5527 c = fgetc(fd);
5528 green = (green << 4) + hex2nr(c);
5529 c = fgetc(fd);
5530 blue = hex2nr(c);
5531 c = fgetc(fd);
5532 blue = (blue << 4) + hex2nr(c);
5533 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005534 if (!SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005535 dump_is_corrupt(&ga_text);
Keith Thompson184f71c2024-01-04 21:19:04 +01005536 while (SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005537 {
5538 index = index * 10 + (c - '0');
5539 c = fgetc(fd);
5540 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005541 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005542 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005543 type = VTERM_COLOR_RGB;
5544 if (index == 0)
5545 {
5546 if (is_bg)
5547 type |= VTERM_COLOR_DEFAULT_BG;
5548 else
5549 type |= VTERM_COLOR_DEFAULT_FG;
5550 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005551 }
5552 else
5553 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005554 type = VTERM_COLOR_INDEXED;
5555 index -= 1;
5556 }
5557 if (is_bg)
5558 {
5559 cell.bg.type = type;
5560 cell.bg.red = red;
5561 cell.bg.green = green;
5562 cell.bg.blue = blue;
5563 cell.bg.index = index;
5564 }
5565 else
5566 {
5567 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005568 cell.fg.red = red;
5569 cell.fg.green = green;
5570 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005571 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005572 }
5573 }
5574 else
5575 dump_is_corrupt(&ga_text);
5576 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005577 }
5578 else
5579 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005580 }
5581 else
5582 dump_is_corrupt(&ga_text);
5583
5584 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005585 if (cell.width == 2)
5586 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005587 }
5588 else if (c == '@')
5589 {
5590 if (prev_char == NULL)
5591 dump_is_corrupt(&ga_text);
5592 else
5593 {
5594 int count = 0;
5595
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005596 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005597 for (;;)
5598 {
5599 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005600 if (!SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005601 break;
5602 count = count * 10 + (c - '0');
5603 }
5604
5605 while (count-- > 0)
5606 {
5607 ga_concat(&ga_text, prev_char);
5608 append_cell(&ga_cell, &cell);
5609 }
5610 }
5611 }
5612 else
5613 {
5614 dump_is_corrupt(&ga_text);
5615 c = fgetc(fd);
5616 }
5617 }
5618
5619 if (ga_text.ga_len > 0)
5620 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005621 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005622 dump_is_corrupt(&ga_text);
5623 ga_append(&ga_text, NUL);
5624 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5625 ga_text.ga_len, FALSE);
5626 }
5627
5628 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005629 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005630 vim_free(prev_char);
5631
5632 return max_cells;
5633}
5634
5635/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005636 * Return an allocated string with at least "text_width" "=" characters and
5637 * "fname" inserted in the middle.
5638 */
5639 static char_u *
5640get_separator(int text_width, char_u *fname)
5641{
5642 int width = MAX(text_width, curwin->w_width);
5643 char_u *textline;
5644 int fname_size;
5645 char_u *p = fname;
5646 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005647 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005648
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005649 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005650 if (textline == NULL)
5651 return NULL;
5652
5653 fname_size = vim_strsize(fname);
5654 if (fname_size < width - 8)
5655 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005656 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005657 width = MAX(text_width, fname_size + 8);
5658 }
5659 else if (fname_size > width - 8)
5660 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005661 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005662 p = gettail(fname);
5663 fname_size = vim_strsize(p);
5664 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005665 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005666 while (fname_size > width - 8)
5667 {
5668 p += (*mb_ptr2len)(p);
5669 fname_size = vim_strsize(p);
5670 }
5671
5672 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5673 textline[i] = '=';
5674 textline[i++] = ' ';
5675
5676 STRCPY(textline + i, p);
5677 off = STRLEN(textline);
5678 textline[off] = ' ';
5679 for (i = 1; i < (width - fname_size) / 2; ++i)
5680 textline[off + i] = '=';
5681 textline[off + i] = NUL;
5682
5683 return textline;
5684}
5685
5686/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005687 * Common for "term_dumpdiff()" and "term_dumpload()".
5688 */
5689 static void
5690term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5691{
5692 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005693 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005694 char_u buf1[NUMBUFLEN];
5695 char_u buf2[NUMBUFLEN];
5696 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005697 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005698 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005699 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005700 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005701 char_u *textline = NULL;
5702
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005703 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005704 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005705 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005706 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005707 if (fname1 == NULL || (do_diff && fname2 == NULL))
5708 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005709 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005710 return;
5711 }
5712 fd1 = mch_fopen((char *)fname1, READBIN);
5713 if (fd1 == NULL)
5714 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005715 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005716 return;
5717 }
5718 if (do_diff)
5719 {
5720 fd2 = mch_fopen((char *)fname2, READBIN);
5721 if (fd2 == NULL)
5722 {
5723 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005724 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005725 return;
5726 }
5727 }
5728
5729 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005730 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5731 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5732 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5733 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5734 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005735
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005736 if (opt.jo_term_name == NULL)
5737 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005738 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005739
Bram Moolenaar51e14382019-05-25 20:21:28 +02005740 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005741 if (fname_tofree != NULL)
5742 {
5743 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5744 opt.jo_term_name = fname_tofree;
5745 }
5746 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005747
Bram Moolenaar87abab92019-06-03 21:14:59 +02005748 if (opt.jo_bufnr_buf != NULL)
5749 {
5750 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5751
5752 // With "bufnr" argument: enter the window with this buffer and make it
5753 // empty.
5754 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005755 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005756 else
5757 {
5758 buf = curbuf;
5759 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005760 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005761 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005762 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005763 }
5764 }
5765 else
5766 // Create a new terminal window.
5767 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5768
Bram Moolenaard96ff162018-02-18 22:13:29 +01005769 if (buf != NULL && buf->b_term != NULL)
5770 {
5771 int i;
5772 linenr_T bot_lnum;
5773 linenr_T lnum;
5774 term_T *term = buf->b_term;
5775 int width;
5776 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005777 VTermPos cursor_pos1;
5778 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005779
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005780 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005781
Bram Moolenaard96ff162018-02-18 22:13:29 +01005782 rettv->vval.v_number = buf->b_fnum;
5783
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005784 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005785 width = read_dump_file(fd1, &cursor_pos1);
5786
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005787 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005788 if (cursor_pos1.row >= 0)
5789 {
5790 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5791 coladvance(cursor_pos1.col);
5792 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005793
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005794 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005795 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005796
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005797 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005798 if (!do_diff)
5799 goto theend;
5800
5801 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5802
Bram Moolenaar4a696342018-04-05 18:45:26 +02005803 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005804 if (textline == NULL)
5805 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005806 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5807 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5808 vim_free(textline);
5809
5810 textline = get_separator(width, fname2);
5811 if (textline == NULL)
5812 goto theend;
5813 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5814 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005815 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005816
5817 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005818 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005819 if (width2 > width)
5820 {
5821 vim_free(textline);
5822 textline = alloc(width2 + 1);
5823 if (textline == NULL)
5824 goto theend;
5825 width = width2;
5826 textline[width] = NUL;
5827 }
5828 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5829
5830 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5831 {
5832 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5833 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005834 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005835 for (i = 0; i < width; ++i)
5836 textline[i] = '-';
5837 }
5838 else
5839 {
5840 char_u *line1;
5841 char_u *line2;
5842 char_u *p1;
5843 char_u *p2;
5844 int col;
5845 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5846 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5847 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5848 ->sb_cells;
5849
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005850 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005851 line1 = vim_strsave(ml_get(lnum));
5852 if (line1 == NULL)
5853 break;
5854 p1 = line1;
5855
5856 line2 = ml_get(lnum + bot_lnum);
5857 p2 = line2;
5858 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5859 {
5860 int len1 = utfc_ptr2len(p1);
5861 int len2 = utfc_ptr2len(p2);
5862
5863 textline[col] = ' ';
5864 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005865 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005866 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005867 else if (lnum == cursor_pos1.row + 1
5868 && col == cursor_pos1.col
5869 && (cursor_pos1.row != cursor_pos2.row
5870 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005871 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005872 textline[col] = '>';
5873 else if (lnum == cursor_pos2.row + 1
5874 && col == cursor_pos2.col
5875 && (cursor_pos1.row != cursor_pos2.row
5876 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005877 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005878 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005879 else if (cellattr1 != NULL && cellattr2 != NULL)
5880 {
5881 if ((cellattr1 + col)->width
5882 != (cellattr2 + col)->width)
5883 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005884 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005885 &(cellattr2 + col)->fg))
5886 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005887 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005888 &(cellattr2 + col)->bg))
5889 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005890 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5891 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005892 textline[col] = 'a';
5893 }
5894 p1 += len1;
5895 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005896 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005897 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005898
5899 while (col < width)
5900 {
5901 if (*p1 == NUL && *p2 == NUL)
5902 textline[col] = '?';
5903 else if (*p1 == NUL)
5904 {
5905 textline[col] = '+';
5906 p2 += utfc_ptr2len(p2);
5907 }
5908 else
5909 {
5910 textline[col] = '-';
5911 p1 += utfc_ptr2len(p1);
5912 }
5913 ++col;
5914 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005915
5916 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005917 }
5918 if (add_empty_scrollback(term, &term->tl_default_color,
5919 term->tl_top_diff_rows) == OK)
5920 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5921 ++bot_lnum;
5922 }
5923
5924 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5925 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005926 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005927 for (i = 0; i < width; ++i)
5928 textline[i] = '+';
5929 if (add_empty_scrollback(term, &term->tl_default_color,
5930 term->tl_top_diff_rows) == OK)
5931 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5932 ++lnum;
5933 ++bot_lnum;
5934 }
5935
5936 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005937
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005938 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005939 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005940 }
5941
5942theend:
5943 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005944 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005945 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005946 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005947 fclose(fd2);
5948}
5949
5950/*
5951 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5952 * bottom files.
5953 * Return FAIL when this is not possible.
5954 */
5955 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005956term_swap_diff(void)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005957{
5958 term_T *term = curbuf->b_term;
5959 linenr_T line_count;
5960 linenr_T top_rows;
5961 linenr_T bot_rows;
5962 linenr_T bot_start;
5963 linenr_T lnum;
5964 char_u *p;
5965 sb_line_T *sb_line;
5966
5967 if (term == NULL
5968 || !term_is_finished(curbuf)
5969 || term->tl_top_diff_rows == 0
5970 || term->tl_scrollback.ga_len == 0)
5971 return FAIL;
5972
5973 line_count = curbuf->b_ml.ml_line_count;
5974 top_rows = term->tl_top_diff_rows;
5975 bot_rows = term->tl_bot_diff_rows;
5976 bot_start = line_count - bot_rows;
5977 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5978
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005979 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005980 for (lnum = 1; lnum <= top_rows; ++lnum)
5981 {
5982 p = vim_strsave(ml_get(1));
5983 if (p == NULL)
5984 return OK;
5985 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005986 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005987 vim_free(p);
5988 }
5989
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005990 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005991 for (lnum = 1; lnum <= bot_rows; ++lnum)
5992 {
5993 p = vim_strsave(ml_get(bot_start + lnum));
5994 if (p == NULL)
5995 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005996 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005997 ml_append(lnum - 1, p, 0, FALSE);
5998 vim_free(p);
5999 }
6000
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01006001 // move top title to bottom
6002 p = vim_strsave(ml_get(bot_rows + 1));
6003 if (p == NULL)
6004 return OK;
6005 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02006006 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01006007 vim_free(p);
6008
6009 // move bottom title to top
6010 p = vim_strsave(ml_get(line_count - top_rows));
6011 if (p == NULL)
6012 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02006013 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01006014 ml_append(bot_rows, p, 0, FALSE);
6015 vim_free(p);
6016
Bram Moolenaard96ff162018-02-18 22:13:29 +01006017 if (top_rows == bot_rows)
6018 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006019 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01006020 for (lnum = 0; lnum < top_rows; ++lnum)
6021 {
6022 sb_line_T temp;
6023
6024 temp = *(sb_line + lnum);
6025 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
6026 *(sb_line + bot_start + lnum) = temp;
6027 }
6028 }
6029 else
6030 {
6031 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006032 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006033
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006034 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01006035 if (temp != NULL)
6036 {
6037 mch_memmove(temp, term->tl_scrollback.ga_data, size);
6038 mch_memmove(term->tl_scrollback.ga_data,
6039 temp + bot_start,
6040 sizeof(sb_line_T) * bot_rows);
6041 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
6042 temp + top_rows,
6043 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
6044 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
6045 + line_count - top_rows,
6046 temp,
6047 sizeof(sb_line_T) * top_rows);
6048 vim_free(temp);
6049 }
6050 }
6051
6052 term->tl_top_diff_rows = bot_rows;
6053 term->tl_bot_diff_rows = top_rows;
6054
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006055 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006056 return OK;
6057}
6058
6059/*
6060 * "term_dumpdiff(filename, filename, options)" function
6061 */
6062 void
6063f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
6064{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02006065 if (in_vim9script()
6066 && (check_for_string_arg(argvars, 0) == FAIL
6067 || check_for_string_arg(argvars, 1) == FAIL
6068 || check_for_opt_dict_arg(argvars, 2) == FAIL))
6069 return;
6070
Bram Moolenaard96ff162018-02-18 22:13:29 +01006071 term_load_dump(argvars, rettv, TRUE);
6072}
6073
6074/*
6075 * "term_dumpload(filename, options)" function
6076 */
6077 void
6078f_term_dumpload(typval_T *argvars, typval_T *rettv)
6079{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006080 if (in_vim9script()
6081 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02006082 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006083 return;
6084
Bram Moolenaard96ff162018-02-18 22:13:29 +01006085 term_load_dump(argvars, rettv, FALSE);
6086}
6087
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006088/*
6089 * "term_getaltscreen(buf)" function
6090 */
6091 void
6092f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
6093{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006094 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006095
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006096 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6097 return;
6098
6099 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006100 if (buf == NULL)
6101 return;
6102 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
6103}
6104
6105/*
6106 * "term_getattr(attr, name)" function
6107 */
6108 void
6109f_term_getattr(typval_T *argvars, typval_T *rettv)
6110{
6111 int attr;
6112 size_t i;
6113 char_u *name;
6114
6115 static struct {
6116 char *name;
6117 int attr;
6118 } attrs[] = {
6119 {"bold", HL_BOLD},
6120 {"italic", HL_ITALIC},
6121 {"underline", HL_UNDERLINE},
6122 {"strike", HL_STRIKETHROUGH},
6123 {"reverse", HL_INVERSE},
6124 };
6125
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02006126 if (in_vim9script()
6127 && (check_for_number_arg(argvars, 0) == FAIL
6128 || check_for_string_arg(argvars, 1) == FAIL))
6129 return;
6130
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006131 attr = tv_get_number(&argvars[0]);
6132 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006133 if (name == NULL)
6134 return;
6135
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02006136 if (attr > HL_ALL)
6137 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02006138 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006139 if (STRCMP(name, attrs[i].name) == 0)
6140 {
6141 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
6142 break;
6143 }
6144}
6145
6146/*
6147 * "term_getcursor(buf)" function
6148 */
6149 void
6150f_term_getcursor(typval_T *argvars, typval_T *rettv)
6151{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006152 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006153 term_T *term;
6154 list_T *l;
6155 dict_T *d;
6156
6157 if (rettv_list_alloc(rettv) == FAIL)
6158 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006159
6160 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6161 return;
6162
6163 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006164 if (buf == NULL)
6165 return;
6166 term = buf->b_term;
6167
6168 l = rettv->vval.v_list;
6169 list_append_number(l, term->tl_cursor_pos.row + 1);
6170 list_append_number(l, term->tl_cursor_pos.col + 1);
6171
6172 d = dict_alloc();
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00006173 if (d == NULL)
6174 return;
6175
6176 dict_add_number(d, "visible", term->tl_cursor_visible);
6177 dict_add_number(d, "blink", blink_state_is_inverted()
6178 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6179 dict_add_number(d, "shape", term->tl_cursor_shape);
6180 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
6181 list_append_dict(l, d);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006182}
6183
6184/*
6185 * "term_getjob(buf)" function
6186 */
6187 void
6188f_term_getjob(typval_T *argvars, typval_T *rettv)
6189{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006190 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006191
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006192 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6193 return;
6194
6195 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006196 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006197 {
Ernie Raela78eb252024-06-13 17:24:54 +02006198 if (in_vim9script())
6199 {
6200 rettv->v_type = VAR_JOB;
6201 rettv->vval.v_job = NULL;
6202 }
6203 else
6204 {
6205 rettv->v_type = VAR_SPECIAL;
6206 rettv->vval.v_number = VVAL_NULL;
6207 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006208 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006209 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006210
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006211 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006212 rettv->vval.v_job = buf->b_term->tl_job;
6213 if (rettv->vval.v_job != NULL)
6214 ++rettv->vval.v_job->jv_refcount;
6215}
6216
6217 static int
6218get_row_number(typval_T *tv, term_T *term)
6219{
6220 if (tv->v_type == VAR_STRING
6221 && tv->vval.v_string != NULL
6222 && STRCMP(tv->vval.v_string, ".") == 0)
6223 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006224 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006225}
6226
6227/*
6228 * "term_getline(buf, row)" function
6229 */
6230 void
6231f_term_getline(typval_T *argvars, typval_T *rettv)
6232{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006233 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006234 term_T *term;
6235 int row;
6236
6237 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006238
6239 if (in_vim9script()
6240 && (check_for_buffer_arg(argvars, 0) == FAIL
6241 || check_for_lnum_arg(argvars, 1) == FAIL))
6242 return;
6243
6244 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006245 if (buf == NULL)
6246 return;
6247 term = buf->b_term;
6248 row = get_row_number(&argvars[1], term);
6249
6250 if (term->tl_vterm == NULL)
6251 {
6252 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6253
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006254 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006255 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6256 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6257 }
6258 else
6259 {
6260 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6261 VTermRect rect;
6262 int len;
6263 char_u *p;
6264
6265 if (row < 0 || row >= term->tl_rows)
6266 return;
6267 len = term->tl_cols * MB_MAXBYTES + 1;
6268 p = alloc(len);
6269 if (p == NULL)
6270 return;
6271 rettv->vval.v_string = p;
6272
6273 rect.start_col = 0;
6274 rect.end_col = term->tl_cols;
6275 rect.start_row = row;
6276 rect.end_row = row + 1;
6277 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6278 }
6279}
6280
6281/*
6282 * "term_getscrolled(buf)" function
6283 */
6284 void
6285f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6286{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006287 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006288
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006289 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6290 return;
6291
6292 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006293 if (buf == NULL)
6294 return;
6295 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6296}
6297
6298/*
6299 * "term_getsize(buf)" function
6300 */
6301 void
6302f_term_getsize(typval_T *argvars, typval_T *rettv)
6303{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006304 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006305 list_T *l;
6306
6307 if (rettv_list_alloc(rettv) == FAIL)
6308 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006309
6310 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6311 return;
6312
6313 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006314 if (buf == NULL)
6315 return;
6316
6317 l = rettv->vval.v_list;
6318 list_append_number(l, buf->b_term->tl_rows);
6319 list_append_number(l, buf->b_term->tl_cols);
6320}
6321
6322/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006323 * "term_setsize(buf, rows, cols)" function
6324 */
6325 void
Dominique Pellé0268ff32024-07-28 21:12:20 +02006326f_term_setsize(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006327{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006328 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006329 term_T *term;
6330 varnumber_T rows, cols;
6331
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006332 if (in_vim9script()
6333 && (check_for_buffer_arg(argvars, 0) == FAIL
6334 || check_for_number_arg(argvars, 1) == FAIL
6335 || check_for_number_arg(argvars, 2) == FAIL))
6336 return;
6337
6338 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006339 if (buf == NULL)
6340 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006341 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006342 return;
6343 }
6344 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006345 return;
6346 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006347 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006348 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006349 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006350 cols = cols <= 0 ? term->tl_cols : cols;
6351 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006352 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006353
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006354 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006355 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6356 term_report_winsize(term, term->tl_rows, term->tl_cols);
6357}
6358
6359/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006360 * "term_getstatus(buf)" function
6361 */
6362 void
6363f_term_getstatus(typval_T *argvars, typval_T *rettv)
6364{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006365 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006366 term_T *term;
6367 char_u val[100];
6368
6369 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006370
6371 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6372 return;
6373
6374 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006375 if (buf == NULL)
6376 return;
6377 term = buf->b_term;
6378
6379 if (term_job_running(term))
6380 STRCPY(val, "running");
6381 else
6382 STRCPY(val, "finished");
6383 if (term->tl_normal_mode)
6384 STRCAT(val, ",normal");
6385 rettv->vval.v_string = vim_strsave(val);
6386}
6387
6388/*
6389 * "term_gettitle(buf)" function
6390 */
6391 void
6392f_term_gettitle(typval_T *argvars, typval_T *rettv)
6393{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006394 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006395
6396 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006397
6398 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6399 return;
6400
6401 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006402 if (buf == NULL)
6403 return;
6404
6405 if (buf->b_term->tl_title != NULL)
6406 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6407}
6408
6409/*
6410 * "term_gettty(buf)" function
6411 */
6412 void
6413f_term_gettty(typval_T *argvars, typval_T *rettv)
6414{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006415 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006416 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006417 int num = 0;
6418
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006419 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006420 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006421 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6422 return;
6423
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006424 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006425 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006426 if (buf == NULL)
6427 return;
6428 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006429 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006430
6431 switch (num)
6432 {
6433 case 0:
6434 if (buf->b_term->tl_job != NULL)
6435 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006436 break;
6437 case 1:
6438 if (buf->b_term->tl_job != NULL)
6439 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006440 break;
6441 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006442 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006443 return;
6444 }
6445 if (p != NULL)
6446 rettv->vval.v_string = vim_strsave(p);
6447}
6448
6449/*
6450 * "term_list()" function
6451 */
6452 void
6453f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6454{
6455 term_T *tp;
6456 list_T *l;
6457
6458 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6459 return;
6460
6461 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006462 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006463 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006464 if (list_append_number(l,
6465 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6466 return;
6467}
6468
6469/*
6470 * "term_scrape(buf, row)" function
6471 */
6472 void
6473f_term_scrape(typval_T *argvars, typval_T *rettv)
6474{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006475 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006476 VTermScreen *screen = NULL;
6477 VTermPos pos;
6478 list_T *l;
6479 term_T *term;
6480 char_u *p;
6481 sb_line_T *line;
6482
6483 if (rettv_list_alloc(rettv) == FAIL)
6484 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006485
6486 if (in_vim9script()
6487 && (check_for_buffer_arg(argvars, 0) == FAIL
6488 || check_for_lnum_arg(argvars, 1) == FAIL))
6489 return;
6490
6491 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006492 if (buf == NULL)
6493 return;
6494 term = buf->b_term;
6495
6496 l = rettv->vval.v_list;
6497 pos.row = get_row_number(&argvars[1], term);
6498
6499 if (term->tl_vterm != NULL)
6500 {
6501 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006502 if (screen == NULL) // can't really happen
6503 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006504 p = NULL;
6505 line = NULL;
6506 }
6507 else
6508 {
6509 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6510
6511 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6512 return;
6513 p = ml_get_buf(buf, lnum + 1, FALSE);
6514 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6515 }
6516
6517 for (pos.col = 0; pos.col < term->tl_cols; )
6518 {
6519 dict_T *dcell;
6520 int width;
6521 VTermScreenCellAttrs attrs;
6522 VTermColor fg, bg;
6523 char_u rgb[8];
6524 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6525 int off = 0;
6526 int i;
6527
6528 if (screen == NULL)
6529 {
6530 cellattr_T *cellattr;
6531 int len;
6532
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006533 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006534 if (pos.col >= line->sb_cols)
6535 break;
6536 cellattr = line->sb_cells + pos.col;
6537 width = cellattr->width;
6538 attrs = cellattr->attrs;
6539 fg = cellattr->fg;
6540 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006541 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006542 mch_memmove(mbs, p, len);
6543 mbs[len] = NUL;
6544 p += len;
6545 }
6546 else
6547 {
6548 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006549
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006550 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6551 break;
6552 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6553 {
6554 if (cell.chars[i] == 0)
6555 break;
6556 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6557 }
6558 mbs[off] = NUL;
6559 width = cell.width;
6560 attrs = cell.attrs;
6561 fg = cell.fg;
6562 bg = cell.bg;
6563 }
6564 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006565 if (dcell == NULL)
6566 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006567 list_append_dict(l, dcell);
6568
Bram Moolenaare0be1672018-07-08 16:50:37 +02006569 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006570
6571 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6572 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006573 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006574 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6575 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006576 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006577
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006578 dict_add_number(dcell, "attr",
6579 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006580 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006581
6582 ++pos.col;
6583 if (width == 2)
6584 ++pos.col;
6585 }
6586}
6587
6588/*
6589 * "term_sendkeys(buf, keys)" function
6590 */
6591 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006592f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006593{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006594 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006595 char_u *msg;
6596 term_T *term;
6597
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006598 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006599 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006600 || check_for_string_arg(argvars, 1) == FAIL))
6601 return;
6602
6603 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006604 if (buf == NULL)
6605 return;
6606
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006607 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006608 if (msg == NULL)
6609 return;
6610 term = buf->b_term;
6611 if (term->tl_vterm == NULL)
6612 return;
6613
6614 while (*msg != NUL)
6615 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006616 int c;
6617
6618 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6619 {
6620 c = TO_SPECIAL(msg[1], msg[2]);
6621 msg += 3;
6622 }
6623 else
6624 {
6625 c = PTR2CHAR(msg);
6626 msg += MB_CPTR2LEN(msg);
6627 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006628 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006629 }
6630}
6631
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006632#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6633/*
6634 * "term_getansicolors(buf)" function
6635 */
6636 void
6637f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6638{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006639 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006640 term_T *term;
6641 VTermState *state;
6642 VTermColor color;
6643 char_u hexbuf[10];
6644 int index;
6645 list_T *list;
6646
6647 if (rettv_list_alloc(rettv) == FAIL)
6648 return;
6649
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006650 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6651 return;
6652
6653 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006654 if (buf == NULL)
6655 return;
6656 term = buf->b_term;
6657 if (term->tl_vterm == NULL)
6658 return;
6659
6660 list = rettv->vval.v_list;
6661 state = vterm_obtain_state(term->tl_vterm);
6662 for (index = 0; index < 16; index++)
6663 {
6664 vterm_state_get_palette_color(state, index, &color);
6665 sprintf((char *)hexbuf, "#%02x%02x%02x",
6666 color.red, color.green, color.blue);
6667 if (list_append_string(list, hexbuf, 7) == FAIL)
6668 return;
6669 }
6670}
6671
6672/*
6673 * "term_setansicolors(buf, list)" function
6674 */
6675 void
6676f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6677{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006678 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006679 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006680 listitem_T *li;
6681 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006682
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006683 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006684 && (check_for_buffer_arg(argvars, 0) == FAIL
6685 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006686 return;
6687
6688 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006689 if (buf == NULL)
6690 return;
6691 term = buf->b_term;
6692 if (term->tl_vterm == NULL)
6693 return;
6694
Bram Moolenaard83392a2022-09-01 12:22:46 +01006695 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006696 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006697
LemonBoyb2b3acb2022-05-20 10:10:34 +01006698 if (argvars[1].vval.v_list->lv_first == &range_list_item
6699 || argvars[1].vval.v_list->lv_len != 16)
6700 {
Bram Moolenaar23919542023-05-05 22:12:22 +01006701 semsg(_(e_invalid_value_for_argument_str), "\"colors\"");
LemonBoyb2b3acb2022-05-20 10:10:34 +01006702 return;
6703 }
6704
6705 if (term->tl_palette == NULL)
6706 term->tl_palette = ALLOC_MULT(long_u, 16);
6707 if (term->tl_palette == NULL)
6708 return;
6709
6710 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6711 {
6712 char_u *color_name;
6713 guicolor_T guicolor;
6714
6715 color_name = tv_get_string_chk(&li->li_tv);
6716 if (color_name == NULL)
6717 return;
6718
6719 guicolor = GUI_GET_COLOR(color_name);
6720 if (guicolor == INVALCOLOR)
6721 {
6722 semsg(_(e_cannot_allocate_color_str), color_name);
6723 return;
6724 }
6725
6726 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6727 }
6728
6729 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006730}
6731#endif
6732
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006733/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006734 * "term_setapi(buf, api)" function
6735 */
6736 void
6737f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6738{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006739 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006740 term_T *term;
6741 char_u *api;
6742
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006743 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006744 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006745 || check_for_string_arg(argvars, 1) == FAIL))
6746 return;
6747
6748 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006749 if (buf == NULL)
6750 return;
6751 term = buf->b_term;
6752 vim_free(term->tl_api);
6753 api = tv_get_string_chk(&argvars[1]);
6754 if (api != NULL)
6755 term->tl_api = vim_strsave(api);
6756 else
6757 term->tl_api = NULL;
6758}
6759
6760/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006761 * "term_setrestore(buf, command)" function
6762 */
6763 void
6764f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6765{
6766#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006767 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006768 term_T *term;
6769 char_u *cmd;
6770
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006771 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006772 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006773 || check_for_string_arg(argvars, 1) == FAIL))
6774 return;
6775
6776 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006777 if (buf == NULL)
6778 return;
6779 term = buf->b_term;
6780 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006781 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006782 if (cmd != NULL)
6783 term->tl_command = vim_strsave(cmd);
6784 else
6785 term->tl_command = NULL;
6786#endif
6787}
6788
6789/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006790 * "term_setkill(buf, how)" function
6791 */
6792 void
6793f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6794{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006795 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006796 term_T *term;
6797 char_u *how;
6798
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006799 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006800 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006801 || check_for_string_arg(argvars, 1) == FAIL))
6802 return;
6803
6804 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006805 if (buf == NULL)
6806 return;
6807 term = buf->b_term;
6808 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006809 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006810 if (how != NULL)
6811 term->tl_kill = vim_strsave(how);
6812 else
6813 term->tl_kill = NULL;
6814}
6815
6816/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006817 * "term_start(command, options)" function
6818 */
6819 void
6820f_term_start(typval_T *argvars, typval_T *rettv)
6821{
6822 jobopt_T opt;
6823 buf_T *buf;
6824
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006825 if (in_vim9script()
6826 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6827 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6828 return;
6829
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006830 init_job_options(&opt);
6831 if (argvars[1].v_type != VAR_UNKNOWN
6832 && get_job_options(&argvars[1], &opt,
6833 JO_TIMEOUT_ALL + JO_STOPONEXIT
6834 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6835 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6836 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6837 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006838 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006839 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006840 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006841 return;
6842
Bram Moolenaar13568252018-03-16 20:46:58 +01006843 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006844
6845 if (buf != NULL && buf->b_term != NULL)
6846 rettv->vval.v_number = buf->b_fnum;
6847}
6848
6849/*
6850 * "term_wait" function
6851 */
6852 void
6853f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6854{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006855 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006856
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006857 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006858 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006859 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006860 return;
6861
6862 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006863 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006864 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006865 if (buf->b_term->tl_job == NULL)
6866 {
6867 ch_log(NULL, "term_wait(): no job to wait for");
6868 return;
6869 }
6870 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006871 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006872 return;
6873
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006874 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006875 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006876 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6877 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006878 // The job is dead, keep reading channel I/O until the channel is
6879 // closed. buf->b_term may become NULL if the terminal was closed while
6880 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006881 ch_log(NULL, "term_wait(): waiting for channel to close");
6882 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6883 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006884 term_flush_messages();
6885
Bram Moolenaard45aa552018-05-21 22:50:29 +02006886 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006887 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006888 // If the terminal is closed when the channel is closed the
6889 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006890 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006891 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6892 // came here from a close callback, only wait one time
6893 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006894 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006895
6896 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006897 }
6898 else
6899 {
6900 long wait = 10L;
6901
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006902 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006903
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006904 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006905 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006906 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006907 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006908
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006909 // Flushing messages on channels is hopefully sufficient.
6910 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006911 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006912 }
6913}
6914
6915/*
6916 * Called when a channel has sent all the lines to a terminal.
6917 * Send a CTRL-D to mark the end of the text.
6918 */
6919 void
6920term_send_eof(channel_T *ch)
6921{
6922 term_T *term;
6923
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006924 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006925 if (term->tl_job == ch->ch_job)
6926 {
6927 if (term->tl_eof_chars != NULL)
6928 {
6929 channel_send(ch, PART_IN, term->tl_eof_chars,
6930 (int)STRLEN(term->tl_eof_chars), NULL);
6931 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6932 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006933# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006934 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006935 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006936 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6937# endif
6938 }
6939}
6940
Bram Moolenaar113e1072019-01-20 15:30:40 +01006941#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006942 job_T *
6943term_getjob(term_T *term)
6944{
6945 return term != NULL ? term->tl_job : NULL;
6946}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006947#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006948
Bram Moolenaar4f974752019-02-17 17:44:42 +01006949# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006950
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006951///////////////////////////////////////
6952// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006953#ifdef PROTO
6954typedef int COORD;
6955typedef int DWORD;
6956typedef int HANDLE;
6957typedef int *DWORD_PTR;
6958typedef int HPCON;
6959typedef int HRESULT;
6960typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006961typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006962typedef int PSIZE_T;
6963typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006964typedef int BOOL;
6965# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006966#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006967
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006968HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6969HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6970HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006971BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6972BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6973void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006974
6975 static int
6976dyn_conpty_init(int verbose)
6977{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006978 static HMODULE hKerneldll = NULL;
6979 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006980 static struct
6981 {
6982 char *name;
6983 FARPROC *ptr;
6984 } conpty_entry[] =
6985 {
6986 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6987 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6988 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6989 {"InitializeProcThreadAttributeList",
6990 (FARPROC*)&pInitializeProcThreadAttributeList},
6991 {"UpdateProcThreadAttribute",
6992 (FARPROC*)&pUpdateProcThreadAttribute},
6993 {"DeleteProcThreadAttributeList",
6994 (FARPROC*)&pDeleteProcThreadAttributeList},
6995 {NULL, NULL}
6996 };
6997
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006998 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006999 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007000 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00007001 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007002 return FAIL;
7003 }
7004
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007005 // No need to initialize twice.
7006 if (hKerneldll)
7007 return OK;
7008
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007009 hKerneldll = vimLoadLib("kernel32.dll");
7010 for (i = 0; conpty_entry[i].name != NULL
7011 && conpty_entry[i].ptr != NULL; ++i)
7012 {
7013 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
7014 conpty_entry[i].name)) == NULL)
7015 {
7016 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007017 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007018 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007019 return FAIL;
7020 }
7021 }
7022
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007023 return OK;
7024}
7025
7026 static int
7027conpty_term_and_job_init(
7028 term_T *term,
7029 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007030 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007031 jobopt_T *opt,
7032 jobopt_T *orig_opt)
7033{
7034 WCHAR *cmd_wchar = NULL;
7035 WCHAR *cmd_wchar_copy = NULL;
7036 WCHAR *cwd_wchar = NULL;
7037 WCHAR *env_wchar = NULL;
7038 channel_T *channel = NULL;
7039 job_T *job = NULL;
7040 HANDLE jo = NULL;
7041 garray_T ga_cmd, ga_env;
7042 char_u *cmd = NULL;
7043 HRESULT hr;
7044 COORD consize;
7045 SIZE_T breq;
7046 PROCESS_INFORMATION proc_info;
7047 HANDLE i_theirs = NULL;
7048 HANDLE o_theirs = NULL;
7049 HANDLE i_ours = NULL;
7050 HANDLE o_ours = NULL;
7051
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007052 ga_init2(&ga_cmd, sizeof(char*), 20);
7053 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007054
7055 if (argvar->v_type == VAR_STRING)
7056 {
7057 cmd = argvar->vval.v_string;
7058 }
7059 else if (argvar->v_type == VAR_LIST)
7060 {
7061 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
7062 goto failed;
7063 cmd = ga_cmd.ga_data;
7064 }
7065 if (cmd == NULL || *cmd == NUL)
7066 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007067 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007068 goto failed;
7069 }
7070
7071 term->tl_arg0_cmd = vim_strsave(cmd);
7072
7073 cmd_wchar = enc_to_utf16(cmd, NULL);
7074
7075 if (cmd_wchar != NULL)
7076 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007077 // Request by CreateProcessW
7078 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007079 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007080 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
7081 }
7082
7083 ga_clear(&ga_cmd);
7084 if (cmd_wchar == NULL)
7085 goto failed;
7086 if (opt->jo_cwd != NULL)
John Marriott031f2272025-04-23 20:56:08 +02007087 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007088 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
John Marriott031f2272025-04-23 20:56:08 +02007089 if (cwd_wchar == NULL)
7090 goto failed;
7091 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007092
7093 win32_build_env(opt->jo_env, &ga_env, TRUE);
7094 env_wchar = ga_env.ga_data;
7095
7096 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
7097 goto failed;
7098 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
7099 goto failed;
7100
7101 consize.X = term->tl_cols;
7102 consize.Y = term->tl_rows;
7103 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
7104 &term->tl_conpty);
7105 if (FAILED(hr))
7106 goto failed;
7107
7108 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
7109
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007110 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007111 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007112 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007113 if (!term->tl_siex.lpAttributeList)
7114 goto failed;
7115 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
7116 0, &breq))
7117 goto failed;
7118 if (!pUpdateProcThreadAttribute(
7119 term->tl_siex.lpAttributeList, 0,
7120 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
7121 sizeof(HPCON), NULL, NULL))
7122 goto failed;
7123
7124 channel = add_channel();
7125 if (channel == NULL)
7126 goto failed;
7127
7128 job = job_alloc();
7129 if (job == NULL)
7130 goto failed;
7131 if (argvar->v_type == VAR_STRING)
7132 {
7133 int argc;
7134
7135 build_argv_from_string(cmd, &job->jv_argv, &argc);
7136 }
7137 else
7138 {
7139 int argc;
7140
7141 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7142 }
7143
7144 if (opt->jo_set & JO_IN_BUF)
7145 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7146
7147 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
7148 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02007149 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007150 env_wchar, cwd_wchar,
7151 &term->tl_siex.StartupInfo, &proc_info))
7152 goto failed;
7153
7154 CloseHandle(i_theirs);
7155 CloseHandle(o_theirs);
7156
7157 channel_set_pipes(channel,
7158 (sock_T)i_ours,
7159 (sock_T)o_ours,
7160 (sock_T)o_ours);
7161
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007162 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007163 channel->ch_write_text_mode = TRUE;
7164
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007165 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007166 channel->ch_anonymous_pipe = TRUE;
7167
7168 jo = CreateJobObject(NULL, NULL);
7169 if (jo == NULL)
7170 goto failed;
7171
7172 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7173 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007174 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007175 CloseHandle(jo);
7176 jo = NULL;
7177 }
7178
7179 ResumeThread(proc_info.hThread);
7180 CloseHandle(proc_info.hThread);
7181
7182 vim_free(cmd_wchar);
7183 vim_free(cmd_wchar_copy);
7184 vim_free(cwd_wchar);
7185 vim_free(env_wchar);
7186
7187 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7188 goto failed;
7189
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007190#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007191 if (term_use_palette())
7192 {
7193 if (term->tl_palette != NULL)
7194 set_vterm_palette(term->tl_vterm, term->tl_palette);
7195 else
7196 init_vterm_ansi_colors(term->tl_vterm);
7197 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007198#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007199
7200 channel_set_job(channel, job, opt);
7201 job_set_options(job, opt);
7202
7203 job->jv_channel = channel;
7204 job->jv_proc_info = proc_info;
7205 job->jv_job_object = jo;
7206 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007207 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007208 ++job->jv_refcount;
7209 term->tl_job = job;
7210
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007211 // Redirecting stdout and stderr doesn't work at the job level. Instead
7212 // open the file here and handle it in. opt->jo_io was changed in
7213 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007214 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7215 {
7216 char_u *fname = opt->jo_io_name[PART_OUT];
7217
7218 ch_log(channel, "Opening output file %s", fname);
7219 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7220 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007221 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007222 }
7223
7224 return OK;
7225
7226failed:
7227 ga_clear(&ga_cmd);
7228 ga_clear(&ga_env);
7229 vim_free(cmd_wchar);
7230 vim_free(cmd_wchar_copy);
7231 vim_free(cwd_wchar);
7232 if (channel != NULL)
7233 channel_clear(channel);
7234 if (job != NULL)
7235 {
7236 job->jv_channel = NULL;
7237 job_cleanup(job);
7238 }
7239 term->tl_job = NULL;
7240 if (jo != NULL)
7241 CloseHandle(jo);
7242
7243 if (term->tl_siex.lpAttributeList != NULL)
7244 {
7245 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7246 vim_free(term->tl_siex.lpAttributeList);
7247 }
7248 term->tl_siex.lpAttributeList = NULL;
7249 if (o_theirs != NULL)
7250 CloseHandle(o_theirs);
7251 if (o_ours != NULL)
7252 CloseHandle(o_ours);
7253 if (i_ours != NULL)
7254 CloseHandle(i_ours);
7255 if (i_theirs != NULL)
7256 CloseHandle(i_theirs);
7257 if (term->tl_conpty != NULL)
7258 pClosePseudoConsole(term->tl_conpty);
7259 term->tl_conpty = NULL;
7260 return FAIL;
7261}
7262
7263 static void
7264conpty_term_report_winsize(term_T *term, int rows, int cols)
7265{
7266 COORD consize;
7267
7268 consize.X = cols;
7269 consize.Y = rows;
7270 pResizePseudoConsole(term->tl_conpty, consize);
7271}
7272
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007273 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007274term_free_conpty(term_T *term)
7275{
7276 if (term->tl_siex.lpAttributeList != NULL)
7277 {
7278 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7279 vim_free(term->tl_siex.lpAttributeList);
7280 }
7281 term->tl_siex.lpAttributeList = NULL;
7282 if (term->tl_conpty != NULL)
7283 pClosePseudoConsole(term->tl_conpty);
7284 term->tl_conpty = NULL;
7285}
7286
7287 int
7288use_conpty(void)
7289{
7290 return has_conpty;
7291}
7292
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007293# ifndef PROTO
7294
7295#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7296#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007297#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007298
7299void* (*winpty_config_new)(UINT64, void*);
7300void* (*winpty_open)(void*, void*);
7301void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7302BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7303void (*winpty_config_set_mouse_mode)(void*, int);
7304void (*winpty_config_set_initial_size)(void*, int, int);
7305LPCWSTR (*winpty_conin_name)(void*);
7306LPCWSTR (*winpty_conout_name)(void*);
7307LPCWSTR (*winpty_conerr_name)(void*);
7308void (*winpty_free)(void*);
7309void (*winpty_config_free)(void*);
7310void (*winpty_spawn_config_free)(void*);
7311void (*winpty_error_free)(void*);
7312LPCWSTR (*winpty_error_msg)(void*);
7313BOOL (*winpty_set_size)(void*, int, int, void*);
7314HANDLE (*winpty_agent_process)(void*);
7315
7316#define WINPTY_DLL "winpty.dll"
7317
7318static HINSTANCE hWinPtyDLL = NULL;
7319# endif
7320
7321 static int
7322dyn_winpty_init(int verbose)
7323{
7324 int i;
7325 static struct
7326 {
7327 char *name;
7328 FARPROC *ptr;
7329 } winpty_entry[] =
7330 {
7331 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7332 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7333 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7334 {"winpty_config_set_mouse_mode",
7335 (FARPROC*)&winpty_config_set_mouse_mode},
7336 {"winpty_config_set_initial_size",
7337 (FARPROC*)&winpty_config_set_initial_size},
7338 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7339 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7340 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7341 {"winpty_free", (FARPROC*)&winpty_free},
7342 {"winpty_open", (FARPROC*)&winpty_open},
7343 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7344 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7345 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7346 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7347 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7348 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7349 {NULL, NULL}
7350 };
7351
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007352 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007353 if (hWinPtyDLL)
7354 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007355 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7356 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007357 if (*p_winptydll != NUL)
7358 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7359 if (!hWinPtyDLL)
7360 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7361 if (!hWinPtyDLL)
7362 {
7363 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007364 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007365 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7366 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007367 return FAIL;
7368 }
7369 for (i = 0; winpty_entry[i].name != NULL
7370 && winpty_entry[i].ptr != NULL; ++i)
7371 {
7372 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7373 winpty_entry[i].name)) == NULL)
7374 {
7375 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007376 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007377 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007378 return FAIL;
7379 }
7380 }
7381
7382 return OK;
7383}
7384
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007385 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007386winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007387 term_T *term,
7388 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007389 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007390 jobopt_T *opt,
7391 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007392{
7393 WCHAR *cmd_wchar = NULL;
7394 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007395 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007396 channel_T *channel = NULL;
7397 job_T *job = NULL;
7398 DWORD error;
7399 HANDLE jo = NULL;
7400 HANDLE child_process_handle;
7401 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007402 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007403 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007404 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007405 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007406
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007407 ga_init2(&ga_cmd, sizeof(char*), 20);
7408 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007409
7410 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007411 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007412 cmd = argvar->vval.v_string;
7413 }
7414 else if (argvar->v_type == VAR_LIST)
7415 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007416 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007417 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007418 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007419 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007420 if (cmd == NULL || *cmd == NUL)
7421 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007422 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007423 goto failed;
7424 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007425
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007426 term->tl_arg0_cmd = vim_strsave(cmd);
7427
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007428 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007429 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007430 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007431 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007432 if (opt->jo_cwd != NULL)
John Marriott031f2272025-04-23 20:56:08 +02007433 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007434 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
John Marriott031f2272025-04-23 20:56:08 +02007435 if (cwd_wchar == NULL)
7436 goto failed;
7437 }
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007438
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007439 win32_build_env(opt->jo_env, &ga_env, TRUE);
7440 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007441
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007442 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7443 if (term->tl_winpty_config == NULL)
7444 goto failed;
7445
7446 winpty_config_set_mouse_mode(term->tl_winpty_config,
7447 WINPTY_MOUSE_MODE_FORCE);
7448 winpty_config_set_initial_size(term->tl_winpty_config,
7449 term->tl_cols, term->tl_rows);
7450 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7451 if (term->tl_winpty == NULL)
7452 goto failed;
7453
7454 spawn_config = winpty_spawn_config_new(
7455 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7456 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7457 NULL,
7458 cmd_wchar,
7459 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007460 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007461 &winpty_err);
7462 if (spawn_config == NULL)
7463 goto failed;
7464
7465 channel = add_channel();
7466 if (channel == NULL)
7467 goto failed;
7468
7469 job = job_alloc();
7470 if (job == NULL)
7471 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007472 if (argvar->v_type == VAR_STRING)
7473 {
7474 int argc;
7475
7476 build_argv_from_string(cmd, &job->jv_argv, &argc);
7477 }
7478 else
7479 {
7480 int argc;
7481
7482 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7483 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007484
7485 if (opt->jo_set & JO_IN_BUF)
7486 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7487
7488 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7489 &child_thread_handle, &error, &winpty_err))
7490 goto failed;
7491
7492 channel_set_pipes(channel,
7493 (sock_T)CreateFileW(
7494 winpty_conin_name(term->tl_winpty),
7495 GENERIC_WRITE, 0, NULL,
7496 OPEN_EXISTING, 0, NULL),
7497 (sock_T)CreateFileW(
7498 winpty_conout_name(term->tl_winpty),
7499 GENERIC_READ, 0, NULL,
7500 OPEN_EXISTING, 0, NULL),
7501 (sock_T)CreateFileW(
7502 winpty_conerr_name(term->tl_winpty),
7503 GENERIC_READ, 0, NULL,
7504 OPEN_EXISTING, 0, NULL));
7505
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007506 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007507 channel->ch_write_text_mode = TRUE;
7508
7509 jo = CreateJobObject(NULL, NULL);
7510 if (jo == NULL)
7511 goto failed;
7512
7513 if (!AssignProcessToJobObject(jo, child_process_handle))
7514 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007515 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007516 CloseHandle(jo);
7517 jo = NULL;
7518 }
7519
7520 winpty_spawn_config_free(spawn_config);
7521 vim_free(cmd_wchar);
7522 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007523 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007524
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007525 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7526 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007527
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007528#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007529 if (term_use_palette())
7530 {
7531 if (term->tl_palette != NULL)
7532 set_vterm_palette(term->tl_vterm, term->tl_palette);
7533 else
7534 init_vterm_ansi_colors(term->tl_vterm);
7535 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007536#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007537
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007538 channel_set_job(channel, job, opt);
7539 job_set_options(job, opt);
7540
7541 job->jv_channel = channel;
7542 job->jv_proc_info.hProcess = child_process_handle;
7543 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7544 job->jv_job_object = jo;
7545 job->jv_status = JOB_STARTED;
7546 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007547 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007548 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007549 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007550 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007551 ++job->jv_refcount;
7552 term->tl_job = job;
7553
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007554 // Redirecting stdout and stderr doesn't work at the job level. Instead
7555 // open the file here and handle it in. opt->jo_io was changed in
7556 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007557 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7558 {
7559 char_u *fname = opt->jo_io_name[PART_OUT];
7560
7561 ch_log(channel, "Opening output file %s", fname);
7562 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7563 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007564 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007565 }
7566
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007567 return OK;
7568
7569failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007570 ga_clear(&ga_cmd);
7571 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007572 vim_free(cmd_wchar);
7573 vim_free(cwd_wchar);
7574 if (spawn_config != NULL)
7575 winpty_spawn_config_free(spawn_config);
7576 if (channel != NULL)
7577 channel_clear(channel);
7578 if (job != NULL)
7579 {
7580 job->jv_channel = NULL;
7581 job_cleanup(job);
7582 }
7583 term->tl_job = NULL;
7584 if (jo != NULL)
7585 CloseHandle(jo);
7586 if (term->tl_winpty != NULL)
7587 winpty_free(term->tl_winpty);
7588 term->tl_winpty = NULL;
7589 if (term->tl_winpty_config != NULL)
7590 winpty_config_free(term->tl_winpty_config);
7591 term->tl_winpty_config = NULL;
7592 if (winpty_err != NULL)
7593 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007594 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007595 (short_u *)winpty_error_msg(winpty_err), NULL);
7596
John Marriott031f2272025-04-23 20:56:08 +02007597 if (msg != NULL)
7598 {
7599 emsg(msg);
7600 vim_free(msg);
7601 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007602 winpty_error_free(winpty_err);
7603 }
7604 return FAIL;
7605}
7606
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007607/*
7608 * Create a new terminal of "rows" by "cols" cells.
7609 * Store a reference in "term".
7610 * Return OK or FAIL.
7611 */
7612 static int
7613term_and_job_init(
7614 term_T *term,
7615 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007616 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007617 jobopt_T *opt,
7618 jobopt_T *orig_opt)
7619{
7620 int use_winpty = FALSE;
7621 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007622 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007623
7624 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7625 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7626
7627 if (!has_winpty && !has_conpty)
7628 // If neither is available give the errors for winpty, since when
7629 // conpty is not available it can't be installed either.
7630 return dyn_winpty_init(TRUE);
7631
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007632 if (opt->jo_tty_type != NUL)
7633 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007634
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007635 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007636 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007637 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007638 use_conpty = TRUE;
7639 else if (has_winpty)
7640 use_winpty = TRUE;
7641 // else: error
7642 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007643 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007644 {
7645 if (has_winpty)
7646 use_winpty = TRUE;
7647 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007648 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007649 {
7650 if (has_conpty)
7651 use_conpty = TRUE;
7652 else
7653 return dyn_conpty_init(TRUE);
7654 }
7655
7656 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007657 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007658
7659 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007660 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007661
7662 // error
7663 return dyn_winpty_init(TRUE);
7664}
7665
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007666 static int
7667create_pty_only(term_T *term, jobopt_T *options)
7668{
7669 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7670 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7671 char in_name[80], out_name[80];
7672 channel_T *channel = NULL;
7673
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007674 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7675 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007676
7677 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7678 GetCurrentProcessId(),
7679 curbuf->b_fnum);
7680 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7681 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7682 PIPE_UNLIMITED_INSTANCES,
7683 0, 0, NMPWAIT_NOWAIT, NULL);
7684 if (hPipeIn == INVALID_HANDLE_VALUE)
7685 goto failed;
7686
7687 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7688 GetCurrentProcessId(),
7689 curbuf->b_fnum);
7690 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7691 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7692 PIPE_UNLIMITED_INSTANCES,
7693 0, 0, 0, NULL);
7694 if (hPipeOut == INVALID_HANDLE_VALUE)
7695 goto failed;
7696
7697 ConnectNamedPipe(hPipeIn, NULL);
7698 ConnectNamedPipe(hPipeOut, NULL);
7699
7700 term->tl_job = job_alloc();
7701 if (term->tl_job == NULL)
7702 goto failed;
7703 ++term->tl_job->jv_refcount;
7704
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007705 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007706 term->tl_job->jv_status = JOB_FINISHED;
7707
7708 channel = add_channel();
7709 if (channel == NULL)
7710 goto failed;
7711 term->tl_job->jv_channel = channel;
7712 channel->ch_keep_open = TRUE;
7713 channel->ch_named_pipe = TRUE;
7714
7715 channel_set_pipes(channel,
7716 (sock_T)hPipeIn,
7717 (sock_T)hPipeOut,
7718 (sock_T)hPipeOut);
7719 channel_set_job(channel, term->tl_job, options);
7720 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7721 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7722
7723 return OK;
7724
7725failed:
7726 if (hPipeIn != NULL)
7727 CloseHandle(hPipeIn);
7728 if (hPipeOut != NULL)
7729 CloseHandle(hPipeOut);
7730 return FAIL;
7731}
7732
7733/*
7734 * Free the terminal emulator part of "term".
7735 */
7736 static void
7737term_free_vterm(term_T *term)
7738{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007739 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007740 if (term->tl_winpty != NULL)
7741 winpty_free(term->tl_winpty);
7742 term->tl_winpty = NULL;
7743 if (term->tl_winpty_config != NULL)
7744 winpty_config_free(term->tl_winpty_config);
7745 term->tl_winpty_config = NULL;
7746 if (term->tl_vterm != NULL)
7747 vterm_free(term->tl_vterm);
7748 term->tl_vterm = NULL;
7749}
7750
7751/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007752 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007753 */
7754 static void
7755term_report_winsize(term_T *term, int rows, int cols)
7756{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007757 if (term->tl_conpty)
7758 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007759 if (term->tl_winpty)
7760 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7761}
7762
7763 int
7764terminal_enabled(void)
7765{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007766 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007767}
7768
7769# else
7770
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007771///////////////////////////////////////
7772// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007773
7774/*
7775 * Create a new terminal of "rows" by "cols" cells.
7776 * Start job for "cmd".
7777 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007778 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007779 * Return OK or FAIL.
7780 */
7781 static int
7782term_and_job_init(
7783 term_T *term,
7784 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007785 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007786 jobopt_T *opt,
7787 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007788{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007789 term->tl_arg0_cmd = NULL;
7790
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007791 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7792 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007793
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007794#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007795 if (term_use_palette())
7796 {
7797 if (term->tl_palette != NULL)
7798 set_vterm_palette(term->tl_vterm, term->tl_palette);
7799 else
7800 init_vterm_ansi_colors(term->tl_vterm);
7801 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007802#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007803
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007804 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007805 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007806 if (term->tl_job != NULL)
7807 ++term->tl_job->jv_refcount;
7808
7809 return term->tl_job != NULL
7810 && term->tl_job->jv_channel != NULL
7811 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7812}
7813
7814 static int
7815create_pty_only(term_T *term, jobopt_T *opt)
7816{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007817 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7818 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007819
7820 term->tl_job = job_alloc();
7821 if (term->tl_job == NULL)
7822 return FAIL;
7823 ++term->tl_job->jv_refcount;
7824
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007825 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007826 term->tl_job->jv_status = JOB_FINISHED;
7827
7828 return mch_create_pty_channel(term->tl_job, opt);
7829}
7830
7831/*
7832 * Free the terminal emulator part of "term".
7833 */
7834 static void
7835term_free_vterm(term_T *term)
7836{
7837 if (term->tl_vterm != NULL)
7838 vterm_free(term->tl_vterm);
7839 term->tl_vterm = NULL;
7840}
7841
7842/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007843 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007844 */
7845 static void
7846term_report_winsize(term_T *term, int rows, int cols)
7847{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007848 // Use an ioctl() to report the new window size to the job.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007849 if (term->tl_job == NULL || term->tl_job->jv_channel == NULL)
7850 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007851
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007852 int fd = -1;
7853 int part;
7854
7855 for (part = PART_OUT; part < PART_COUNT; ++part)
7856 {
7857 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
7858 if (mch_isatty(fd))
7859 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007860 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007861 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7862 mch_signal_job(term->tl_job, (char_u *)"winch");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007863}
7864
7865# endif
7866
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007867#endif // FEAT_TERMINAL