blob: 28e1abfec3f01a24d5e7a0a753b86828095fce61 [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020039 */
40
41#include "vim.h"
42
43#if defined(FEAT_TERMINAL) || defined(PROTO)
44
45#ifndef MIN
46# define MIN(x,y) ((x) < (y) ? (x) : (y))
47#endif
48#ifndef MAX
49# define MAX(x,y) ((x) > (y) ? (x) : (y))
50#endif
51
52#include "libvterm/include/vterm.h"
53
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010054// This is VTermScreenCell without the characters, thus much smaller.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055typedef struct {
56 VTermScreenCellAttrs attrs;
57 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010058 VTermColor fg;
59 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060} cellattr_T;
61
62typedef struct sb_line_S {
Bram Moolenaar29ae2232019-02-14 21:22:01 +010063 int sb_cols; // can differ per line
64 cellattr_T *sb_cells; // allocated
65 cellattr_T sb_fill_attr; // for short line
66 char_u *sb_text; // for tl_scrollback_postponed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067} sb_line_T;
68
Bram Moolenaar4f974752019-02-17 17:44:42 +010069#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010070# ifndef HPCON
71# define HPCON VOID*
72# endif
73# ifndef EXTENDED_STARTUPINFO_PRESENT
74# define EXTENDED_STARTUPINFO_PRESENT 0x00080000
75# endif
76# ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
77# define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE 0x00020016
78# endif
79typedef struct _DYN_STARTUPINFOEXW
80{
81 STARTUPINFOW StartupInfo;
82 LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
83} DYN_STARTUPINFOEXW, *PDYN_STARTUPINFOEXW;
84#endif
85
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010086// typedef term_T in structs.h
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020087struct terminal_S {
88 term_T *tl_next;
89
90 VTerm *tl_vterm;
91 job_T *tl_job;
92 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010093#if defined(FEAT_GUI)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010094 int tl_system; // when non-zero used for :!cmd output
95 int tl_toprow; // row with first line of system terminal
Bram Moolenaar13568252018-03-16 20:46:58 +010096#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010098 // Set when setting the size of a vterm, reset after redrawing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020099 int tl_vterm_size_changed;
100
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100101 int tl_normal_mode; // TRUE: Terminal-Normal mode
Bram Moolenaareea32af2021-11-21 14:51:13 +0000102 int tl_channel_closing;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200103 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200104 int tl_channel_recently_closed; // still need to handle tl_finish
105
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100106 int tl_finish;
107#define TL_FINISH_UNSET NUL
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100108#define TL_FINISH_CLOSE 'c' // ++close or :terminal without argument
109#define TL_FINISH_NOCLOSE 'n' // ++noclose
110#define TL_FINISH_OPEN 'o' // ++open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200111 char_u *tl_opencmd;
112 char_u *tl_eof_chars;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200113 char_u *tl_api; // prefix for terminal API function
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200114
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100115 char_u *tl_arg0_cmd; // To format the status bar
116
Bram Moolenaar4f974752019-02-17 17:44:42 +0100117#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200118 void *tl_winpty_config;
119 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200120
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100121 HPCON tl_conpty;
122 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
123
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200124 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200125#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100126#if defined(FEAT_SESSION)
127 char_u *tl_command;
128#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100129 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100131 // last known vterm size
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200132 int tl_rows;
133 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200134
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100135 char_u *tl_title; // NULL or allocated
136 char_u *tl_status_text; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200137
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100138 // Range of screen rows to update. Zero based.
139 int tl_dirty_row_start; // MAX_ROW if nothing dirty
140 int tl_dirty_row_end; // row below last one to update
141 int tl_dirty_snapshot; // text updated after making snapshot
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200142#ifdef FEAT_TIMERS
143 int tl_timer_set;
144 proftime_T tl_timer_due;
145#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100146 int tl_postponed_scroll; // to be scrolled up
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200148 garray_T tl_scrollback;
149 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100150 garray_T tl_scrollback_postponed;
151
Bram Moolenaar83d47902020-03-26 20:34:00 +0100152 char_u *tl_highlight_name; // replaces "Terminal"; allocated
153
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200154 cellattr_T tl_default_color;
155
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100156 linenr_T tl_top_diff_rows; // rows of top diff file or zero
157 linenr_T tl_bot_diff_rows; // rows of bottom diff file
Bram Moolenaard96ff162018-02-18 22:13:29 +0100158
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200159 VTermPos tl_cursor_pos;
160 int tl_cursor_visible;
161 int tl_cursor_blink;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100162 int tl_cursor_shape; // 1: block, 2: underline, 3: bar
163 char_u *tl_cursor_color; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200164
LemonBoyb2b3acb2022-05-20 10:10:34 +0100165 long_u *tl_palette; // array of 16 colors specified by term_start, can
166 // be NULL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167 int tl_using_altscreen;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200168 garray_T tl_osc_buf; // incomplete OSC string
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200169};
170
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100171#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
172#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200173
174/*
175 * List of all active terminals.
176 */
177static term_T *first_term = NULL;
178
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100179// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200180static term_T *in_terminal_loop = NULL;
181
Bram Moolenaar4f974752019-02-17 17:44:42 +0100182#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100183static BOOL has_winpty = FALSE;
184static BOOL has_conpty = FALSE;
185#endif
186
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100187#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188#define KEY_BUF_LEN 200
189
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200190#define FOR_ALL_TERMS(term) \
191 for ((term) = first_term; (term) != NULL; (term) = (term)->tl_next)
192
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193/*
194 * Functions with separate implementation for MS-Windows and Unix-like systems.
195 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200196static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200197static int create_pty_only(term_T *term, jobopt_T *opt);
198static void term_report_winsize(term_T *term, int rows, int cols);
199static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100200#ifdef FEAT_GUI
201static void update_system_term(term_T *term);
202#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200203
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100204static void handle_postponed_scrollback(term_T *term);
205
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100206// The character that we know (or assume) that the terminal expects for the
207// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200208static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200209
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100210// Store the last set and the desired cursor properties, so that we only update
211// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200212static char_u *last_set_cursor_color = NULL;
213static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100214static int last_set_cursor_shape = -1;
215static int desired_cursor_shape = -1;
216static int last_set_cursor_blink = -1;
217static int desired_cursor_blink = -1;
218
219
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100220///////////////////////////////////////
221// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200222
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200223 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200224cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
225{
226 if (lhs_color != NULL && rhs_color != NULL)
227 return STRCMP(lhs_color, rhs_color) == 0;
228 return lhs_color == NULL && rhs_color == NULL;
229}
230
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200231 static void
232cursor_color_copy(char_u **to_color, char_u *from_color)
233{
234 // Avoid a free & alloc if the value is already right.
235 if (cursor_color_equal(*to_color, from_color))
236 return;
237 vim_free(*to_color);
238 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
239}
240
241 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200242cursor_color_get(char_u *color)
243{
244 return (color == NULL) ? (char_u *)"" : color;
245}
246
247
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200248/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200249 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200250 * current window.
251 * Sets "rows" and/or "cols" to zero when it should follow the window size.
252 * Return TRUE if the size is the minimum size: "24*80".
253 */
254 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200255parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200256{
257 int minsize = FALSE;
258
259 *rows = 0;
260 *cols = 0;
261
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000262 if (*wp->w_p_tws == NUL)
263 return FALSE;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200264
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000265 char_u *p = vim_strchr(wp->w_p_tws, 'x');
266
267 // Syntax of value was already checked when it's set.
268 if (p == NULL)
269 {
270 minsize = TRUE;
271 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200272 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000273 *rows = atoi((char *)wp->w_p_tws);
274 *cols = atoi((char *)p + 1);
Christian Brabandtceee7a82023-09-21 16:55:06 +0200275 if (*rows > VTERM_MAX_ROWS)
276 *rows = VTERM_MAX_ROWS;
277 if (*cols > VTERM_MAX_COLS)
278 *cols = VTERM_MAX_COLS;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200279 return minsize;
280}
281
282/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200283 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200284 */
285 static void
Bram Moolenaarb936b792020-09-04 18:34:09 +0200286set_term_and_win_size(term_T *term, jobopt_T *opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200287{
Bram Moolenaarb936b792020-09-04 18:34:09 +0200288 int rows, cols;
289 int minsize;
290
Bram Moolenaar13568252018-03-16 20:46:58 +0100291#ifdef FEAT_GUI
292 if (term->tl_system)
293 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100294 // Use the whole screen for the system command. However, it will start
295 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100296 term->tl_rows = Rows;
297 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200298 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100299 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100300#endif
Bram Moolenaarb936b792020-09-04 18:34:09 +0200301 term->tl_rows = curwin->w_height;
302 term->tl_cols = curwin->w_width;
303
304 minsize = parse_termwinsize(curwin, &rows, &cols);
305 if (minsize)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200306 {
Bram Moolenaarb936b792020-09-04 18:34:09 +0200307 if (term->tl_rows < rows)
308 term->tl_rows = rows;
309 if (term->tl_cols < cols)
310 term->tl_cols = cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200312 if ((opt->jo_set2 & JO2_TERM_ROWS))
313 term->tl_rows = opt->jo_term_rows;
314 else if (rows != 0)
315 term->tl_rows = rows;
316 if ((opt->jo_set2 & JO2_TERM_COLS))
317 term->tl_cols = opt->jo_term_cols;
318 else if (cols != 0)
319 term->tl_cols = cols;
320
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200321 if (!opt->jo_hidden)
Bram Moolenaarb936b792020-09-04 18:34:09 +0200322 {
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200323 if (term->tl_rows != curwin->w_height)
324 win_setheight_win(term->tl_rows, curwin);
325 if (term->tl_cols != curwin->w_width)
326 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaarb936b792020-09-04 18:34:09 +0200327
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200328 // Set 'winsize' now to avoid a resize at the next redraw.
329 if (!minsize && *curwin->w_p_tws != NUL)
330 {
331 char_u buf[100];
332
333 vim_snprintf((char *)buf, 100, "%dx%d",
334 term->tl_rows, term->tl_cols);
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100335 set_option_value_give_err((char_u *)"termwinsize",
336 0L, buf, OPT_LOCAL);
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200337 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200338 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200339}
340
341/*
342 * Initialize job options for a terminal job.
343 * Caller may overrule some of them.
344 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100345 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346init_job_options(jobopt_T *opt)
347{
348 clear_job_options(opt);
349
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100350 opt->jo_mode = CH_MODE_RAW;
351 opt->jo_out_mode = CH_MODE_RAW;
352 opt->jo_err_mode = CH_MODE_RAW;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200353 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
354}
355
356/*
357 * Set job options mandatory for a terminal job.
358 */
359 static void
360setup_job_options(jobopt_T *opt, int rows, int cols)
361{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100362#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100363 // Win32: Redirecting the job output won't work, thus always connect stdout
364 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200365 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200366#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200367 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100368 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200369 opt->jo_io[PART_OUT] = JIO_BUFFER;
370 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
371 opt->jo_modifiable[PART_OUT] = 0;
372 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
373 }
374
Bram Moolenaar4f974752019-02-17 17:44:42 +0100375#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100376 // Win32: Redirecting the job output won't work, thus always connect stderr
377 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200378 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200379#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200380 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100381 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200382 opt->jo_io[PART_ERR] = JIO_BUFFER;
383 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
384 opt->jo_modifiable[PART_ERR] = 0;
385 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
386 }
387
388 opt->jo_pty = TRUE;
389 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
390 opt->jo_term_rows = rows;
391 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
392 opt->jo_term_cols = cols;
393}
394
395/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200396 * Flush messages on channels.
397 */
398 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +0000399term_flush_messages(void)
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200400{
401 mch_check_messages();
402 parse_queued_messages();
403}
404
405/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100406 * Close a terminal buffer (and its window). Used when creating the terminal
407 * fails.
408 */
409 static void
410term_close_buffer(buf_T *buf, buf_T *old_curbuf)
411{
412 free_terminal(buf);
413 if (old_curbuf != NULL)
414 {
415 --curbuf->b_nwindows;
416 curbuf = old_curbuf;
417 curwin->w_buffer = curbuf;
418 ++curbuf->b_nwindows;
419 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100420 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100421
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100422 // Wiping out the buffer will also close the window and call
423 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100424 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
425}
426
427/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100429 * Use either "argvar" or "argv", the other must be NULL.
430 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
431 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200432 * Returns NULL when failed.
433 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100434 buf_T *
435term_start(
436 typval_T *argvar,
437 char **argv,
438 jobopt_T *opt,
439 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200440{
441 exarg_T split_ea;
442 win_T *old_curwin = curwin;
443 term_T *term;
444 buf_T *old_curbuf = NULL;
445 int res;
446 buf_T *newbuf;
Bram Moolenaare1004402020-10-24 20:49:43 +0200447 int vertical = opt->jo_vertical || (cmdmod.cmod_split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200448 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200449
450 if (check_restricted() || check_secure())
451 return NULL;
Bram Moolenaare5b44862021-05-30 13:54:03 +0200452 if (cmdwin_type != 0)
453 {
454 emsg(_(e_cannot_open_terminal_from_command_line_window));
455 return NULL;
456 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200457
458 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
459 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
460 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100461 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
462 || (argvar != NULL
463 && argvar->v_type == VAR_LIST
464 && argvar->vval.v_list != NULL
465 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200466 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000467 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200468 return NULL;
469 }
470
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200471 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200472 if (term == NULL)
473 return NULL;
474 term->tl_dirty_row_end = MAX_ROW;
475 term->tl_cursor_visible = TRUE;
476 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
477 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100478#ifdef FEAT_GUI
479 term->tl_system = (flags & TERM_START_SYSTEM);
480#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200481 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100482 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200483 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200484
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200485 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200486 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200487 if (opt->jo_curwin)
488 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100489 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100490 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200491 {
492 no_write_message();
493 vim_free(term);
494 return NULL;
495 }
496 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200497 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
498 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
499 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200500 {
501 vim_free(term);
502 return NULL;
503 }
504 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100505 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200506 {
507 buf_T *buf;
508
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100509 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100510 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200511 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
512 BLN_NEW | BLN_LISTED);
513 if (buf == NULL || ml_open(buf) == FAIL)
514 {
515 vim_free(term);
516 return NULL;
517 }
518 old_curbuf = curbuf;
519 --curbuf->b_nwindows;
520 curbuf = buf;
521 curwin->w_buffer = buf;
522 ++curbuf->b_nwindows;
523 }
524 else
525 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100526 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200527 split_ea.cmdidx = CMD_new;
528 split_ea.cmd = (char_u *)"new";
529 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100530 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200531 {
532 split_ea.line2 = opt->jo_term_rows;
533 split_ea.addr_count = 1;
534 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100535 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200536 {
537 split_ea.line2 = opt->jo_term_cols;
538 split_ea.addr_count = 1;
539 }
540
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200541 int cmod_split_modified = FALSE;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100542 if (vertical)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200543 {
Bram Moolenaare1004402020-10-24 20:49:43 +0200544 cmdmod.cmod_split |= WSP_VERT;
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200545 cmod_split_modified = TRUE;
546 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200547 ex_splitview(&split_ea);
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200548 if (vertical && cmod_split_modified)
549 cmdmod.cmod_split &= ~WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200550 if (curwin == old_curwin)
551 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100552 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200553 vim_free(term);
554 return NULL;
555 }
556 }
557 term->tl_buffer = curbuf;
558 curbuf->b_term = term;
559
560 if (!opt->jo_hidden)
561 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100562 // Only one size was taken care of with :new, do the other one. With
563 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100564 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200565 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100566 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200567 win_setwidth(opt->jo_term_cols);
568 }
569
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100570 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200571 term->tl_next = first_term;
572 first_term = term;
573
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100574 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
575
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200576 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100577 {
578 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200579 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100580 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100581 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100582 {
583 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100584 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100585 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200586 else
587 {
588 int i;
589 size_t len;
590 char_u *cmd, *p;
591
592 if (argvar->v_type == VAR_STRING)
593 {
594 cmd = argvar->vval.v_string;
595 if (cmd == NULL)
596 cmd = (char_u *)"";
597 else if (STRCMP(cmd, "NONE") == 0)
598 cmd = (char_u *)"pty";
599 }
600 else if (argvar->v_type != VAR_LIST
601 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100602 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100603 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200604 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
605 cmd = (char_u*)"";
606
607 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200608 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200609
610 for (i = 0; p != NULL; ++i)
611 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100612 // Prepend a ! to the command name to avoid the buffer name equals
613 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200614 if (i == 0)
615 vim_snprintf((char *)p, len, "!%s", cmd);
616 else
617 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
618 if (buflist_findname(p) == NULL)
619 {
620 vim_free(curbuf->b_ffname);
621 curbuf->b_ffname = p;
622 break;
623 }
624 }
625 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100626 vim_free(curbuf->b_sfname);
627 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200628 curbuf->b_fname = curbuf->b_ffname;
629
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100630 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
631
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200632 if (opt->jo_term_opencmd != NULL)
633 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
634
635 if (opt->jo_eof_chars != NULL)
636 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
637
638 set_string_option_direct((char_u *)"buftype", -1,
639 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200640 // Avoid that 'buftype' is reset when this buffer is entered.
641 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200642
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100643 // Mark the buffer as not modifiable. It can only be made modifiable after
644 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200645 curbuf->b_p_ma = FALSE;
646
Bram Moolenaarb936b792020-09-04 18:34:09 +0200647 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100648#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200649 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
650#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200651 setup_job_options(opt, term->tl_rows, term->tl_cols);
652
Bram Moolenaar13568252018-03-16 20:46:58 +0100653 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100654 return curbuf;
655
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100656#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100657 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100658 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100659 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100660 else if (argvar->v_type == VAR_STRING)
661 {
662 char_u *cmd = argvar->vval.v_string;
663
664 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
665 term->tl_command = vim_strsave(cmd);
666 }
667 else if (argvar->v_type == VAR_LIST
668 && argvar->vval.v_list != NULL
669 && argvar->vval.v_list->lv_len > 0)
670 {
671 garray_T ga;
672 listitem_T *item;
673
674 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200675 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100676 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100677 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100678 char_u *p;
679
680 if (s == NULL)
681 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100682 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100683 if (p == NULL)
684 break;
685 ga_concat(&ga, p);
686 vim_free(p);
687 ga_append(&ga, ' ');
688 }
689 if (item == NULL)
690 {
691 ga_append(&ga, NUL);
692 term->tl_command = ga.ga_data;
693 }
694 else
695 ga_clear(&ga);
696 }
697#endif
698
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100699 if (opt->jo_term_kill != NULL)
700 {
701 char_u *p = skiptowhite(opt->jo_term_kill);
702
703 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
704 }
705
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200706 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100707 {
708 char_u *p = skiptowhite(opt->jo_term_api);
709
710 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
711 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200712 else
713 term->tl_api = vim_strsave((char_u *)"Tapi_");
714
Bram Moolenaar83d47902020-03-26 20:34:00 +0100715 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
716 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
717
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100718#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100719 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
720 if (opt->jo_set2 & JO2_ANSI_COLORS)
721 {
722 term->tl_palette = ALLOC_MULT(long_u, 16);
723 if (term->tl_palette == NULL)
724 {
725 vim_free(term);
726 return NULL;
727 }
728 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
729 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100730#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100731
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100732 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100733 if (argv == NULL
734 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200735 && argvar->vval.v_string != NULL
736 && STRCMP(argvar->vval.v_string, "NONE") == 0)
737 res = create_pty_only(term, opt);
738 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200739 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200740
741 newbuf = curbuf;
742 if (res == OK)
743 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100744 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200745 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
746 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100747#ifdef FEAT_GUI
748 if (term->tl_system)
749 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100750 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100751 term->tl_toprow = msg_row + 1;
752 term->tl_dirty_row_end = 0;
753 }
754#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200755
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100756 // Make sure we don't get stuck on sending keys to the job, it leads to
757 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200758 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
759
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200760 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200761 {
762 --curbuf->b_nwindows;
763 curbuf = old_curbuf;
764 curwin->w_buffer = curbuf;
765 ++curbuf->b_nwindows;
766 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000767 else if (vgetc_busy
768#ifdef FEAT_TIMERS
769 || timer_busy
770#endif
771 || input_busy)
772 {
773 char_u ignore[4];
774
775 // When waiting for input need to return and possibly end up in
776 // terminal_loop() instead.
777 ignore[0] = K_SPECIAL;
778 ignore[1] = KS_EXTRA;
779 ignore[2] = KE_IGNORE;
780 ignore[3] = NUL;
781 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
782 typebuf_was_filled = TRUE;
783 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200784 }
785 else
786 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100787 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788 return NULL;
789 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100790
Bram Moolenaar13568252018-03-16 20:46:58 +0100791 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200792 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
793 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200794 return newbuf;
795}
796
797/*
798 * ":terminal": open a terminal window and execute a job in it.
799 */
800 void
801ex_terminal(exarg_T *eap)
802{
803 typval_T argvar[2];
804 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100805 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200806 char_u *cmd;
807 char_u *tofree = NULL;
808
809 init_job_options(&opt);
810
811 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100812 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200813 {
814 char_u *p, *ep;
815
816 cmd += 2;
817 p = skiptowhite(cmd);
818 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200819 if (ep != NULL)
820 {
821 if (ep < p)
822 p = ep;
823 else
824 ep = NULL;
825 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200826
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200827 // Note: Keep this in sync with get_terminalopt_name.
828
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200829# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
830 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
831 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200832 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200833 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100834 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200835 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200836 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200837 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200838 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200839 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200840 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200841 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100842 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100843 else if (OPTARG_HAS("shell"))
844 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200845 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100846 {
847 opt.jo_set2 |= JO2_TERM_KILL;
848 opt.jo_term_kill = ep + 1;
849 p = skiptowhite(cmd);
850 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200851 else if (OPTARG_HAS("api"))
852 {
853 opt.jo_set2 |= JO2_TERM_API;
854 if (ep != NULL)
855 {
856 opt.jo_term_api = ep + 1;
857 p = skiptowhite(cmd);
858 }
859 else
860 opt.jo_term_api = NULL;
861 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100862 else if (OPTARG_HAS("rows") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200863 {
864 opt.jo_set2 |= JO2_TERM_ROWS;
865 opt.jo_term_rows = atoi((char *)ep + 1);
866 p = skiptowhite(cmd);
867 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100868 else if (OPTARG_HAS("cols") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200869 {
870 opt.jo_set2 |= JO2_TERM_COLS;
871 opt.jo_term_cols = atoi((char *)ep + 1);
872 p = skiptowhite(cmd);
873 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200874 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200875 {
876 char_u *buf = NULL;
877 char_u *keys;
878
Bram Moolenaar21109272020-01-30 16:27:20 +0100879 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200880 p = skiptowhite(cmd);
881 *p = NUL;
zeertzjq7e0bae02023-08-11 23:15:38 +0200882 keys = replace_termcodes(ep + 1, &buf, 0,
Bram Moolenaar459fd782019-10-13 16:43:39 +0200883 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200884 opt.jo_set2 |= JO2_EOF_CHARS;
885 opt.jo_eof_chars = vim_strsave(keys);
886 vim_free(buf);
887 *p = ' ';
888 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100889#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100890 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
891 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100892 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100893 int tty_type = NUL;
894
895 p = skiptowhite(cmd);
896 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
897 tty_type = 'w';
898 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
899 tty_type = 'c';
900 else
901 {
Bram Moolenaar50809a42023-05-20 16:39:07 +0100902 semsg(_(e_invalid_value_for_argument_str), "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100903 goto theend;
904 }
905 opt.jo_set2 |= JO2_TTY_TYPE;
906 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100907 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100908#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200909 else
910 {
911 if (*p)
912 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000913 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100914 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200915 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200916# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200917 cmd = skipwhite(p);
918 }
919 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100920 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100921 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200922 tofree = cmd = vim_strsave(p_sh);
923
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100924 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100925 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200926 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100927 }
928
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200929 if (eap->addr_count > 0)
930 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100931 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200932 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
933 opt.jo_io[PART_IN] = JIO_BUFFER;
934 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
935 opt.jo_in_top = eap->line1;
936 opt.jo_in_bot = eap->line2;
937 }
938
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100939 if (opt_shell && tofree == NULL)
940 {
941#ifdef UNIX
942 char **argv = NULL;
943 char_u *tofree1 = NULL;
944 char_u *tofree2 = NULL;
945
946 // :term ++shell command
947 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
948 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100949 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100950 vim_free(tofree1);
951 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100952 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100953#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100954# ifdef MSWIN
955 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
956 char_u *newcmd;
957
958 newcmd = alloc(cmdlen);
959 if (newcmd == NULL)
960 goto theend;
961 tofree = newcmd;
962 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
963 cmd = newcmd;
964# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000965 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100966 goto theend;
967# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100968#endif
969 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100970 argvar[0].v_type = VAR_STRING;
971 argvar[0].vval.v_string = cmd;
972 argvar[1].v_type = VAR_UNKNOWN;
973 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100974
975theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100976 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200977 vim_free(opt.jo_eof_chars);
978}
979
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200980 static char_u *
981get_terminalopt_name(expand_T *xp UNUSED, int idx)
982{
983 // Note: Keep this in sync with ex_terminal.
984 static char *(p_termopt_values[]) =
985 {
986 "close",
987 "noclose",
988 "open",
989 "curwin",
990 "hidden",
991 "norestore",
992 "shell",
993 "kill=",
994 "rows=",
995 "cols=",
996 "eof=",
997 "type=",
998 "api=",
999 };
1000
1001 if (idx < (int)ARRAY_LENGTH(p_termopt_values))
1002 return (char_u*)p_termopt_values[idx];
1003 return NULL;
1004}
1005
1006 static char_u *
1007get_termkill_name(expand_T *xp UNUSED, int idx)
1008{
1009 // These are platform-specific values used for job_stop(). They are defined
1010 // in each platform's mch_signal_job(). Just use a unified auto-complete
1011 // list for simplicity.
1012 static char *(p_termkill_values[]) =
1013 {
1014 "term",
1015 "hup",
1016 "quit",
1017 "int",
1018 "kill",
1019 "winch",
1020 };
1021
1022 if (idx < (int)ARRAY_LENGTH(p_termkill_values))
1023 return (char_u*)p_termkill_values[idx];
1024 return NULL;
1025}
1026
1027/*
1028 * Command-line expansion for :terminal [options]
1029 */
1030 int
1031expand_terminal_opt(
1032 char_u *pat,
1033 expand_T *xp,
1034 regmatch_T *rmp,
1035 char_u ***matches,
1036 int *numMatches)
1037{
1038 if (xp->xp_pattern > xp->xp_line && *(xp->xp_pattern-1) == '=')
1039 {
1040 char_u *(*cb)(expand_T *, int) = NULL;
1041
1042 char_u *name_end = xp->xp_pattern - 1;
1043 if (name_end - xp->xp_line >= 4
1044 && STRNCMP(name_end - 4, "kill", 4) == 0)
1045 cb = get_termkill_name;
1046
1047 if (cb != NULL)
1048 {
1049 return ExpandGeneric(
1050 pat,
1051 xp,
1052 rmp,
1053 matches,
1054 numMatches,
1055 cb,
1056 FALSE);
1057 }
1058 return FAIL;
1059 }
1060 return ExpandGeneric(
1061 pat,
1062 xp,
1063 rmp,
1064 matches,
1065 numMatches,
1066 get_terminalopt_name,
1067 FALSE);
1068}
1069
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001070#if defined(FEAT_SESSION) || defined(PROTO)
1071/*
1072 * Write a :terminal command to the session file to restore the terminal in
1073 * window "wp".
1074 * Return FAIL if writing fails.
1075 */
1076 int
Bram Moolenaar0e655112020-09-11 20:36:36 +02001077term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001078{
Bram Moolenaar0e655112020-09-11 20:36:36 +02001079 const int bufnr = wp->w_buffer->b_fnum;
1080 term_T *term = wp->w_buffer->b_term;
1081
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001082 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001083 {
1084 // There are multiple views into this terminal buffer. We don't want to
1085 // create the terminal multiple times. If it's the first time, create,
1086 // otherwise link to the first buffer.
1087 char id_as_str[NUMBUFLEN];
1088 hashitem_T *entry;
1089
1090 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
1091
1092 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
1093 if (!HASHITEM_EMPTY(entry))
1094 {
1095 // we've already opened this terminal buffer
1096 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
1097 return FAIL;
1098 return put_eol(fd);
1099 }
1100 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001101
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001102 // Create the terminal and run the command. This is not without
1103 // risk, but let's assume the user only creates a session when this
1104 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001105 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1106 term->tl_cols, term->tl_rows) < 0)
1107 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001108#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001109 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1110 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001111#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001112 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1113 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001114 if (put_eol(fd) != OK)
1115 return FAIL;
1116
1117 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1118 return FAIL;
1119
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001120 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001121 {
1122 char *hash_key = alloc(NUMBUFLEN);
1123
1124 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00001125 hash_add(terminal_bufs, (char_u *)hash_key, "terminal session");
Bram Moolenaar0e655112020-09-11 20:36:36 +02001126 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001127
1128 return put_eol(fd);
1129}
1130
1131/*
1132 * Return TRUE if "buf" has a terminal that should be restored.
1133 */
1134 int
1135term_should_restore(buf_T *buf)
1136{
1137 term_T *term = buf->b_term;
1138
1139 return term != NULL && (term->tl_command == NULL
1140 || STRCMP(term->tl_command, "NONE") != 0);
1141}
1142#endif
1143
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001144/*
1145 * Free the scrollback buffer for "term".
1146 */
1147 static void
1148free_scrollback(term_T *term)
1149{
1150 int i;
1151
1152 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1153 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1154 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001155 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1156 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1157 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001158}
1159
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001160
1161// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001162static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001163
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001164/*
1165 * Free a terminal and everything it refers to.
1166 * Kills the job if there is one.
1167 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001168 * The actual terminal structure is freed later in free_unused_terminals(),
1169 * because callbacks may wipe out a buffer while the terminal is still
1170 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001171 */
1172 void
1173free_terminal(buf_T *buf)
1174{
1175 term_T *term = buf->b_term;
1176 term_T *tp;
1177
1178 if (term == NULL)
1179 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001180
1181 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001182 if (first_term == term)
1183 first_term = term->tl_next;
1184 else
1185 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1186 if (tp->tl_next == term)
1187 {
1188 tp->tl_next = term->tl_next;
1189 break;
1190 }
1191
1192 if (term->tl_job != NULL)
1193 {
1194 if (term->tl_job->jv_status != JOB_ENDED
1195 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001196 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001197 job_stop(term->tl_job, NULL, "kill");
1198 job_unref(term->tl_job);
1199 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001200 term->tl_next = terminals_to_free;
1201 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001202
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001203 buf->b_term = NULL;
1204 if (in_terminal_loop == term)
1205 in_terminal_loop = NULL;
1206}
1207
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001208 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00001209free_unused_terminals(void)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001210{
1211 while (terminals_to_free != NULL)
1212 {
1213 term_T *term = terminals_to_free;
1214
1215 terminals_to_free = term->tl_next;
1216
1217 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001218 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001219
1220 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001221 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001222 vim_free(term->tl_title);
1223#ifdef FEAT_SESSION
1224 vim_free(term->tl_command);
1225#endif
1226 vim_free(term->tl_kill);
1227 vim_free(term->tl_status_text);
1228 vim_free(term->tl_opencmd);
1229 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001230 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001231#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001232 if (term->tl_out_fd != NULL)
1233 fclose(term->tl_out_fd);
1234#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001235 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001236 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001237 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001238 vim_free(term);
1239 }
1240}
1241
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001242/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001243 * Get the part that is connected to the tty. Normally this is PART_IN, but
1244 * when writing buffer lines to the job it can be another. This makes it
1245 * possible to do "1,5term vim -".
1246 */
1247 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001248get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001249{
1250#ifdef UNIX
1251 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1252 int i;
1253
1254 for (i = 0; i < 3; ++i)
1255 {
1256 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1257
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001258 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001259 return parts[i];
1260 }
1261#endif
1262 return PART_IN;
1263}
1264
1265/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001266 * Read any vterm output and send it on the channel.
1267 */
1268 static void
1269term_forward_output(term_T *term)
1270{
1271 VTerm *vterm = term->tl_vterm;
1272 char buf[KEY_BUF_LEN];
1273 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1274
1275 if (curlen > 0)
1276 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1277 (char_u *)buf, (int)curlen, NULL);
1278}
1279
1280/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001281 * Write job output "msg[len]" to the vterm.
1282 */
1283 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001284term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001285{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001286 char_u *msg = msg_arg;
1287 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001288 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001289 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001290 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1291
1292 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1293 // the end.
1294 if (len > limit)
1295 {
1296 char_u *p = msg + len - limit;
1297
1298 p -= (*mb_head_off)(msg, p);
1299 len -= p - msg;
1300 msg = p;
1301 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001302
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001303 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001304
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001305 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001306 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001307 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001308
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001309 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001310 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1311}
1312
1313 static void
Bram Moolenaar58806c12023-04-29 14:26:02 +01001314position_cursor(win_T *wp, VTermPos *pos)
1315{
1316 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1317 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1318#ifdef FEAT_PROP_POPUP
1319 if (popup_is_popup(wp))
1320 {
1321 wp->w_wrow += popup_top_extra(wp);
1322 wp->w_wcol += popup_left_extra(wp);
1323 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
1324 }
1325 else
1326 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
1327#endif
1328 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1329}
1330
1331 static void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001332update_cursor(term_T *term, int redraw)
1333{
1334 if (term->tl_normal_mode)
1335 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001336#ifdef FEAT_GUI
1337 if (term->tl_system)
1338 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1339 term->tl_cursor_pos.col);
1340 else
1341#endif
Bram Moolenaar58806c12023-04-29 14:26:02 +01001342 if (!term_job_running(term))
1343 // avoid the cursor positioned below the last used line
Bram Moolenaar13568252018-03-16 20:46:58 +01001344 setcursor();
Bram Moolenaar58806c12023-04-29 14:26:02 +01001345 else
1346 {
1347 // do not use the window cursor position
1348 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1349 windgoto(W_WINROW(curwin) + curwin->w_wrow,
1350 curwin->w_wincol + curwin->w_wcol);
1351 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001352 if (redraw)
1353 {
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001354 aco_save_T aco;
1355
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001356 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1357 cursor_on();
1358 out_flush();
1359#ifdef FEAT_GUI
1360 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001361 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001362 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001363 gui_mch_flush();
1364 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001365#endif
Bram Moolenaar24fe33a2022-11-24 00:09:02 +00001366 // Make sure an invoked autocmd doesn't delete the buffer (and the
1367 // terminal) under our fingers.
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001368 ++term->tl_buffer->b_locked;
1369
1370 // save and restore curwin and curbuf, in case the autocmd changes them
1371 aucmd_prepbuf(&aco, curbuf);
1372 apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, FALSE, term->tl_buffer);
1373 aucmd_restbuf(&aco);
1374
1375 --term->tl_buffer->b_locked;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001376 }
1377}
1378
1379/*
1380 * Invoked when "msg" output from a job was received. Write it to the terminal
1381 * of "buffer".
1382 */
1383 void
1384write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1385{
1386 size_t len = STRLEN(msg);
1387 term_T *term = buffer->b_term;
1388
Bram Moolenaar4f974752019-02-17 17:44:42 +01001389#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001390 // Win32: Cannot redirect output of the job, intercept it here and write to
1391 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001392 if (term->tl_out_fd != NULL)
1393 {
1394 ch_log(channel, "Writing %d bytes to output file", (int)len);
1395 fwrite(msg, len, 1, term->tl_out_fd);
1396 return;
1397 }
1398#endif
1399
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001400 if (term->tl_vterm == NULL)
1401 {
1402 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1403 return;
1404 }
1405 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001406 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001407 term_write_job_output(term, msg, len);
1408
Bram Moolenaar13568252018-03-16 20:46:58 +01001409#ifdef FEAT_GUI
1410 if (term->tl_system)
1411 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001412 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001413 update_system_term(term);
1414 update_cursor(term, TRUE);
1415 }
1416 else
1417#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001418 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1419 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001420 if (!term->tl_normal_mode)
1421 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001422 // Don't use update_screen() when editing the command line, it gets
1423 // cleared.
1424 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001425 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001426 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001427 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001428 update_screen(UPD_VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001429 // update_screen() can be slow, check the terminal wasn't closed
1430 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001431 if (buffer == curbuf && curbuf->b_term != NULL)
1432 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001433 }
1434 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001435 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001436 }
1437}
1438
1439/*
1440 * Send a mouse position and click to the vterm
1441 */
1442 static int
1443term_send_mouse(VTerm *vterm, int button, int pressed)
1444{
1445 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001446 int row = mouse_row - W_WINROW(curwin);
1447 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001448
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001449#ifdef FEAT_PROP_POPUP
1450 if (popup_is_popup(curwin))
1451 {
1452 row -= popup_top_extra(curwin);
1453 col -= popup_left_extra(curwin);
1454 }
1455#endif
1456 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001457 if (button != 0)
1458 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001459 return TRUE;
1460}
1461
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001462static int enter_mouse_col = -1;
1463static int enter_mouse_row = -1;
1464
1465/*
1466 * Handle a mouse click, drag or release.
1467 * Return TRUE when a mouse event is sent to the terminal.
1468 */
1469 static int
1470term_mouse_click(VTerm *vterm, int key)
1471{
1472#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001473 // For modeless selection mouse drag and release events are ignored, unless
1474 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001475 static int ignore_drag_release = TRUE;
1476 VTermMouseState mouse_state;
1477
1478 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1479 if (mouse_state.flags == 0)
1480 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001481 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001482 switch (key)
1483 {
1484 case K_LEFTDRAG:
1485 case K_LEFTRELEASE:
1486 case K_RIGHTDRAG:
1487 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001488 // Ignore drag and release events when the button-down wasn't
1489 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001490 if (ignore_drag_release)
1491 {
1492 int save_mouse_col, save_mouse_row;
1493
1494 if (enter_mouse_col < 0)
1495 break;
1496
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001497 // mouse click in the window gave us focus, handle that
1498 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001499 save_mouse_col = mouse_col;
1500 save_mouse_row = mouse_row;
1501 mouse_col = enter_mouse_col;
1502 mouse_row = enter_mouse_row;
1503 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1504 mouse_col = save_mouse_col;
1505 mouse_row = save_mouse_row;
1506 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001507 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001508 case K_LEFTMOUSE:
1509 case K_RIGHTMOUSE:
1510 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1511 ignore_drag_release = TRUE;
1512 else
1513 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001514 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001515 if (clip_star.available)
1516 {
1517 int button, is_click, is_drag;
1518
1519 button = get_mouse_button(KEY2TERMCAP1(key),
1520 &is_click, &is_drag);
1521 if (mouse_model_popup() && button == MOUSE_LEFT
1522 && (mod_mask & MOD_MASK_SHIFT))
1523 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001524 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001525 button = MOUSE_RIGHT;
1526 mod_mask &= ~MOD_MASK_SHIFT;
1527 }
1528 clip_modeless(button, is_click, is_drag);
1529 }
1530 break;
1531
1532 case K_MIDDLEMOUSE:
1533 if (clip_star.available)
1534 insert_reg('*', TRUE);
1535 break;
1536 }
1537 enter_mouse_col = -1;
1538 return FALSE;
1539 }
1540#endif
1541 enter_mouse_col = -1;
1542
1543 switch (key)
1544 {
1545 case K_LEFTMOUSE:
1546 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1547 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1548 case K_LEFTRELEASE:
1549 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1550 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1551 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1552 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1553 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1554 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1555 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1556 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1557 }
1558 return TRUE;
1559}
1560
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001561/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001562 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1563 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001564 * Return the number of bytes in "buf".
1565 */
1566 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001567term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001568{
1569 VTerm *vterm = term->tl_vterm;
1570 VTermKey key = VTERM_KEY_NONE;
1571 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001572 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001573
1574 switch (c)
1575 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001576 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001577
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001578 // don't use VTERM_KEY_BACKSPACE, it always
1579 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001580 case K_BS: c = term_backspace_char; break;
1581
1582 case ESC: key = VTERM_KEY_ESCAPE; break;
1583 case K_DEL: key = VTERM_KEY_DEL; break;
1584 case K_DOWN: key = VTERM_KEY_DOWN; break;
1585 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1586 key = VTERM_KEY_DOWN; break;
1587 case K_END: key = VTERM_KEY_END; break;
1588 case K_S_END: mod = VTERM_MOD_SHIFT;
1589 key = VTERM_KEY_END; break;
1590 case K_C_END: mod = VTERM_MOD_CTRL;
1591 key = VTERM_KEY_END; break;
1592 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1593 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1594 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1595 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1596 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1597 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1598 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1599 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1600 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1601 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1602 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1603 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1604 case K_HOME: key = VTERM_KEY_HOME; break;
1605 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1606 key = VTERM_KEY_HOME; break;
1607 case K_C_HOME: mod = VTERM_MOD_CTRL;
1608 key = VTERM_KEY_HOME; break;
1609 case K_INS: key = VTERM_KEY_INS; break;
1610 case K_K0: key = VTERM_KEY_KP_0; break;
1611 case K_K1: key = VTERM_KEY_KP_1; break;
1612 case K_K2: key = VTERM_KEY_KP_2; break;
1613 case K_K3: key = VTERM_KEY_KP_3; break;
1614 case K_K4: key = VTERM_KEY_KP_4; break;
1615 case K_K5: key = VTERM_KEY_KP_5; break;
1616 case K_K6: key = VTERM_KEY_KP_6; break;
1617 case K_K7: key = VTERM_KEY_KP_7; break;
1618 case K_K8: key = VTERM_KEY_KP_8; break;
1619 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001620 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001621 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001622 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001623 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001624 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1625 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001626 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1627 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001628 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1629 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001630 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1631 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1632 case K_LEFT: key = VTERM_KEY_LEFT; break;
1633 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1634 key = VTERM_KEY_LEFT; break;
1635 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1636 key = VTERM_KEY_LEFT; break;
1637 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1638 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1639 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1640 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1641 key = VTERM_KEY_RIGHT; break;
1642 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1643 key = VTERM_KEY_RIGHT; break;
1644 case K_UP: key = VTERM_KEY_UP; break;
1645 case K_S_UP: mod = VTERM_MOD_SHIFT;
1646 key = VTERM_KEY_UP; break;
1647 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001648 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1649 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001650
Bram Moolenaara42ad572017-11-16 13:08:04 +01001651 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1652 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001653 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1654 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001655
1656 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001657 case K_LEFTMOUSE_NM:
1658 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001659 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001660 case K_LEFTRELEASE_NM:
1661 case K_MOUSEMOVE:
1662 case K_MIDDLEMOUSE:
1663 case K_MIDDLEDRAG:
1664 case K_MIDDLERELEASE:
1665 case K_RIGHTMOUSE:
1666 case K_RIGHTDRAG:
1667 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1668 return 0;
1669 other = TRUE;
1670 break;
1671
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001672 case K_X1MOUSE: /* TODO */ return 0;
1673 case K_X1DRAG: /* TODO */ return 0;
1674 case K_X1RELEASE: /* TODO */ return 0;
1675 case K_X2MOUSE: /* TODO */ return 0;
1676 case K_X2DRAG: /* TODO */ return 0;
1677 case K_X2RELEASE: /* TODO */ return 0;
1678
1679 case K_IGNORE: return 0;
1680 case K_NOP: return 0;
1681 case K_UNDO: return 0;
1682 case K_HELP: return 0;
1683 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1684 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1685 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1686 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1687 case K_SELECT: return 0;
1688#ifdef FEAT_GUI
1689 case K_VER_SCROLLBAR: return 0;
1690 case K_HOR_SCROLLBAR: return 0;
1691#endif
1692#ifdef FEAT_GUI_TABLINE
1693 case K_TABLINE: return 0;
1694 case K_TABMENU: return 0;
1695#endif
1696#ifdef FEAT_NETBEANS_INTG
1697 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1698#endif
1699#ifdef FEAT_DND
1700 case K_DROP: return 0;
1701#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001702 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001703 case K_PS: vterm_keyboard_start_paste(vterm);
1704 other = TRUE;
1705 break;
1706 case K_PE: vterm_keyboard_end_paste(vterm);
1707 other = TRUE;
1708 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001709 }
1710
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001711 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001712 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001713 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001714 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001715 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001716 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001717 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001718
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001719 // Ctrl-Shift-i may have the key "I" instead of "i", but for the kitty
1720 // keyboard protocol should use "i". Applies to all ascii letters.
1721 if (ASCII_ISUPPER(c)
Bram Moolenaarebed1b02022-11-24 14:05:19 +00001722 && vterm_is_kitty_keyboard(vterm)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001723 && mod == (VTERM_MOD_CTRL | VTERM_MOD_SHIFT))
1724 c = TOLOWER_ASC(c);
1725
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001726 /*
1727 * Convert special keys to vterm keys:
1728 * - Write keys to vterm: vterm_keyboard_key()
1729 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001730 */
1731 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001732 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001733 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001734 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001735 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001736 vterm_keyboard_unichar(vterm, c, mod);
1737
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001738 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001739 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1740}
1741
1742/*
1743 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001744 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001745 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001746 */
1747 static int
1748term_job_running_check(term_T *term, int check_job_status)
1749{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001750 // Also consider the job finished when the channel is closed, to avoid a
1751 // race condition when updating the title.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001752 if (term == NULL
1753 || term->tl_job == NULL
1754 || !channel_is_open(term->tl_job->jv_channel))
1755 return FALSE;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001756
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001757 job_T *job = term->tl_job;
1758
1759 // Careful: Checking the job status may invoke callbacks, which close
1760 // the buffer and terminate "term". However, "job" will not be freed
1761 // yet.
1762 if (check_job_status)
1763 job_status(job);
1764 return (job->jv_status == JOB_STARTED
1765 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001766}
1767
1768/*
1769 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001770 */
1771 int
1772term_job_running(term_T *term)
1773{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001774 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001775}
1776
1777/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001778 * Return TRUE if the job for "term" is still running, ignoring the job was
1779 * "NONE".
1780 */
1781 int
1782term_job_running_not_none(term_T *term)
1783{
1784 return term_job_running(term) && !term_none_open(term);
1785}
1786
1787/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001788 * Return TRUE if "term" has an active channel and used ":term NONE".
1789 */
1790 int
1791term_none_open(term_T *term)
1792{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001793 // Also consider the job finished when the channel is closed, to avoid a
1794 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001795 return term != NULL
1796 && term->tl_job != NULL
1797 && channel_is_open(term->tl_job->jv_channel)
1798 && term->tl_job->jv_channel->ch_keep_open;
1799}
1800
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001801//
1802// Used to confirm whether we would like to kill a terminal.
1803// Return OK when the user confirms to kill it.
1804// Return FAIL if the user selects otherwise.
1805//
1806 int
1807term_confirm_stop(buf_T *buf)
1808{
1809 char_u buff[DIALOG_MSG_SIZE];
1810 int ret;
1811
1812 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1813 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1814 if (ret == VIM_YES)
1815 return OK;
1816 else
1817 return FAIL;
1818}
1819
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001820/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001821 * Used when exiting: kill the job in "buf" if so desired.
1822 * Return OK when the job finished.
1823 * Return FAIL when the job is still running.
1824 */
1825 int
1826term_try_stop_job(buf_T *buf)
1827{
1828 int count;
1829 char *how = (char *)buf->b_term->tl_kill;
1830
1831#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001832 if ((how == NULL || *how == NUL)
1833 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001834 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001835 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001836 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001837 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001838 return FAIL;
1839 }
1840#endif
1841 if (how == NULL || *how == NUL)
1842 return FAIL;
1843
1844 job_stop(buf->b_term->tl_job, NULL, how);
1845
Bram Moolenaar9172d232019-01-29 23:06:54 +01001846 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001847 for (count = 0; count < 100; ++count)
1848 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001849 job_T *job;
1850
1851 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001852 if (!buf_valid(buf)
1853 || buf->b_term == NULL
1854 || buf->b_term->tl_job == NULL)
1855 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001856 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001857
Bram Moolenaar9172d232019-01-29 23:06:54 +01001858 // Call job_status() to update jv_status. It may cause the job to be
1859 // cleaned up but it won't be freed.
1860 job_status(job);
1861 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001862 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001863
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001864 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001865 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001866 }
1867 return FAIL;
1868}
1869
1870/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001871 * Add the last line of the scrollback buffer to the buffer in the window.
1872 */
1873 static void
1874add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1875{
1876 buf_T *buf = term->tl_buffer;
1877 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1878 linenr_T lnum = buf->b_ml.ml_line_count;
1879
Bram Moolenaar4f974752019-02-17 17:44:42 +01001880#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001881 if (!enc_utf8 && enc_codepage > 0)
1882 {
1883 WCHAR *ret = NULL;
1884 int length = 0;
1885
1886 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1887 &ret, &length);
1888 if (ret != NULL)
1889 {
1890 WideCharToMultiByte_alloc(enc_codepage, 0,
1891 ret, length, (char **)&text, &len, 0, 0);
1892 vim_free(ret);
1893 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1894 vim_free(text);
1895 }
1896 }
1897 else
1898#endif
1899 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1900 if (empty)
1901 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001902 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001903 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001904 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001905 curbuf = curwin->w_buffer;
1906 }
1907}
1908
1909 static void
1910cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1911{
1912 attr->width = cell->width;
1913 attr->attrs = cell->attrs;
1914 attr->fg = cell->fg;
1915 attr->bg = cell->bg;
1916}
1917
1918 static int
1919equal_celattr(cellattr_T *a, cellattr_T *b)
1920{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001921 // We only compare the RGB colors, ignoring the ANSI index and type.
1922 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001923 return a->fg.red == b->fg.red
1924 && a->fg.green == b->fg.green
1925 && a->fg.blue == b->fg.blue
1926 && a->bg.red == b->bg.red
1927 && a->bg.green == b->bg.green
1928 && a->bg.blue == b->bg.blue;
1929}
1930
Bram Moolenaard96ff162018-02-18 22:13:29 +01001931/*
1932 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1933 * line at this position. Otherwise at the end.
1934 */
1935 static int
1936add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1937{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001938 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
1939 return FALSE;
1940
1941 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1942 + term->tl_scrollback.ga_len;
1943
1944 if (lnum > 0)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001945 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001946 int i;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001947
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001948 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001949 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001950 *line = *(line - 1);
1951 --line;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001952 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01001953 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001954 line->sb_cols = 0;
1955 line->sb_cells = NULL;
1956 line->sb_fill_attr = *fill_attr;
1957 ++term->tl_scrollback.ga_len;
1958 return OK;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001959}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001960
1961/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001962 * Remove the terminal contents from the scrollback and the buffer.
1963 * Used before adding a new scrollback line or updating the buffer for lines
1964 * displayed in the terminal.
1965 */
1966 static void
1967cleanup_scrollback(term_T *term)
1968{
1969 sb_line_T *line;
1970 garray_T *gap;
1971
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001972 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001973 gap = &term->tl_scrollback;
1974 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1975 && gap->ga_len > 0)
1976 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001977 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001978 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1979 vim_free(line->sb_cells);
1980 --gap->ga_len;
1981 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001982 curbuf = curwin->w_buffer;
1983 if (curbuf == term->tl_buffer)
1984 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001985}
1986
1987/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001988 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001989 */
1990 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001991update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001992{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001993 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001994 int len;
1995 int lines_skipped = 0;
1996 VTermPos pos;
1997 VTermScreenCell cell;
1998 cellattr_T fill_attr, new_fill_attr;
1999 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002000
2001 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
2002 "Adding terminal window snapshot to buffer");
2003
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002004 // First remove the lines that were appended before, they might be
2005 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002006 cleanup_scrollback(term);
2007
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002008 screen = vterm_obtain_screen(term->tl_vterm);
2009 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002010 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
2011 {
2012 len = 0;
2013 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
2014 if (vterm_screen_get_cell(screen, pos, &cell) != 0
2015 && cell.chars[0] != NUL)
2016 {
2017 len = pos.col + 1;
2018 new_fill_attr = term->tl_default_color;
2019 }
2020 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002021 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022 cell2cellattr(&cell, &new_fill_attr);
2023
2024 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
2025 ++lines_skipped;
2026 else
2027 {
2028 while (lines_skipped > 0)
2029 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002030 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002031 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002032 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002033 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002034 }
2035
2036 if (len == 0)
2037 p = NULL;
2038 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002039 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002040 if ((p != NULL || len == 0)
2041 && ga_grow(&term->tl_scrollback, 1) == OK)
2042 {
2043 garray_T ga;
2044 int width;
2045 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
2046 + term->tl_scrollback.ga_len;
2047
2048 ga_init2(&ga, 1, 100);
2049 for (pos.col = 0; pos.col < len; pos.col += width)
2050 {
2051 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2052 {
2053 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02002054 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002055 if (ga_grow(&ga, 1) == OK)
2056 ga.ga_len += utf_char2bytes(' ',
2057 (char_u *)ga.ga_data + ga.ga_len);
2058 }
2059 else
2060 {
2061 width = cell.width;
2062
2063 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01002064 if (width == 2)
2065 // second cell of double-width character has the
2066 // same attributes.
2067 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002068
Bram Moolenaara79fd562018-12-20 20:47:32 +01002069 // Each character can be up to 6 bytes.
2070 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002071 {
2072 int i;
2073 int c;
2074
2075 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
2076 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2077 (char_u *)ga.ga_data + ga.ga_len);
2078 }
2079 }
2080 }
2081 line->sb_cols = len;
2082 line->sb_cells = p;
2083 line->sb_fill_attr = new_fill_attr;
2084 fill_attr = new_fill_attr;
2085 ++term->tl_scrollback.ga_len;
2086
2087 if (ga_grow(&ga, 1) == FAIL)
2088 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2089 else
2090 {
2091 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2092 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2093 }
2094 ga_clear(&ga);
2095 }
2096 else
2097 vim_free(p);
2098 }
2099 }
2100
Bram Moolenaarf3aea592018-11-11 22:18:21 +01002101 // Add trailing empty lines.
2102 for (pos.row = term->tl_scrollback.ga_len;
2103 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
2104 ++pos.row)
2105 {
2106 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
2107 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2108 }
2109
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002110 term->tl_dirty_snapshot = FALSE;
2111#ifdef FEAT_TIMERS
2112 term->tl_timer_set = FALSE;
2113#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002114}
2115
2116/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002117 * Loop over all windows in the current tab, and also curwin, which is not
2118 * encountered when using a terminal in a popup window.
2119 * Return TRUE if "*wp" was set to the next window.
2120 */
2121 static int
2122for_all_windows_and_curwin(win_T **wp, int *did_curwin)
2123{
2124 if (*wp == NULL)
2125 *wp = firstwin;
2126 else if ((*wp)->w_next != NULL)
2127 *wp = (*wp)->w_next;
2128 else if (!*did_curwin)
2129 *wp = curwin;
2130 else
2131 return FALSE;
2132 if (*wp == curwin)
2133 *did_curwin = TRUE;
2134 return TRUE;
2135}
2136
2137/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002138 * If needed, add the current lines of the terminal to scrollback and to the
2139 * buffer. Called after the job has ended and when switching to
2140 * Terminal-Normal mode.
2141 * When "redraw" is TRUE redraw the windows that show the terminal.
2142 */
2143 static void
2144may_move_terminal_to_buffer(term_T *term, int redraw)
2145{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002146 if (term->tl_vterm == NULL)
2147 return;
2148
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002149 // Update the snapshot only if something changes or the buffer does not
2150 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002151 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2152 <= term->tl_scrollback_scrolled)
2153 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002154
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002155 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002156 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2157 &term->tl_default_color.fg, &term->tl_default_color.bg);
2158
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002159 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002160 {
2161 win_T *wp = NULL;
2162 int did_curwin = FALSE;
2163
2164 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002165 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002166 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002167 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002168 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2169 wp->w_cursor.col = 0;
2170 wp->w_valid = 0;
2171 if (wp->w_cursor.lnum >= wp->w_height)
2172 {
2173 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002174
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002175 if (wp->w_topline < min_topline)
2176 wp->w_topline = min_topline;
2177 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002178 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002179 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002180 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002181 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002182}
2183
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002184#if defined(FEAT_TIMERS) || defined(PROTO)
2185/*
2186 * Check if any terminal timer expired. If so, copy text from the terminal to
2187 * the buffer.
2188 * Return the time until the next timer will expire.
2189 */
2190 int
2191term_check_timers(int next_due_arg, proftime_T *now)
2192{
2193 term_T *term;
2194 int next_due = next_due_arg;
2195
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002196 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002197 {
2198 if (term->tl_timer_set && !term->tl_normal_mode)
2199 {
2200 long this_due = proftime_time_left(&term->tl_timer_due, now);
2201
2202 if (this_due <= 1)
2203 {
2204 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002205 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002206 }
2207 else if (next_due == -1 || next_due > this_due)
2208 next_due = this_due;
2209 }
2210 }
2211
2212 return next_due;
2213}
2214#endif
2215
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002216/*
2217 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2218 * otherwise end it.
2219 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002220 static void
2221set_terminal_mode(term_T *term, int normal_mode)
2222{
2223 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002224 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002225 if (!normal_mode)
2226 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002227 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002228 if (term->tl_buffer == curbuf)
2229 maketitle();
2230}
2231
2232/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002233 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002234 * Move the vterm contents into the scrollback buffer and free the vterm.
2235 */
2236 static void
2237cleanup_vterm(term_T *term)
2238{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002239 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002240 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002241 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002242 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002243}
2244
2245/*
2246 * Switch from Terminal-Job mode to Terminal-Normal mode.
2247 * Suspends updating the terminal window.
2248 */
2249 static void
2250term_enter_normal_mode(void)
2251{
2252 term_T *term = curbuf->b_term;
2253
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002254 set_terminal_mode(term, TRUE);
2255
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002256 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002257 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002258
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002259 // Move the window cursor to the position of the cursor in the
2260 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002261 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2262 + term->tl_cursor_pos.row + 1;
2263 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002264 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2265 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002266 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002267
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002268 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002269 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2270}
2271
2272/*
2273 * Returns TRUE if the current window contains a terminal and we are in
2274 * Terminal-Normal mode.
2275 */
2276 int
2277term_in_normal_mode(void)
2278{
2279 term_T *term = curbuf->b_term;
2280
2281 return term != NULL && term->tl_normal_mode;
2282}
2283
2284/*
2285 * Switch from Terminal-Normal mode to Terminal-Job mode.
2286 * Restores updating the terminal window.
2287 */
2288 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002289term_enter_job_mode(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002290{
2291 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002292
2293 set_terminal_mode(term, FALSE);
2294
2295 if (term->tl_channel_closed)
2296 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002297 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002298#ifdef FEAT_PROP_POPUP
2299 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002300 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002301#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002302}
2303
2304/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002305 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2306 * modifiers into a basic key. However, we may only find out after calling
2307 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2308 * "no_reduce_keys" before using it.
2309 */
2310typedef enum {
2311 NRKS_NONE, // initial value
2312 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2313 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2314 // check_no_reduce_keys(), must be decremented.
2315} reduce_key_state_T;
2316
2317static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2318
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002319/*
2320 * Return TRUE if the term is using modifyOtherKeys level 2 or the kitty
2321 * keyboard protocol.
2322 */
2323 static int
2324vterm_using_key_protocol(void)
2325{
2326 return curbuf->b_term != NULL
2327 && curbuf->b_term->tl_vterm != NULL
2328 && (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm)
2329 || vterm_is_kitty_keyboard(curbuf->b_term->tl_vterm));
2330}
2331
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002332 void
2333check_no_reduce_keys(void)
2334{
2335 if (no_reduce_key_state != NRKS_CHECK
2336 || no_reduce_keys >= 1
2337 || curbuf->b_term == NULL
2338 || curbuf->b_term->tl_vterm == NULL)
2339 return;
2340
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002341 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002342 {
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002343 // "modify_other_keys" or kitty keyboard protocol was enabled while
2344 // waiting.
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002345 no_reduce_key_state = NRKS_SET;
2346 ++no_reduce_keys;
2347 }
2348}
2349
2350/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002351 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002352 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002353 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002354 */
2355 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002356term_vgetc(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002357{
2358 int c;
2359 int save_State = State;
2360
Bram Moolenaar24959102022-05-07 20:01:16 +01002361 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002362 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002363#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002364 ctrl_break_was_pressed = FALSE;
2365#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002366
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002367 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002368 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002369 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002370 no_reduce_key_state = NRKS_SET;
2371 }
2372 else
2373 {
2374 no_reduce_key_state = NRKS_CHECK;
2375 }
2376
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002377 c = vgetc();
2378 got_int = FALSE;
2379 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002380
2381 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002382 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002383 no_reduce_key_state = NRKS_NONE;
2384
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002385 return c;
2386}
2387
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002388static int mouse_was_outside = FALSE;
2389
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002390/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002391 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002392 * Return FAIL when the key needs to be handled in Normal mode.
2393 * Return OK when the key was dropped or sent to the terminal.
2394 */
2395 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002396send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002397{
2398 char msg[KEY_BUF_LEN];
2399 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002400 int dragging_outside = FALSE;
2401
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002402 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002403 switch (c)
2404 {
2405 case NUL:
2406 case K_ZERO:
2407 if (typed)
2408 stuffcharReadbuff(c);
2409 return FAIL;
2410
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002411 case K_TABLINE:
2412 stuffcharReadbuff(c);
2413 return FAIL;
2414
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002415 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002416 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002417 return FAIL;
2418
2419 case K_LEFTDRAG:
2420 case K_MIDDLEDRAG:
2421 case K_RIGHTDRAG:
2422 case K_X1DRAG:
2423 case K_X2DRAG:
2424 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002425 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002426 case K_LEFTMOUSE:
2427 case K_LEFTMOUSE_NM:
2428 case K_LEFTRELEASE:
2429 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002430 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002431 case K_MIDDLEMOUSE:
2432 case K_MIDDLERELEASE:
2433 case K_RIGHTMOUSE:
2434 case K_RIGHTRELEASE:
2435 case K_X1MOUSE:
2436 case K_X1RELEASE:
2437 case K_X2MOUSE:
2438 case K_X2RELEASE:
2439
2440 case K_MOUSEUP:
2441 case K_MOUSEDOWN:
2442 case K_MOUSELEFT:
2443 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002444 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002445 int row = mouse_row;
2446 int col = mouse_col;
2447
2448#ifdef FEAT_PROP_POPUP
2449 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002450 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002451 row -= popup_top_extra(curwin);
2452 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002453 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002454#endif
2455 if (row < W_WINROW(curwin)
2456 || row >= (W_WINROW(curwin) + curwin->w_height)
2457 || col < curwin->w_wincol
2458 || col >= W_ENDCOL(curwin)
2459 || dragging_outside)
2460 {
2461 // click or scroll outside the current window or on status
2462 // line or vertical separator
2463 if (typed)
2464 {
2465 stuffcharReadbuff(c);
2466 mouse_was_outside = TRUE;
2467 }
2468 return FAIL;
2469 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002470 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002471 break;
2472
2473 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002474 case K_SCRIPT_COMMAND:
2475 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002476 }
2477 if (typed)
2478 mouse_was_outside = FALSE;
2479
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002480 // Convert the typed key to a sequence of bytes for the job.
2481 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002482 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002483 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002484 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2485 (char_u *)msg, (int)len, NULL);
2486
2487 return OK;
2488}
2489
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002490/*
2491 * Handle CTRL-W "": send register contents to the job.
2492 */
2493 static void
2494term_paste_register(int prev_c UNUSED)
2495{
2496 int c;
2497 list_T *l;
2498 listitem_T *item;
2499 long reglen = 0;
2500 int type;
2501
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002502 if (add_to_showcmd(prev_c))
2503 if (add_to_showcmd('"'))
2504 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002505
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002506 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002507 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002508
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002509 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002510 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002511 return;
2512
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002513 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002514 if (c == '=' && get_expr_register() != '=')
2515 return;
2516 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002517 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002518 return;
2519
2520 l = (list_T *)get_reg_contents(c, GREG_LIST);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002521 if (l == NULL)
2522 return;
2523
2524 type = get_reg_type(c, &reglen);
2525 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002526 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002527 char_u *s = tv_get_string(&item->li_tv);
2528#ifdef MSWIN
2529 char_u *tmp = s;
2530
2531 if (!enc_utf8 && enc_codepage > 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002532 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002533 WCHAR *ret = NULL;
2534 int length = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002535
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002536 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2537 (int)STRLEN(s), &ret, &length);
2538 if (ret != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002540 WideCharToMultiByte_alloc(CP_UTF8, 0,
2541 ret, length, (char **)&s, &length, 0, 0);
2542 vim_free(ret);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002543 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002544 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002545#endif
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002546 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2547 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002548#ifdef MSWIN
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002549 if (tmp != s)
2550 vim_free(s);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002551#endif
2552
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002553 if (item->li_next != NULL || type == MLINE)
2554 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2555 (char_u *)"\r", 1, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002556 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002557 list_free(l);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002558}
2559
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002560/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002561 * Return TRUE when waiting for a character in the terminal, the cursor of the
2562 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002563 */
2564 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002565terminal_is_active(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002566{
2567 return in_terminal_loop != NULL;
2568}
2569
Bram Moolenaar83d47902020-03-26 20:34:00 +01002570/*
dundargocc57b5bc2022-11-02 13:30:51 +00002571 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002572 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002573 static int
2574term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002575{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002576 char_u *name;
2577
2578 if (wp != NULL && *wp->w_p_wcr != NUL)
2579 name = wp->w_p_wcr;
2580 else if (term->tl_highlight_name != NULL)
2581 name = term->tl_highlight_name;
2582 else
2583 name = (char_u*)"Terminal";
2584
2585 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002586}
2587
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002588#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002589 cursorentry_T *
2590term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2591{
2592 term_T *term = in_terminal_loop;
2593 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002594 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002595 guicolor_T term_fg = INVALCOLOR;
2596 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002597
Bram Moolenaara80faa82020-04-12 19:37:17 +02002598 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002599 entry.shape = entry.mshape =
2600 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2601 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2602 SHAPE_BLOCK;
2603 entry.percentage = 20;
2604 if (term->tl_cursor_blink)
2605 {
2606 entry.blinkwait = 700;
2607 entry.blinkon = 400;
2608 entry.blinkoff = 250;
2609 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002610
Bram Moolenaar83d47902020-03-26 20:34:00 +01002611 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002612 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002613 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002614 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002615 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002616 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002617 else
2618 *fg = gui.back_pixel;
2619
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002620 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002621 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002622 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002623 *bg = term_fg;
2624 else
2625 *bg = gui.norm_pixel;
2626 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002627 else
2628 *bg = color_name2handle(term->tl_cursor_color);
2629 entry.name = "n";
2630 entry.used_for = SHAPE_CURSOR;
2631
2632 return &entry;
2633}
2634#endif
2635
Bram Moolenaard317b382018-02-08 22:33:31 +01002636 static void
2637may_output_cursor_props(void)
2638{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002639 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002640 || last_set_cursor_shape != desired_cursor_shape
2641 || last_set_cursor_blink != desired_cursor_blink)
2642 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002643 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002644 last_set_cursor_shape = desired_cursor_shape;
2645 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002646 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002647 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002648 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002649 ui_cursor_shape_forced(TRUE);
2650 else
2651 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2652 }
2653}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002654
Bram Moolenaard317b382018-02-08 22:33:31 +01002655/*
2656 * Set the cursor color and shape, if not last set to these.
2657 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002658 static void
2659may_set_cursor_props(term_T *term)
2660{
2661#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002662 // For the GUI the cursor properties are obtained with
2663 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002664 if (gui.in_use)
2665 return;
2666#endif
2667 if (in_terminal_loop == term)
2668 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002669 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002670 desired_cursor_shape = term->tl_cursor_shape;
2671 desired_cursor_blink = term->tl_cursor_blink;
2672 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002673 }
2674}
2675
Bram Moolenaard317b382018-02-08 22:33:31 +01002676/*
2677 * Reset the desired cursor properties and restore them when needed.
2678 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002679 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002680prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002681{
2682#ifdef FEAT_GUI
2683 if (gui.in_use)
2684 return;
2685#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002686 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002687 desired_cursor_shape = -1;
2688 desired_cursor_blink = -1;
2689 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002690}
2691
2692/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002693 * Returns TRUE if the current window contains a terminal and we are sending
2694 * keys to the job.
2695 * If "check_job_status" is TRUE update the job status.
2696 */
2697 static int
2698term_use_loop_check(int check_job_status)
2699{
2700 term_T *term = curbuf->b_term;
2701
2702 return term != NULL
2703 && !term->tl_normal_mode
2704 && term->tl_vterm != NULL
2705 && term_job_running_check(term, check_job_status);
2706}
2707
2708/*
2709 * Returns TRUE if the current window contains a terminal and we are sending
2710 * keys to the job.
2711 */
2712 int
2713term_use_loop(void)
2714{
2715 return term_use_loop_check(FALSE);
2716}
2717
2718/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002719 * Called when entering a window with the mouse. If this is a terminal window
2720 * we may want to change state.
2721 */
2722 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002723term_win_entered(void)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002724{
2725 term_T *term = curbuf->b_term;
2726
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002727 if (term == NULL)
2728 return;
2729
2730 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002731 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002732 reset_VIsual_and_resel();
2733 if (State & MODE_INSERT)
2734 stop_insert_mode = TRUE;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002735 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002736 mouse_was_outside = FALSE;
2737 enter_mouse_col = mouse_col;
2738 enter_mouse_row = mouse_row;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002739}
2740
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002741 void
2742term_focus_change(int in_focus)
2743{
2744 term_T *term = curbuf->b_term;
2745
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002746 if (term == NULL || term->tl_vterm == NULL)
2747 return;
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002748
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002749 VTermState *state = vterm_obtain_state(term->tl_vterm);
2750
2751 if (in_focus)
2752 vterm_state_focus_in(state);
2753 else
2754 vterm_state_focus_out(state);
2755 term_forward_output(term);
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002756}
2757
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002758/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002759 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2760 * Return the Ctrl-key value in that case.
2761 */
2762 static int
2763raw_c_to_ctrl(int c)
2764{
2765 if ((mod_mask & MOD_MASK_CTRL)
2766 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2767 return c & 0x1f;
2768 return c;
2769}
2770
2771/*
2772 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002773 * Also when the Kitty keyboard protocol is used.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002774 * May set "mod_mask".
2775 */
2776 static int
2777ctrl_to_raw_c(int c)
2778{
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002779 if (c < 0x20 && vterm_using_key_protocol())
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002780 {
2781 mod_mask |= MOD_MASK_CTRL;
2782 return c + '@';
2783 }
2784 return c;
2785}
2786
2787/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002788 * Wait for input and send it to the job.
2789 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2790 * when there is no more typahead.
2791 * Return when the start of a CTRL-W command is typed or anything else that
2792 * should be handled as a Normal mode command.
2793 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2794 * the terminal was closed.
2795 */
2796 int
2797terminal_loop(int blocking)
2798{
2799 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002800 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002801 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002802 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002803#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002804 int tty_fd = curbuf->b_term->tl_job->jv_channel
2805 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002806#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002807 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002808
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002809 // Remember the terminal we are sending keys to. However, the terminal
2810 // might be closed while waiting for a character, e.g. typing "exit" in a
2811 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2812 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002813 in_terminal_loop = curbuf->b_term;
2814
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002815 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002816 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002817 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002818 if (termwinkey == Ctrl_W)
2819 termwinkey = 0;
2820 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002821 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002822 may_set_cursor_props(curbuf->b_term);
2823
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002824 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002825 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002826#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002827 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002828#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002829 // TODO: skip screen update when handling a sequence of keys.
2830 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002831 while (must_redraw != 0)
2832 if (update_screen(0) == FAIL)
2833 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002834 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002835 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002836 break;
2837
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002838 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002839 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002840
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002841 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002842 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002843 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002844 // Job finished while waiting for a character. Push back the
2845 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002846 if (raw_c != K_IGNORE)
2847 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002848 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002849 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002850 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002851 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002852 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002853
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002854#ifdef UNIX
2855 /*
2856 * The shell or another program may change the tty settings. Getting
2857 * them for every typed character is a bit of overhead, but it's needed
2858 * for the first character typed, e.g. when Vim starts in a shell.
2859 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002860 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002861 {
2862 ttyinfo_T info;
2863
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002864 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002865 if (get_tty_info(tty_fd, &info) == OK)
2866 term_backspace_char = info.backspace;
2867 }
2868#endif
2869
Bram Moolenaar4f974752019-02-17 17:44:42 +01002870#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002871 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2872 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002873 if (ctrl_break_was_pressed)
2874 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2875#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002876 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2877 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002878 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002879#ifdef FEAT_GUI
2880 && !curbuf->b_term->tl_system
2881#endif
2882 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002883 {
2884 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002885 int prev_raw_c = raw_c;
2886 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002887
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888 if (add_to_showcmd(c))
2889 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002890
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002891 raw_c = term_vgetc();
2892 c = raw_c_to_ctrl(raw_c);
2893
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002894 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002895
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002896 if (!term_use_loop_check(TRUE)
2897 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002898 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002899 break;
2900
2901 if (prev_c == Ctrl_BSL)
2902 {
2903 if (c == Ctrl_N)
2904 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002905 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002906 term_enter_normal_mode();
2907 ret = FAIL;
2908 goto theend;
2909 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002910 // Send both keys to the terminal, first one here, second one
2911 // below.
2912 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2913 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002914 }
2915 else if (c == Ctrl_C)
2916 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002917 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002918 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2919 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002920 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002921 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002922 // "CTRL-W .": send CTRL-W to the job
2923 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002924 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002926 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002927 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002928 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002929 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002930 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002931 else if (c == 'N')
2932 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002933 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002934 term_enter_normal_mode();
2935 ret = FAIL;
2936 goto theend;
2937 }
2938 else if (c == '"')
2939 {
2940 term_paste_register(prev_c);
2941 continue;
2942 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002943 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002944 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002945 // space for CTRL-W, modifier, multi-byte char and NUL
2946 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002947
2948 // Put the command into the typeahead buffer, when using the
2949 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2950 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002951 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002952 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002953 ret = OK;
2954 goto theend;
2955 }
2956 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002957# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002958 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002959 {
2960 WCHAR wc;
2961 char_u mb[3];
2962
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002963 mb[0] = (unsigned)raw_c >> 8;
2964 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002965 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002966 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002967 }
2968# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002969 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002970 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002971 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002972 // We are sure to come back here, don't reset the cursor color
2973 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002974 restore_cursor = FALSE;
2975
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002976 ret = OK;
2977 goto theend;
2978 }
2979 }
2980 ret = FAIL;
2981
2982theend:
2983 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002984 if (restore_cursor)
2985 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002986
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002987 // Move a snapshot of the screen contents to the buffer, so that completion
2988 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002989 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2990 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002991
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002992 return ret;
2993}
2994
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002995 static void
2996may_toggle_cursor(term_T *term)
2997{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002998 if (in_terminal_loop != term)
2999 return;
3000
3001 if (term->tl_cursor_visible)
3002 cursor_on();
3003 else
3004 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003005}
3006
3007/*
3008 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01003009 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003010 */
3011 static int
3012color2index(VTermColor *color, int fg, int *boldp)
3013{
3014 int red = color->red;
3015 int blue = color->blue;
3016 int green = color->green;
3017
LemonBoyb2b3acb2022-05-20 10:10:34 +01003018 *boldp = FALSE;
3019
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003020 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003021 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01003022
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003023 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003024 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003025 // Use the color as-is if possible, give up otherwise.
3026 if (color->index < t_colors)
3027 return color->index + 1;
3028 // 8-color terminals can actually display twice as many colors by
3029 // setting the high-intensity/bold bit.
3030 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003031 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003032 *boldp = TRUE;
3033 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003034 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01003035 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003036 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01003037
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003038 if (t_colors >= 256)
3039 {
3040 if (red == blue && red == green)
3041 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003042 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003043 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003044 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
3045 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
3046 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003047 int i;
3048
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003049 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003050 return 17; // 00/00/00
3051 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003052 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003053 for (i = 0; i < 23; ++i)
3054 if (red < cutoff[i])
3055 return i + 233;
3056 return 256;
3057 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003058 {
3059 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
3060 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003061
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003062 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003063 for (ri = 0; ri < 5; ++ri)
3064 if (red < cutoff[ri])
3065 break;
3066 for (gi = 0; gi < 5; ++gi)
3067 if (green < cutoff[gi])
3068 break;
3069 for (bi = 0; bi < 5; ++bi)
3070 if (blue < cutoff[bi])
3071 break;
3072 return 17 + ri * 36 + gi * 6 + bi;
3073 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003074 }
3075 return 0;
3076}
3077
3078/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01003079 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003080 */
3081 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003082vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003083{
3084 int attr = 0;
3085
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003086 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003087 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003088 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003089 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003090 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003091 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003092 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003093 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003094 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003096 return attr;
3097}
3098
3099/*
3100 * Store Vterm attributes in "cell" from highlight flags.
3101 */
3102 static void
3103hl2vtermAttr(int attr, cellattr_T *cell)
3104{
Bram Moolenaara80faa82020-04-12 19:37:17 +02003105 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003106 if (attr & HL_BOLD)
3107 cell->attrs.bold = 1;
3108 if (attr & HL_UNDERLINE)
3109 cell->attrs.underline = 1;
3110 if (attr & HL_ITALIC)
3111 cell->attrs.italic = 1;
3112 if (attr & HL_STRIKETHROUGH)
3113 cell->attrs.strike = 1;
3114 if (attr & HL_INVERSE)
3115 cell->attrs.reverse = 1;
3116}
3117
3118/*
3119 * Convert the attributes of a vterm cell into an attribute index.
3120 */
3121 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003122cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003123 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003124 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003125 VTermScreenCellAttrs *cellattrs,
3126 VTermColor *cellfg,
3127 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003128{
3129 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003130 VTermColor *fg = cellfg;
3131 VTermColor *bg = cellbg;
3132 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3133 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3134
3135 if (is_default_fg || is_default_bg)
3136 {
3137 if (wp != NULL && *wp->w_p_wcr != NUL)
3138 {
3139 if (is_default_fg)
3140 fg = &wp->w_term_wincolor.fg;
3141 if (is_default_bg)
3142 bg = &wp->w_term_wincolor.bg;
3143 }
3144 else
3145 {
3146 if (is_default_fg)
3147 fg = &term->tl_default_color.fg;
3148 if (is_default_bg)
3149 bg = &term->tl_default_color.bg;
3150 }
3151 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003152
3153#ifdef FEAT_GUI
3154 if (gui.in_use)
3155 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003156 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3157 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3158 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003159 }
3160 else
3161#endif
3162#ifdef FEAT_TERMGUICOLORS
3163 if (p_tgc)
3164 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003165 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3166 ? INVALCOLOR
3167 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3168 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3169 ? INVALCOLOR
3170 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3171 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003172 }
3173 else
3174#endif
3175 {
3176 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003177 int ctermfg = color2index(fg, TRUE, &bold);
3178 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003179
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003180 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003181 if (bold == TRUE)
3182 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003183
3184 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003185 }
3186 return 0;
3187}
3188
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003189 static void
3190set_dirty_snapshot(term_T *term)
3191{
3192 term->tl_dirty_snapshot = TRUE;
3193#ifdef FEAT_TIMERS
3194 if (!term->tl_normal_mode)
3195 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003196 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003197 profile_setlimit(100L, &term->tl_timer_due);
3198 term->tl_timer_set = TRUE;
3199 }
3200#endif
3201}
3202
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003203 static int
3204handle_damage(VTermRect rect, void *user)
3205{
3206 term_T *term = (term_T *)user;
3207
3208 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3209 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003210 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003211 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003212 return 1;
3213}
3214
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003215 static void
3216term_scroll_up(term_T *term, int start_row, int count)
3217{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003218 win_T *wp = NULL;
3219 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003220 VTermColor fg, bg;
3221 VTermScreenCellAttrs attr;
3222 int clear_attr;
3223
Bram Moolenaara80faa82020-04-12 19:37:17 +02003224 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003225
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003226 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003227 {
3228 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003229 {
3230 // Set the color to clear lines with.
3231 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3232 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003233 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003234 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003235 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003236 }
3237}
3238
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003239 static int
3240handle_moverect(VTermRect dest, VTermRect src, void *user)
3241{
3242 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003243 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003244
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003245 // Scrolling up is done much more efficiently by deleting lines instead of
3246 // redrawing the text. But avoid doing this multiple times, postpone until
3247 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003248 if (dest.start_col == src.start_col
3249 && dest.end_col == src.end_col
3250 && dest.start_row < src.start_row)
3251 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003252 if (dest.start_row == 0)
3253 term->tl_postponed_scroll += count;
3254 else
3255 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003256 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003257
3258 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3259 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003260 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003261
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003262 // Note sure if the scrolling will work correctly, let's do a complete
3263 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003264 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003265 return 1;
3266}
3267
3268 static int
3269handle_movecursor(
3270 VTermPos pos,
3271 VTermPos oldpos UNUSED,
3272 int visible,
3273 void *user)
3274{
3275 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003276 win_T *wp = NULL;
3277 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003278
3279 term->tl_cursor_pos = pos;
3280 term->tl_cursor_visible = visible;
3281
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003282 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003283 {
3284 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003285 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003286 }
3287 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003288 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003289
3290 return 1;
3291}
3292
3293 static int
3294handle_settermprop(
3295 VTermProp prop,
3296 VTermValue *value,
3297 void *user)
3298{
3299 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003300 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003301
3302 switch (prop)
3303 {
3304 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003305 if (disable_vterm_title_for_testing)
3306 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003307 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003308 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003309 if (strval == NULL)
3310 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003311 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003312 // a blank title isn't useful, make it empty, so that "running" is
3313 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003314 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003315 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003316 // Same as blank
3317 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003318 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003319 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3320 term->tl_title = NULL;
3321 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003322 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003323 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003324#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003325 else if (!enc_utf8 && enc_codepage > 0)
3326 {
3327 WCHAR *ret = NULL;
3328 int length = 0;
3329
3330 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003331 (char*)value->string.str,
3332 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003333 if (ret != NULL)
3334 {
3335 WideCharToMultiByte_alloc(enc_codepage, 0,
3336 ret, length, (char**)&term->tl_title,
3337 &length, 0, 0);
3338 vim_free(ret);
3339 }
3340 }
3341#endif
3342 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003343 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003344 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003345 strval = NULL;
3346 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003347 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003348 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003349 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003350 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003351 curwin->w_redr_status = TRUE;
3352 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003353 break;
3354
3355 case VTERM_PROP_CURSORVISIBLE:
3356 term->tl_cursor_visible = value->boolean;
3357 may_toggle_cursor(term);
3358 out_flush();
3359 break;
3360
3361 case VTERM_PROP_CURSORBLINK:
3362 term->tl_cursor_blink = value->boolean;
3363 may_set_cursor_props(term);
3364 break;
3365
3366 case VTERM_PROP_CURSORSHAPE:
3367 term->tl_cursor_shape = value->number;
3368 may_set_cursor_props(term);
3369 break;
3370
3371 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003372 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003373 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003374 if (strval == NULL)
3375 break;
3376 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003377 may_set_cursor_props(term);
3378 break;
3379
3380 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003381 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003382 term->tl_using_altscreen = value->boolean;
3383 break;
3384
3385 default:
3386 break;
3387 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003388 vim_free(strval);
3389
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003390 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003391 return 1;
3392}
3393
3394/*
3395 * The job running in the terminal resized the terminal.
3396 */
3397 static int
3398handle_resize(int rows, int cols, void *user)
3399{
3400 term_T *term = (term_T *)user;
3401 win_T *wp;
3402
3403 term->tl_rows = rows;
3404 term->tl_cols = cols;
3405 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003406 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003407 term->tl_vterm_size_changed = FALSE;
3408 else
3409 {
3410 FOR_ALL_WINDOWS(wp)
3411 {
3412 if (wp->w_buffer == term->tl_buffer)
3413 {
3414 win_setheight_win(rows, wp);
3415 win_setwidth_win(cols, wp);
3416 }
3417 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003418 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003419 }
3420 return 1;
3421}
3422
3423/*
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003424 * If the number of lines that are stored goes over 'termwinscroll' then
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003425 * delete the first 10%.
3426 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3427 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003428 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003429 static void
3430limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003431{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003432 if (gap->ga_len < term->tl_buffer->b_p_twsl)
3433 return;
3434
3435 int todo = term->tl_buffer->b_p_twsl / 10;
3436 int i;
3437
3438 curbuf = term->tl_buffer;
3439 for (i = 0; i < todo; ++i)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003440 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003441 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003442 if (update_buffer)
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003443 ml_delete(1);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003444 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003445 curbuf = curwin->w_buffer;
3446
3447 gap->ga_len -= todo;
3448 mch_memmove(gap->ga_data,
3449 (sb_line_T *)gap->ga_data + todo,
3450 sizeof(sb_line_T) * gap->ga_len);
3451 if (update_buffer)
3452 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003453}
3454
3455/*
3456 * Handle a line that is pushed off the top of the screen.
3457 */
3458 static int
3459handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3460{
3461 term_T *term = (term_T *)user;
3462 garray_T *gap;
3463 int update_buffer;
3464
3465 if (term->tl_normal_mode)
3466 {
3467 // In Terminal-Normal mode the user interacts with the buffer, thus we
3468 // must not change it. Postpone adding the scrollback lines.
3469 gap = &term->tl_scrollback_postponed;
3470 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003471 }
3472 else
3473 {
3474 // First remove the lines that were appended before, the pushed line
3475 // goes above it.
3476 cleanup_scrollback(term);
3477 gap = &term->tl_scrollback;
3478 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003479 }
3480
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003481 limit_scrollback(term, gap, update_buffer);
3482
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003483 if (ga_grow(gap, 1) == FAIL)
3484 return 0;
3485
3486 cellattr_T *p = NULL;
3487 int len = 0;
3488 int i;
3489 int c;
3490 int col;
3491 int text_len;
3492 char_u *text;
3493 sb_line_T *line;
3494 garray_T ga;
3495 cellattr_T fill_attr = term->tl_default_color;
3496
3497 // do not store empty cells at the end
3498 for (i = 0; i < cols; ++i)
3499 if (cells[i].chars[0] != 0)
3500 len = i + 1;
3501 else
3502 cell2cellattr(&cells[i], &fill_attr);
3503
3504 ga_init2(&ga, 1, 100);
3505 if (len > 0)
3506 p = ALLOC_MULT(cellattr_T, len);
3507 if (p != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003508 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003509 for (col = 0; col < len; col += cells[col].width)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003510 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003511 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003512 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003513 ga.ga_len = 0;
3514 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003515 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003516 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3517 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3518 (char_u *)ga.ga_data + ga.ga_len);
3519 cell2cellattr(&cells[col], &p[col]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003520 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003521 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003522 if (ga_grow(&ga, 1) == FAIL)
3523 {
3524 if (update_buffer)
3525 text = (char_u *)"";
3526 else
3527 text = vim_strsave((char_u *)"");
3528 text_len = 0;
3529 }
3530 else
3531 {
3532 text = ga.ga_data;
3533 text_len = ga.ga_len;
3534 *(text + text_len) = NUL;
3535 }
3536 if (update_buffer)
3537 add_scrollback_line_to_buffer(term, text, text_len);
3538
3539 line = (sb_line_T *)gap->ga_data + gap->ga_len;
3540 line->sb_cols = len;
3541 line->sb_cells = p;
3542 line->sb_fill_attr = fill_attr;
3543 if (update_buffer)
3544 {
3545 line->sb_text = NULL;
3546 ++term->tl_scrollback_scrolled;
3547 ga_clear(&ga); // free the text
3548 }
3549 else
3550 {
3551 line->sb_text = text;
3552 ga_init(&ga); // text is kept in tl_scrollback_postponed
3553 }
3554 ++gap->ga_len;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003555 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003556}
3557
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003558/*
3559 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3560 * received and stored in tl_scrollback_postponed.
3561 */
3562 static void
3563handle_postponed_scrollback(term_T *term)
3564{
3565 int i;
3566
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003567 if (term->tl_scrollback_postponed.ga_len == 0)
3568 return;
3569 ch_log(NULL, "Moving postponed scrollback to scrollback");
3570
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003571 // First remove the lines that were appended before, the pushed lines go
3572 // above it.
3573 cleanup_scrollback(term);
3574
3575 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3576 {
3577 char_u *text;
3578 sb_line_T *pp_line;
3579 sb_line_T *line;
3580
3581 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3582 break;
3583 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3584
3585 text = pp_line->sb_text;
3586 if (text == NULL)
3587 text = (char_u *)"";
3588 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3589 vim_free(pp_line->sb_text);
3590
3591 line = (sb_line_T *)term->tl_scrollback.ga_data
3592 + term->tl_scrollback.ga_len;
3593 line->sb_cols = pp_line->sb_cols;
3594 line->sb_cells = pp_line->sb_cells;
3595 line->sb_fill_attr = pp_line->sb_fill_attr;
3596 line->sb_text = NULL;
3597 ++term->tl_scrollback_scrolled;
3598 ++term->tl_scrollback.ga_len;
3599 }
3600
3601 ga_clear(&term->tl_scrollback_postponed);
3602 limit_scrollback(term, &term->tl_scrollback, TRUE);
3603}
3604
LemonBoy77771d32022-04-13 11:47:25 +01003605/*
3606 * Called when the terminal wants to ring the system bell.
3607 */
3608 static int
3609handle_bell(void *user UNUSED)
3610{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003611 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003612 return 0;
3613}
3614
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003615static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003616 handle_damage, // damage
3617 handle_moverect, // moverect
3618 handle_movecursor, // movecursor
3619 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003620 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003621 handle_resize, // resize
3622 handle_pushline, // sb_pushline
Bram Moolenaar6a12d262022-10-16 19:26:52 +01003623 NULL, // sb_popline
3624 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003625};
3626
3627/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003628 * Do the work after the channel of a terminal was closed.
3629 * Must be called only when updating_screen is FALSE.
3630 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3631 */
3632 static int
3633term_after_channel_closed(term_T *term)
3634{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003635 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003636 if (!term->tl_normal_mode)
3637 {
3638 int fnum = term->tl_buffer->b_fnum;
3639
3640 cleanup_vterm(term);
3641
3642 if (term->tl_finish == TL_FINISH_CLOSE)
3643 {
3644 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003645 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003646#ifdef FEAT_PROP_POPUP
3647 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003648
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003649 // If this was a terminal in a popup window, go back to the
3650 // previous window.
3651 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3652 {
3653 pwin = curwin;
3654 if (win_valid(prevwin))
3655 win_enter(prevwin, FALSE);
3656 }
3657 else
3658#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003659 // If this is the last normal window: exit Vim.
3660 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3661 {
3662 exarg_T ea;
3663
Bram Moolenaara80faa82020-04-12 19:37:17 +02003664 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003665 ex_quit(&ea);
3666 return TRUE;
3667 }
3668
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003669 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003670 ch_log(NULL, "terminal job finished, closing window");
3671 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaare76062c2022-11-28 18:51:43 +00003672 if (curbuf == term->tl_buffer)
3673 {
3674 // Avoid closing the window if we temporarily use it.
3675 if (is_aucmd_win(curwin))
3676 do_set_w_closing = TRUE;
3677 if (do_set_w_closing)
3678 curwin->w_closing = TRUE;
3679 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
3680 if (do_set_w_closing)
3681 curwin->w_closing = FALSE;
3682 aucmd_restbuf(&aco);
3683 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003684#ifdef FEAT_PROP_POPUP
3685 if (pwin != NULL)
3686 popup_close_with_retval(pwin, 0);
3687#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003688 return TRUE;
3689 }
3690 if (term->tl_finish == TL_FINISH_OPEN
3691 && term->tl_buffer->b_nwindows == 0)
3692 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003693 char *cmd = term->tl_opencmd == NULL
3694 ? "botright sbuf %d"
3695 : (char *)term->tl_opencmd;
3696 size_t len = strlen(cmd) + 50;
3697 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003698
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003699 if (buf != NULL)
3700 {
3701 ch_log(NULL, "terminal job finished, opening window");
3702 vim_snprintf(buf, len, cmd, fnum);
3703 do_cmdline_cmd((char_u *)buf);
3704 vim_free(buf);
3705 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003706 }
3707 else
3708 ch_log(NULL, "terminal job finished");
3709 }
3710
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003711 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003712 return FALSE;
3713}
3714
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003715#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3716/*
3717 * If the current window is a terminal in a popup window and the job has
3718 * finished, close the popup window and to back to the previous window.
3719 * Otherwise return FAIL.
3720 */
3721 int
3722may_close_term_popup(void)
3723{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003724 if (!popup_is_popup(curwin) || curbuf->b_term == NULL
3725 || term_job_running_not_none(curbuf->b_term))
3726 return FAIL;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003727
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003728 win_T *pwin = curwin;
3729
3730 if (win_valid(prevwin))
3731 win_enter(prevwin, FALSE);
3732 popup_close_with_retval(pwin, 0);
3733 return OK;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003734}
3735#endif
3736
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003737/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003738 * Called when a channel is going to be closed, before invoking the close
3739 * callback.
3740 */
3741 void
3742term_channel_closing(channel_T *ch)
3743{
3744 term_T *term;
3745
3746 for (term = first_term; term != NULL; term = term->tl_next)
3747 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3748 term->tl_channel_closing = TRUE;
3749}
3750
3751/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003752 * Called when a channel has been closed.
3753 * If this was a channel for a terminal window then finish it up.
3754 */
3755 void
3756term_channel_closed(channel_T *ch)
3757{
3758 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003759 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003760 int did_one = FALSE;
3761
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003762 for (term = first_term; term != NULL; term = next_term)
3763 {
3764 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003765 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003766 {
3767 term->tl_channel_closed = TRUE;
3768 did_one = TRUE;
3769
Bram Moolenaard23a8232018-02-10 18:45:26 +01003770 VIM_CLEAR(term->tl_title);
3771 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003772#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003773 if (term->tl_out_fd != NULL)
3774 {
3775 fclose(term->tl_out_fd);
3776 term->tl_out_fd = NULL;
3777 }
3778#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003779
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003780 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003781 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003782 // Cannot open or close windows now. Can happen when
3783 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003784 term->tl_channel_recently_closed = TRUE;
3785 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003786 }
3787
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003788 if (term_after_channel_closed(term))
3789 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003790 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003791 }
3792
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003793 if (did_one)
3794 {
3795 redraw_statuslines();
3796
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003797 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003798 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003799 typebuf_was_filled = TRUE;
3800
3801 term = curbuf->b_term;
3802 if (term != NULL)
3803 {
3804 if (term->tl_job == ch->ch_job)
3805 maketitle();
3806 update_cursor(term, term->tl_cursor_visible);
3807 }
3808 }
3809}
3810
3811/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003812 * To be called after resetting updating_screen: handle any terminal where the
3813 * channel was closed.
3814 */
3815 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003816term_check_channel_closed_recently(void)
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003817{
3818 term_T *term;
3819 term_T *next_term;
3820
3821 for (term = first_term; term != NULL; term = next_term)
3822 {
3823 next_term = term->tl_next;
3824 if (term->tl_channel_recently_closed)
3825 {
3826 term->tl_channel_recently_closed = FALSE;
3827 if (term_after_channel_closed(term))
3828 // start over, the list may have changed
3829 next_term = first_term;
3830 }
3831 }
3832}
3833
3834/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003835 * Fill one screen line from a line of the terminal.
3836 * Advances "pos" to past the last column.
3837 */
3838 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003839term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003840 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003841 win_T *wp,
3842 VTermScreen *screen,
3843 VTermPos *pos,
3844 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003845{
3846 int off = screen_get_current_line_off();
3847
3848 for (pos->col = 0; pos->col < max_col; )
3849 {
3850 VTermScreenCell cell;
3851 int c;
3852
3853 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003854 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003855
3856 c = cell.chars[0];
3857 if (c == NUL)
3858 {
3859 ScreenLines[off] = ' ';
3860 if (enc_utf8)
3861 ScreenLinesUC[off] = NUL;
3862 }
3863 else
3864 {
3865 if (enc_utf8)
3866 {
3867 int i;
3868
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003869 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003870 for (i = 0; i < Screen_mco
3871 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3872 {
3873 ScreenLinesC[i][off] = cell.chars[i + 1];
3874 if (cell.chars[i + 1] == 0)
3875 break;
3876 }
3877 if (c >= 0x80 || (Screen_mco > 0
3878 && ScreenLinesC[0][off] != 0))
3879 {
3880 ScreenLines[off] = ' ';
3881 ScreenLinesUC[off] = c;
3882 }
3883 else
3884 {
3885 ScreenLines[off] = c;
3886 ScreenLinesUC[off] = NUL;
3887 }
3888 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003889#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003890 else if (has_mbyte && c >= 0x80)
3891 {
3892 char_u mb[MB_MAXBYTES+1];
3893 WCHAR wc = c;
3894
3895 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3896 (char*)mb, 2, 0, 0) > 1)
3897 {
3898 ScreenLines[off] = mb[0];
3899 ScreenLines[off + 1] = mb[1];
3900 cell.width = mb_ptr2cells(mb);
3901 }
3902 else
3903 ScreenLines[off] = c;
3904 }
3905#endif
3906 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003907 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003908 ScreenLines[off] = c;
3909 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003910 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3911 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003912
3913 ++pos->col;
3914 ++off;
3915 if (cell.width == 2)
3916 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003917 // don't set the second byte to NUL for a DBCS encoding, it
3918 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003919 if (enc_utf8)
3920 {
3921 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003922 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003923 }
3924 else if (!has_mbyte)
3925 {
3926 // Can't show a double-width character with a single-byte
3927 // 'encoding', just use a space.
3928 ScreenLines[off] = ' ';
3929 ScreenAttrs[off] = ScreenAttrs[off - 1];
3930 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003931
3932 ++pos->col;
3933 ++off;
3934 }
3935 }
3936}
3937
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003938#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003939 static void
3940update_system_term(term_T *term)
3941{
3942 VTermPos pos;
3943 VTermScreen *screen;
3944
3945 if (term->tl_vterm == NULL)
3946 return;
3947 screen = vterm_obtain_screen(term->tl_vterm);
3948
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003949 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003950 while (term->tl_toprow > 0
3951 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3952 {
3953 int save_p_more = p_more;
3954
3955 p_more = FALSE;
3956 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003957 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003958 p_more = save_p_more;
3959 --term->tl_toprow;
3960 }
3961
3962 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3963 && pos.row < Rows; ++pos.row)
3964 {
3965 if (pos.row < term->tl_rows)
3966 {
3967 int max_col = MIN(Columns, term->tl_cols);
3968
Bram Moolenaar83d47902020-03-26 20:34:00 +01003969 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003970 }
3971 else
3972 pos.col = 0;
3973
zeertzjqd0c1b772024-03-16 15:03:33 +01003974 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, -1,
3975 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003976 }
3977
3978 term->tl_dirty_row_start = MAX_ROW;
3979 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003980}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003981#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003982
3983/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003984 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3985 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003986 * Terminal-Normal mode.
3987 */
3988 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003989term_do_update_window(win_T *wp)
3990{
3991 term_T *term = wp->w_buffer->b_term;
3992
3993 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3994}
3995
3996/*
3997 * Called to update a window that contains an active terminal.
3998 */
3999 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004000term_update_window(win_T *wp)
4001{
4002 term_T *term = wp->w_buffer->b_term;
4003 VTerm *vterm;
4004 VTermScreen *screen;
4005 VTermState *state;
4006 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004007 int rows, cols;
4008 int newrows, newcols;
4009 int minsize;
4010 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004011
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004012 vterm = term->tl_vterm;
4013 screen = vterm_obtain_screen(vterm);
4014 state = vterm_obtain_state(vterm);
4015
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004016 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
4017 // With UPD_SOME_VALID only redraw what was marked dirty.
4018 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004019 {
4020 term->tl_dirty_row_start = 0;
4021 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004022
4023 if (term->tl_postponed_scroll > 0
4024 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004025 // Scrolling is usually faster than redrawing, when there are only
4026 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004027 term_scroll_up(term, 0, term->tl_postponed_scroll);
4028 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004029 }
4030
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004031 /*
4032 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004033 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004034 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004035 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004036
Bram Moolenaar498c2562018-04-15 23:45:15 +02004037 newrows = 99999;
4038 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004039 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02004040 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004041 // Always use curwin, it may be a popup window.
4042 win_T *wwp = twp == NULL ? curwin : twp;
4043
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004044 // When more than one window shows the same terminal, use the
4045 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004046 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004047 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004048 newrows = MIN(newrows, wwp->w_height);
4049 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004050 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004051 if (twp == NULL)
4052 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004053 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02004054 if (newrows == 99999 || newcols == 99999)
4055 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02004056 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
4057 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
4058
Bram Moolenaareba13e42021-02-23 17:47:23 +01004059 // If no cell is visible there is no point in resizing. Also, vterm can't
4060 // handle a zero height.
4061 if (newrows == 0 || newcols == 0)
4062 return;
4063
Bram Moolenaar498c2562018-04-15 23:45:15 +02004064 if (term->tl_rows != newrows || term->tl_cols != newcols)
4065 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004066 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004067 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004068 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02004069 newrows);
4070 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02004071
4072 // Updating the terminal size will cause the snapshot to be cleared.
4073 // When not in terminal_loop() we need to restore it.
4074 if (term != in_terminal_loop)
4075 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004076 }
4077
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004078 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004079 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01004080 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004081
Bram Moolenaar3a497e12017-09-30 20:40:27 +02004082 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
4083 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004084 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004085 if (pos.row < term->tl_rows)
4086 {
Bram Moolenaar13568252018-03-16 20:46:58 +01004087 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004088
Bram Moolenaar83d47902020-03-26 20:34:00 +01004089 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004090 }
4091 else
4092 pos.col = 0;
4093
Bram Moolenaar510f0372022-07-04 17:46:22 +01004094 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01004095#ifdef FEAT_MENU
4096 + winbar_height(wp)
4097#endif
zeertzjqd0c1b772024-03-16 15:03:33 +01004098 , wp->w_wincol, pos.col, wp->w_width, -1,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004099#ifdef FEAT_PROP_POPUP
4100 popup_is_popup(wp) ? SLF_POPUP :
4101#endif
4102 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004103 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00004104}
4105
4106/*
4107 * Called after updating all windows: may reset dirty rows.
4108 */
4109 void
4110term_did_update_window(win_T *wp)
4111{
4112 term_T *term = wp->w_buffer->b_term;
4113
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004114 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode
4115 || wp->w_redr_type != 0)
4116 return;
4117
4118 term->tl_dirty_row_start = MAX_ROW;
4119 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004120}
4121
4122/*
4123 * Return TRUE if "wp" is a terminal window where the job has finished.
4124 */
4125 int
4126term_is_finished(buf_T *buf)
4127{
4128 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
4129}
4130
4131/*
4132 * Return TRUE if "wp" is a terminal window where the job has finished or we
4133 * are in Terminal-Normal mode, thus we show the buffer contents.
4134 */
4135 int
4136term_show_buffer(buf_T *buf)
4137{
4138 term_T *term = buf->b_term;
4139
4140 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4141}
4142
4143/*
4144 * The current buffer is going to be changed. If there is terminal
4145 * highlighting remove it now.
4146 */
4147 void
4148term_change_in_curbuf(void)
4149{
4150 term_T *term = curbuf->b_term;
4151
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004152 if (!term_is_finished(curbuf) || term->tl_scrollback.ga_len <= 0)
4153 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004154
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004155 free_scrollback(term);
4156 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
4157
4158 // The buffer is now like a normal buffer, it cannot be easily
4159 // abandoned when changed.
4160 set_string_option_direct((char_u *)"buftype", -1,
4161 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004162}
4163
4164/*
4165 * Get the screen attribute for a position in the buffer.
4166 * Use a negative "col" to get the filler background color.
4167 */
4168 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004169term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004170{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004171 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004172 term_T *term = buf->b_term;
4173 sb_line_T *line;
4174 cellattr_T *cellattr;
4175
4176 if (lnum > term->tl_scrollback.ga_len)
4177 cellattr = &term->tl_default_color;
4178 else
4179 {
4180 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4181 if (col < 0 || col >= line->sb_cols)
4182 cellattr = &line->sb_fill_attr;
4183 else
4184 cellattr = line->sb_cells + col;
4185 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004186 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004187}
4188
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004189/*
4190 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004191 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004192 */
4193 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004194cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004195{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004196 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4197 if (rgb->index == 0)
4198 rgb->type = VTERM_COLOR_RGB;
4199 else
4200 {
4201 rgb->type = VTERM_COLOR_INDEXED;
4202 --rgb->index;
4203 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004204}
4205
4206/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004207 * Initialize vterm color from the synID.
4208 * Returns TRUE if color is set to "fg" and "bg".
4209 * Otherwise returns FALSE.
4210 */
4211 static int
4212get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4213{
4214#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4215 // Use the actual color for the GUI and when 'termguicolors' is set.
4216 if (0
4217# ifdef FEAT_GUI
4218 || gui.in_use
4219# endif
4220# ifdef FEAT_TERMGUICOLORS
4221 || p_tgc
4222# ifdef FEAT_VTP
4223 // Finally get INVALCOLOR on this execution path
4224 || (!p_tgc && t_colors >= 256)
4225# endif
4226# endif
4227 )
4228 {
4229 guicolor_T fg_rgb = INVALCOLOR;
4230 guicolor_T bg_rgb = INVALCOLOR;
4231
4232 if (id > 0)
4233 syn_id2colors(id, &fg_rgb, &bg_rgb);
4234
4235 if (fg_rgb != INVALCOLOR)
4236 {
4237 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4238 fg->red = (unsigned)(rgb >> 16);
4239 fg->green = (unsigned)(rgb >> 8) & 255;
4240 fg->blue = (unsigned)rgb & 255;
4241 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4242 }
4243 else
4244 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4245
4246 if (bg_rgb != INVALCOLOR)
4247 {
4248 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4249 bg->red = (unsigned)(rgb >> 16);
4250 bg->green = (unsigned)(rgb >> 8) & 255;
4251 bg->blue = (unsigned)rgb & 255;
4252 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4253 }
4254 else
4255 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4256
4257 return TRUE;
4258 }
4259 else
4260#endif
4261 if (t_colors >= 16)
4262 {
4263 int cterm_fg = -1;
4264 int cterm_bg = -1;
4265
4266 if (id > 0)
4267 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4268
4269 if (cterm_fg >= 0)
4270 {
4271 cterm_color2vterm(cterm_fg, fg);
4272 fg->type |= VTERM_COLOR_DEFAULT_FG;
4273 }
4274 else
4275 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4276
4277 if (cterm_bg >= 0)
4278 {
4279 cterm_color2vterm(cterm_bg, bg);
4280 bg->type |= VTERM_COLOR_DEFAULT_BG;
4281 }
4282 else
4283 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4284
4285 return TRUE;
4286 }
4287
4288 return FALSE;
4289}
4290
4291 void
4292term_reset_wincolor(win_T *wp)
4293{
4294 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4295 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4296}
4297
4298/*
4299 * Cache the color of 'wincolor'.
4300 */
4301 void
4302term_update_wincolor(win_T *wp)
4303{
4304 int id = 0;
4305
4306 if (*wp->w_p_wcr != NUL)
4307 id = syn_name2id(wp->w_p_wcr);
4308 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4309 &wp->w_term_wincolor.bg))
4310 term_reset_wincolor(wp);
4311}
4312
4313/*
4314 * Called when option 'termguicolors' was set,
4315 * or when any highlight is changed.
4316 */
4317 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004318term_update_wincolor_all(void)
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004319{
4320 win_T *wp = NULL;
4321 int did_curwin = FALSE;
4322
4323 while (for_all_windows_and_curwin(&wp, &did_curwin))
4324 term_update_wincolor(wp);
4325}
4326
4327/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004328 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004329 */
4330 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004331init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004332{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004333 VTermColor *fg, *bg;
4334 int fgval, bgval;
4335 int id;
4336
Bram Moolenaara80faa82020-04-12 19:37:17 +02004337 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004338 term->tl_default_color.width = 1;
4339 fg = &term->tl_default_color.fg;
4340 bg = &term->tl_default_color.bg;
4341
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004342 // Vterm uses a default black background. Set it to white when
4343 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004344 if (*p_bg == 'l')
4345 {
4346 fgval = 0;
4347 bgval = 255;
4348 }
4349 else
4350 {
4351 fgval = 255;
4352 bgval = 0;
4353 }
4354 fg->red = fg->green = fg->blue = fgval;
4355 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004356 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4357 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004358
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004359 // The highlight group overrules the defaults.
4360 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004361
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004362 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004363 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004364#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004365 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004366#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004367
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004368 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004369 if (cterm_normal_fg_color > 0)
4370 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004371 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004372# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4373# ifdef VIMDLL
4374 if (!gui.in_use)
4375# endif
4376 {
4377 tmp = fg->red;
4378 fg->red = fg->blue;
4379 fg->blue = tmp;
4380 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004381# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004382 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004383# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004384 else
4385 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004386# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004387
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004388 if (cterm_normal_bg_color > 0)
4389 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004390 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004391# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4392# ifdef VIMDLL
4393 if (!gui.in_use)
4394# endif
4395 {
4396 tmp = fg->red;
4397 fg->red = fg->blue;
4398 fg->blue = tmp;
4399 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004400# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004401 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004402# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004403 else
4404 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004405# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004406 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004407}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004408
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004409#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4410/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004411 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4412 * "ansi_colors" argument in term_start()) shall be applied.
4413 */
4414 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004415term_use_palette(void)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004416{
4417 if (0
4418#ifdef FEAT_GUI
4419 || gui.in_use
4420#endif
4421#ifdef FEAT_TERMGUICOLORS
4422 || p_tgc
4423#endif
4424 )
4425 return TRUE;
4426 return FALSE;
4427}
4428
4429/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004430 * Set the 16 ANSI colors from array of RGB values
4431 */
4432 static void
4433set_vterm_palette(VTerm *vterm, long_u *rgb)
4434{
4435 int index = 0;
4436 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004437
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004438 for (; index < 16; index++)
4439 {
4440 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004441
Millyb771b6b2021-11-23 12:07:25 +00004442 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004443 color.red = (unsigned)(rgb[index] >> 16);
4444 color.green = (unsigned)(rgb[index] >> 8) & 255;
4445 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004446 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004447 vterm_state_set_palette_color(state, index, &color);
4448 }
4449}
4450
4451/*
4452 * Set the ANSI color palette from a list of colors
4453 */
4454 static int
4455set_ansi_colors_list(VTerm *vterm, list_T *list)
4456{
4457 int n = 0;
4458 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004459 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004460
Bram Moolenaarb0992022020-01-30 14:55:42 +01004461 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004462 {
4463 char_u *color_name;
4464 guicolor_T guicolor;
4465
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004466 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004467 if (color_name == NULL)
4468 return FAIL;
4469
4470 guicolor = GUI_GET_COLOR(color_name);
4471 if (guicolor == INVALCOLOR)
4472 return FAIL;
4473
4474 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4475 }
4476
4477 if (n != 16 || li != NULL)
4478 return FAIL;
4479
4480 set_vterm_palette(vterm, rgb);
4481
4482 return OK;
4483}
4484
4485/*
4486 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4487 */
4488 static void
4489init_vterm_ansi_colors(VTerm *vterm)
4490{
4491 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4492
LemonBoyb2b3acb2022-05-20 10:10:34 +01004493 if (var == NULL)
4494 return;
4495
4496 if (var->di_tv.v_type != VAR_LIST
4497 || var->di_tv.vval.v_list == NULL
4498 || var->di_tv.vval.v_list->lv_first == &range_list_item
4499 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004500 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004501}
4502#endif
4503
Bram Moolenaar52acb112018-03-18 19:20:22 +01004504/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004505 * Handles a "drop" command from the job in the terminal.
4506 * "item" is the file name, "item->li_next" may have options.
4507 */
4508 static void
4509handle_drop_command(listitem_T *item)
4510{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004511 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004512 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004513 int bufnr;
4514 win_T *wp;
4515 tabpage_T *tp;
4516 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004517 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004518
4519 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4520 FOR_ALL_TAB_WINDOWS(tp, wp)
4521 {
4522 if (wp->w_buffer->b_fnum == bufnr)
4523 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004524 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004525 goto_tabpage_win(tp, wp);
4526 return;
4527 }
4528 }
4529
Bram Moolenaara80faa82020-04-12 19:37:17 +02004530 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004531
4532 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4533 && opt_item->li_tv.vval.v_dict != NULL)
4534 {
4535 dict_T *dict = opt_item->li_tv.vval.v_dict;
4536 char_u *p;
4537
Bram Moolenaard61efa52022-07-23 09:52:04 +01004538 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004539 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004540 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004541 if (p != NULL)
4542 {
4543 if (check_ff_value(p) == FAIL)
4544 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4545 else
4546 ea.force_ff = *p;
4547 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004548 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004549 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004550 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004551 if (p != NULL)
4552 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004553 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004554 if (ea.cmd != NULL)
4555 {
4556 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4557 ea.force_enc = 11;
4558 tofree = ea.cmd;
4559 }
4560 }
4561
Bram Moolenaard61efa52022-07-23 09:52:04 +01004562 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004563 if (p != NULL)
4564 get_bad_opt(p, &ea);
4565
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004566 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004567 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004568 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004569 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004570 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004571 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004572 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004573 ea.force_bin = FORCE_NOBIN;
4574 }
4575
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004576 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004577 if (ea.cmd == NULL)
4578 ea.cmd = (char_u *)"split";
4579 ea.arg = fname;
4580 ea.cmdidx = CMD_split;
4581 ex_splitview(&ea);
4582
4583 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004584}
4585
4586/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004587 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4588 */
4589 static int
4590is_permitted_term_api(char_u *func, char_u *pat)
4591{
4592 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4593}
4594
4595/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004596 * Handles a function call from the job running in a terminal.
4597 * "item" is the function name, "item->li_next" has the arguments.
4598 */
4599 static void
4600handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4601{
4602 char_u *func;
4603 typval_T argvars[2];
4604 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004605 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004606
4607 if (item->li_next == NULL)
4608 {
4609 ch_log(channel, "Missing function arguments for call");
4610 return;
4611 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004612 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004613
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004614 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004615 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004616 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004617 return;
4618 }
4619
4620 argvars[0].v_type = VAR_NUMBER;
4621 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4622 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004623 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004624 funcexe.fe_firstline = 1L;
4625 funcexe.fe_lastline = 1L;
4626 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004627 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004628 {
4629 clear_tv(&rettv);
4630 ch_log(channel, "Function %s called", func);
4631 }
4632 else
4633 ch_log(channel, "Calling function %s failed", func);
4634}
4635
4636/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004637 * URL decoding (also know as Percent-encoding).
4638 *
4639 * Note this function currently is only used for decoding shell's
4640 * OSC 7 escape sequence which we can assume all bytes are valid
4641 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4642 * encoding bytes like 0xfe, 0xff.
4643 */
4644 static size_t
4645url_decode(const char *src, const size_t len, char_u *dst)
4646{
4647 size_t i = 0, j = 0;
4648
4649 while (i < len)
4650 {
4651 if (src[i] == '%' && i + 2 < len)
4652 {
4653 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4654 j++;
4655 i += 3;
4656 }
4657 else
4658 {
4659 dst[j] = src[i];
4660 i++;
4661 j++;
4662 }
4663 }
4664 dst[j] = '\0';
4665 return j;
4666}
4667
4668/*
4669 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4670 *
4671 * The OSC 7 sequence has the format of
4672 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4673 * and what VTerm provides via VTermStringFragment is
4674 * "file://HOSTNAME/CURRENT/DIR"
4675 */
4676 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004677sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004678{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004679 int offset = 7; // len of "file://" is 7
4680 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004681 char_u *new_dir;
4682
4683 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004684 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004685 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004686 ++offset;
4687 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004688 }
4689
Bram Moolenaar474ad392022-08-21 11:37:17 +01004690 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004691 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004692 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004693 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004694 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004695 }
4696
Bram Moolenaar474ad392022-08-21 11:37:17 +01004697 new_dir = alloc(gap->ga_len - offset + 1);
4698 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004699 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4700 vim_free(new_dir);
4701}
4702
4703/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004704 * Called by libvterm when it cannot recognize an OSC sequence.
4705 * We recognize a terminal API command.
4706 */
4707 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004708parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004709{
4710 term_T *term = (term_T *)user;
4711 js_read_T reader;
4712 typval_T tv;
4713 channel_T *channel = term->tl_job == NULL ? NULL
4714 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004715 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004716
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004717 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004718 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004719 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004720
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004721 // Concatenate what was received until the final piece is found.
4722 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4723 {
4724 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004725 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004726 }
4727 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004728 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004729 if (!frag.final)
4730 return 1;
4731
4732 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004733
4734 if (command == 7)
4735 {
4736 sync_shell_dir(gap);
4737 ga_clear(gap);
4738 return 1;
4739 }
4740
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004741 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004742 reader.js_fill = NULL;
4743 reader.js_used = 0;
4744 if (json_decode(&reader, &tv, 0) == OK
4745 && tv.v_type == VAR_LIST
4746 && tv.vval.v_list != NULL)
4747 {
4748 listitem_T *item = tv.vval.v_list->lv_first;
4749
4750 if (item == NULL)
4751 ch_log(channel, "Missing command");
4752 else
4753 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004754 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004755
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004756 // Make sure an invoked command doesn't delete the buffer (and the
4757 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004758 ++term->tl_buffer->b_locked;
4759
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004760 item = item->li_next;
4761 if (item == NULL)
4762 ch_log(channel, "Missing argument for %s", cmd);
4763 else if (STRCMP(cmd, "drop") == 0)
4764 handle_drop_command(item);
4765 else if (STRCMP(cmd, "call") == 0)
4766 handle_call_command(term, channel, item);
4767 else
4768 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004769 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004770 }
4771 }
4772 else
4773 ch_log(channel, "Invalid JSON received");
4774
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004775 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004776 clear_tv(&tv);
4777 return 1;
4778}
4779
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004780/*
4781 * Called by libvterm when it cannot recognize a CSI sequence.
4782 * We recognize the window position report.
4783 */
4784 static int
4785parse_csi(
4786 const char *leader UNUSED,
4787 const long args[],
4788 int argcount,
4789 const char *intermed UNUSED,
4790 char command,
4791 void *user)
4792{
4793 term_T *term = (term_T *)user;
4794 char buf[100];
4795 int len;
4796 int x = 0;
4797 int y = 0;
4798 win_T *wp;
4799
4800 // We recognize only CSI 13 t
4801 if (command != 't' || argcount != 1 || args[0] != 13)
4802 return 0; // not handled
4803
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004804 // When getting the window position is not possible or it fails it results
4805 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004806#if defined(FEAT_GUI) \
4807 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4808 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004809 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004810#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004811
4812 FOR_ALL_WINDOWS(wp)
4813 if (wp->w_buffer == term->tl_buffer)
4814 break;
4815 if (wp != NULL)
4816 {
4817#ifdef FEAT_GUI
4818 if (gui.in_use)
4819 {
4820 x += wp->w_wincol * gui.char_width;
4821 y += W_WINROW(wp) * gui.char_height;
4822 }
4823 else
4824#endif
4825 {
4826 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004827 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004828 x += wp->w_wincol * 7;
4829 y += W_WINROW(wp) * 10;
4830 }
4831 }
4832
4833 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4834 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4835 (char_u *)buf, len, NULL);
4836 return 1;
4837}
4838
Bram Moolenaard8637282020-05-20 18:41:41 +02004839static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004840 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004841 parse_csi, // csi
4842 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004843 NULL, // dcs
4844 NULL, // apc
4845 NULL, // pm
4846 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004847};
4848
4849/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004850 * Use Vim's allocation functions for vterm so profiling works.
4851 */
4852 static void *
4853vterm_malloc(size_t size, void *data UNUSED)
4854{
Bram Moolenaar88137392021-11-12 16:01:15 +00004855 // make sure that the length is not zero
4856 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004857}
4858
4859 static void
4860vterm_memfree(void *ptr, void *data UNUSED)
4861{
4862 vim_free(ptr);
4863}
4864
4865static VTermAllocatorFunctions vterm_allocator = {
4866 &vterm_malloc,
4867 &vterm_memfree
4868};
4869
4870/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004871 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004872 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004873 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004874 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004875create_vterm(term_T *term, int rows, int cols)
4876{
4877 VTerm *vterm;
4878 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004879 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004880 VTermValue value;
4881
Bram Moolenaar756ef112018-04-10 12:04:27 +02004882 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004883 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004884 if (vterm == NULL)
4885 return FAIL;
4886
4887 // Allocate screen and state here, so we can bail out if that fails.
4888 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004889 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004890 if (state == NULL || screen == NULL)
4891 {
4892 vterm_free(vterm);
4893 return FAIL;
4894 }
4895
Bram Moolenaar52acb112018-03-18 19:20:22 +01004896 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004897 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004898 vterm_set_utf8(vterm, 1);
4899
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004900 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004901
4902 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004903 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004904 &term->tl_default_color.fg,
4905 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004906
Bram Moolenaar9e587872019-05-13 20:27:23 +02004907 if (t_colors < 16)
4908 // Less than 16 colors: assume that bold means using a bright color for
4909 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004910 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4911
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004912 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004913 vterm_screen_reset(screen, 1 /* hard */);
4914
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004915 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004916 vterm_screen_enable_altscreen(screen, 1);
4917
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004918 // For unix do not use a blinking cursor. In an xterm this causes the
4919 // cursor to blink if it's blinking in the xterm.
4920 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004921#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004922 if (GetCaretBlinkTime() == INFINITE)
4923 value.boolean = 0;
4924 else
4925 value.boolean = 1;
4926#else
4927 value.boolean = 0;
4928#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004929 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004930 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004931
4932 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004933}
4934
4935/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004936 * Reset the terminal palette to its default value.
4937 */
4938 static void
4939term_reset_palette(VTerm *vterm)
4940{
4941 VTermState *state = vterm_obtain_state(vterm);
4942 int index;
4943
4944 for (index = 0; index < 16; index++)
4945 {
4946 VTermColor color;
4947
4948 color.type = VTERM_COLOR_INDEXED;
4949 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4950 &color.index);
4951 // The first valid index starts at 1.
4952 color.index -= 1;
4953
4954 vterm_state_set_palette_color(state, index, &color);
4955 }
4956}
4957
4958 static void
4959term_update_palette(term_T *term)
4960{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004961#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004962 if (term_use_palette()
4963 && (term->tl_palette != NULL
4964 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004965 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004966 {
4967 if (term->tl_palette != NULL)
4968 set_vterm_palette(term->tl_vterm, term->tl_palette);
4969 else
4970 init_vterm_ansi_colors(term->tl_vterm);
4971 }
4972 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004973#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004974 term_reset_palette(term->tl_vterm);
4975}
4976
4977/*
4978 * Called when option 'termguicolors' is changed.
4979 */
4980 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004981term_update_palette_all(void)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004982{
4983 term_T *term;
4984
4985 FOR_ALL_TERMS(term)
4986 {
4987 if (term->tl_vterm == NULL)
4988 continue;
4989 term_update_palette(term);
4990 }
4991}
4992
4993/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004994 * Called when option 'background' or 'termguicolors' was set,
4995 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02004996 */
4997 void
4998term_update_colors_all(void)
4999{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005000 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02005001
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005002 FOR_ALL_TERMS(term)
5003 {
5004 if (term->tl_vterm == NULL)
5005 continue;
5006 init_default_colors(term);
5007 vterm_state_set_default_colors(
5008 vterm_obtain_state(term->tl_vterm),
5009 &term->tl_default_color.fg,
5010 &term->tl_default_color.bg);
5011 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005012}
5013
5014/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005015 * Return the text to show for the buffer name and status.
5016 */
5017 char_u *
5018term_get_status_text(term_T *term)
5019{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005020 if (term->tl_status_text != NULL)
5021 return term->tl_status_text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005022
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005023 char_u *txt;
5024 size_t len;
5025 char_u *fname;
5026
5027 if (term->tl_normal_mode)
5028 {
5029 if (term_job_running(term))
5030 txt = (char_u *)_("Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005031 else
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005032 txt = (char_u *)_("Terminal-finished");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005033 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005034 else if (term->tl_title != NULL)
5035 txt = term->tl_title;
5036 else if (term_none_open(term))
5037 txt = (char_u *)_("active");
5038 else if (term_job_running(term))
5039 txt = (char_u *)_("running");
5040 else
5041 txt = (char_u *)_("finished");
5042 fname = buf_get_fname(term->tl_buffer);
5043 len = 9 + STRLEN(fname) + STRLEN(txt);
5044 term->tl_status_text = alloc(len);
5045 if (term->tl_status_text != NULL)
5046 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
5047 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005048 return term->tl_status_text;
5049}
5050
5051/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00005052 * Clear the cached value of the status text.
5053 */
5054 void
5055term_clear_status_text(term_T *term)
5056{
5057 VIM_CLEAR(term->tl_status_text);
5058}
5059
5060/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005061 * Mark references in jobs of terminals.
5062 */
5063 int
5064set_ref_in_term(int copyID)
5065{
5066 int abort = FALSE;
5067 term_T *term;
5068 typval_T tv;
5069
Bram Moolenaar75a1a942019-06-20 03:45:36 +02005070 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005071 if (term->tl_job != NULL)
5072 {
5073 tv.v_type = VAR_JOB;
5074 tv.vval.v_job = term->tl_job;
5075 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
5076 }
5077 return abort;
5078}
5079
5080/*
5081 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005082 * Returns NULL when the buffer is not for a terminal window and logs a message
5083 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005084 */
5085 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005086term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005087{
5088 buf_T *buf;
5089
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005090 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01005091 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005092 --emsg_off;
5093 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005094 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01005095 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005096 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005097 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005098 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005099 return buf;
5100}
5101
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005102 static void
5103clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005104{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005105 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005106 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
5107 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005108}
5109
5110 static void
5111dump_term_color(FILE *fd, VTermColor *color)
5112{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005113 int index;
5114
5115 if (VTERM_COLOR_IS_INDEXED(color))
5116 index = color->index + 1;
5117 else if (color->type == 0)
5118 // use RGB values
5119 index = 255;
5120 else
5121 // default color
5122 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005123 fprintf(fd, "%02x%02x%02x%d",
5124 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005125 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005126}
5127
5128/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005129 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01005130 *
5131 * Each screen cell in full is:
5132 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5133 * {characters} is a space for an empty cell
5134 * For a double-width character "+" is changed to "*" and the next cell is
5135 * skipped.
5136 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5137 * when "&" use the same as the previous cell.
5138 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5139 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5140 * {color-idx} is a number from 0 to 255
5141 *
5142 * Screen cell with same width, attributes and color as the previous one:
5143 * |{characters}
5144 *
5145 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5146 *
5147 * Repeating the previous screen cell:
5148 * @{count}
5149 */
5150 void
5151f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5152{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005153 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005154 term_T *term;
5155 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005156 int max_height = 0;
5157 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005158 stat_T st;
5159 FILE *fd;
5160 VTermPos pos;
5161 VTermScreen *screen;
5162 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005163 VTermState *state;
5164 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005165
5166 if (check_restricted() || check_secure())
5167 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005168
5169 if (in_vim9script()
5170 && (check_for_buffer_arg(argvars, 0) == FAIL
5171 || check_for_string_arg(argvars, 1) == FAIL
5172 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5173 return;
5174
5175 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005176 if (buf == NULL)
5177 return;
5178 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005179 if (term->tl_vterm == NULL)
5180 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005181 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005182 return;
5183 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005184
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005185 if (argvars[2].v_type != VAR_UNKNOWN)
5186 {
5187 dict_T *d;
5188
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005189 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005190 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005191 d = argvars[2].vval.v_dict;
5192 if (d != NULL)
5193 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005194 max_height = dict_get_number(d, "rows");
5195 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005196 }
5197 }
5198
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005199 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005200 if (fname == NULL)
5201 return;
5202 if (mch_stat((char *)fname, &st) >= 0)
5203 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005204 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005205 return;
5206 }
5207
Bram Moolenaard96ff162018-02-18 22:13:29 +01005208 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5209 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005210 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005211 return;
5212 }
5213
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005214 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005215
5216 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005217 state = vterm_obtain_state(term->tl_vterm);
5218 vterm_state_get_cursorpos(state, &cursor_pos);
5219
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005220 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5221 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005222 {
5223 int repeat = 0;
5224
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005225 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5226 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005227 {
5228 VTermScreenCell cell;
5229 int same_attr;
5230 int same_chars = TRUE;
5231 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005232 int is_cursor_pos = (pos.col == cursor_pos.col
5233 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005234
5235 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005236 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005237
5238 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5239 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005240 int c = cell.chars[i];
5241 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005242 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005243
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005244 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005245 if (i == 0)
5246 {
5247 c = (c == NUL) ? ' ' : c;
5248 pc = (pc == NUL) ? ' ' : pc;
5249 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005250 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005251 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005252 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005253 break;
5254 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005255 same_attr = vtermAttr2hl(&cell.attrs)
5256 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005257 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5258 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005259 if (same_chars && cell.width == prev_cell.width && same_attr
5260 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005261 {
5262 ++repeat;
5263 }
5264 else
5265 {
5266 if (repeat > 0)
5267 {
5268 fprintf(fd, "@%d", repeat);
5269 repeat = 0;
5270 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005271 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005272
5273 if (cell.chars[0] == NUL)
5274 fputs(" ", fd);
5275 else
5276 {
5277 char_u charbuf[10];
5278 int len;
5279
5280 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5281 && cell.chars[i] != NUL; ++i)
5282 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005283 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005284 fwrite(charbuf, len, 1, fd);
5285 }
5286 }
5287
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005288 // When only the characters differ we don't write anything, the
5289 // following "|", "@" or NL will indicate using the same
5290 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005291 if (cell.width != prev_cell.width || !same_attr)
5292 {
5293 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005294 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005295 else
5296 fputs("+", fd);
5297
5298 if (same_attr)
5299 {
5300 fputs("&", fd);
5301 }
5302 else
5303 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005304 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005305 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005306 fputs("&", fd);
5307 else
5308 {
5309 fputs("#", fd);
5310 dump_term_color(fd, &cell.fg);
5311 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005312 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005313 fputs("&", fd);
5314 else
5315 {
5316 fputs("#", fd);
5317 dump_term_color(fd, &cell.bg);
5318 }
5319 }
5320 }
5321
5322 prev_cell = cell;
5323 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005324
5325 if (cell.width == 2)
5326 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005327 }
5328 if (repeat > 0)
5329 fprintf(fd, "@%d", repeat);
5330 fputs("\n", fd);
5331 }
5332
5333 fclose(fd);
5334}
5335
5336/*
5337 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5338 */
5339 static void
5340dump_is_corrupt(garray_T *gap)
5341{
5342 ga_concat(gap, (char_u *)"CORRUPT");
5343}
5344
5345 static void
5346append_cell(garray_T *gap, cellattr_T *cell)
5347{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005348 if (ga_grow(gap, 1) == FAIL)
5349 return;
5350
5351 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5352 ++gap->ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005353}
5354
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005355 static void
5356clear_cellattr(cellattr_T *cell)
5357{
5358 CLEAR_FIELD(*cell);
5359 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5360 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5361}
5362
Bram Moolenaard96ff162018-02-18 22:13:29 +01005363/*
5364 * Read the dump file from "fd" and append lines to the current buffer.
5365 * Return the cell width of the longest line.
5366 */
5367 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005368read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005369{
5370 int c;
5371 garray_T ga_text;
5372 garray_T ga_cell;
5373 char_u *prev_char = NULL;
5374 int attr = 0;
5375 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005376 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005377 term_T *term = curbuf->b_term;
5378 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005379 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005380
5381 ga_init2(&ga_text, 1, 90);
5382 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005383 clear_cellattr(&cell);
5384 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005385 cursor_pos->row = -1;
5386 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005387
5388 c = fgetc(fd);
5389 for (;;)
5390 {
5391 if (c == EOF)
5392 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005393 if (c == '\r')
5394 {
5395 // DOS line endings? Ignore.
5396 c = fgetc(fd);
5397 }
5398 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005399 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005400 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005401 if (ga_text.ga_data == NULL)
5402 dump_is_corrupt(&ga_text);
5403 if (ga_grow(&term->tl_scrollback, 1) == OK)
5404 {
5405 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5406 + term->tl_scrollback.ga_len;
5407
5408 if (max_cells < ga_cell.ga_len)
5409 max_cells = ga_cell.ga_len;
5410 line->sb_cols = ga_cell.ga_len;
5411 line->sb_cells = ga_cell.ga_data;
5412 line->sb_fill_attr = term->tl_default_color;
5413 ++term->tl_scrollback.ga_len;
5414 ga_init(&ga_cell);
5415
5416 ga_append(&ga_text, NUL);
5417 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5418 ga_text.ga_len, FALSE);
5419 }
5420 else
5421 ga_clear(&ga_cell);
5422 ga_text.ga_len = 0;
5423
5424 c = fgetc(fd);
5425 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005426 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005427 {
5428 int prev_len = ga_text.ga_len;
5429
Bram Moolenaar9271d052018-02-25 21:39:46 +01005430 if (c == '>')
5431 {
5432 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005433 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005434 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5435 cursor_pos->col = ga_cell.ga_len;
5436 }
5437
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005438 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005439 c = fgetc(fd);
5440 if (c != EOF)
5441 ga_append(&ga_text, c);
5442 for (;;)
5443 {
5444 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005445 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005446 || c == EOF || c == '\n')
5447 break;
5448 ga_append(&ga_text, c);
5449 }
5450
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005451 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005452 vim_free(prev_char);
5453 if (ga_text.ga_data != NULL)
5454 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5455 ga_text.ga_len - prev_len);
5456
Bram Moolenaar9271d052018-02-25 21:39:46 +01005457 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005458 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005459 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005460 }
5461 else if (c == '+' || c == '*')
5462 {
5463 int is_bg;
5464
5465 cell.width = c == '+' ? 1 : 2;
5466
5467 c = fgetc(fd);
5468 if (c == '&')
5469 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005470 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005471 c = fgetc(fd);
5472 }
Keith Thompson184f71c2024-01-04 21:19:04 +01005473 else if (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005474 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005475 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005476 attr = 0;
Keith Thompson184f71c2024-01-04 21:19:04 +01005477 while (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005478 {
5479 attr = attr * 10 + (c - '0');
5480 c = fgetc(fd);
5481 }
5482 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005483
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005484 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005485 for (is_bg = 0; is_bg <= 1; ++is_bg)
5486 {
5487 if (c == '&')
5488 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005489 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005490 c = fgetc(fd);
5491 }
5492 else if (c == '#')
5493 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005494 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005495
5496 c = fgetc(fd);
5497 red = hex2nr(c);
5498 c = fgetc(fd);
5499 red = (red << 4) + hex2nr(c);
5500 c = fgetc(fd);
5501 green = hex2nr(c);
5502 c = fgetc(fd);
5503 green = (green << 4) + hex2nr(c);
5504 c = fgetc(fd);
5505 blue = hex2nr(c);
5506 c = fgetc(fd);
5507 blue = (blue << 4) + hex2nr(c);
5508 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005509 if (!SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005510 dump_is_corrupt(&ga_text);
Keith Thompson184f71c2024-01-04 21:19:04 +01005511 while (SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005512 {
5513 index = index * 10 + (c - '0');
5514 c = fgetc(fd);
5515 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005516 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005517 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005518 type = VTERM_COLOR_RGB;
5519 if (index == 0)
5520 {
5521 if (is_bg)
5522 type |= VTERM_COLOR_DEFAULT_BG;
5523 else
5524 type |= VTERM_COLOR_DEFAULT_FG;
5525 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005526 }
5527 else
5528 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005529 type = VTERM_COLOR_INDEXED;
5530 index -= 1;
5531 }
5532 if (is_bg)
5533 {
5534 cell.bg.type = type;
5535 cell.bg.red = red;
5536 cell.bg.green = green;
5537 cell.bg.blue = blue;
5538 cell.bg.index = index;
5539 }
5540 else
5541 {
5542 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005543 cell.fg.red = red;
5544 cell.fg.green = green;
5545 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005546 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005547 }
5548 }
5549 else
5550 dump_is_corrupt(&ga_text);
5551 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005552 }
5553 else
5554 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005555 }
5556 else
5557 dump_is_corrupt(&ga_text);
5558
5559 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005560 if (cell.width == 2)
5561 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005562 }
5563 else if (c == '@')
5564 {
5565 if (prev_char == NULL)
5566 dump_is_corrupt(&ga_text);
5567 else
5568 {
5569 int count = 0;
5570
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005571 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005572 for (;;)
5573 {
5574 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005575 if (!SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005576 break;
5577 count = count * 10 + (c - '0');
5578 }
5579
5580 while (count-- > 0)
5581 {
5582 ga_concat(&ga_text, prev_char);
5583 append_cell(&ga_cell, &cell);
5584 }
5585 }
5586 }
5587 else
5588 {
5589 dump_is_corrupt(&ga_text);
5590 c = fgetc(fd);
5591 }
5592 }
5593
5594 if (ga_text.ga_len > 0)
5595 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005596 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005597 dump_is_corrupt(&ga_text);
5598 ga_append(&ga_text, NUL);
5599 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5600 ga_text.ga_len, FALSE);
5601 }
5602
5603 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005604 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005605 vim_free(prev_char);
5606
5607 return max_cells;
5608}
5609
5610/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005611 * Return an allocated string with at least "text_width" "=" characters and
5612 * "fname" inserted in the middle.
5613 */
5614 static char_u *
5615get_separator(int text_width, char_u *fname)
5616{
5617 int width = MAX(text_width, curwin->w_width);
5618 char_u *textline;
5619 int fname_size;
5620 char_u *p = fname;
5621 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005622 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005623
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005624 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005625 if (textline == NULL)
5626 return NULL;
5627
5628 fname_size = vim_strsize(fname);
5629 if (fname_size < width - 8)
5630 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005631 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005632 width = MAX(text_width, fname_size + 8);
5633 }
5634 else if (fname_size > width - 8)
5635 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005636 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005637 p = gettail(fname);
5638 fname_size = vim_strsize(p);
5639 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005640 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005641 while (fname_size > width - 8)
5642 {
5643 p += (*mb_ptr2len)(p);
5644 fname_size = vim_strsize(p);
5645 }
5646
5647 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5648 textline[i] = '=';
5649 textline[i++] = ' ';
5650
5651 STRCPY(textline + i, p);
5652 off = STRLEN(textline);
5653 textline[off] = ' ';
5654 for (i = 1; i < (width - fname_size) / 2; ++i)
5655 textline[off + i] = '=';
5656 textline[off + i] = NUL;
5657
5658 return textline;
5659}
5660
5661/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005662 * Common for "term_dumpdiff()" and "term_dumpload()".
5663 */
5664 static void
5665term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5666{
5667 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005668 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005669 char_u buf1[NUMBUFLEN];
5670 char_u buf2[NUMBUFLEN];
5671 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005672 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005673 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005674 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005675 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005676 char_u *textline = NULL;
5677
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005678 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005679 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005680 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005681 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005682 if (fname1 == NULL || (do_diff && fname2 == NULL))
5683 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005684 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005685 return;
5686 }
5687 fd1 = mch_fopen((char *)fname1, READBIN);
5688 if (fd1 == NULL)
5689 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005690 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005691 return;
5692 }
5693 if (do_diff)
5694 {
5695 fd2 = mch_fopen((char *)fname2, READBIN);
5696 if (fd2 == NULL)
5697 {
5698 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005699 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005700 return;
5701 }
5702 }
5703
5704 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005705 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5706 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5707 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5708 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5709 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005710
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005711 if (opt.jo_term_name == NULL)
5712 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005713 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005714
Bram Moolenaar51e14382019-05-25 20:21:28 +02005715 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005716 if (fname_tofree != NULL)
5717 {
5718 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5719 opt.jo_term_name = fname_tofree;
5720 }
5721 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005722
Bram Moolenaar87abab92019-06-03 21:14:59 +02005723 if (opt.jo_bufnr_buf != NULL)
5724 {
5725 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5726
5727 // With "bufnr" argument: enter the window with this buffer and make it
5728 // empty.
5729 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005730 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005731 else
5732 {
5733 buf = curbuf;
5734 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005735 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005736 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005737 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005738 }
5739 }
5740 else
5741 // Create a new terminal window.
5742 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5743
Bram Moolenaard96ff162018-02-18 22:13:29 +01005744 if (buf != NULL && buf->b_term != NULL)
5745 {
5746 int i;
5747 linenr_T bot_lnum;
5748 linenr_T lnum;
5749 term_T *term = buf->b_term;
5750 int width;
5751 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005752 VTermPos cursor_pos1;
5753 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005754
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005755 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005756
Bram Moolenaard96ff162018-02-18 22:13:29 +01005757 rettv->vval.v_number = buf->b_fnum;
5758
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005759 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005760 width = read_dump_file(fd1, &cursor_pos1);
5761
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005762 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005763 if (cursor_pos1.row >= 0)
5764 {
5765 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5766 coladvance(cursor_pos1.col);
5767 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005768
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005769 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005770 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005771
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005772 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005773 if (!do_diff)
5774 goto theend;
5775
5776 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5777
Bram Moolenaar4a696342018-04-05 18:45:26 +02005778 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005779 if (textline == NULL)
5780 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005781 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5782 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5783 vim_free(textline);
5784
5785 textline = get_separator(width, fname2);
5786 if (textline == NULL)
5787 goto theend;
5788 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5789 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005790 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005791
5792 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005793 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005794 if (width2 > width)
5795 {
5796 vim_free(textline);
5797 textline = alloc(width2 + 1);
5798 if (textline == NULL)
5799 goto theend;
5800 width = width2;
5801 textline[width] = NUL;
5802 }
5803 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5804
5805 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5806 {
5807 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5808 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005809 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005810 for (i = 0; i < width; ++i)
5811 textline[i] = '-';
5812 }
5813 else
5814 {
5815 char_u *line1;
5816 char_u *line2;
5817 char_u *p1;
5818 char_u *p2;
5819 int col;
5820 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5821 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5822 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5823 ->sb_cells;
5824
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005825 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005826 line1 = vim_strsave(ml_get(lnum));
5827 if (line1 == NULL)
5828 break;
5829 p1 = line1;
5830
5831 line2 = ml_get(lnum + bot_lnum);
5832 p2 = line2;
5833 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5834 {
5835 int len1 = utfc_ptr2len(p1);
5836 int len2 = utfc_ptr2len(p2);
5837
5838 textline[col] = ' ';
5839 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005840 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005841 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005842 else if (lnum == cursor_pos1.row + 1
5843 && col == cursor_pos1.col
5844 && (cursor_pos1.row != cursor_pos2.row
5845 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005846 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005847 textline[col] = '>';
5848 else if (lnum == cursor_pos2.row + 1
5849 && col == cursor_pos2.col
5850 && (cursor_pos1.row != cursor_pos2.row
5851 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005852 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005853 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005854 else if (cellattr1 != NULL && cellattr2 != NULL)
5855 {
5856 if ((cellattr1 + col)->width
5857 != (cellattr2 + col)->width)
5858 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005859 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005860 &(cellattr2 + col)->fg))
5861 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005862 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005863 &(cellattr2 + col)->bg))
5864 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005865 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5866 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005867 textline[col] = 'a';
5868 }
5869 p1 += len1;
5870 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005871 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005872 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005873
5874 while (col < width)
5875 {
5876 if (*p1 == NUL && *p2 == NUL)
5877 textline[col] = '?';
5878 else if (*p1 == NUL)
5879 {
5880 textline[col] = '+';
5881 p2 += utfc_ptr2len(p2);
5882 }
5883 else
5884 {
5885 textline[col] = '-';
5886 p1 += utfc_ptr2len(p1);
5887 }
5888 ++col;
5889 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005890
5891 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005892 }
5893 if (add_empty_scrollback(term, &term->tl_default_color,
5894 term->tl_top_diff_rows) == OK)
5895 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5896 ++bot_lnum;
5897 }
5898
5899 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5900 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005901 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005902 for (i = 0; i < width; ++i)
5903 textline[i] = '+';
5904 if (add_empty_scrollback(term, &term->tl_default_color,
5905 term->tl_top_diff_rows) == OK)
5906 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5907 ++lnum;
5908 ++bot_lnum;
5909 }
5910
5911 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005912
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005913 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005914 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005915 }
5916
5917theend:
5918 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005919 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005920 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005921 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005922 fclose(fd2);
5923}
5924
5925/*
5926 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5927 * bottom files.
5928 * Return FAIL when this is not possible.
5929 */
5930 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005931term_swap_diff(void)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005932{
5933 term_T *term = curbuf->b_term;
5934 linenr_T line_count;
5935 linenr_T top_rows;
5936 linenr_T bot_rows;
5937 linenr_T bot_start;
5938 linenr_T lnum;
5939 char_u *p;
5940 sb_line_T *sb_line;
5941
5942 if (term == NULL
5943 || !term_is_finished(curbuf)
5944 || term->tl_top_diff_rows == 0
5945 || term->tl_scrollback.ga_len == 0)
5946 return FAIL;
5947
5948 line_count = curbuf->b_ml.ml_line_count;
5949 top_rows = term->tl_top_diff_rows;
5950 bot_rows = term->tl_bot_diff_rows;
5951 bot_start = line_count - bot_rows;
5952 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5953
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005954 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005955 for (lnum = 1; lnum <= top_rows; ++lnum)
5956 {
5957 p = vim_strsave(ml_get(1));
5958 if (p == NULL)
5959 return OK;
5960 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005961 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005962 vim_free(p);
5963 }
5964
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005965 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005966 for (lnum = 1; lnum <= bot_rows; ++lnum)
5967 {
5968 p = vim_strsave(ml_get(bot_start + lnum));
5969 if (p == NULL)
5970 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005971 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005972 ml_append(lnum - 1, p, 0, FALSE);
5973 vim_free(p);
5974 }
5975
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005976 // move top title to bottom
5977 p = vim_strsave(ml_get(bot_rows + 1));
5978 if (p == NULL)
5979 return OK;
5980 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005981 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005982 vim_free(p);
5983
5984 // move bottom title to top
5985 p = vim_strsave(ml_get(line_count - top_rows));
5986 if (p == NULL)
5987 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005988 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005989 ml_append(bot_rows, p, 0, FALSE);
5990 vim_free(p);
5991
Bram Moolenaard96ff162018-02-18 22:13:29 +01005992 if (top_rows == bot_rows)
5993 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005994 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005995 for (lnum = 0; lnum < top_rows; ++lnum)
5996 {
5997 sb_line_T temp;
5998
5999 temp = *(sb_line + lnum);
6000 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
6001 *(sb_line + bot_start + lnum) = temp;
6002 }
6003 }
6004 else
6005 {
6006 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006007 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006008
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006009 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01006010 if (temp != NULL)
6011 {
6012 mch_memmove(temp, term->tl_scrollback.ga_data, size);
6013 mch_memmove(term->tl_scrollback.ga_data,
6014 temp + bot_start,
6015 sizeof(sb_line_T) * bot_rows);
6016 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
6017 temp + top_rows,
6018 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
6019 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
6020 + line_count - top_rows,
6021 temp,
6022 sizeof(sb_line_T) * top_rows);
6023 vim_free(temp);
6024 }
6025 }
6026
6027 term->tl_top_diff_rows = bot_rows;
6028 term->tl_bot_diff_rows = top_rows;
6029
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006030 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006031 return OK;
6032}
6033
6034/*
6035 * "term_dumpdiff(filename, filename, options)" function
6036 */
6037 void
6038f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
6039{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02006040 if (in_vim9script()
6041 && (check_for_string_arg(argvars, 0) == FAIL
6042 || check_for_string_arg(argvars, 1) == FAIL
6043 || check_for_opt_dict_arg(argvars, 2) == FAIL))
6044 return;
6045
Bram Moolenaard96ff162018-02-18 22:13:29 +01006046 term_load_dump(argvars, rettv, TRUE);
6047}
6048
6049/*
6050 * "term_dumpload(filename, options)" function
6051 */
6052 void
6053f_term_dumpload(typval_T *argvars, typval_T *rettv)
6054{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006055 if (in_vim9script()
6056 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02006057 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006058 return;
6059
Bram Moolenaard96ff162018-02-18 22:13:29 +01006060 term_load_dump(argvars, rettv, FALSE);
6061}
6062
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006063/*
6064 * "term_getaltscreen(buf)" function
6065 */
6066 void
6067f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
6068{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006069 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006070
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006071 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6072 return;
6073
6074 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006075 if (buf == NULL)
6076 return;
6077 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
6078}
6079
6080/*
6081 * "term_getattr(attr, name)" function
6082 */
6083 void
6084f_term_getattr(typval_T *argvars, typval_T *rettv)
6085{
6086 int attr;
6087 size_t i;
6088 char_u *name;
6089
6090 static struct {
6091 char *name;
6092 int attr;
6093 } attrs[] = {
6094 {"bold", HL_BOLD},
6095 {"italic", HL_ITALIC},
6096 {"underline", HL_UNDERLINE},
6097 {"strike", HL_STRIKETHROUGH},
6098 {"reverse", HL_INVERSE},
6099 };
6100
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02006101 if (in_vim9script()
6102 && (check_for_number_arg(argvars, 0) == FAIL
6103 || check_for_string_arg(argvars, 1) == FAIL))
6104 return;
6105
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006106 attr = tv_get_number(&argvars[0]);
6107 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006108 if (name == NULL)
6109 return;
6110
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02006111 if (attr > HL_ALL)
6112 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02006113 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006114 if (STRCMP(name, attrs[i].name) == 0)
6115 {
6116 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
6117 break;
6118 }
6119}
6120
6121/*
6122 * "term_getcursor(buf)" function
6123 */
6124 void
6125f_term_getcursor(typval_T *argvars, typval_T *rettv)
6126{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006127 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006128 term_T *term;
6129 list_T *l;
6130 dict_T *d;
6131
6132 if (rettv_list_alloc(rettv) == FAIL)
6133 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006134
6135 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6136 return;
6137
6138 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006139 if (buf == NULL)
6140 return;
6141 term = buf->b_term;
6142
6143 l = rettv->vval.v_list;
6144 list_append_number(l, term->tl_cursor_pos.row + 1);
6145 list_append_number(l, term->tl_cursor_pos.col + 1);
6146
6147 d = dict_alloc();
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00006148 if (d == NULL)
6149 return;
6150
6151 dict_add_number(d, "visible", term->tl_cursor_visible);
6152 dict_add_number(d, "blink", blink_state_is_inverted()
6153 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6154 dict_add_number(d, "shape", term->tl_cursor_shape);
6155 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
6156 list_append_dict(l, d);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006157}
6158
6159/*
6160 * "term_getjob(buf)" function
6161 */
6162 void
6163f_term_getjob(typval_T *argvars, typval_T *rettv)
6164{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006165 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006166
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006167 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6168 return;
6169
6170 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006171 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006172 {
6173 rettv->v_type = VAR_SPECIAL;
6174 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006175 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006176 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006177
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006178 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006179 rettv->vval.v_job = buf->b_term->tl_job;
6180 if (rettv->vval.v_job != NULL)
6181 ++rettv->vval.v_job->jv_refcount;
6182}
6183
6184 static int
6185get_row_number(typval_T *tv, term_T *term)
6186{
6187 if (tv->v_type == VAR_STRING
6188 && tv->vval.v_string != NULL
6189 && STRCMP(tv->vval.v_string, ".") == 0)
6190 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006191 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006192}
6193
6194/*
6195 * "term_getline(buf, row)" function
6196 */
6197 void
6198f_term_getline(typval_T *argvars, typval_T *rettv)
6199{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006200 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006201 term_T *term;
6202 int row;
6203
6204 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006205
6206 if (in_vim9script()
6207 && (check_for_buffer_arg(argvars, 0) == FAIL
6208 || check_for_lnum_arg(argvars, 1) == FAIL))
6209 return;
6210
6211 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006212 if (buf == NULL)
6213 return;
6214 term = buf->b_term;
6215 row = get_row_number(&argvars[1], term);
6216
6217 if (term->tl_vterm == NULL)
6218 {
6219 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6220
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006221 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006222 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6223 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6224 }
6225 else
6226 {
6227 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6228 VTermRect rect;
6229 int len;
6230 char_u *p;
6231
6232 if (row < 0 || row >= term->tl_rows)
6233 return;
6234 len = term->tl_cols * MB_MAXBYTES + 1;
6235 p = alloc(len);
6236 if (p == NULL)
6237 return;
6238 rettv->vval.v_string = p;
6239
6240 rect.start_col = 0;
6241 rect.end_col = term->tl_cols;
6242 rect.start_row = row;
6243 rect.end_row = row + 1;
6244 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6245 }
6246}
6247
6248/*
6249 * "term_getscrolled(buf)" function
6250 */
6251 void
6252f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6253{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006254 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006255
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006256 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6257 return;
6258
6259 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006260 if (buf == NULL)
6261 return;
6262 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6263}
6264
6265/*
6266 * "term_getsize(buf)" function
6267 */
6268 void
6269f_term_getsize(typval_T *argvars, typval_T *rettv)
6270{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006271 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006272 list_T *l;
6273
6274 if (rettv_list_alloc(rettv) == FAIL)
6275 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006276
6277 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6278 return;
6279
6280 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006281 if (buf == NULL)
6282 return;
6283
6284 l = rettv->vval.v_list;
6285 list_append_number(l, buf->b_term->tl_rows);
6286 list_append_number(l, buf->b_term->tl_cols);
6287}
6288
6289/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006290 * "term_setsize(buf, rows, cols)" function
6291 */
6292 void
6293f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6294{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006295 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006296 term_T *term;
6297 varnumber_T rows, cols;
6298
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006299 if (in_vim9script()
6300 && (check_for_buffer_arg(argvars, 0) == FAIL
6301 || check_for_number_arg(argvars, 1) == FAIL
6302 || check_for_number_arg(argvars, 2) == FAIL))
6303 return;
6304
6305 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006306 if (buf == NULL)
6307 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006308 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006309 return;
6310 }
6311 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006312 return;
6313 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006314 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006315 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006316 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006317 cols = cols <= 0 ? term->tl_cols : cols;
6318 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006319 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006320
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006321 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006322 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6323 term_report_winsize(term, term->tl_rows, term->tl_cols);
6324}
6325
6326/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006327 * "term_getstatus(buf)" function
6328 */
6329 void
6330f_term_getstatus(typval_T *argvars, typval_T *rettv)
6331{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006332 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006333 term_T *term;
6334 char_u val[100];
6335
6336 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006337
6338 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6339 return;
6340
6341 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006342 if (buf == NULL)
6343 return;
6344 term = buf->b_term;
6345
6346 if (term_job_running(term))
6347 STRCPY(val, "running");
6348 else
6349 STRCPY(val, "finished");
6350 if (term->tl_normal_mode)
6351 STRCAT(val, ",normal");
6352 rettv->vval.v_string = vim_strsave(val);
6353}
6354
6355/*
6356 * "term_gettitle(buf)" function
6357 */
6358 void
6359f_term_gettitle(typval_T *argvars, typval_T *rettv)
6360{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006361 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006362
6363 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006364
6365 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6366 return;
6367
6368 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006369 if (buf == NULL)
6370 return;
6371
6372 if (buf->b_term->tl_title != NULL)
6373 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6374}
6375
6376/*
6377 * "term_gettty(buf)" function
6378 */
6379 void
6380f_term_gettty(typval_T *argvars, typval_T *rettv)
6381{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006382 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006383 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006384 int num = 0;
6385
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006386 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006387 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006388 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6389 return;
6390
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006391 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006392 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006393 if (buf == NULL)
6394 return;
6395 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006396 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006397
6398 switch (num)
6399 {
6400 case 0:
6401 if (buf->b_term->tl_job != NULL)
6402 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006403 break;
6404 case 1:
6405 if (buf->b_term->tl_job != NULL)
6406 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006407 break;
6408 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006409 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006410 return;
6411 }
6412 if (p != NULL)
6413 rettv->vval.v_string = vim_strsave(p);
6414}
6415
6416/*
6417 * "term_list()" function
6418 */
6419 void
6420f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6421{
6422 term_T *tp;
6423 list_T *l;
6424
6425 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6426 return;
6427
6428 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006429 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006430 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006431 if (list_append_number(l,
6432 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6433 return;
6434}
6435
6436/*
6437 * "term_scrape(buf, row)" function
6438 */
6439 void
6440f_term_scrape(typval_T *argvars, typval_T *rettv)
6441{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006442 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006443 VTermScreen *screen = NULL;
6444 VTermPos pos;
6445 list_T *l;
6446 term_T *term;
6447 char_u *p;
6448 sb_line_T *line;
6449
6450 if (rettv_list_alloc(rettv) == FAIL)
6451 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006452
6453 if (in_vim9script()
6454 && (check_for_buffer_arg(argvars, 0) == FAIL
6455 || check_for_lnum_arg(argvars, 1) == FAIL))
6456 return;
6457
6458 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006459 if (buf == NULL)
6460 return;
6461 term = buf->b_term;
6462
6463 l = rettv->vval.v_list;
6464 pos.row = get_row_number(&argvars[1], term);
6465
6466 if (term->tl_vterm != NULL)
6467 {
6468 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006469 if (screen == NULL) // can't really happen
6470 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006471 p = NULL;
6472 line = NULL;
6473 }
6474 else
6475 {
6476 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6477
6478 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6479 return;
6480 p = ml_get_buf(buf, lnum + 1, FALSE);
6481 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6482 }
6483
6484 for (pos.col = 0; pos.col < term->tl_cols; )
6485 {
6486 dict_T *dcell;
6487 int width;
6488 VTermScreenCellAttrs attrs;
6489 VTermColor fg, bg;
6490 char_u rgb[8];
6491 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6492 int off = 0;
6493 int i;
6494
6495 if (screen == NULL)
6496 {
6497 cellattr_T *cellattr;
6498 int len;
6499
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006500 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006501 if (pos.col >= line->sb_cols)
6502 break;
6503 cellattr = line->sb_cells + pos.col;
6504 width = cellattr->width;
6505 attrs = cellattr->attrs;
6506 fg = cellattr->fg;
6507 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006508 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006509 mch_memmove(mbs, p, len);
6510 mbs[len] = NUL;
6511 p += len;
6512 }
6513 else
6514 {
6515 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006516
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006517 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6518 break;
6519 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6520 {
6521 if (cell.chars[i] == 0)
6522 break;
6523 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6524 }
6525 mbs[off] = NUL;
6526 width = cell.width;
6527 attrs = cell.attrs;
6528 fg = cell.fg;
6529 bg = cell.bg;
6530 }
6531 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006532 if (dcell == NULL)
6533 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006534 list_append_dict(l, dcell);
6535
Bram Moolenaare0be1672018-07-08 16:50:37 +02006536 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006537
6538 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6539 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006540 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006541 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6542 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006543 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006544
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006545 dict_add_number(dcell, "attr",
6546 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006547 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006548
6549 ++pos.col;
6550 if (width == 2)
6551 ++pos.col;
6552 }
6553}
6554
6555/*
6556 * "term_sendkeys(buf, keys)" function
6557 */
6558 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006559f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006560{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006561 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006562 char_u *msg;
6563 term_T *term;
6564
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006565 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006566 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006567 || check_for_string_arg(argvars, 1) == FAIL))
6568 return;
6569
6570 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006571 if (buf == NULL)
6572 return;
6573
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006574 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006575 if (msg == NULL)
6576 return;
6577 term = buf->b_term;
6578 if (term->tl_vterm == NULL)
6579 return;
6580
6581 while (*msg != NUL)
6582 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006583 int c;
6584
6585 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6586 {
6587 c = TO_SPECIAL(msg[1], msg[2]);
6588 msg += 3;
6589 }
6590 else
6591 {
6592 c = PTR2CHAR(msg);
6593 msg += MB_CPTR2LEN(msg);
6594 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006595 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006596 }
6597}
6598
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006599#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6600/*
6601 * "term_getansicolors(buf)" function
6602 */
6603 void
6604f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6605{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006606 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006607 term_T *term;
6608 VTermState *state;
6609 VTermColor color;
6610 char_u hexbuf[10];
6611 int index;
6612 list_T *list;
6613
6614 if (rettv_list_alloc(rettv) == FAIL)
6615 return;
6616
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006617 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6618 return;
6619
6620 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006621 if (buf == NULL)
6622 return;
6623 term = buf->b_term;
6624 if (term->tl_vterm == NULL)
6625 return;
6626
6627 list = rettv->vval.v_list;
6628 state = vterm_obtain_state(term->tl_vterm);
6629 for (index = 0; index < 16; index++)
6630 {
6631 vterm_state_get_palette_color(state, index, &color);
6632 sprintf((char *)hexbuf, "#%02x%02x%02x",
6633 color.red, color.green, color.blue);
6634 if (list_append_string(list, hexbuf, 7) == FAIL)
6635 return;
6636 }
6637}
6638
6639/*
6640 * "term_setansicolors(buf, list)" function
6641 */
6642 void
6643f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6644{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006645 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006646 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006647 listitem_T *li;
6648 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006649
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006650 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006651 && (check_for_buffer_arg(argvars, 0) == FAIL
6652 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006653 return;
6654
6655 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006656 if (buf == NULL)
6657 return;
6658 term = buf->b_term;
6659 if (term->tl_vterm == NULL)
6660 return;
6661
Bram Moolenaard83392a2022-09-01 12:22:46 +01006662 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006663 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006664
LemonBoyb2b3acb2022-05-20 10:10:34 +01006665 if (argvars[1].vval.v_list->lv_first == &range_list_item
6666 || argvars[1].vval.v_list->lv_len != 16)
6667 {
Bram Moolenaar23919542023-05-05 22:12:22 +01006668 semsg(_(e_invalid_value_for_argument_str), "\"colors\"");
LemonBoyb2b3acb2022-05-20 10:10:34 +01006669 return;
6670 }
6671
6672 if (term->tl_palette == NULL)
6673 term->tl_palette = ALLOC_MULT(long_u, 16);
6674 if (term->tl_palette == NULL)
6675 return;
6676
6677 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6678 {
6679 char_u *color_name;
6680 guicolor_T guicolor;
6681
6682 color_name = tv_get_string_chk(&li->li_tv);
6683 if (color_name == NULL)
6684 return;
6685
6686 guicolor = GUI_GET_COLOR(color_name);
6687 if (guicolor == INVALCOLOR)
6688 {
6689 semsg(_(e_cannot_allocate_color_str), color_name);
6690 return;
6691 }
6692
6693 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6694 }
6695
6696 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006697}
6698#endif
6699
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006700/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006701 * "term_setapi(buf, api)" function
6702 */
6703 void
6704f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6705{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006706 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006707 term_T *term;
6708 char_u *api;
6709
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006710 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006711 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006712 || check_for_string_arg(argvars, 1) == FAIL))
6713 return;
6714
6715 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006716 if (buf == NULL)
6717 return;
6718 term = buf->b_term;
6719 vim_free(term->tl_api);
6720 api = tv_get_string_chk(&argvars[1]);
6721 if (api != NULL)
6722 term->tl_api = vim_strsave(api);
6723 else
6724 term->tl_api = NULL;
6725}
6726
6727/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006728 * "term_setrestore(buf, command)" function
6729 */
6730 void
6731f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6732{
6733#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006734 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006735 term_T *term;
6736 char_u *cmd;
6737
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006738 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006739 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006740 || check_for_string_arg(argvars, 1) == FAIL))
6741 return;
6742
6743 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006744 if (buf == NULL)
6745 return;
6746 term = buf->b_term;
6747 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006748 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006749 if (cmd != NULL)
6750 term->tl_command = vim_strsave(cmd);
6751 else
6752 term->tl_command = NULL;
6753#endif
6754}
6755
6756/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006757 * "term_setkill(buf, how)" function
6758 */
6759 void
6760f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6761{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006762 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006763 term_T *term;
6764 char_u *how;
6765
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006766 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006767 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006768 || check_for_string_arg(argvars, 1) == FAIL))
6769 return;
6770
6771 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006772 if (buf == NULL)
6773 return;
6774 term = buf->b_term;
6775 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006776 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006777 if (how != NULL)
6778 term->tl_kill = vim_strsave(how);
6779 else
6780 term->tl_kill = NULL;
6781}
6782
6783/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006784 * "term_start(command, options)" function
6785 */
6786 void
6787f_term_start(typval_T *argvars, typval_T *rettv)
6788{
6789 jobopt_T opt;
6790 buf_T *buf;
6791
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006792 if (in_vim9script()
6793 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6794 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6795 return;
6796
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006797 init_job_options(&opt);
6798 if (argvars[1].v_type != VAR_UNKNOWN
6799 && get_job_options(&argvars[1], &opt,
6800 JO_TIMEOUT_ALL + JO_STOPONEXIT
6801 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6802 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6803 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6804 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006805 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006806 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006807 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006808 return;
6809
Bram Moolenaar13568252018-03-16 20:46:58 +01006810 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006811
6812 if (buf != NULL && buf->b_term != NULL)
6813 rettv->vval.v_number = buf->b_fnum;
6814}
6815
6816/*
6817 * "term_wait" function
6818 */
6819 void
6820f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6821{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006822 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006823
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006824 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006825 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006826 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006827 return;
6828
6829 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006830 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006831 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006832 if (buf->b_term->tl_job == NULL)
6833 {
6834 ch_log(NULL, "term_wait(): no job to wait for");
6835 return;
6836 }
6837 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006838 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006839 return;
6840
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006841 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006842 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006843 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6844 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006845 // The job is dead, keep reading channel I/O until the channel is
6846 // closed. buf->b_term may become NULL if the terminal was closed while
6847 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006848 ch_log(NULL, "term_wait(): waiting for channel to close");
6849 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6850 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006851 term_flush_messages();
6852
Bram Moolenaard45aa552018-05-21 22:50:29 +02006853 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006854 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006855 // If the terminal is closed when the channel is closed the
6856 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006857 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006858 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6859 // came here from a close callback, only wait one time
6860 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006861 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006862
6863 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006864 }
6865 else
6866 {
6867 long wait = 10L;
6868
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006869 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006870
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006871 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006872 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006873 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006874 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006875
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006876 // Flushing messages on channels is hopefully sufficient.
6877 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006878 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006879 }
6880}
6881
6882/*
6883 * Called when a channel has sent all the lines to a terminal.
6884 * Send a CTRL-D to mark the end of the text.
6885 */
6886 void
6887term_send_eof(channel_T *ch)
6888{
6889 term_T *term;
6890
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006891 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006892 if (term->tl_job == ch->ch_job)
6893 {
6894 if (term->tl_eof_chars != NULL)
6895 {
6896 channel_send(ch, PART_IN, term->tl_eof_chars,
6897 (int)STRLEN(term->tl_eof_chars), NULL);
6898 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6899 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006900# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006901 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006902 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006903 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6904# endif
6905 }
6906}
6907
Bram Moolenaar113e1072019-01-20 15:30:40 +01006908#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006909 job_T *
6910term_getjob(term_T *term)
6911{
6912 return term != NULL ? term->tl_job : NULL;
6913}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006914#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006915
Bram Moolenaar4f974752019-02-17 17:44:42 +01006916# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006917
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006918///////////////////////////////////////
6919// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006920#ifdef PROTO
6921typedef int COORD;
6922typedef int DWORD;
6923typedef int HANDLE;
6924typedef int *DWORD_PTR;
6925typedef int HPCON;
6926typedef int HRESULT;
6927typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006928typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006929typedef int PSIZE_T;
6930typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006931typedef int BOOL;
6932# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006933#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006934
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006935HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6936HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6937HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006938BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6939BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6940void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006941
6942 static int
6943dyn_conpty_init(int verbose)
6944{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006945 static HMODULE hKerneldll = NULL;
6946 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006947 static struct
6948 {
6949 char *name;
6950 FARPROC *ptr;
6951 } conpty_entry[] =
6952 {
6953 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6954 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6955 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6956 {"InitializeProcThreadAttributeList",
6957 (FARPROC*)&pInitializeProcThreadAttributeList},
6958 {"UpdateProcThreadAttribute",
6959 (FARPROC*)&pUpdateProcThreadAttribute},
6960 {"DeleteProcThreadAttributeList",
6961 (FARPROC*)&pDeleteProcThreadAttributeList},
6962 {NULL, NULL}
6963 };
6964
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006965 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006966 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006967 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006968 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006969 return FAIL;
6970 }
6971
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006972 // No need to initialize twice.
6973 if (hKerneldll)
6974 return OK;
6975
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006976 hKerneldll = vimLoadLib("kernel32.dll");
6977 for (i = 0; conpty_entry[i].name != NULL
6978 && conpty_entry[i].ptr != NULL; ++i)
6979 {
6980 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6981 conpty_entry[i].name)) == NULL)
6982 {
6983 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006984 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006985 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006986 return FAIL;
6987 }
6988 }
6989
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006990 return OK;
6991}
6992
6993 static int
6994conpty_term_and_job_init(
6995 term_T *term,
6996 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006997 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006998 jobopt_T *opt,
6999 jobopt_T *orig_opt)
7000{
7001 WCHAR *cmd_wchar = NULL;
7002 WCHAR *cmd_wchar_copy = NULL;
7003 WCHAR *cwd_wchar = NULL;
7004 WCHAR *env_wchar = NULL;
7005 channel_T *channel = NULL;
7006 job_T *job = NULL;
7007 HANDLE jo = NULL;
7008 garray_T ga_cmd, ga_env;
7009 char_u *cmd = NULL;
7010 HRESULT hr;
7011 COORD consize;
7012 SIZE_T breq;
7013 PROCESS_INFORMATION proc_info;
7014 HANDLE i_theirs = NULL;
7015 HANDLE o_theirs = NULL;
7016 HANDLE i_ours = NULL;
7017 HANDLE o_ours = NULL;
7018
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007019 ga_init2(&ga_cmd, sizeof(char*), 20);
7020 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007021
7022 if (argvar->v_type == VAR_STRING)
7023 {
7024 cmd = argvar->vval.v_string;
7025 }
7026 else if (argvar->v_type == VAR_LIST)
7027 {
7028 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
7029 goto failed;
7030 cmd = ga_cmd.ga_data;
7031 }
7032 if (cmd == NULL || *cmd == NUL)
7033 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007034 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007035 goto failed;
7036 }
7037
7038 term->tl_arg0_cmd = vim_strsave(cmd);
7039
7040 cmd_wchar = enc_to_utf16(cmd, NULL);
7041
7042 if (cmd_wchar != NULL)
7043 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007044 // Request by CreateProcessW
7045 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007046 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007047 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
7048 }
7049
7050 ga_clear(&ga_cmd);
7051 if (cmd_wchar == NULL)
7052 goto failed;
7053 if (opt->jo_cwd != NULL)
7054 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
7055
7056 win32_build_env(opt->jo_env, &ga_env, TRUE);
7057 env_wchar = ga_env.ga_data;
7058
7059 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
7060 goto failed;
7061 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
7062 goto failed;
7063
7064 consize.X = term->tl_cols;
7065 consize.Y = term->tl_rows;
7066 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
7067 &term->tl_conpty);
7068 if (FAILED(hr))
7069 goto failed;
7070
7071 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
7072
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007073 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007074 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007075 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007076 if (!term->tl_siex.lpAttributeList)
7077 goto failed;
7078 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
7079 0, &breq))
7080 goto failed;
7081 if (!pUpdateProcThreadAttribute(
7082 term->tl_siex.lpAttributeList, 0,
7083 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
7084 sizeof(HPCON), NULL, NULL))
7085 goto failed;
7086
7087 channel = add_channel();
7088 if (channel == NULL)
7089 goto failed;
7090
7091 job = job_alloc();
7092 if (job == NULL)
7093 goto failed;
7094 if (argvar->v_type == VAR_STRING)
7095 {
7096 int argc;
7097
7098 build_argv_from_string(cmd, &job->jv_argv, &argc);
7099 }
7100 else
7101 {
7102 int argc;
7103
7104 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7105 }
7106
7107 if (opt->jo_set & JO_IN_BUF)
7108 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7109
7110 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
7111 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02007112 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007113 env_wchar, cwd_wchar,
7114 &term->tl_siex.StartupInfo, &proc_info))
7115 goto failed;
7116
7117 CloseHandle(i_theirs);
7118 CloseHandle(o_theirs);
7119
7120 channel_set_pipes(channel,
7121 (sock_T)i_ours,
7122 (sock_T)o_ours,
7123 (sock_T)o_ours);
7124
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007125 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007126 channel->ch_write_text_mode = TRUE;
7127
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007128 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007129 channel->ch_anonymous_pipe = TRUE;
7130
7131 jo = CreateJobObject(NULL, NULL);
7132 if (jo == NULL)
7133 goto failed;
7134
7135 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7136 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007137 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007138 CloseHandle(jo);
7139 jo = NULL;
7140 }
7141
7142 ResumeThread(proc_info.hThread);
7143 CloseHandle(proc_info.hThread);
7144
7145 vim_free(cmd_wchar);
7146 vim_free(cmd_wchar_copy);
7147 vim_free(cwd_wchar);
7148 vim_free(env_wchar);
7149
7150 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7151 goto failed;
7152
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007153#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007154 if (term_use_palette())
7155 {
7156 if (term->tl_palette != NULL)
7157 set_vterm_palette(term->tl_vterm, term->tl_palette);
7158 else
7159 init_vterm_ansi_colors(term->tl_vterm);
7160 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007161#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007162
7163 channel_set_job(channel, job, opt);
7164 job_set_options(job, opt);
7165
7166 job->jv_channel = channel;
7167 job->jv_proc_info = proc_info;
7168 job->jv_job_object = jo;
7169 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007170 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007171 ++job->jv_refcount;
7172 term->tl_job = job;
7173
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007174 // Redirecting stdout and stderr doesn't work at the job level. Instead
7175 // open the file here and handle it in. opt->jo_io was changed in
7176 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007177 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7178 {
7179 char_u *fname = opt->jo_io_name[PART_OUT];
7180
7181 ch_log(channel, "Opening output file %s", fname);
7182 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7183 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007184 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007185 }
7186
7187 return OK;
7188
7189failed:
7190 ga_clear(&ga_cmd);
7191 ga_clear(&ga_env);
7192 vim_free(cmd_wchar);
7193 vim_free(cmd_wchar_copy);
7194 vim_free(cwd_wchar);
7195 if (channel != NULL)
7196 channel_clear(channel);
7197 if (job != NULL)
7198 {
7199 job->jv_channel = NULL;
7200 job_cleanup(job);
7201 }
7202 term->tl_job = NULL;
7203 if (jo != NULL)
7204 CloseHandle(jo);
7205
7206 if (term->tl_siex.lpAttributeList != NULL)
7207 {
7208 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7209 vim_free(term->tl_siex.lpAttributeList);
7210 }
7211 term->tl_siex.lpAttributeList = NULL;
7212 if (o_theirs != NULL)
7213 CloseHandle(o_theirs);
7214 if (o_ours != NULL)
7215 CloseHandle(o_ours);
7216 if (i_ours != NULL)
7217 CloseHandle(i_ours);
7218 if (i_theirs != NULL)
7219 CloseHandle(i_theirs);
7220 if (term->tl_conpty != NULL)
7221 pClosePseudoConsole(term->tl_conpty);
7222 term->tl_conpty = NULL;
7223 return FAIL;
7224}
7225
7226 static void
7227conpty_term_report_winsize(term_T *term, int rows, int cols)
7228{
7229 COORD consize;
7230
7231 consize.X = cols;
7232 consize.Y = rows;
7233 pResizePseudoConsole(term->tl_conpty, consize);
7234}
7235
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007236 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007237term_free_conpty(term_T *term)
7238{
7239 if (term->tl_siex.lpAttributeList != NULL)
7240 {
7241 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7242 vim_free(term->tl_siex.lpAttributeList);
7243 }
7244 term->tl_siex.lpAttributeList = NULL;
7245 if (term->tl_conpty != NULL)
7246 pClosePseudoConsole(term->tl_conpty);
7247 term->tl_conpty = NULL;
7248}
7249
7250 int
7251use_conpty(void)
7252{
7253 return has_conpty;
7254}
7255
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007256# ifndef PROTO
7257
7258#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7259#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007260#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007261
7262void* (*winpty_config_new)(UINT64, void*);
7263void* (*winpty_open)(void*, void*);
7264void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7265BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7266void (*winpty_config_set_mouse_mode)(void*, int);
7267void (*winpty_config_set_initial_size)(void*, int, int);
7268LPCWSTR (*winpty_conin_name)(void*);
7269LPCWSTR (*winpty_conout_name)(void*);
7270LPCWSTR (*winpty_conerr_name)(void*);
7271void (*winpty_free)(void*);
7272void (*winpty_config_free)(void*);
7273void (*winpty_spawn_config_free)(void*);
7274void (*winpty_error_free)(void*);
7275LPCWSTR (*winpty_error_msg)(void*);
7276BOOL (*winpty_set_size)(void*, int, int, void*);
7277HANDLE (*winpty_agent_process)(void*);
7278
7279#define WINPTY_DLL "winpty.dll"
7280
7281static HINSTANCE hWinPtyDLL = NULL;
7282# endif
7283
7284 static int
7285dyn_winpty_init(int verbose)
7286{
7287 int i;
7288 static struct
7289 {
7290 char *name;
7291 FARPROC *ptr;
7292 } winpty_entry[] =
7293 {
7294 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7295 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7296 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7297 {"winpty_config_set_mouse_mode",
7298 (FARPROC*)&winpty_config_set_mouse_mode},
7299 {"winpty_config_set_initial_size",
7300 (FARPROC*)&winpty_config_set_initial_size},
7301 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7302 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7303 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7304 {"winpty_free", (FARPROC*)&winpty_free},
7305 {"winpty_open", (FARPROC*)&winpty_open},
7306 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7307 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7308 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7309 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7310 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7311 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7312 {NULL, NULL}
7313 };
7314
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007315 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007316 if (hWinPtyDLL)
7317 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007318 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7319 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007320 if (*p_winptydll != NUL)
7321 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7322 if (!hWinPtyDLL)
7323 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7324 if (!hWinPtyDLL)
7325 {
7326 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007327 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007328 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7329 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007330 return FAIL;
7331 }
7332 for (i = 0; winpty_entry[i].name != NULL
7333 && winpty_entry[i].ptr != NULL; ++i)
7334 {
7335 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7336 winpty_entry[i].name)) == NULL)
7337 {
7338 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007339 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007340 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007341 return FAIL;
7342 }
7343 }
7344
7345 return OK;
7346}
7347
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007348 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007349winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007350 term_T *term,
7351 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007352 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007353 jobopt_T *opt,
7354 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007355{
7356 WCHAR *cmd_wchar = NULL;
7357 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007358 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007359 channel_T *channel = NULL;
7360 job_T *job = NULL;
7361 DWORD error;
7362 HANDLE jo = NULL;
7363 HANDLE child_process_handle;
7364 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007365 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007366 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007367 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007368 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007369
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007370 ga_init2(&ga_cmd, sizeof(char*), 20);
7371 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007372
7373 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007374 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007375 cmd = argvar->vval.v_string;
7376 }
7377 else if (argvar->v_type == VAR_LIST)
7378 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007379 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007380 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007381 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007382 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007383 if (cmd == NULL || *cmd == NUL)
7384 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007385 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007386 goto failed;
7387 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007388
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007389 term->tl_arg0_cmd = vim_strsave(cmd);
7390
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007391 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007392 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007393 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007394 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007395 if (opt->jo_cwd != NULL)
7396 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007397
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007398 win32_build_env(opt->jo_env, &ga_env, TRUE);
7399 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007400
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007401 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7402 if (term->tl_winpty_config == NULL)
7403 goto failed;
7404
7405 winpty_config_set_mouse_mode(term->tl_winpty_config,
7406 WINPTY_MOUSE_MODE_FORCE);
7407 winpty_config_set_initial_size(term->tl_winpty_config,
7408 term->tl_cols, term->tl_rows);
7409 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7410 if (term->tl_winpty == NULL)
7411 goto failed;
7412
7413 spawn_config = winpty_spawn_config_new(
7414 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7415 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7416 NULL,
7417 cmd_wchar,
7418 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007419 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007420 &winpty_err);
7421 if (spawn_config == NULL)
7422 goto failed;
7423
7424 channel = add_channel();
7425 if (channel == NULL)
7426 goto failed;
7427
7428 job = job_alloc();
7429 if (job == NULL)
7430 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007431 if (argvar->v_type == VAR_STRING)
7432 {
7433 int argc;
7434
7435 build_argv_from_string(cmd, &job->jv_argv, &argc);
7436 }
7437 else
7438 {
7439 int argc;
7440
7441 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7442 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007443
7444 if (opt->jo_set & JO_IN_BUF)
7445 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7446
7447 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7448 &child_thread_handle, &error, &winpty_err))
7449 goto failed;
7450
7451 channel_set_pipes(channel,
7452 (sock_T)CreateFileW(
7453 winpty_conin_name(term->tl_winpty),
7454 GENERIC_WRITE, 0, NULL,
7455 OPEN_EXISTING, 0, NULL),
7456 (sock_T)CreateFileW(
7457 winpty_conout_name(term->tl_winpty),
7458 GENERIC_READ, 0, NULL,
7459 OPEN_EXISTING, 0, NULL),
7460 (sock_T)CreateFileW(
7461 winpty_conerr_name(term->tl_winpty),
7462 GENERIC_READ, 0, NULL,
7463 OPEN_EXISTING, 0, NULL));
7464
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007465 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007466 channel->ch_write_text_mode = TRUE;
7467
7468 jo = CreateJobObject(NULL, NULL);
7469 if (jo == NULL)
7470 goto failed;
7471
7472 if (!AssignProcessToJobObject(jo, child_process_handle))
7473 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007474 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007475 CloseHandle(jo);
7476 jo = NULL;
7477 }
7478
7479 winpty_spawn_config_free(spawn_config);
7480 vim_free(cmd_wchar);
7481 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007482 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007483
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007484 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7485 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007486
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007487#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007488 if (term_use_palette())
7489 {
7490 if (term->tl_palette != NULL)
7491 set_vterm_palette(term->tl_vterm, term->tl_palette);
7492 else
7493 init_vterm_ansi_colors(term->tl_vterm);
7494 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007495#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007496
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007497 channel_set_job(channel, job, opt);
7498 job_set_options(job, opt);
7499
7500 job->jv_channel = channel;
7501 job->jv_proc_info.hProcess = child_process_handle;
7502 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7503 job->jv_job_object = jo;
7504 job->jv_status = JOB_STARTED;
7505 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007506 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007507 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007508 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007509 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007510 ++job->jv_refcount;
7511 term->tl_job = job;
7512
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007513 // Redirecting stdout and stderr doesn't work at the job level. Instead
7514 // open the file here and handle it in. opt->jo_io was changed in
7515 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007516 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7517 {
7518 char_u *fname = opt->jo_io_name[PART_OUT];
7519
7520 ch_log(channel, "Opening output file %s", fname);
7521 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7522 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007523 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007524 }
7525
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007526 return OK;
7527
7528failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007529 ga_clear(&ga_cmd);
7530 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007531 vim_free(cmd_wchar);
7532 vim_free(cwd_wchar);
7533 if (spawn_config != NULL)
7534 winpty_spawn_config_free(spawn_config);
7535 if (channel != NULL)
7536 channel_clear(channel);
7537 if (job != NULL)
7538 {
7539 job->jv_channel = NULL;
7540 job_cleanup(job);
7541 }
7542 term->tl_job = NULL;
7543 if (jo != NULL)
7544 CloseHandle(jo);
7545 if (term->tl_winpty != NULL)
7546 winpty_free(term->tl_winpty);
7547 term->tl_winpty = NULL;
7548 if (term->tl_winpty_config != NULL)
7549 winpty_config_free(term->tl_winpty_config);
7550 term->tl_winpty_config = NULL;
7551 if (winpty_err != NULL)
7552 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007553 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007554 (short_u *)winpty_error_msg(winpty_err), NULL);
7555
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007556 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007557 winpty_error_free(winpty_err);
7558 }
7559 return FAIL;
7560}
7561
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007562/*
7563 * Create a new terminal of "rows" by "cols" cells.
7564 * Store a reference in "term".
7565 * Return OK or FAIL.
7566 */
7567 static int
7568term_and_job_init(
7569 term_T *term,
7570 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007571 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007572 jobopt_T *opt,
7573 jobopt_T *orig_opt)
7574{
7575 int use_winpty = FALSE;
7576 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007577 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007578
7579 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7580 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7581
7582 if (!has_winpty && !has_conpty)
7583 // If neither is available give the errors for winpty, since when
7584 // conpty is not available it can't be installed either.
7585 return dyn_winpty_init(TRUE);
7586
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007587 if (opt->jo_tty_type != NUL)
7588 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007589
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007590 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007591 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007592 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007593 use_conpty = TRUE;
7594 else if (has_winpty)
7595 use_winpty = TRUE;
7596 // else: error
7597 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007598 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007599 {
7600 if (has_winpty)
7601 use_winpty = TRUE;
7602 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007603 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007604 {
7605 if (has_conpty)
7606 use_conpty = TRUE;
7607 else
7608 return dyn_conpty_init(TRUE);
7609 }
7610
7611 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007612 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007613
7614 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007615 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007616
7617 // error
7618 return dyn_winpty_init(TRUE);
7619}
7620
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007621 static int
7622create_pty_only(term_T *term, jobopt_T *options)
7623{
7624 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7625 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7626 char in_name[80], out_name[80];
7627 channel_T *channel = NULL;
7628
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007629 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7630 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007631
7632 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7633 GetCurrentProcessId(),
7634 curbuf->b_fnum);
7635 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7636 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7637 PIPE_UNLIMITED_INSTANCES,
7638 0, 0, NMPWAIT_NOWAIT, NULL);
7639 if (hPipeIn == INVALID_HANDLE_VALUE)
7640 goto failed;
7641
7642 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7643 GetCurrentProcessId(),
7644 curbuf->b_fnum);
7645 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7646 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7647 PIPE_UNLIMITED_INSTANCES,
7648 0, 0, 0, NULL);
7649 if (hPipeOut == INVALID_HANDLE_VALUE)
7650 goto failed;
7651
7652 ConnectNamedPipe(hPipeIn, NULL);
7653 ConnectNamedPipe(hPipeOut, NULL);
7654
7655 term->tl_job = job_alloc();
7656 if (term->tl_job == NULL)
7657 goto failed;
7658 ++term->tl_job->jv_refcount;
7659
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007660 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007661 term->tl_job->jv_status = JOB_FINISHED;
7662
7663 channel = add_channel();
7664 if (channel == NULL)
7665 goto failed;
7666 term->tl_job->jv_channel = channel;
7667 channel->ch_keep_open = TRUE;
7668 channel->ch_named_pipe = TRUE;
7669
7670 channel_set_pipes(channel,
7671 (sock_T)hPipeIn,
7672 (sock_T)hPipeOut,
7673 (sock_T)hPipeOut);
7674 channel_set_job(channel, term->tl_job, options);
7675 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7676 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7677
7678 return OK;
7679
7680failed:
7681 if (hPipeIn != NULL)
7682 CloseHandle(hPipeIn);
7683 if (hPipeOut != NULL)
7684 CloseHandle(hPipeOut);
7685 return FAIL;
7686}
7687
7688/*
7689 * Free the terminal emulator part of "term".
7690 */
7691 static void
7692term_free_vterm(term_T *term)
7693{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007694 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007695 if (term->tl_winpty != NULL)
7696 winpty_free(term->tl_winpty);
7697 term->tl_winpty = NULL;
7698 if (term->tl_winpty_config != NULL)
7699 winpty_config_free(term->tl_winpty_config);
7700 term->tl_winpty_config = NULL;
7701 if (term->tl_vterm != NULL)
7702 vterm_free(term->tl_vterm);
7703 term->tl_vterm = NULL;
7704}
7705
7706/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007707 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007708 */
7709 static void
7710term_report_winsize(term_T *term, int rows, int cols)
7711{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007712 if (term->tl_conpty)
7713 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007714 if (term->tl_winpty)
7715 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7716}
7717
7718 int
7719terminal_enabled(void)
7720{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007721 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007722}
7723
7724# else
7725
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007726///////////////////////////////////////
7727// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007728
7729/*
7730 * Create a new terminal of "rows" by "cols" cells.
7731 * Start job for "cmd".
7732 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007733 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007734 * Return OK or FAIL.
7735 */
7736 static int
7737term_and_job_init(
7738 term_T *term,
7739 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007740 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007741 jobopt_T *opt,
7742 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007743{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007744 term->tl_arg0_cmd = NULL;
7745
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007746 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7747 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007748
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007749#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007750 if (term_use_palette())
7751 {
7752 if (term->tl_palette != NULL)
7753 set_vterm_palette(term->tl_vterm, term->tl_palette);
7754 else
7755 init_vterm_ansi_colors(term->tl_vterm);
7756 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007757#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007758
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007759 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007760 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007761 if (term->tl_job != NULL)
7762 ++term->tl_job->jv_refcount;
7763
7764 return term->tl_job != NULL
7765 && term->tl_job->jv_channel != NULL
7766 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7767}
7768
7769 static int
7770create_pty_only(term_T *term, jobopt_T *opt)
7771{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007772 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7773 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007774
7775 term->tl_job = job_alloc();
7776 if (term->tl_job == NULL)
7777 return FAIL;
7778 ++term->tl_job->jv_refcount;
7779
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007780 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007781 term->tl_job->jv_status = JOB_FINISHED;
7782
7783 return mch_create_pty_channel(term->tl_job, opt);
7784}
7785
7786/*
7787 * Free the terminal emulator part of "term".
7788 */
7789 static void
7790term_free_vterm(term_T *term)
7791{
7792 if (term->tl_vterm != NULL)
7793 vterm_free(term->tl_vterm);
7794 term->tl_vterm = NULL;
7795}
7796
7797/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007798 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007799 */
7800 static void
7801term_report_winsize(term_T *term, int rows, int cols)
7802{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007803 // Use an ioctl() to report the new window size to the job.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007804 if (term->tl_job == NULL || term->tl_job->jv_channel == NULL)
7805 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007806
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007807 int fd = -1;
7808 int part;
7809
7810 for (part = PART_OUT; part < PART_COUNT; ++part)
7811 {
7812 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
7813 if (mch_isatty(fd))
7814 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007815 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007816 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7817 mch_signal_job(term->tl_job, (char_u *)"winch");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007818}
7819
7820# endif
7821
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007822#endif // FEAT_TERMINAL