blob: eb27fa5c4c5a2bb2d3faf50ae666ec3ec36b30f0 [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
Christian Brabandt991657e2024-10-15 20:31:14 +0200449 pos_T save_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200450
451 if (check_restricted() || check_secure())
452 return NULL;
Bram Moolenaare5b44862021-05-30 13:54:03 +0200453 if (cmdwin_type != 0)
454 {
455 emsg(_(e_cannot_open_terminal_from_command_line_window));
456 return NULL;
457 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200458
459 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
460 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
461 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100462 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
463 || (argvar != NULL
464 && argvar->v_type == VAR_LIST
465 && argvar->vval.v_list != NULL
466 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200467 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000468 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200469 return NULL;
470 }
471
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200472 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200473 if (term == NULL)
474 return NULL;
475 term->tl_dirty_row_end = MAX_ROW;
476 term->tl_cursor_visible = TRUE;
477 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
478 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100479#ifdef FEAT_GUI
480 term->tl_system = (flags & TERM_START_SYSTEM);
481#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200482 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100483 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200484 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200485
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200486 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200487 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200488 if (opt->jo_curwin)
489 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100490 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100491 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200492 {
493 no_write_message();
494 vim_free(term);
495 return NULL;
496 }
497 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200498 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
499 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
500 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200501 {
502 vim_free(term);
503 return NULL;
504 }
505 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100506 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200507 {
508 buf_T *buf;
509
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100510 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100511 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200512 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
513 BLN_NEW | BLN_LISTED);
514 if (buf == NULL || ml_open(buf) == FAIL)
515 {
516 vim_free(term);
517 return NULL;
518 }
519 old_curbuf = curbuf;
520 --curbuf->b_nwindows;
521 curbuf = buf;
Christian Brabandt991657e2024-10-15 20:31:14 +0200522 save_cursor = curwin->w_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200523 curwin->w_buffer = buf;
524 ++curbuf->b_nwindows;
525 }
526 else
527 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100528 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200529 split_ea.cmdidx = CMD_new;
530 split_ea.cmd = (char_u *)"new";
531 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100532 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200533 {
534 split_ea.line2 = opt->jo_term_rows;
535 split_ea.addr_count = 1;
536 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100537 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200538 {
539 split_ea.line2 = opt->jo_term_cols;
540 split_ea.addr_count = 1;
541 }
542
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200543 int cmod_split_modified = FALSE;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100544 if (vertical)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200545 {
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200546 if (!(cmdmod.cmod_split & WSP_VERT))
547 cmod_split_modified = TRUE;
Bram Moolenaare1004402020-10-24 20:49:43 +0200548 cmdmod.cmod_split |= WSP_VERT;
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200549 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200550 ex_splitview(&split_ea);
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200551 if (cmod_split_modified)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200552 cmdmod.cmod_split &= ~WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200553 if (curwin == old_curwin)
554 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100555 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200556 vim_free(term);
557 return NULL;
558 }
559 }
560 term->tl_buffer = curbuf;
561 curbuf->b_term = term;
562
563 if (!opt->jo_hidden)
564 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100565 // Only one size was taken care of with :new, do the other one. With
566 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100567 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100569 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200570 win_setwidth(opt->jo_term_cols);
571 }
572
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100573 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200574 term->tl_next = first_term;
575 first_term = term;
576
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100577 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
578
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200579 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100580 {
581 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200582 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100583 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100584 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100585 {
586 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100587 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100588 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200589 else
590 {
591 int i;
592 size_t len;
593 char_u *cmd, *p;
594
595 if (argvar->v_type == VAR_STRING)
596 {
597 cmd = argvar->vval.v_string;
598 if (cmd == NULL)
599 cmd = (char_u *)"";
600 else if (STRCMP(cmd, "NONE") == 0)
601 cmd = (char_u *)"pty";
602 }
603 else if (argvar->v_type != VAR_LIST
604 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100605 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100606 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200607 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
608 cmd = (char_u*)"";
609
610 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200611 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200612
613 for (i = 0; p != NULL; ++i)
614 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100615 // Prepend a ! to the command name to avoid the buffer name equals
616 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200617 if (i == 0)
618 vim_snprintf((char *)p, len, "!%s", cmd);
619 else
620 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
621 if (buflist_findname(p) == NULL)
622 {
623 vim_free(curbuf->b_ffname);
624 curbuf->b_ffname = p;
625 break;
626 }
627 }
628 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100629 vim_free(curbuf->b_sfname);
630 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200631 curbuf->b_fname = curbuf->b_ffname;
632
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100633 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
634
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200635 if (opt->jo_term_opencmd != NULL)
636 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
637
638 if (opt->jo_eof_chars != NULL)
639 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
640
641 set_string_option_direct((char_u *)"buftype", -1,
642 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200643 // Avoid that 'buftype' is reset when this buffer is entered.
644 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200645
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100646 // Mark the buffer as not modifiable. It can only be made modifiable after
647 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200648 curbuf->b_p_ma = FALSE;
649
Bram Moolenaarb936b792020-09-04 18:34:09 +0200650 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100651#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200652 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
653#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200654 setup_job_options(opt, term->tl_rows, term->tl_cols);
655
Bram Moolenaar13568252018-03-16 20:46:58 +0100656 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100657 return curbuf;
658
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100659#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100660 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100661 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100662 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100663 else if (argvar->v_type == VAR_STRING)
664 {
665 char_u *cmd = argvar->vval.v_string;
666
667 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
668 term->tl_command = vim_strsave(cmd);
669 }
670 else if (argvar->v_type == VAR_LIST
671 && argvar->vval.v_list != NULL
672 && argvar->vval.v_list->lv_len > 0)
673 {
674 garray_T ga;
675 listitem_T *item;
676
677 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200678 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100679 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100680 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100681 char_u *p;
682
683 if (s == NULL)
684 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100685 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100686 if (p == NULL)
687 break;
688 ga_concat(&ga, p);
689 vim_free(p);
690 ga_append(&ga, ' ');
691 }
692 if (item == NULL)
693 {
694 ga_append(&ga, NUL);
695 term->tl_command = ga.ga_data;
696 }
697 else
698 ga_clear(&ga);
699 }
700#endif
701
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100702 if (opt->jo_term_kill != NULL)
703 {
704 char_u *p = skiptowhite(opt->jo_term_kill);
705
706 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
707 }
708
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200709 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100710 {
711 char_u *p = skiptowhite(opt->jo_term_api);
712
713 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
714 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200715 else
716 term->tl_api = vim_strsave((char_u *)"Tapi_");
717
Bram Moolenaar83d47902020-03-26 20:34:00 +0100718 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
719 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
720
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100721#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100722 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
723 if (opt->jo_set2 & JO2_ANSI_COLORS)
724 {
725 term->tl_palette = ALLOC_MULT(long_u, 16);
726 if (term->tl_palette == NULL)
727 {
728 vim_free(term);
729 return NULL;
730 }
731 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
732 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100733#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100734
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100735 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100736 if (argv == NULL
737 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200738 && argvar->vval.v_string != NULL
739 && STRCMP(argvar->vval.v_string, "NONE") == 0)
740 res = create_pty_only(term, opt);
741 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200742 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200743
744 newbuf = curbuf;
745 if (res == OK)
746 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100747 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200748 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
749 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100750#ifdef FEAT_GUI
751 if (term->tl_system)
752 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100753 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100754 term->tl_toprow = msg_row + 1;
755 term->tl_dirty_row_end = 0;
756 }
757#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200758
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100759 // Make sure we don't get stuck on sending keys to the job, it leads to
760 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200761 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
762
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200763 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200764 {
765 --curbuf->b_nwindows;
766 curbuf = old_curbuf;
767 curwin->w_buffer = curbuf;
Christian Brabandt991657e2024-10-15 20:31:14 +0200768 curwin->w_cursor = save_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200769 ++curbuf->b_nwindows;
770 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000771 else if (vgetc_busy
772#ifdef FEAT_TIMERS
773 || timer_busy
774#endif
775 || input_busy)
776 {
777 char_u ignore[4];
778
779 // When waiting for input need to return and possibly end up in
780 // terminal_loop() instead.
781 ignore[0] = K_SPECIAL;
782 ignore[1] = KS_EXTRA;
783 ignore[2] = KE_IGNORE;
784 ignore[3] = NUL;
785 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
786 typebuf_was_filled = TRUE;
787 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788 }
789 else
790 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100791 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200792 return NULL;
793 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100794
Bram Moolenaar13568252018-03-16 20:46:58 +0100795 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200796 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
797 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200798 return newbuf;
799}
800
801/*
802 * ":terminal": open a terminal window and execute a job in it.
803 */
804 void
805ex_terminal(exarg_T *eap)
806{
807 typval_T argvar[2];
808 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100809 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200810 char_u *cmd;
811 char_u *tofree = NULL;
812
813 init_job_options(&opt);
814
815 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100816 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200817 {
818 char_u *p, *ep;
819
820 cmd += 2;
821 p = skiptowhite(cmd);
822 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200823 if (ep != NULL)
824 {
825 if (ep < p)
826 p = ep;
827 else
828 ep = NULL;
829 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200830
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200831 // Note: Keep this in sync with get_terminalopt_name.
832
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200833# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
834 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
835 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200836 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200837 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100838 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200839 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200840 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200841 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200842 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200843 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200844 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200845 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100846 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100847 else if (OPTARG_HAS("shell"))
848 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200849 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100850 {
851 opt.jo_set2 |= JO2_TERM_KILL;
852 opt.jo_term_kill = ep + 1;
853 p = skiptowhite(cmd);
854 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200855 else if (OPTARG_HAS("api"))
856 {
857 opt.jo_set2 |= JO2_TERM_API;
858 if (ep != NULL)
859 {
860 opt.jo_term_api = ep + 1;
861 p = skiptowhite(cmd);
862 }
863 else
864 opt.jo_term_api = NULL;
865 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100866 else if (OPTARG_HAS("rows") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200867 {
868 opt.jo_set2 |= JO2_TERM_ROWS;
869 opt.jo_term_rows = atoi((char *)ep + 1);
870 p = skiptowhite(cmd);
871 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100872 else if (OPTARG_HAS("cols") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200873 {
874 opt.jo_set2 |= JO2_TERM_COLS;
875 opt.jo_term_cols = atoi((char *)ep + 1);
876 p = skiptowhite(cmd);
877 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200878 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200879 {
880 char_u *buf = NULL;
881 char_u *keys;
882
Bram Moolenaar21109272020-01-30 16:27:20 +0100883 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200884 p = skiptowhite(cmd);
885 *p = NUL;
zeertzjq7e0bae02023-08-11 23:15:38 +0200886 keys = replace_termcodes(ep + 1, &buf, 0,
Bram Moolenaar459fd782019-10-13 16:43:39 +0200887 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200888 opt.jo_set2 |= JO2_EOF_CHARS;
889 opt.jo_eof_chars = vim_strsave(keys);
890 vim_free(buf);
891 *p = ' ';
892 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100893#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100894 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
895 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100896 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100897 int tty_type = NUL;
898
899 p = skiptowhite(cmd);
900 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
901 tty_type = 'w';
902 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
903 tty_type = 'c';
904 else
905 {
Bram Moolenaar50809a42023-05-20 16:39:07 +0100906 semsg(_(e_invalid_value_for_argument_str), "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100907 goto theend;
908 }
909 opt.jo_set2 |= JO2_TTY_TYPE;
910 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100911 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100912#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200913 else
914 {
915 if (*p)
916 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000917 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100918 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200919 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200920# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200921 cmd = skipwhite(p);
922 }
923 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100924 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100925 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200926 tofree = cmd = vim_strsave(p_sh);
927
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100928 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100929 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200930 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100931 }
932
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200933 if (eap->addr_count > 0)
934 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100935 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200936 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
937 opt.jo_io[PART_IN] = JIO_BUFFER;
938 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
939 opt.jo_in_top = eap->line1;
940 opt.jo_in_bot = eap->line2;
941 }
942
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100943 if (opt_shell && tofree == NULL)
944 {
945#ifdef UNIX
946 char **argv = NULL;
947 char_u *tofree1 = NULL;
948 char_u *tofree2 = NULL;
949
950 // :term ++shell command
951 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
952 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100953 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100954 vim_free(tofree1);
955 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100956 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100957#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100958# ifdef MSWIN
959 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
960 char_u *newcmd;
961
962 newcmd = alloc(cmdlen);
963 if (newcmd == NULL)
964 goto theend;
965 tofree = newcmd;
966 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
967 cmd = newcmd;
968# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000969 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100970 goto theend;
971# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100972#endif
973 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100974 argvar[0].v_type = VAR_STRING;
975 argvar[0].vval.v_string = cmd;
976 argvar[1].v_type = VAR_UNKNOWN;
977 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100978
979theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100980 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200981 vim_free(opt.jo_eof_chars);
982}
983
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200984 static char_u *
985get_terminalopt_name(expand_T *xp UNUSED, int idx)
986{
987 // Note: Keep this in sync with ex_terminal.
988 static char *(p_termopt_values[]) =
989 {
990 "close",
991 "noclose",
992 "open",
993 "curwin",
994 "hidden",
995 "norestore",
996 "shell",
997 "kill=",
998 "rows=",
999 "cols=",
1000 "eof=",
1001 "type=",
1002 "api=",
1003 };
1004
1005 if (idx < (int)ARRAY_LENGTH(p_termopt_values))
1006 return (char_u*)p_termopt_values[idx];
1007 return NULL;
1008}
1009
1010 static char_u *
1011get_termkill_name(expand_T *xp UNUSED, int idx)
1012{
1013 // These are platform-specific values used for job_stop(). They are defined
1014 // in each platform's mch_signal_job(). Just use a unified auto-complete
1015 // list for simplicity.
1016 static char *(p_termkill_values[]) =
1017 {
1018 "term",
1019 "hup",
1020 "quit",
1021 "int",
1022 "kill",
1023 "winch",
1024 };
1025
1026 if (idx < (int)ARRAY_LENGTH(p_termkill_values))
1027 return (char_u*)p_termkill_values[idx];
1028 return NULL;
1029}
1030
1031/*
1032 * Command-line expansion for :terminal [options]
1033 */
1034 int
1035expand_terminal_opt(
1036 char_u *pat,
1037 expand_T *xp,
1038 regmatch_T *rmp,
1039 char_u ***matches,
1040 int *numMatches)
1041{
1042 if (xp->xp_pattern > xp->xp_line && *(xp->xp_pattern-1) == '=')
1043 {
1044 char_u *(*cb)(expand_T *, int) = NULL;
1045
1046 char_u *name_end = xp->xp_pattern - 1;
1047 if (name_end - xp->xp_line >= 4
1048 && STRNCMP(name_end - 4, "kill", 4) == 0)
1049 cb = get_termkill_name;
1050
1051 if (cb != NULL)
1052 {
1053 return ExpandGeneric(
1054 pat,
1055 xp,
1056 rmp,
1057 matches,
1058 numMatches,
1059 cb,
1060 FALSE);
1061 }
1062 return FAIL;
1063 }
1064 return ExpandGeneric(
1065 pat,
1066 xp,
1067 rmp,
1068 matches,
1069 numMatches,
1070 get_terminalopt_name,
1071 FALSE);
1072}
1073
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001074#if defined(FEAT_SESSION) || defined(PROTO)
1075/*
1076 * Write a :terminal command to the session file to restore the terminal in
1077 * window "wp".
1078 * Return FAIL if writing fails.
1079 */
1080 int
Bram Moolenaar0e655112020-09-11 20:36:36 +02001081term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001082{
Bram Moolenaar0e655112020-09-11 20:36:36 +02001083 const int bufnr = wp->w_buffer->b_fnum;
1084 term_T *term = wp->w_buffer->b_term;
1085
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001086 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001087 {
1088 // There are multiple views into this terminal buffer. We don't want to
1089 // create the terminal multiple times. If it's the first time, create,
1090 // otherwise link to the first buffer.
1091 char id_as_str[NUMBUFLEN];
1092 hashitem_T *entry;
1093
1094 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
1095
1096 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
1097 if (!HASHITEM_EMPTY(entry))
1098 {
1099 // we've already opened this terminal buffer
1100 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
1101 return FAIL;
1102 return put_eol(fd);
1103 }
1104 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001105
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001106 // Create the terminal and run the command. This is not without
1107 // risk, but let's assume the user only creates a session when this
1108 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001109 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1110 term->tl_cols, term->tl_rows) < 0)
1111 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001112#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001113 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1114 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001115#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001116 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1117 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001118 if (put_eol(fd) != OK)
1119 return FAIL;
1120
1121 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1122 return FAIL;
1123
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001124 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001125 {
1126 char *hash_key = alloc(NUMBUFLEN);
1127
1128 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00001129 hash_add(terminal_bufs, (char_u *)hash_key, "terminal session");
Bram Moolenaar0e655112020-09-11 20:36:36 +02001130 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001131
1132 return put_eol(fd);
1133}
1134
1135/*
1136 * Return TRUE if "buf" has a terminal that should be restored.
1137 */
1138 int
1139term_should_restore(buf_T *buf)
1140{
1141 term_T *term = buf->b_term;
1142
1143 return term != NULL && (term->tl_command == NULL
1144 || STRCMP(term->tl_command, "NONE") != 0);
1145}
1146#endif
1147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001148/*
1149 * Free the scrollback buffer for "term".
1150 */
1151 static void
1152free_scrollback(term_T *term)
1153{
1154 int i;
1155
1156 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1157 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1158 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001159 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1160 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1161 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001162}
1163
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001164
1165// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001166static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001167
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001168/*
1169 * Free a terminal and everything it refers to.
1170 * Kills the job if there is one.
1171 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001172 * The actual terminal structure is freed later in free_unused_terminals(),
1173 * because callbacks may wipe out a buffer while the terminal is still
1174 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001175 */
1176 void
1177free_terminal(buf_T *buf)
1178{
1179 term_T *term = buf->b_term;
1180 term_T *tp;
1181
1182 if (term == NULL)
1183 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001184
1185 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001186 if (first_term == term)
1187 first_term = term->tl_next;
1188 else
1189 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1190 if (tp->tl_next == term)
1191 {
1192 tp->tl_next = term->tl_next;
1193 break;
1194 }
1195
1196 if (term->tl_job != NULL)
1197 {
1198 if (term->tl_job->jv_status != JOB_ENDED
1199 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001200 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001201 job_stop(term->tl_job, NULL, "kill");
1202 job_unref(term->tl_job);
1203 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001204 term->tl_next = terminals_to_free;
1205 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001206
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001207 buf->b_term = NULL;
1208 if (in_terminal_loop == term)
1209 in_terminal_loop = NULL;
1210}
1211
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001212 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00001213free_unused_terminals(void)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001214{
1215 while (terminals_to_free != NULL)
1216 {
1217 term_T *term = terminals_to_free;
1218
1219 terminals_to_free = term->tl_next;
1220
1221 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001222 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001223
1224 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001225 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001226 vim_free(term->tl_title);
1227#ifdef FEAT_SESSION
1228 vim_free(term->tl_command);
1229#endif
1230 vim_free(term->tl_kill);
1231 vim_free(term->tl_status_text);
1232 vim_free(term->tl_opencmd);
1233 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001234 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001235#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001236 if (term->tl_out_fd != NULL)
1237 fclose(term->tl_out_fd);
1238#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001239 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001240 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001241 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001242 vim_free(term);
1243 }
1244}
1245
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001246/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001247 * Get the part that is connected to the tty. Normally this is PART_IN, but
1248 * when writing buffer lines to the job it can be another. This makes it
1249 * possible to do "1,5term vim -".
1250 */
1251 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001252get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001253{
1254#ifdef UNIX
1255 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1256 int i;
1257
1258 for (i = 0; i < 3; ++i)
1259 {
1260 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1261
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001262 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001263 return parts[i];
1264 }
1265#endif
1266 return PART_IN;
1267}
1268
1269/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001270 * Read any vterm output and send it on the channel.
1271 */
1272 static void
1273term_forward_output(term_T *term)
1274{
1275 VTerm *vterm = term->tl_vterm;
1276 char buf[KEY_BUF_LEN];
1277 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1278
1279 if (curlen > 0)
1280 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1281 (char_u *)buf, (int)curlen, NULL);
1282}
1283
1284/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001285 * Write job output "msg[len]" to the vterm.
1286 */
1287 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001288term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001289{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001290 char_u *msg = msg_arg;
1291 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001292 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001293 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001294 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1295
1296 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1297 // the end.
1298 if (len > limit)
1299 {
1300 char_u *p = msg + len - limit;
1301
1302 p -= (*mb_head_off)(msg, p);
1303 len -= p - msg;
1304 msg = p;
1305 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001306
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001307 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001308
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001309 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001310 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001311 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001312
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001313 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001314 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1315}
1316
1317 static void
Bram Moolenaar58806c12023-04-29 14:26:02 +01001318position_cursor(win_T *wp, VTermPos *pos)
1319{
1320 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1321 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1322#ifdef FEAT_PROP_POPUP
1323 if (popup_is_popup(wp))
1324 {
1325 wp->w_wrow += popup_top_extra(wp);
1326 wp->w_wcol += popup_left_extra(wp);
1327 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
1328 }
1329 else
1330 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
1331#endif
1332 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1333}
1334
1335 static void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001336update_cursor(term_T *term, int redraw)
1337{
1338 if (term->tl_normal_mode)
1339 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001340#ifdef FEAT_GUI
1341 if (term->tl_system)
1342 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1343 term->tl_cursor_pos.col);
1344 else
1345#endif
Bram Moolenaar58806c12023-04-29 14:26:02 +01001346 if (!term_job_running(term))
1347 // avoid the cursor positioned below the last used line
Bram Moolenaar13568252018-03-16 20:46:58 +01001348 setcursor();
Bram Moolenaar58806c12023-04-29 14:26:02 +01001349 else
1350 {
1351 // do not use the window cursor position
1352 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1353 windgoto(W_WINROW(curwin) + curwin->w_wrow,
1354 curwin->w_wincol + curwin->w_wcol);
1355 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001356 if (redraw)
1357 {
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001358 aco_save_T aco;
1359
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001360 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1361 cursor_on();
1362 out_flush();
1363#ifdef FEAT_GUI
1364 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001365 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001366 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001367 gui_mch_flush();
1368 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001369#endif
Bram Moolenaar24fe33a2022-11-24 00:09:02 +00001370 // Make sure an invoked autocmd doesn't delete the buffer (and the
1371 // terminal) under our fingers.
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001372 ++term->tl_buffer->b_locked;
1373
1374 // save and restore curwin and curbuf, in case the autocmd changes them
1375 aucmd_prepbuf(&aco, curbuf);
1376 apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, FALSE, term->tl_buffer);
1377 aucmd_restbuf(&aco);
1378
1379 --term->tl_buffer->b_locked;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001380 }
1381}
1382
1383/*
1384 * Invoked when "msg" output from a job was received. Write it to the terminal
1385 * of "buffer".
1386 */
1387 void
1388write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1389{
1390 size_t len = STRLEN(msg);
1391 term_T *term = buffer->b_term;
1392
Bram Moolenaar4f974752019-02-17 17:44:42 +01001393#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001394 // Win32: Cannot redirect output of the job, intercept it here and write to
1395 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001396 if (term->tl_out_fd != NULL)
1397 {
1398 ch_log(channel, "Writing %d bytes to output file", (int)len);
1399 fwrite(msg, len, 1, term->tl_out_fd);
1400 return;
1401 }
1402#endif
1403
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001404 if (term->tl_vterm == NULL)
1405 {
1406 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1407 return;
1408 }
1409 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001410 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001411 term_write_job_output(term, msg, len);
1412
Bram Moolenaar13568252018-03-16 20:46:58 +01001413#ifdef FEAT_GUI
1414 if (term->tl_system)
1415 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001416 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001417 update_system_term(term);
1418 update_cursor(term, TRUE);
1419 }
1420 else
1421#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001422 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1423 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001424 if (!term->tl_normal_mode)
1425 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001426 // Don't use update_screen() when editing the command line, it gets
1427 // cleared.
1428 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001429 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001430 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001431 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001432 update_screen(UPD_VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001433 // update_screen() can be slow, check the terminal wasn't closed
1434 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001435 if (buffer == curbuf && curbuf->b_term != NULL)
1436 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001437 }
1438 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001439 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001440 }
1441}
1442
1443/*
1444 * Send a mouse position and click to the vterm
1445 */
1446 static int
1447term_send_mouse(VTerm *vterm, int button, int pressed)
1448{
1449 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001450 int row = mouse_row - W_WINROW(curwin);
1451 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001452
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001453#ifdef FEAT_PROP_POPUP
1454 if (popup_is_popup(curwin))
1455 {
1456 row -= popup_top_extra(curwin);
1457 col -= popup_left_extra(curwin);
1458 }
1459#endif
1460 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001461 if (button != 0)
1462 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001463 return TRUE;
1464}
1465
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001466static int enter_mouse_col = -1;
1467static int enter_mouse_row = -1;
1468
1469/*
1470 * Handle a mouse click, drag or release.
1471 * Return TRUE when a mouse event is sent to the terminal.
1472 */
1473 static int
1474term_mouse_click(VTerm *vterm, int key)
1475{
1476#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001477 // For modeless selection mouse drag and release events are ignored, unless
1478 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001479 static int ignore_drag_release = TRUE;
1480 VTermMouseState mouse_state;
1481
1482 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1483 if (mouse_state.flags == 0)
1484 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001485 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001486 switch (key)
1487 {
1488 case K_LEFTDRAG:
1489 case K_LEFTRELEASE:
1490 case K_RIGHTDRAG:
1491 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001492 // Ignore drag and release events when the button-down wasn't
1493 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001494 if (ignore_drag_release)
1495 {
1496 int save_mouse_col, save_mouse_row;
1497
1498 if (enter_mouse_col < 0)
1499 break;
1500
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001501 // mouse click in the window gave us focus, handle that
1502 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001503 save_mouse_col = mouse_col;
1504 save_mouse_row = mouse_row;
1505 mouse_col = enter_mouse_col;
1506 mouse_row = enter_mouse_row;
1507 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1508 mouse_col = save_mouse_col;
1509 mouse_row = save_mouse_row;
1510 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001511 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001512 case K_LEFTMOUSE:
1513 case K_RIGHTMOUSE:
1514 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1515 ignore_drag_release = TRUE;
1516 else
1517 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001518 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001519 if (clip_star.available)
1520 {
1521 int button, is_click, is_drag;
1522
1523 button = get_mouse_button(KEY2TERMCAP1(key),
1524 &is_click, &is_drag);
1525 if (mouse_model_popup() && button == MOUSE_LEFT
1526 && (mod_mask & MOD_MASK_SHIFT))
1527 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001528 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001529 button = MOUSE_RIGHT;
1530 mod_mask &= ~MOD_MASK_SHIFT;
1531 }
1532 clip_modeless(button, is_click, is_drag);
1533 }
1534 break;
1535
1536 case K_MIDDLEMOUSE:
1537 if (clip_star.available)
1538 insert_reg('*', TRUE);
1539 break;
1540 }
1541 enter_mouse_col = -1;
1542 return FALSE;
1543 }
1544#endif
1545 enter_mouse_col = -1;
1546
1547 switch (key)
1548 {
1549 case K_LEFTMOUSE:
1550 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1551 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1552 case K_LEFTRELEASE:
1553 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1554 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1555 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1556 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1557 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1558 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1559 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1560 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1561 }
1562 return TRUE;
1563}
1564
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001565/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001566 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1567 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001568 * Return the number of bytes in "buf".
1569 */
1570 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001571term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001572{
1573 VTerm *vterm = term->tl_vterm;
1574 VTermKey key = VTERM_KEY_NONE;
1575 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001576 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001577
1578 switch (c)
1579 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001580 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001581
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001582 // don't use VTERM_KEY_BACKSPACE, it always
1583 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001584 case K_BS: c = term_backspace_char; break;
1585
1586 case ESC: key = VTERM_KEY_ESCAPE; break;
1587 case K_DEL: key = VTERM_KEY_DEL; break;
1588 case K_DOWN: key = VTERM_KEY_DOWN; break;
1589 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1590 key = VTERM_KEY_DOWN; break;
1591 case K_END: key = VTERM_KEY_END; break;
1592 case K_S_END: mod = VTERM_MOD_SHIFT;
1593 key = VTERM_KEY_END; break;
1594 case K_C_END: mod = VTERM_MOD_CTRL;
1595 key = VTERM_KEY_END; break;
1596 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1597 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1598 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1599 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1600 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1601 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1602 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1603 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1604 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1605 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1606 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1607 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1608 case K_HOME: key = VTERM_KEY_HOME; break;
1609 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1610 key = VTERM_KEY_HOME; break;
1611 case K_C_HOME: mod = VTERM_MOD_CTRL;
1612 key = VTERM_KEY_HOME; break;
1613 case K_INS: key = VTERM_KEY_INS; break;
1614 case K_K0: key = VTERM_KEY_KP_0; break;
1615 case K_K1: key = VTERM_KEY_KP_1; break;
1616 case K_K2: key = VTERM_KEY_KP_2; break;
1617 case K_K3: key = VTERM_KEY_KP_3; break;
1618 case K_K4: key = VTERM_KEY_KP_4; break;
1619 case K_K5: key = VTERM_KEY_KP_5; break;
1620 case K_K6: key = VTERM_KEY_KP_6; break;
1621 case K_K7: key = VTERM_KEY_KP_7; break;
1622 case K_K8: key = VTERM_KEY_KP_8; break;
1623 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001624 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001625 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001626 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001628 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1629 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001630 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1631 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001632 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1633 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001634 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1635 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1636 case K_LEFT: key = VTERM_KEY_LEFT; break;
1637 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1638 key = VTERM_KEY_LEFT; break;
1639 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1640 key = VTERM_KEY_LEFT; break;
1641 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1642 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1643 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1644 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1645 key = VTERM_KEY_RIGHT; break;
1646 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1647 key = VTERM_KEY_RIGHT; break;
1648 case K_UP: key = VTERM_KEY_UP; break;
1649 case K_S_UP: mod = VTERM_MOD_SHIFT;
1650 key = VTERM_KEY_UP; break;
1651 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001652 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1653 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001654
Bram Moolenaara42ad572017-11-16 13:08:04 +01001655 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1656 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001657 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1658 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001659
1660 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001661 case K_LEFTMOUSE_NM:
1662 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001663 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001664 case K_LEFTRELEASE_NM:
1665 case K_MOUSEMOVE:
1666 case K_MIDDLEMOUSE:
1667 case K_MIDDLEDRAG:
1668 case K_MIDDLERELEASE:
1669 case K_RIGHTMOUSE:
1670 case K_RIGHTDRAG:
1671 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1672 return 0;
1673 other = TRUE;
1674 break;
1675
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001676 case K_X1MOUSE: /* TODO */ return 0;
1677 case K_X1DRAG: /* TODO */ return 0;
1678 case K_X1RELEASE: /* TODO */ return 0;
1679 case K_X2MOUSE: /* TODO */ return 0;
1680 case K_X2DRAG: /* TODO */ return 0;
1681 case K_X2RELEASE: /* TODO */ return 0;
1682
1683 case K_IGNORE: return 0;
1684 case K_NOP: return 0;
1685 case K_UNDO: return 0;
1686 case K_HELP: return 0;
1687 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1688 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1689 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1690 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1691 case K_SELECT: return 0;
1692#ifdef FEAT_GUI
1693 case K_VER_SCROLLBAR: return 0;
1694 case K_HOR_SCROLLBAR: return 0;
1695#endif
1696#ifdef FEAT_GUI_TABLINE
1697 case K_TABLINE: return 0;
1698 case K_TABMENU: return 0;
1699#endif
1700#ifdef FEAT_NETBEANS_INTG
1701 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1702#endif
1703#ifdef FEAT_DND
1704 case K_DROP: return 0;
1705#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001706 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001707 case K_PS: vterm_keyboard_start_paste(vterm);
1708 other = TRUE;
1709 break;
1710 case K_PE: vterm_keyboard_end_paste(vterm);
1711 other = TRUE;
1712 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001713 }
1714
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001715 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001716 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001717 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001718 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001719 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001720 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001721 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001722
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001723 // Ctrl-Shift-i may have the key "I" instead of "i", but for the kitty
1724 // keyboard protocol should use "i". Applies to all ascii letters.
1725 if (ASCII_ISUPPER(c)
Bram Moolenaarebed1b02022-11-24 14:05:19 +00001726 && vterm_is_kitty_keyboard(vterm)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001727 && mod == (VTERM_MOD_CTRL | VTERM_MOD_SHIFT))
1728 c = TOLOWER_ASC(c);
1729
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001730 /*
1731 * Convert special keys to vterm keys:
1732 * - Write keys to vterm: vterm_keyboard_key()
1733 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 */
1735 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001736 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001737 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001738 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001739 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001740 vterm_keyboard_unichar(vterm, c, mod);
1741
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001742 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001743 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1744}
1745
1746/*
1747 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001748 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001749 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001750 */
1751 static int
1752term_job_running_check(term_T *term, int check_job_status)
1753{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001754 // Also consider the job finished when the channel is closed, to avoid a
1755 // race condition when updating the title.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001756 if (term == NULL
1757 || term->tl_job == NULL
1758 || !channel_is_open(term->tl_job->jv_channel))
1759 return FALSE;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001760
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001761 job_T *job = term->tl_job;
1762
1763 // Careful: Checking the job status may invoke callbacks, which close
1764 // the buffer and terminate "term". However, "job" will not be freed
1765 // yet.
1766 if (check_job_status)
1767 job_status(job);
1768 return (job->jv_status == JOB_STARTED
1769 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001770}
1771
1772/*
1773 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001774 */
1775 int
1776term_job_running(term_T *term)
1777{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001778 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001779}
1780
1781/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001782 * Return TRUE if the job for "term" is still running, ignoring the job was
1783 * "NONE".
1784 */
1785 int
1786term_job_running_not_none(term_T *term)
1787{
1788 return term_job_running(term) && !term_none_open(term);
1789}
1790
1791/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001792 * Return TRUE if "term" has an active channel and used ":term NONE".
1793 */
1794 int
1795term_none_open(term_T *term)
1796{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001797 // Also consider the job finished when the channel is closed, to avoid a
1798 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001799 return term != NULL
1800 && term->tl_job != NULL
1801 && channel_is_open(term->tl_job->jv_channel)
1802 && term->tl_job->jv_channel->ch_keep_open;
1803}
1804
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001805//
1806// Used to confirm whether we would like to kill a terminal.
1807// Return OK when the user confirms to kill it.
1808// Return FAIL if the user selects otherwise.
1809//
1810 int
1811term_confirm_stop(buf_T *buf)
1812{
1813 char_u buff[DIALOG_MSG_SIZE];
1814 int ret;
1815
1816 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1817 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1818 if (ret == VIM_YES)
1819 return OK;
1820 else
1821 return FAIL;
1822}
1823
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001825 * Used when exiting: kill the job in "buf" if so desired.
1826 * Return OK when the job finished.
1827 * Return FAIL when the job is still running.
1828 */
1829 int
1830term_try_stop_job(buf_T *buf)
1831{
1832 int count;
1833 char *how = (char *)buf->b_term->tl_kill;
1834
1835#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001836 if ((how == NULL || *how == NUL)
1837 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001838 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001839 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001840 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001841 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001842 return FAIL;
1843 }
1844#endif
1845 if (how == NULL || *how == NUL)
1846 return FAIL;
1847
1848 job_stop(buf->b_term->tl_job, NULL, how);
1849
Bram Moolenaar9172d232019-01-29 23:06:54 +01001850 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001851 for (count = 0; count < 100; ++count)
1852 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001853 job_T *job;
1854
1855 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001856 if (!buf_valid(buf)
1857 || buf->b_term == NULL
1858 || buf->b_term->tl_job == NULL)
1859 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001860 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001861
Bram Moolenaar9172d232019-01-29 23:06:54 +01001862 // Call job_status() to update jv_status. It may cause the job to be
1863 // cleaned up but it won't be freed.
1864 job_status(job);
1865 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001866 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001867
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001868 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001869 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001870 }
1871 return FAIL;
1872}
1873
1874/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875 * Add the last line of the scrollback buffer to the buffer in the window.
1876 */
1877 static void
1878add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1879{
1880 buf_T *buf = term->tl_buffer;
1881 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1882 linenr_T lnum = buf->b_ml.ml_line_count;
1883
Bram Moolenaar4f974752019-02-17 17:44:42 +01001884#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001885 if (!enc_utf8 && enc_codepage > 0)
1886 {
1887 WCHAR *ret = NULL;
1888 int length = 0;
1889
1890 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1891 &ret, &length);
1892 if (ret != NULL)
1893 {
1894 WideCharToMultiByte_alloc(enc_codepage, 0,
1895 ret, length, (char **)&text, &len, 0, 0);
1896 vim_free(ret);
1897 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1898 vim_free(text);
1899 }
1900 }
1901 else
1902#endif
1903 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1904 if (empty)
1905 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001906 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001907 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001908 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001909 curbuf = curwin->w_buffer;
1910 }
1911}
1912
1913 static void
1914cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1915{
1916 attr->width = cell->width;
1917 attr->attrs = cell->attrs;
1918 attr->fg = cell->fg;
1919 attr->bg = cell->bg;
1920}
1921
1922 static int
1923equal_celattr(cellattr_T *a, cellattr_T *b)
1924{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001925 // We only compare the RGB colors, ignoring the ANSI index and type.
1926 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001927 return a->fg.red == b->fg.red
1928 && a->fg.green == b->fg.green
1929 && a->fg.blue == b->fg.blue
1930 && a->bg.red == b->bg.red
1931 && a->bg.green == b->bg.green
1932 && a->bg.blue == b->bg.blue;
1933}
1934
Bram Moolenaard96ff162018-02-18 22:13:29 +01001935/*
1936 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1937 * line at this position. Otherwise at the end.
1938 */
1939 static int
1940add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1941{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001942 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
1943 return FALSE;
1944
1945 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1946 + term->tl_scrollback.ga_len;
1947
1948 if (lnum > 0)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001949 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001950 int i;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001951
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001952 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001953 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001954 *line = *(line - 1);
1955 --line;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001956 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01001957 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001958 line->sb_cols = 0;
1959 line->sb_cells = NULL;
1960 line->sb_fill_attr = *fill_attr;
1961 ++term->tl_scrollback.ga_len;
1962 return OK;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001963}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001964
1965/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001966 * Remove the terminal contents from the scrollback and the buffer.
1967 * Used before adding a new scrollback line or updating the buffer for lines
1968 * displayed in the terminal.
1969 */
1970 static void
1971cleanup_scrollback(term_T *term)
1972{
1973 sb_line_T *line;
1974 garray_T *gap;
1975
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001976 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001977 gap = &term->tl_scrollback;
1978 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1979 && gap->ga_len > 0)
1980 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001981 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001982 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1983 vim_free(line->sb_cells);
1984 --gap->ga_len;
1985 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001986 curbuf = curwin->w_buffer;
1987 if (curbuf == term->tl_buffer)
1988 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001989}
1990
1991/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001992 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993 */
1994 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001995update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001996{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001997 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001998 int len;
1999 int lines_skipped = 0;
2000 VTermPos pos;
2001 VTermScreenCell cell;
2002 cellattr_T fill_attr, new_fill_attr;
2003 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002004
2005 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
2006 "Adding terminal window snapshot to buffer");
2007
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002008 // First remove the lines that were appended before, they might be
2009 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002010 cleanup_scrollback(term);
2011
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002012 screen = vterm_obtain_screen(term->tl_vterm);
2013 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002014 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
2015 {
2016 len = 0;
2017 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
2018 if (vterm_screen_get_cell(screen, pos, &cell) != 0
2019 && cell.chars[0] != NUL)
2020 {
2021 len = pos.col + 1;
2022 new_fill_attr = term->tl_default_color;
2023 }
2024 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002025 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002026 cell2cellattr(&cell, &new_fill_attr);
2027
2028 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
2029 ++lines_skipped;
2030 else
2031 {
2032 while (lines_skipped > 0)
2033 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002034 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002035 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002036 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002037 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002038 }
2039
2040 if (len == 0)
2041 p = NULL;
2042 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002043 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002044 if ((p != NULL || len == 0)
2045 && ga_grow(&term->tl_scrollback, 1) == OK)
2046 {
2047 garray_T ga;
2048 int width;
2049 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
2050 + term->tl_scrollback.ga_len;
2051
2052 ga_init2(&ga, 1, 100);
2053 for (pos.col = 0; pos.col < len; pos.col += width)
2054 {
2055 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2056 {
2057 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02002058 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002059 if (ga_grow(&ga, 1) == OK)
2060 ga.ga_len += utf_char2bytes(' ',
2061 (char_u *)ga.ga_data + ga.ga_len);
2062 }
2063 else
2064 {
2065 width = cell.width;
2066
2067 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01002068 if (width == 2)
2069 // second cell of double-width character has the
2070 // same attributes.
2071 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002072
Bram Moolenaara79fd562018-12-20 20:47:32 +01002073 // Each character can be up to 6 bytes.
2074 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002075 {
2076 int i;
2077 int c;
2078
2079 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
2080 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2081 (char_u *)ga.ga_data + ga.ga_len);
2082 }
2083 }
2084 }
2085 line->sb_cols = len;
2086 line->sb_cells = p;
2087 line->sb_fill_attr = new_fill_attr;
2088 fill_attr = new_fill_attr;
2089 ++term->tl_scrollback.ga_len;
2090
2091 if (ga_grow(&ga, 1) == FAIL)
2092 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2093 else
2094 {
2095 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2096 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2097 }
2098 ga_clear(&ga);
2099 }
2100 else
2101 vim_free(p);
2102 }
2103 }
2104
Bram Moolenaarf3aea592018-11-11 22:18:21 +01002105 // Add trailing empty lines.
2106 for (pos.row = term->tl_scrollback.ga_len;
2107 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
2108 ++pos.row)
2109 {
2110 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
2111 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2112 }
2113
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002114 term->tl_dirty_snapshot = FALSE;
2115#ifdef FEAT_TIMERS
2116 term->tl_timer_set = FALSE;
2117#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002118}
2119
2120/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002121 * Loop over all windows in the current tab, and also curwin, which is not
2122 * encountered when using a terminal in a popup window.
2123 * Return TRUE if "*wp" was set to the next window.
2124 */
2125 static int
2126for_all_windows_and_curwin(win_T **wp, int *did_curwin)
2127{
2128 if (*wp == NULL)
2129 *wp = firstwin;
2130 else if ((*wp)->w_next != NULL)
2131 *wp = (*wp)->w_next;
2132 else if (!*did_curwin)
2133 *wp = curwin;
2134 else
2135 return FALSE;
2136 if (*wp == curwin)
2137 *did_curwin = TRUE;
2138 return TRUE;
2139}
2140
2141/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002142 * If needed, add the current lines of the terminal to scrollback and to the
2143 * buffer. Called after the job has ended and when switching to
2144 * Terminal-Normal mode.
2145 * When "redraw" is TRUE redraw the windows that show the terminal.
2146 */
2147 static void
2148may_move_terminal_to_buffer(term_T *term, int redraw)
2149{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002150 if (term->tl_vterm == NULL)
2151 return;
2152
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002153 // Update the snapshot only if something changes or the buffer does not
2154 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002155 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2156 <= term->tl_scrollback_scrolled)
2157 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002158
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002159 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002160 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2161 &term->tl_default_color.fg, &term->tl_default_color.bg);
2162
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002163 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002164 {
2165 win_T *wp = NULL;
2166 int did_curwin = FALSE;
2167
2168 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002169 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002170 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002171 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002172 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2173 wp->w_cursor.col = 0;
2174 wp->w_valid = 0;
2175 if (wp->w_cursor.lnum >= wp->w_height)
2176 {
2177 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002178
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002179 if (wp->w_topline < min_topline)
2180 wp->w_topline = min_topline;
2181 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002182 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002183 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002184 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002185 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002186}
2187
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002188#if defined(FEAT_TIMERS) || defined(PROTO)
2189/*
2190 * Check if any terminal timer expired. If so, copy text from the terminal to
2191 * the buffer.
2192 * Return the time until the next timer will expire.
2193 */
2194 int
2195term_check_timers(int next_due_arg, proftime_T *now)
2196{
2197 term_T *term;
2198 int next_due = next_due_arg;
2199
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002200 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002201 {
2202 if (term->tl_timer_set && !term->tl_normal_mode)
2203 {
2204 long this_due = proftime_time_left(&term->tl_timer_due, now);
2205
2206 if (this_due <= 1)
2207 {
2208 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002209 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002210 }
2211 else if (next_due == -1 || next_due > this_due)
2212 next_due = this_due;
2213 }
2214 }
2215
2216 return next_due;
2217}
2218#endif
2219
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002220/*
2221 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2222 * otherwise end it.
2223 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002224 static void
2225set_terminal_mode(term_T *term, int normal_mode)
2226{
2227 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002228 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002229 if (!normal_mode)
2230 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002231 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002232 if (term->tl_buffer == curbuf)
2233 maketitle();
2234}
2235
2236/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002237 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002238 * Move the vterm contents into the scrollback buffer and free the vterm.
2239 */
2240 static void
2241cleanup_vterm(term_T *term)
2242{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002243 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002244 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002245 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002246 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002247}
2248
2249/*
2250 * Switch from Terminal-Job mode to Terminal-Normal mode.
2251 * Suspends updating the terminal window.
2252 */
2253 static void
2254term_enter_normal_mode(void)
2255{
2256 term_T *term = curbuf->b_term;
2257
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002258 set_terminal_mode(term, TRUE);
2259
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002260 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002261 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002263 // Move the window cursor to the position of the cursor in the
2264 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002265 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2266 + term->tl_cursor_pos.row + 1;
2267 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002268 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2269 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002270 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002271
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002272 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002273 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2274}
2275
2276/*
2277 * Returns TRUE if the current window contains a terminal and we are in
2278 * Terminal-Normal mode.
2279 */
2280 int
2281term_in_normal_mode(void)
2282{
2283 term_T *term = curbuf->b_term;
2284
2285 return term != NULL && term->tl_normal_mode;
2286}
2287
2288/*
2289 * Switch from Terminal-Normal mode to Terminal-Job mode.
2290 * Restores updating the terminal window.
2291 */
2292 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002293term_enter_job_mode(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002294{
2295 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002296
2297 set_terminal_mode(term, FALSE);
2298
2299 if (term->tl_channel_closed)
2300 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002301 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002302#ifdef FEAT_PROP_POPUP
2303 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002304 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002305#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002306}
2307
2308/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002309 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2310 * modifiers into a basic key. However, we may only find out after calling
2311 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2312 * "no_reduce_keys" before using it.
2313 */
2314typedef enum {
2315 NRKS_NONE, // initial value
2316 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2317 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2318 // check_no_reduce_keys(), must be decremented.
2319} reduce_key_state_T;
2320
2321static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2322
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002323/*
2324 * Return TRUE if the term is using modifyOtherKeys level 2 or the kitty
2325 * keyboard protocol.
2326 */
2327 static int
2328vterm_using_key_protocol(void)
2329{
2330 return curbuf->b_term != NULL
2331 && curbuf->b_term->tl_vterm != NULL
2332 && (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm)
2333 || vterm_is_kitty_keyboard(curbuf->b_term->tl_vterm));
2334}
2335
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002336 void
2337check_no_reduce_keys(void)
2338{
2339 if (no_reduce_key_state != NRKS_CHECK
2340 || no_reduce_keys >= 1
2341 || curbuf->b_term == NULL
2342 || curbuf->b_term->tl_vterm == NULL)
2343 return;
2344
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002345 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002346 {
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002347 // "modify_other_keys" or kitty keyboard protocol was enabled while
2348 // waiting.
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002349 no_reduce_key_state = NRKS_SET;
2350 ++no_reduce_keys;
2351 }
2352}
2353
2354/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002355 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002356 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002357 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358 */
2359 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002360term_vgetc(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002361{
2362 int c;
2363 int save_State = State;
2364
Bram Moolenaar24959102022-05-07 20:01:16 +01002365 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002366 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002367#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002368 ctrl_break_was_pressed = FALSE;
2369#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002370
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002371 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002372 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002373 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002374 no_reduce_key_state = NRKS_SET;
2375 }
2376 else
2377 {
2378 no_reduce_key_state = NRKS_CHECK;
2379 }
2380
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002381 c = vgetc();
2382 got_int = FALSE;
2383 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002384
2385 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002386 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002387 no_reduce_key_state = NRKS_NONE;
2388
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002389 return c;
2390}
2391
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002392static int mouse_was_outside = FALSE;
2393
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002394/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002395 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002396 * Return FAIL when the key needs to be handled in Normal mode.
2397 * Return OK when the key was dropped or sent to the terminal.
2398 */
2399 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002400send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002401{
2402 char msg[KEY_BUF_LEN];
2403 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002404 int dragging_outside = FALSE;
2405
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002406 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002407 switch (c)
2408 {
2409 case NUL:
2410 case K_ZERO:
2411 if (typed)
2412 stuffcharReadbuff(c);
2413 return FAIL;
2414
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002415 case K_TABLINE:
2416 stuffcharReadbuff(c);
2417 return FAIL;
2418
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002419 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002420 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002421 return FAIL;
2422
2423 case K_LEFTDRAG:
2424 case K_MIDDLEDRAG:
2425 case K_RIGHTDRAG:
2426 case K_X1DRAG:
2427 case K_X2DRAG:
2428 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002429 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002430 case K_LEFTMOUSE:
2431 case K_LEFTMOUSE_NM:
2432 case K_LEFTRELEASE:
2433 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002434 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002435 case K_MIDDLEMOUSE:
2436 case K_MIDDLERELEASE:
2437 case K_RIGHTMOUSE:
2438 case K_RIGHTRELEASE:
2439 case K_X1MOUSE:
2440 case K_X1RELEASE:
2441 case K_X2MOUSE:
2442 case K_X2RELEASE:
2443
2444 case K_MOUSEUP:
2445 case K_MOUSEDOWN:
2446 case K_MOUSELEFT:
2447 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002448 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002449 int row = mouse_row;
2450 int col = mouse_col;
2451
2452#ifdef FEAT_PROP_POPUP
2453 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002454 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002455 row -= popup_top_extra(curwin);
2456 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002457 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002458#endif
2459 if (row < W_WINROW(curwin)
2460 || row >= (W_WINROW(curwin) + curwin->w_height)
2461 || col < curwin->w_wincol
2462 || col >= W_ENDCOL(curwin)
2463 || dragging_outside)
2464 {
2465 // click or scroll outside the current window or on status
2466 // line or vertical separator
2467 if (typed)
2468 {
2469 stuffcharReadbuff(c);
2470 mouse_was_outside = TRUE;
2471 }
2472 return FAIL;
2473 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002474 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002475 break;
2476
2477 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002478 case K_SCRIPT_COMMAND:
2479 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002480 }
2481 if (typed)
2482 mouse_was_outside = FALSE;
2483
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002484 // Convert the typed key to a sequence of bytes for the job.
2485 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002486 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002487 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002488 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2489 (char_u *)msg, (int)len, NULL);
2490
2491 return OK;
2492}
2493
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002494/*
2495 * Handle CTRL-W "": send register contents to the job.
2496 */
2497 static void
2498term_paste_register(int prev_c UNUSED)
2499{
2500 int c;
2501 list_T *l;
2502 listitem_T *item;
2503 long reglen = 0;
2504 int type;
2505
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002506 if (add_to_showcmd(prev_c))
2507 if (add_to_showcmd('"'))
2508 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002509
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002510 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002511 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002512
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002513 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002514 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002515 return;
2516
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002517 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002518 if (c == '=' && get_expr_register() != '=')
2519 return;
2520 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002521 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002522 return;
2523
2524 l = (list_T *)get_reg_contents(c, GREG_LIST);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002525 if (l == NULL)
2526 return;
2527
2528 type = get_reg_type(c, &reglen);
2529 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002530 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002531 char_u *s = tv_get_string(&item->li_tv);
2532#ifdef MSWIN
2533 char_u *tmp = s;
2534
2535 if (!enc_utf8 && enc_codepage > 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002536 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002537 WCHAR *ret = NULL;
2538 int length = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002540 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2541 (int)STRLEN(s), &ret, &length);
2542 if (ret != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002543 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002544 WideCharToMultiByte_alloc(CP_UTF8, 0,
2545 ret, length, (char **)&s, &length, 0, 0);
2546 vim_free(ret);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002547 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002548 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002549#endif
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002550 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2551 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002552#ifdef MSWIN
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002553 if (tmp != s)
2554 vim_free(s);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002555#endif
2556
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002557 if (item->li_next != NULL || type == MLINE)
2558 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2559 (char_u *)"\r", 1, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002560 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002561 list_free(l);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002562}
2563
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002564/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002565 * Return TRUE when waiting for a character in the terminal, the cursor of the
2566 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002567 */
2568 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002569terminal_is_active(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002570{
2571 return in_terminal_loop != NULL;
2572}
2573
Bram Moolenaar83d47902020-03-26 20:34:00 +01002574/*
dundargocc57b5bc2022-11-02 13:30:51 +00002575 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002576 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002577 static int
2578term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002579{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002580 char_u *name;
2581
2582 if (wp != NULL && *wp->w_p_wcr != NUL)
2583 name = wp->w_p_wcr;
2584 else if (term->tl_highlight_name != NULL)
2585 name = term->tl_highlight_name;
2586 else
2587 name = (char_u*)"Terminal";
2588
2589 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002590}
2591
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002592#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 cursorentry_T *
2594term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2595{
2596 term_T *term = in_terminal_loop;
2597 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002598 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002599 guicolor_T term_fg = INVALCOLOR;
2600 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002601
Bram Moolenaara80faa82020-04-12 19:37:17 +02002602 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002603 entry.shape = entry.mshape =
2604 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2605 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2606 SHAPE_BLOCK;
2607 entry.percentage = 20;
2608 if (term->tl_cursor_blink)
2609 {
2610 entry.blinkwait = 700;
2611 entry.blinkon = 400;
2612 entry.blinkoff = 250;
2613 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002614
Bram Moolenaar83d47902020-03-26 20:34:00 +01002615 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002616 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002617 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002618 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002619 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002620 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002621 else
2622 *fg = gui.back_pixel;
2623
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002624 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002625 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002626 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002627 *bg = term_fg;
2628 else
2629 *bg = gui.norm_pixel;
2630 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002631 else
2632 *bg = color_name2handle(term->tl_cursor_color);
2633 entry.name = "n";
2634 entry.used_for = SHAPE_CURSOR;
2635
2636 return &entry;
2637}
2638#endif
2639
Bram Moolenaard317b382018-02-08 22:33:31 +01002640 static void
2641may_output_cursor_props(void)
2642{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002643 if (!cursor_color_equal(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)
2646 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002647 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002648 last_set_cursor_shape = desired_cursor_shape;
2649 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002650 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002651 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002652 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002653 ui_cursor_shape_forced(TRUE);
2654 else
2655 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2656 }
2657}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002658
Bram Moolenaard317b382018-02-08 22:33:31 +01002659/*
2660 * Set the cursor color and shape, if not last set to these.
2661 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002662 static void
2663may_set_cursor_props(term_T *term)
2664{
2665#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002666 // For the GUI the cursor properties are obtained with
2667 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002668 if (gui.in_use)
2669 return;
2670#endif
2671 if (in_terminal_loop == term)
2672 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002673 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002674 desired_cursor_shape = term->tl_cursor_shape;
2675 desired_cursor_blink = term->tl_cursor_blink;
2676 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002677 }
2678}
2679
Bram Moolenaard317b382018-02-08 22:33:31 +01002680/*
2681 * Reset the desired cursor properties and restore them when needed.
2682 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002683 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002684prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002685{
2686#ifdef FEAT_GUI
2687 if (gui.in_use)
2688 return;
2689#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002690 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002691 desired_cursor_shape = -1;
2692 desired_cursor_blink = -1;
2693 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002694}
2695
2696/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002697 * Returns TRUE if the current window contains a terminal and we are sending
2698 * keys to the job.
2699 * If "check_job_status" is TRUE update the job status.
2700 */
2701 static int
2702term_use_loop_check(int check_job_status)
2703{
2704 term_T *term = curbuf->b_term;
2705
2706 return term != NULL
2707 && !term->tl_normal_mode
2708 && term->tl_vterm != NULL
2709 && term_job_running_check(term, check_job_status);
2710}
2711
2712/*
2713 * Returns TRUE if the current window contains a terminal and we are sending
2714 * keys to the job.
2715 */
2716 int
2717term_use_loop(void)
2718{
2719 return term_use_loop_check(FALSE);
2720}
2721
2722/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002723 * Called when entering a window with the mouse. If this is a terminal window
2724 * we may want to change state.
2725 */
2726 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002727term_win_entered(void)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002728{
2729 term_T *term = curbuf->b_term;
2730
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002731 if (term == NULL)
2732 return;
2733
2734 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002735 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002736 reset_VIsual_and_resel();
2737 if (State & MODE_INSERT)
2738 stop_insert_mode = TRUE;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002739 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002740 mouse_was_outside = FALSE;
2741 enter_mouse_col = mouse_col;
2742 enter_mouse_row = mouse_row;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002743}
2744
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002745 void
2746term_focus_change(int in_focus)
2747{
2748 term_T *term = curbuf->b_term;
2749
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002750 if (term == NULL || term->tl_vterm == NULL)
2751 return;
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002752
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002753 VTermState *state = vterm_obtain_state(term->tl_vterm);
2754
2755 if (in_focus)
2756 vterm_state_focus_in(state);
2757 else
2758 vterm_state_focus_out(state);
2759 term_forward_output(term);
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002760}
2761
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002762/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002763 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2764 * Return the Ctrl-key value in that case.
2765 */
2766 static int
2767raw_c_to_ctrl(int c)
2768{
2769 if ((mod_mask & MOD_MASK_CTRL)
2770 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2771 return c & 0x1f;
2772 return c;
2773}
2774
2775/*
2776 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002777 * Also when the Kitty keyboard protocol is used.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002778 * May set "mod_mask".
2779 */
2780 static int
2781ctrl_to_raw_c(int c)
2782{
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002783 if (c < 0x20 && vterm_using_key_protocol())
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002784 {
2785 mod_mask |= MOD_MASK_CTRL;
2786 return c + '@';
2787 }
2788 return c;
2789}
2790
2791/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002792 * Wait for input and send it to the job.
2793 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2794 * when there is no more typahead.
2795 * Return when the start of a CTRL-W command is typed or anything else that
2796 * should be handled as a Normal mode command.
2797 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2798 * the terminal was closed.
2799 */
2800 int
2801terminal_loop(int blocking)
2802{
2803 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002804 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002805 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002806 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002807#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002808 int tty_fd = curbuf->b_term->tl_job->jv_channel
2809 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002810#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002811 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002812
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002813 // Remember the terminal we are sending keys to. However, the terminal
2814 // might be closed while waiting for a character, e.g. typing "exit" in a
2815 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2816 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002817 in_terminal_loop = curbuf->b_term;
2818
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002819 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002820 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002821 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002822 if (termwinkey == Ctrl_W)
2823 termwinkey = 0;
2824 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002825 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002826 may_set_cursor_props(curbuf->b_term);
2827
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002828 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002829 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002830#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002831 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002832#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002833 // TODO: skip screen update when handling a sequence of keys.
2834 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002835 while (must_redraw != 0)
2836 if (update_screen(0) == FAIL)
2837 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002838 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002839 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002840 break;
2841
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002842 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002843 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002844
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002845 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002846 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002847 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002848 // Job finished while waiting for a character. Push back the
2849 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002850 if (raw_c != K_IGNORE)
2851 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002852 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002853 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002854 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002855 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002856 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002857
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002858#ifdef UNIX
2859 /*
2860 * The shell or another program may change the tty settings. Getting
2861 * them for every typed character is a bit of overhead, but it's needed
2862 * for the first character typed, e.g. when Vim starts in a shell.
2863 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002864 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002865 {
2866 ttyinfo_T info;
2867
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002868 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002869 if (get_tty_info(tty_fd, &info) == OK)
2870 term_backspace_char = info.backspace;
2871 }
2872#endif
2873
Bram Moolenaar4f974752019-02-17 17:44:42 +01002874#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002875 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2876 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002877 if (ctrl_break_was_pressed)
2878 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2879#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002880 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2881 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002882 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002883#ifdef FEAT_GUI
2884 && !curbuf->b_term->tl_system
2885#endif
2886 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002887 {
2888 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002889 int prev_raw_c = raw_c;
2890 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002891
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002892 if (add_to_showcmd(c))
2893 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002894
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002895 raw_c = term_vgetc();
2896 c = raw_c_to_ctrl(raw_c);
2897
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002898 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002899
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002900 if (!term_use_loop_check(TRUE)
2901 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002902 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002903 break;
2904
2905 if (prev_c == Ctrl_BSL)
2906 {
2907 if (c == Ctrl_N)
2908 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002909 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002910 term_enter_normal_mode();
2911 ret = FAIL;
2912 goto theend;
2913 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002914 // Send both keys to the terminal, first one here, second one
2915 // below.
2916 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2917 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002918 }
2919 else if (c == Ctrl_C)
2920 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002921 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2923 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002924 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002926 // "CTRL-W .": send CTRL-W to the job
2927 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002928 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002929 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002930 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002931 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002932 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002933 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002934 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002935 else if (c == 'N')
2936 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002937 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002938 term_enter_normal_mode();
2939 ret = FAIL;
2940 goto theend;
2941 }
2942 else if (c == '"')
2943 {
2944 term_paste_register(prev_c);
2945 continue;
2946 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002947 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002948 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002949 // space for CTRL-W, modifier, multi-byte char and NUL
2950 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002951
2952 // Put the command into the typeahead buffer, when using the
2953 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2954 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002955 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002956 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002957 ret = OK;
2958 goto theend;
2959 }
2960 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002961# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002962 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002963 {
2964 WCHAR wc;
2965 char_u mb[3];
2966
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002967 mb[0] = (unsigned)raw_c >> 8;
2968 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002969 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002970 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002971 }
2972# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002973 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002974 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002975 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002976 // We are sure to come back here, don't reset the cursor color
2977 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002978 restore_cursor = FALSE;
2979
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002980 ret = OK;
2981 goto theend;
2982 }
2983 }
2984 ret = FAIL;
2985
2986theend:
2987 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002988 if (restore_cursor)
2989 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002990
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002991 // Move a snapshot of the screen contents to the buffer, so that completion
2992 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002993 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2994 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002995
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002996 return ret;
2997}
2998
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002999 static void
3000may_toggle_cursor(term_T *term)
3001{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003002 if (in_terminal_loop != term)
3003 return;
3004
3005 if (term->tl_cursor_visible)
3006 cursor_on();
3007 else
3008 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003009}
3010
3011/*
3012 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01003013 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003014 */
3015 static int
3016color2index(VTermColor *color, int fg, int *boldp)
3017{
3018 int red = color->red;
3019 int blue = color->blue;
3020 int green = color->green;
3021
LemonBoyb2b3acb2022-05-20 10:10:34 +01003022 *boldp = FALSE;
3023
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003024 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003025 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01003026
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003027 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003028 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003029 // Use the color as-is if possible, give up otherwise.
3030 if (color->index < t_colors)
3031 return color->index + 1;
3032 // 8-color terminals can actually display twice as many colors by
3033 // setting the high-intensity/bold bit.
3034 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003035 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003036 *boldp = TRUE;
3037 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003038 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01003039 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003040 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01003041
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003042 if (t_colors >= 256)
3043 {
3044 if (red == blue && red == green)
3045 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003046 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003047 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003048 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
3049 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
3050 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003051 int i;
3052
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003053 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003054 return 17; // 00/00/00
3055 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003056 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003057 for (i = 0; i < 23; ++i)
3058 if (red < cutoff[i])
3059 return i + 233;
3060 return 256;
3061 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003062 {
3063 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
3064 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003065
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003066 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003067 for (ri = 0; ri < 5; ++ri)
3068 if (red < cutoff[ri])
3069 break;
3070 for (gi = 0; gi < 5; ++gi)
3071 if (green < cutoff[gi])
3072 break;
3073 for (bi = 0; bi < 5; ++bi)
3074 if (blue < cutoff[bi])
3075 break;
3076 return 17 + ri * 36 + gi * 6 + bi;
3077 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003078 }
3079 return 0;
3080}
3081
3082/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01003083 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003084 */
3085 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003086vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003087{
3088 int attr = 0;
3089
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003090 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003091 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003092 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003093 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003094 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003096 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003098 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003099 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003100 return attr;
3101}
3102
3103/*
3104 * Store Vterm attributes in "cell" from highlight flags.
3105 */
3106 static void
3107hl2vtermAttr(int attr, cellattr_T *cell)
3108{
Bram Moolenaara80faa82020-04-12 19:37:17 +02003109 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003110 if (attr & HL_BOLD)
3111 cell->attrs.bold = 1;
3112 if (attr & HL_UNDERLINE)
3113 cell->attrs.underline = 1;
3114 if (attr & HL_ITALIC)
3115 cell->attrs.italic = 1;
3116 if (attr & HL_STRIKETHROUGH)
3117 cell->attrs.strike = 1;
3118 if (attr & HL_INVERSE)
3119 cell->attrs.reverse = 1;
3120}
3121
3122/*
3123 * Convert the attributes of a vterm cell into an attribute index.
3124 */
3125 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003126cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003127 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003128 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003129 VTermScreenCellAttrs *cellattrs,
3130 VTermColor *cellfg,
3131 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003132{
3133 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003134 VTermColor *fg = cellfg;
3135 VTermColor *bg = cellbg;
3136 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3137 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3138
3139 if (is_default_fg || is_default_bg)
3140 {
3141 if (wp != NULL && *wp->w_p_wcr != NUL)
3142 {
3143 if (is_default_fg)
3144 fg = &wp->w_term_wincolor.fg;
3145 if (is_default_bg)
3146 bg = &wp->w_term_wincolor.bg;
3147 }
3148 else
3149 {
3150 if (is_default_fg)
3151 fg = &term->tl_default_color.fg;
3152 if (is_default_bg)
3153 bg = &term->tl_default_color.bg;
3154 }
3155 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156
3157#ifdef FEAT_GUI
3158 if (gui.in_use)
3159 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003160 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3161 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3162 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003163 }
3164 else
3165#endif
3166#ifdef FEAT_TERMGUICOLORS
3167 if (p_tgc)
3168 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003169 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3170 ? INVALCOLOR
3171 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3172 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3173 ? INVALCOLOR
3174 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3175 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003176 }
3177 else
3178#endif
3179 {
3180 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003181 int ctermfg = color2index(fg, TRUE, &bold);
3182 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003183
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003184 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003185 if (bold == TRUE)
3186 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003187
3188 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003189 }
3190 return 0;
3191}
3192
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003193 static void
3194set_dirty_snapshot(term_T *term)
3195{
3196 term->tl_dirty_snapshot = TRUE;
3197#ifdef FEAT_TIMERS
3198 if (!term->tl_normal_mode)
3199 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003200 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003201 profile_setlimit(100L, &term->tl_timer_due);
3202 term->tl_timer_set = TRUE;
3203 }
3204#endif
3205}
3206
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003207 static int
3208handle_damage(VTermRect rect, void *user)
3209{
3210 term_T *term = (term_T *)user;
3211
3212 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3213 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003214 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003215 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003216 return 1;
3217}
3218
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003219 static void
3220term_scroll_up(term_T *term, int start_row, int count)
3221{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003222 win_T *wp = NULL;
3223 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003224 VTermColor fg, bg;
3225 VTermScreenCellAttrs attr;
3226 int clear_attr;
3227
Bram Moolenaara80faa82020-04-12 19:37:17 +02003228 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003229
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003230 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003231 {
3232 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003233 {
3234 // Set the color to clear lines with.
3235 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3236 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003237 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003238 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003239 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003240 }
3241}
3242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003243 static int
3244handle_moverect(VTermRect dest, VTermRect src, void *user)
3245{
3246 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003247 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003248
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003249 // Scrolling up is done much more efficiently by deleting lines instead of
3250 // redrawing the text. But avoid doing this multiple times, postpone until
3251 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003252 if (dest.start_col == src.start_col
3253 && dest.end_col == src.end_col
3254 && dest.start_row < src.start_row)
3255 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003256 if (dest.start_row == 0)
3257 term->tl_postponed_scroll += count;
3258 else
3259 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003260 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003261
3262 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3263 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003264 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003265
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003266 // Note sure if the scrolling will work correctly, let's do a complete
3267 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003268 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003269 return 1;
3270}
3271
3272 static int
3273handle_movecursor(
3274 VTermPos pos,
3275 VTermPos oldpos UNUSED,
3276 int visible,
3277 void *user)
3278{
3279 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003280 win_T *wp = NULL;
3281 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003282
3283 term->tl_cursor_pos = pos;
3284 term->tl_cursor_visible = visible;
3285
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003286 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003287 {
3288 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003289 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003290 }
3291 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003292 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003293
3294 return 1;
3295}
3296
3297 static int
3298handle_settermprop(
3299 VTermProp prop,
3300 VTermValue *value,
3301 void *user)
3302{
3303 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003304 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003305
3306 switch (prop)
3307 {
3308 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003309 if (disable_vterm_title_for_testing)
3310 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003311 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003312 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003313 if (strval == NULL)
3314 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003315 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003316 // a blank title isn't useful, make it empty, so that "running" is
3317 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003318 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003319 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003320 // Same as blank
3321 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003322 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003323 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3324 term->tl_title = NULL;
3325 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003326 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003327 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003328#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003329 else if (!enc_utf8 && enc_codepage > 0)
3330 {
3331 WCHAR *ret = NULL;
3332 int length = 0;
3333
3334 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003335 (char*)value->string.str,
3336 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003337 if (ret != NULL)
3338 {
3339 WideCharToMultiByte_alloc(enc_codepage, 0,
3340 ret, length, (char**)&term->tl_title,
3341 &length, 0, 0);
3342 vim_free(ret);
3343 }
3344 }
3345#endif
3346 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003347 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003348 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003349 strval = NULL;
3350 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003351 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003352 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003353 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003354 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003355 curwin->w_redr_status = TRUE;
3356 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357 break;
3358
3359 case VTERM_PROP_CURSORVISIBLE:
3360 term->tl_cursor_visible = value->boolean;
3361 may_toggle_cursor(term);
3362 out_flush();
3363 break;
3364
3365 case VTERM_PROP_CURSORBLINK:
3366 term->tl_cursor_blink = value->boolean;
3367 may_set_cursor_props(term);
3368 break;
3369
3370 case VTERM_PROP_CURSORSHAPE:
3371 term->tl_cursor_shape = value->number;
3372 may_set_cursor_props(term);
3373 break;
3374
3375 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003376 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003377 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003378 if (strval == NULL)
3379 break;
3380 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003381 may_set_cursor_props(term);
3382 break;
3383
3384 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003385 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003386 term->tl_using_altscreen = value->boolean;
3387 break;
3388
3389 default:
3390 break;
3391 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003392 vim_free(strval);
3393
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003394 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003395 return 1;
3396}
3397
3398/*
3399 * The job running in the terminal resized the terminal.
3400 */
3401 static int
3402handle_resize(int rows, int cols, void *user)
3403{
3404 term_T *term = (term_T *)user;
3405 win_T *wp;
3406
3407 term->tl_rows = rows;
3408 term->tl_cols = cols;
3409 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003410 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003411 term->tl_vterm_size_changed = FALSE;
3412 else
3413 {
3414 FOR_ALL_WINDOWS(wp)
3415 {
3416 if (wp->w_buffer == term->tl_buffer)
3417 {
3418 win_setheight_win(rows, wp);
3419 win_setwidth_win(cols, wp);
3420 }
3421 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003422 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003423 }
3424 return 1;
3425}
3426
3427/*
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003428 * If the number of lines that are stored goes over 'termwinscroll' then
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003429 * delete the first 10%.
3430 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3431 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003432 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003433 static void
3434limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003435{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003436 if (gap->ga_len < term->tl_buffer->b_p_twsl)
3437 return;
3438
Milly6d5f4a02024-10-22 23:17:45 +02003439 int todo = MAX(term->tl_buffer->b_p_twsl / 10,
3440 gap->ga_len - term->tl_buffer->b_p_twsl);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003441 int i;
3442
3443 curbuf = term->tl_buffer;
3444 for (i = 0; i < todo; ++i)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003445 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003446 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003447 if (update_buffer)
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003448 ml_delete(1);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003449 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003450 curbuf = curwin->w_buffer;
3451
3452 gap->ga_len -= todo;
3453 mch_memmove(gap->ga_data,
3454 (sb_line_T *)gap->ga_data + todo,
3455 sizeof(sb_line_T) * gap->ga_len);
3456 if (update_buffer)
3457 term->tl_scrollback_scrolled -= todo;
Christian Brabandt1254e6d2024-07-29 21:19:51 +02003458
3459 // make sure cursor is on a valid line
3460 if (curbuf == term->tl_buffer)
3461 check_cursor();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003462}
3463
3464/*
3465 * Handle a line that is pushed off the top of the screen.
3466 */
3467 static int
3468handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3469{
3470 term_T *term = (term_T *)user;
3471 garray_T *gap;
3472 int update_buffer;
3473
3474 if (term->tl_normal_mode)
3475 {
3476 // In Terminal-Normal mode the user interacts with the buffer, thus we
3477 // must not change it. Postpone adding the scrollback lines.
3478 gap = &term->tl_scrollback_postponed;
3479 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003480 }
3481 else
3482 {
3483 // First remove the lines that were appended before, the pushed line
3484 // goes above it.
3485 cleanup_scrollback(term);
3486 gap = &term->tl_scrollback;
3487 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003488 }
3489
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003490 limit_scrollback(term, gap, update_buffer);
3491
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003492 if (ga_grow(gap, 1) == FAIL)
3493 return 0;
3494
3495 cellattr_T *p = NULL;
3496 int len = 0;
3497 int i;
3498 int c;
3499 int col;
3500 int text_len;
3501 char_u *text;
3502 sb_line_T *line;
3503 garray_T ga;
3504 cellattr_T fill_attr = term->tl_default_color;
3505
3506 // do not store empty cells at the end
3507 for (i = 0; i < cols; ++i)
3508 if (cells[i].chars[0] != 0)
3509 len = i + 1;
3510 else
3511 cell2cellattr(&cells[i], &fill_attr);
3512
3513 ga_init2(&ga, 1, 100);
3514 if (len > 0)
3515 p = ALLOC_MULT(cellattr_T, len);
3516 if (p != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003517 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003518 for (col = 0; col < len; col += cells[col].width)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003519 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003520 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003521 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003522 ga.ga_len = 0;
3523 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003524 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003525 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3526 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3527 (char_u *)ga.ga_data + ga.ga_len);
3528 cell2cellattr(&cells[col], &p[col]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003529 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003530 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003531 if (ga_grow(&ga, 1) == FAIL)
3532 {
3533 if (update_buffer)
3534 text = (char_u *)"";
3535 else
3536 text = vim_strsave((char_u *)"");
3537 text_len = 0;
3538 }
3539 else
3540 {
3541 text = ga.ga_data;
3542 text_len = ga.ga_len;
3543 *(text + text_len) = NUL;
3544 }
3545 if (update_buffer)
3546 add_scrollback_line_to_buffer(term, text, text_len);
3547
3548 line = (sb_line_T *)gap->ga_data + gap->ga_len;
3549 line->sb_cols = len;
3550 line->sb_cells = p;
3551 line->sb_fill_attr = fill_attr;
3552 if (update_buffer)
3553 {
3554 line->sb_text = NULL;
3555 ++term->tl_scrollback_scrolled;
3556 ga_clear(&ga); // free the text
3557 }
3558 else
3559 {
3560 line->sb_text = text;
3561 ga_init(&ga); // text is kept in tl_scrollback_postponed
3562 }
3563 ++gap->ga_len;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003564 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003565}
3566
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003567/*
3568 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3569 * received and stored in tl_scrollback_postponed.
3570 */
3571 static void
3572handle_postponed_scrollback(term_T *term)
3573{
3574 int i;
3575
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003576 if (term->tl_scrollback_postponed.ga_len == 0)
3577 return;
3578 ch_log(NULL, "Moving postponed scrollback to scrollback");
3579
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003580 // First remove the lines that were appended before, the pushed lines go
3581 // above it.
3582 cleanup_scrollback(term);
3583
3584 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3585 {
3586 char_u *text;
3587 sb_line_T *pp_line;
3588 sb_line_T *line;
3589
3590 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3591 break;
3592 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3593
3594 text = pp_line->sb_text;
3595 if (text == NULL)
3596 text = (char_u *)"";
3597 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3598 vim_free(pp_line->sb_text);
3599
3600 line = (sb_line_T *)term->tl_scrollback.ga_data
3601 + term->tl_scrollback.ga_len;
3602 line->sb_cols = pp_line->sb_cols;
3603 line->sb_cells = pp_line->sb_cells;
3604 line->sb_fill_attr = pp_line->sb_fill_attr;
3605 line->sb_text = NULL;
3606 ++term->tl_scrollback_scrolled;
3607 ++term->tl_scrollback.ga_len;
3608 }
3609
3610 ga_clear(&term->tl_scrollback_postponed);
3611 limit_scrollback(term, &term->tl_scrollback, TRUE);
3612}
3613
LemonBoy77771d32022-04-13 11:47:25 +01003614/*
3615 * Called when the terminal wants to ring the system bell.
3616 */
3617 static int
3618handle_bell(void *user UNUSED)
3619{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003620 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003621 return 0;
3622}
3623
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003624static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003625 handle_damage, // damage
3626 handle_moverect, // moverect
3627 handle_movecursor, // movecursor
3628 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003629 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003630 handle_resize, // resize
3631 handle_pushline, // sb_pushline
Bram Moolenaar6a12d262022-10-16 19:26:52 +01003632 NULL, // sb_popline
3633 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003634};
3635
3636/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003637 * Do the work after the channel of a terminal was closed.
3638 * Must be called only when updating_screen is FALSE.
3639 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3640 */
3641 static int
3642term_after_channel_closed(term_T *term)
3643{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003644 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003645 if (!term->tl_normal_mode)
3646 {
3647 int fnum = term->tl_buffer->b_fnum;
3648
3649 cleanup_vterm(term);
3650
3651 if (term->tl_finish == TL_FINISH_CLOSE)
3652 {
3653 aco_save_T aco;
zeertzjqbc11f6d2024-08-16 21:11:31 +02003654 int do_set_w_locked = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003655#ifdef FEAT_PROP_POPUP
3656 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003657
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003658 // If this was a terminal in a popup window, go back to the
3659 // previous window.
3660 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3661 {
3662 pwin = curwin;
3663 if (win_valid(prevwin))
3664 win_enter(prevwin, FALSE);
3665 }
3666 else
3667#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003668 // If this is the last normal window: exit Vim.
3669 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3670 {
3671 exarg_T ea;
3672
Bram Moolenaara80faa82020-04-12 19:37:17 +02003673 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003674 ex_quit(&ea);
3675 return TRUE;
3676 }
3677
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003678 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003679 ch_log(NULL, "terminal job finished, closing window");
3680 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaare76062c2022-11-28 18:51:43 +00003681 if (curbuf == term->tl_buffer)
3682 {
3683 // Avoid closing the window if we temporarily use it.
3684 if (is_aucmd_win(curwin))
zeertzjqbc11f6d2024-08-16 21:11:31 +02003685 do_set_w_locked = TRUE;
3686 if (do_set_w_locked)
Christian Brabandt0a6e57b2024-08-15 22:15:28 +02003687 curwin->w_locked = TRUE;
Bram Moolenaare76062c2022-11-28 18:51:43 +00003688 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
zeertzjqbc11f6d2024-08-16 21:11:31 +02003689 if (do_set_w_locked)
Christian Brabandt0a6e57b2024-08-15 22:15:28 +02003690 curwin->w_locked = FALSE;
Bram Moolenaare76062c2022-11-28 18:51:43 +00003691 aucmd_restbuf(&aco);
3692 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003693#ifdef FEAT_PROP_POPUP
3694 if (pwin != NULL)
3695 popup_close_with_retval(pwin, 0);
3696#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003697 return TRUE;
3698 }
3699 if (term->tl_finish == TL_FINISH_OPEN
3700 && term->tl_buffer->b_nwindows == 0)
3701 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003702 char *cmd = term->tl_opencmd == NULL
3703 ? "botright sbuf %d"
3704 : (char *)term->tl_opencmd;
3705 size_t len = strlen(cmd) + 50;
3706 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003707
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003708 if (buf != NULL)
3709 {
3710 ch_log(NULL, "terminal job finished, opening window");
3711 vim_snprintf(buf, len, cmd, fnum);
3712 do_cmdline_cmd((char_u *)buf);
3713 vim_free(buf);
3714 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003715 }
3716 else
3717 ch_log(NULL, "terminal job finished");
3718 }
3719
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003720 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003721 return FALSE;
3722}
3723
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003724#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3725/*
3726 * If the current window is a terminal in a popup window and the job has
3727 * finished, close the popup window and to back to the previous window.
3728 * Otherwise return FAIL.
3729 */
3730 int
3731may_close_term_popup(void)
3732{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003733 if (!popup_is_popup(curwin) || curbuf->b_term == NULL
3734 || term_job_running_not_none(curbuf->b_term))
3735 return FAIL;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003736
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003737 win_T *pwin = curwin;
3738
3739 if (win_valid(prevwin))
3740 win_enter(prevwin, FALSE);
3741 popup_close_with_retval(pwin, 0);
3742 return OK;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003743}
3744#endif
3745
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003746/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003747 * Called when a channel is going to be closed, before invoking the close
3748 * callback.
3749 */
3750 void
3751term_channel_closing(channel_T *ch)
3752{
3753 term_T *term;
3754
3755 for (term = first_term; term != NULL; term = term->tl_next)
3756 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3757 term->tl_channel_closing = TRUE;
3758}
3759
3760/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003761 * Called when a channel has been closed.
3762 * If this was a channel for a terminal window then finish it up.
3763 */
3764 void
3765term_channel_closed(channel_T *ch)
3766{
3767 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003768 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003769 int did_one = FALSE;
3770
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003771 for (term = first_term; term != NULL; term = next_term)
3772 {
3773 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003774 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003775 {
3776 term->tl_channel_closed = TRUE;
3777 did_one = TRUE;
3778
Bram Moolenaard23a8232018-02-10 18:45:26 +01003779 VIM_CLEAR(term->tl_title);
3780 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003781#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003782 if (term->tl_out_fd != NULL)
3783 {
3784 fclose(term->tl_out_fd);
3785 term->tl_out_fd = NULL;
3786 }
3787#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003788
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003789 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003790 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003791 // Cannot open or close windows now. Can happen when
3792 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003793 term->tl_channel_recently_closed = TRUE;
3794 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003795 }
3796
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003797 if (term_after_channel_closed(term))
3798 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003799 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003800 }
3801
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003802 if (did_one)
3803 {
3804 redraw_statuslines();
3805
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003806 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003807 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003808 typebuf_was_filled = TRUE;
3809
3810 term = curbuf->b_term;
3811 if (term != NULL)
3812 {
3813 if (term->tl_job == ch->ch_job)
3814 maketitle();
3815 update_cursor(term, term->tl_cursor_visible);
3816 }
3817 }
3818}
3819
3820/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003821 * To be called after resetting updating_screen: handle any terminal where the
3822 * channel was closed.
3823 */
3824 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003825term_check_channel_closed_recently(void)
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003826{
3827 term_T *term;
3828 term_T *next_term;
3829
3830 for (term = first_term; term != NULL; term = next_term)
3831 {
3832 next_term = term->tl_next;
3833 if (term->tl_channel_recently_closed)
3834 {
3835 term->tl_channel_recently_closed = FALSE;
3836 if (term_after_channel_closed(term))
3837 // start over, the list may have changed
3838 next_term = first_term;
3839 }
3840 }
3841}
3842
3843/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003844 * Fill one screen line from a line of the terminal.
3845 * Advances "pos" to past the last column.
3846 */
3847 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003848term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003849 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003850 win_T *wp,
3851 VTermScreen *screen,
3852 VTermPos *pos,
3853 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003854{
3855 int off = screen_get_current_line_off();
3856
3857 for (pos->col = 0; pos->col < max_col; )
3858 {
3859 VTermScreenCell cell;
3860 int c;
3861
3862 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003863 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003864
3865 c = cell.chars[0];
3866 if (c == NUL)
3867 {
3868 ScreenLines[off] = ' ';
3869 if (enc_utf8)
3870 ScreenLinesUC[off] = NUL;
3871 }
3872 else
3873 {
3874 if (enc_utf8)
3875 {
3876 int i;
3877
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003878 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003879 for (i = 0; i < Screen_mco
3880 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3881 {
3882 ScreenLinesC[i][off] = cell.chars[i + 1];
3883 if (cell.chars[i + 1] == 0)
3884 break;
3885 }
3886 if (c >= 0x80 || (Screen_mco > 0
3887 && ScreenLinesC[0][off] != 0))
3888 {
3889 ScreenLines[off] = ' ';
3890 ScreenLinesUC[off] = c;
3891 }
3892 else
3893 {
3894 ScreenLines[off] = c;
3895 ScreenLinesUC[off] = NUL;
3896 }
3897 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003898#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003899 else if (has_mbyte && c >= 0x80)
3900 {
3901 char_u mb[MB_MAXBYTES+1];
3902 WCHAR wc = c;
3903
3904 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3905 (char*)mb, 2, 0, 0) > 1)
3906 {
3907 ScreenLines[off] = mb[0];
3908 ScreenLines[off + 1] = mb[1];
3909 cell.width = mb_ptr2cells(mb);
3910 }
3911 else
3912 ScreenLines[off] = c;
3913 }
3914#endif
3915 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003916 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003917 ScreenLines[off] = c;
3918 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003919 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3920 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003921
3922 ++pos->col;
3923 ++off;
3924 if (cell.width == 2)
3925 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003926 // don't set the second byte to NUL for a DBCS encoding, it
3927 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003928 if (enc_utf8)
3929 {
3930 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003931 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003932 }
3933 else if (!has_mbyte)
3934 {
3935 // Can't show a double-width character with a single-byte
3936 // 'encoding', just use a space.
3937 ScreenLines[off] = ' ';
3938 ScreenAttrs[off] = ScreenAttrs[off - 1];
3939 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003940
3941 ++pos->col;
3942 ++off;
3943 }
3944 }
3945}
3946
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003947#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003948 static void
3949update_system_term(term_T *term)
3950{
3951 VTermPos pos;
3952 VTermScreen *screen;
3953
3954 if (term->tl_vterm == NULL)
3955 return;
3956 screen = vterm_obtain_screen(term->tl_vterm);
3957
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003958 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003959 while (term->tl_toprow > 0
3960 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3961 {
3962 int save_p_more = p_more;
3963
3964 p_more = FALSE;
3965 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003966 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003967 p_more = save_p_more;
3968 --term->tl_toprow;
3969 }
3970
3971 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3972 && pos.row < Rows; ++pos.row)
3973 {
3974 if (pos.row < term->tl_rows)
3975 {
3976 int max_col = MIN(Columns, term->tl_cols);
3977
Bram Moolenaar83d47902020-03-26 20:34:00 +01003978 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003979 }
3980 else
3981 pos.col = 0;
3982
zeertzjqd0c1b772024-03-16 15:03:33 +01003983 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, -1,
3984 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003985 }
3986
3987 term->tl_dirty_row_start = MAX_ROW;
3988 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003989}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003990#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003991
3992/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003993 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3994 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003995 * Terminal-Normal mode.
3996 */
3997 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003998term_do_update_window(win_T *wp)
3999{
4000 term_T *term = wp->w_buffer->b_term;
4001
4002 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
4003}
4004
4005/*
4006 * Called to update a window that contains an active terminal.
4007 */
4008 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004009term_update_window(win_T *wp)
4010{
4011 term_T *term = wp->w_buffer->b_term;
4012 VTerm *vterm;
4013 VTermScreen *screen;
4014 VTermState *state;
4015 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004016 int rows, cols;
4017 int newrows, newcols;
4018 int minsize;
4019 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004020
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004021 vterm = term->tl_vterm;
4022 screen = vterm_obtain_screen(vterm);
4023 state = vterm_obtain_state(vterm);
4024
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004025 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
4026 // With UPD_SOME_VALID only redraw what was marked dirty.
4027 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004028 {
4029 term->tl_dirty_row_start = 0;
4030 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004031
4032 if (term->tl_postponed_scroll > 0
4033 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004034 // Scrolling is usually faster than redrawing, when there are only
4035 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004036 term_scroll_up(term, 0, term->tl_postponed_scroll);
4037 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004038 }
4039
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004040 /*
4041 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004042 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004043 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004044 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004045
Bram Moolenaar498c2562018-04-15 23:45:15 +02004046 newrows = 99999;
4047 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004048 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02004049 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004050 // Always use curwin, it may be a popup window.
4051 win_T *wwp = twp == NULL ? curwin : twp;
4052
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004053 // When more than one window shows the same terminal, use the
4054 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004055 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004056 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004057 newrows = MIN(newrows, wwp->w_height);
4058 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004059 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004060 if (twp == NULL)
4061 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004062 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02004063 if (newrows == 99999 || newcols == 99999)
4064 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02004065 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
4066 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
4067
Bram Moolenaareba13e42021-02-23 17:47:23 +01004068 // If no cell is visible there is no point in resizing. Also, vterm can't
4069 // handle a zero height.
4070 if (newrows == 0 || newcols == 0)
4071 return;
4072
Bram Moolenaar498c2562018-04-15 23:45:15 +02004073 if (term->tl_rows != newrows || term->tl_cols != newcols)
4074 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004075 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004076 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004077 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02004078 newrows);
4079 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02004080
4081 // Updating the terminal size will cause the snapshot to be cleared.
4082 // When not in terminal_loop() we need to restore it.
4083 if (term != in_terminal_loop)
4084 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004085 }
4086
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004087 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004088 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01004089 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004090
Bram Moolenaar3a497e12017-09-30 20:40:27 +02004091 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
4092 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004093 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004094 if (pos.row < term->tl_rows)
4095 {
Bram Moolenaar13568252018-03-16 20:46:58 +01004096 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004097
Bram Moolenaar83d47902020-03-26 20:34:00 +01004098 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004099 }
4100 else
4101 pos.col = 0;
4102
Bram Moolenaar510f0372022-07-04 17:46:22 +01004103 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01004104#ifdef FEAT_MENU
4105 + winbar_height(wp)
4106#endif
zeertzjqd0c1b772024-03-16 15:03:33 +01004107 , wp->w_wincol, pos.col, wp->w_width, -1,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004108#ifdef FEAT_PROP_POPUP
4109 popup_is_popup(wp) ? SLF_POPUP :
4110#endif
4111 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004112 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00004113}
4114
4115/*
4116 * Called after updating all windows: may reset dirty rows.
4117 */
4118 void
4119term_did_update_window(win_T *wp)
4120{
4121 term_T *term = wp->w_buffer->b_term;
4122
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004123 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode
4124 || wp->w_redr_type != 0)
4125 return;
4126
4127 term->tl_dirty_row_start = MAX_ROW;
4128 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004129}
4130
4131/*
4132 * Return TRUE if "wp" is a terminal window where the job has finished.
4133 */
4134 int
4135term_is_finished(buf_T *buf)
4136{
4137 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
4138}
4139
4140/*
4141 * Return TRUE if "wp" is a terminal window where the job has finished or we
4142 * are in Terminal-Normal mode, thus we show the buffer contents.
4143 */
4144 int
4145term_show_buffer(buf_T *buf)
4146{
4147 term_T *term = buf->b_term;
4148
4149 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4150}
4151
4152/*
4153 * The current buffer is going to be changed. If there is terminal
4154 * highlighting remove it now.
4155 */
4156 void
4157term_change_in_curbuf(void)
4158{
4159 term_T *term = curbuf->b_term;
4160
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004161 if (!term_is_finished(curbuf) || term->tl_scrollback.ga_len <= 0)
4162 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004163
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004164 free_scrollback(term);
4165 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
4166
4167 // The buffer is now like a normal buffer, it cannot be easily
4168 // abandoned when changed.
4169 set_string_option_direct((char_u *)"buftype", -1,
4170 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004171}
4172
4173/*
4174 * Get the screen attribute for a position in the buffer.
4175 * Use a negative "col" to get the filler background color.
4176 */
4177 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004178term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004179{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004180 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004181 term_T *term = buf->b_term;
4182 sb_line_T *line;
4183 cellattr_T *cellattr;
4184
4185 if (lnum > term->tl_scrollback.ga_len)
4186 cellattr = &term->tl_default_color;
4187 else
4188 {
4189 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4190 if (col < 0 || col >= line->sb_cols)
4191 cellattr = &line->sb_fill_attr;
4192 else
4193 cellattr = line->sb_cells + col;
4194 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004195 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004196}
4197
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004198/*
4199 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004200 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004201 */
4202 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004203cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004204{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004205 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4206 if (rgb->index == 0)
4207 rgb->type = VTERM_COLOR_RGB;
4208 else
4209 {
4210 rgb->type = VTERM_COLOR_INDEXED;
4211 --rgb->index;
4212 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004213}
4214
4215/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004216 * Initialize vterm color from the synID.
4217 * Returns TRUE if color is set to "fg" and "bg".
4218 * Otherwise returns FALSE.
4219 */
4220 static int
4221get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4222{
4223#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4224 // Use the actual color for the GUI and when 'termguicolors' is set.
4225 if (0
4226# ifdef FEAT_GUI
4227 || gui.in_use
4228# endif
4229# ifdef FEAT_TERMGUICOLORS
4230 || p_tgc
4231# ifdef FEAT_VTP
4232 // Finally get INVALCOLOR on this execution path
4233 || (!p_tgc && t_colors >= 256)
4234# endif
4235# endif
4236 )
4237 {
4238 guicolor_T fg_rgb = INVALCOLOR;
4239 guicolor_T bg_rgb = INVALCOLOR;
4240
4241 if (id > 0)
4242 syn_id2colors(id, &fg_rgb, &bg_rgb);
4243
4244 if (fg_rgb != INVALCOLOR)
4245 {
4246 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4247 fg->red = (unsigned)(rgb >> 16);
4248 fg->green = (unsigned)(rgb >> 8) & 255;
4249 fg->blue = (unsigned)rgb & 255;
4250 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4251 }
4252 else
4253 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4254
4255 if (bg_rgb != INVALCOLOR)
4256 {
4257 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4258 bg->red = (unsigned)(rgb >> 16);
4259 bg->green = (unsigned)(rgb >> 8) & 255;
4260 bg->blue = (unsigned)rgb & 255;
4261 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4262 }
4263 else
4264 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4265
4266 return TRUE;
4267 }
4268 else
4269#endif
4270 if (t_colors >= 16)
4271 {
4272 int cterm_fg = -1;
4273 int cterm_bg = -1;
4274
4275 if (id > 0)
4276 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4277
4278 if (cterm_fg >= 0)
4279 {
4280 cterm_color2vterm(cterm_fg, fg);
4281 fg->type |= VTERM_COLOR_DEFAULT_FG;
4282 }
4283 else
4284 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4285
4286 if (cterm_bg >= 0)
4287 {
4288 cterm_color2vterm(cterm_bg, bg);
4289 bg->type |= VTERM_COLOR_DEFAULT_BG;
4290 }
4291 else
4292 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4293
4294 return TRUE;
4295 }
4296
4297 return FALSE;
4298}
4299
4300 void
4301term_reset_wincolor(win_T *wp)
4302{
4303 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4304 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4305}
4306
4307/*
4308 * Cache the color of 'wincolor'.
4309 */
4310 void
4311term_update_wincolor(win_T *wp)
4312{
4313 int id = 0;
4314
4315 if (*wp->w_p_wcr != NUL)
4316 id = syn_name2id(wp->w_p_wcr);
4317 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4318 &wp->w_term_wincolor.bg))
4319 term_reset_wincolor(wp);
4320}
4321
4322/*
4323 * Called when option 'termguicolors' was set,
4324 * or when any highlight is changed.
4325 */
4326 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004327term_update_wincolor_all(void)
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004328{
4329 win_T *wp = NULL;
4330 int did_curwin = FALSE;
4331
4332 while (for_all_windows_and_curwin(&wp, &did_curwin))
4333 term_update_wincolor(wp);
4334}
4335
4336/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004337 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004338 */
4339 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004340init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004341{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004342 VTermColor *fg, *bg;
4343 int fgval, bgval;
4344 int id;
4345
Bram Moolenaara80faa82020-04-12 19:37:17 +02004346 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004347 term->tl_default_color.width = 1;
4348 fg = &term->tl_default_color.fg;
4349 bg = &term->tl_default_color.bg;
4350
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004351 // Vterm uses a default black background. Set it to white when
4352 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004353 if (*p_bg == 'l')
4354 {
4355 fgval = 0;
4356 bgval = 255;
4357 }
4358 else
4359 {
4360 fgval = 255;
4361 bgval = 0;
4362 }
4363 fg->red = fg->green = fg->blue = fgval;
4364 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004365 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4366 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004367
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004368 // The highlight group overrules the defaults.
4369 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004370
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004371 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004372 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004373#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004374 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004375#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004376
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004377 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004378 if (cterm_normal_fg_color > 0)
4379 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004380 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004381# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4382# ifdef VIMDLL
4383 if (!gui.in_use)
4384# endif
4385 {
4386 tmp = fg->red;
4387 fg->red = fg->blue;
4388 fg->blue = tmp;
4389 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004390# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004391 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004392# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004393 else
4394 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004395# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004396
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004397 if (cterm_normal_bg_color > 0)
4398 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004399 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004400# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4401# ifdef VIMDLL
4402 if (!gui.in_use)
4403# endif
4404 {
4405 tmp = fg->red;
4406 fg->red = fg->blue;
4407 fg->blue = tmp;
4408 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004409# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004410 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004411# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004412 else
4413 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004414# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004415 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004416}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004417
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004418#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4419/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004420 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4421 * "ansi_colors" argument in term_start()) shall be applied.
4422 */
4423 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004424term_use_palette(void)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004425{
4426 if (0
4427#ifdef FEAT_GUI
4428 || gui.in_use
4429#endif
4430#ifdef FEAT_TERMGUICOLORS
4431 || p_tgc
4432#endif
4433 )
4434 return TRUE;
4435 return FALSE;
4436}
4437
4438/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004439 * Set the 16 ANSI colors from array of RGB values
4440 */
4441 static void
4442set_vterm_palette(VTerm *vterm, long_u *rgb)
4443{
4444 int index = 0;
4445 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004446
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004447 for (; index < 16; index++)
4448 {
4449 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004450
Millyb771b6b2021-11-23 12:07:25 +00004451 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004452 color.red = (unsigned)(rgb[index] >> 16);
4453 color.green = (unsigned)(rgb[index] >> 8) & 255;
4454 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004455 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004456 vterm_state_set_palette_color(state, index, &color);
4457 }
4458}
4459
4460/*
4461 * Set the ANSI color palette from a list of colors
4462 */
4463 static int
4464set_ansi_colors_list(VTerm *vterm, list_T *list)
4465{
4466 int n = 0;
4467 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004468 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004469
Bram Moolenaarb0992022020-01-30 14:55:42 +01004470 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004471 {
4472 char_u *color_name;
4473 guicolor_T guicolor;
4474
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004475 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004476 if (color_name == NULL)
4477 return FAIL;
4478
4479 guicolor = GUI_GET_COLOR(color_name);
4480 if (guicolor == INVALCOLOR)
4481 return FAIL;
4482
4483 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4484 }
4485
4486 if (n != 16 || li != NULL)
4487 return FAIL;
4488
4489 set_vterm_palette(vterm, rgb);
4490
4491 return OK;
4492}
4493
4494/*
4495 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4496 */
4497 static void
4498init_vterm_ansi_colors(VTerm *vterm)
4499{
4500 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4501
LemonBoyb2b3acb2022-05-20 10:10:34 +01004502 if (var == NULL)
4503 return;
4504
4505 if (var->di_tv.v_type != VAR_LIST
4506 || var->di_tv.vval.v_list == NULL
4507 || var->di_tv.vval.v_list->lv_first == &range_list_item
4508 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004509 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004510}
4511#endif
4512
Bram Moolenaar52acb112018-03-18 19:20:22 +01004513/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004514 * Handles a "drop" command from the job in the terminal.
4515 * "item" is the file name, "item->li_next" may have options.
4516 */
4517 static void
4518handle_drop_command(listitem_T *item)
4519{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004520 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004521 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004522 int bufnr;
4523 win_T *wp;
4524 tabpage_T *tp;
4525 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004526 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004527
4528 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4529 FOR_ALL_TAB_WINDOWS(tp, wp)
4530 {
4531 if (wp->w_buffer->b_fnum == bufnr)
4532 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004533 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004534 goto_tabpage_win(tp, wp);
4535 return;
4536 }
4537 }
4538
Bram Moolenaara80faa82020-04-12 19:37:17 +02004539 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004540
4541 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4542 && opt_item->li_tv.vval.v_dict != NULL)
4543 {
4544 dict_T *dict = opt_item->li_tv.vval.v_dict;
4545 char_u *p;
4546
Bram Moolenaard61efa52022-07-23 09:52:04 +01004547 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004548 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004549 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004550 if (p != NULL)
4551 {
4552 if (check_ff_value(p) == FAIL)
4553 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4554 else
4555 ea.force_ff = *p;
4556 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004557 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004558 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004559 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004560 if (p != NULL)
4561 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004562 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004563 if (ea.cmd != NULL)
4564 {
4565 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4566 ea.force_enc = 11;
4567 tofree = ea.cmd;
4568 }
4569 }
4570
Bram Moolenaard61efa52022-07-23 09:52:04 +01004571 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004572 if (p != NULL)
4573 get_bad_opt(p, &ea);
4574
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004575 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004576 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004577 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004578 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004579 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004580 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004581 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004582 ea.force_bin = FORCE_NOBIN;
4583 }
4584
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004585 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004586 if (ea.cmd == NULL)
4587 ea.cmd = (char_u *)"split";
4588 ea.arg = fname;
4589 ea.cmdidx = CMD_split;
4590 ex_splitview(&ea);
4591
4592 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004593}
4594
4595/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004596 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4597 */
4598 static int
4599is_permitted_term_api(char_u *func, char_u *pat)
4600{
4601 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4602}
4603
4604/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004605 * Handles a function call from the job running in a terminal.
4606 * "item" is the function name, "item->li_next" has the arguments.
4607 */
4608 static void
4609handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4610{
4611 char_u *func;
4612 typval_T argvars[2];
4613 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004614 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004615
4616 if (item->li_next == NULL)
4617 {
4618 ch_log(channel, "Missing function arguments for call");
4619 return;
4620 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004621 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004622
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004623 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004624 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004625 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004626 return;
4627 }
4628
4629 argvars[0].v_type = VAR_NUMBER;
4630 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4631 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004632 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004633 funcexe.fe_firstline = 1L;
4634 funcexe.fe_lastline = 1L;
4635 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004636 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004637 {
4638 clear_tv(&rettv);
4639 ch_log(channel, "Function %s called", func);
4640 }
4641 else
4642 ch_log(channel, "Calling function %s failed", func);
4643}
4644
4645/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004646 * URL decoding (also know as Percent-encoding).
4647 *
4648 * Note this function currently is only used for decoding shell's
4649 * OSC 7 escape sequence which we can assume all bytes are valid
4650 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4651 * encoding bytes like 0xfe, 0xff.
4652 */
4653 static size_t
4654url_decode(const char *src, const size_t len, char_u *dst)
4655{
4656 size_t i = 0, j = 0;
4657
4658 while (i < len)
4659 {
4660 if (src[i] == '%' && i + 2 < len)
4661 {
4662 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4663 j++;
4664 i += 3;
4665 }
4666 else
4667 {
4668 dst[j] = src[i];
4669 i++;
4670 j++;
4671 }
4672 }
4673 dst[j] = '\0';
4674 return j;
4675}
4676
4677/*
4678 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4679 *
4680 * The OSC 7 sequence has the format of
4681 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4682 * and what VTerm provides via VTermStringFragment is
4683 * "file://HOSTNAME/CURRENT/DIR"
4684 */
4685 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004686sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004687{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004688 int offset = 7; // len of "file://" is 7
4689 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004690 char_u *new_dir;
4691
4692 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004693 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004694 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004695 ++offset;
4696 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004697 }
4698
Bram Moolenaar474ad392022-08-21 11:37:17 +01004699 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004700 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004701 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004702 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004703 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004704 }
4705
Bram Moolenaar474ad392022-08-21 11:37:17 +01004706 new_dir = alloc(gap->ga_len - offset + 1);
4707 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004708 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4709 vim_free(new_dir);
4710}
4711
4712/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004713 * Called by libvterm when it cannot recognize an OSC sequence.
4714 * We recognize a terminal API command.
4715 */
4716 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004717parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004718{
4719 term_T *term = (term_T *)user;
4720 js_read_T reader;
4721 typval_T tv;
4722 channel_T *channel = term->tl_job == NULL ? NULL
4723 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004724 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004725
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004726 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004727 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004728 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004729
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004730 // Concatenate what was received until the final piece is found.
4731 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4732 {
4733 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004734 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004735 }
4736 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004737 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004738 if (!frag.final)
4739 return 1;
4740
4741 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004742
4743 if (command == 7)
4744 {
4745 sync_shell_dir(gap);
4746 ga_clear(gap);
4747 return 1;
4748 }
4749
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004750 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004751 reader.js_fill = NULL;
4752 reader.js_used = 0;
4753 if (json_decode(&reader, &tv, 0) == OK
4754 && tv.v_type == VAR_LIST
4755 && tv.vval.v_list != NULL)
4756 {
4757 listitem_T *item = tv.vval.v_list->lv_first;
4758
4759 if (item == NULL)
4760 ch_log(channel, "Missing command");
4761 else
4762 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004763 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004764
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004765 // Make sure an invoked command doesn't delete the buffer (and the
4766 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004767 ++term->tl_buffer->b_locked;
4768
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004769 item = item->li_next;
4770 if (item == NULL)
4771 ch_log(channel, "Missing argument for %s", cmd);
4772 else if (STRCMP(cmd, "drop") == 0)
4773 handle_drop_command(item);
4774 else if (STRCMP(cmd, "call") == 0)
4775 handle_call_command(term, channel, item);
4776 else
4777 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004778 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004779 }
4780 }
4781 else
4782 ch_log(channel, "Invalid JSON received");
4783
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004784 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004785 clear_tv(&tv);
4786 return 1;
4787}
4788
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004789/*
4790 * Called by libvterm when it cannot recognize a CSI sequence.
4791 * We recognize the window position report.
4792 */
4793 static int
4794parse_csi(
4795 const char *leader UNUSED,
4796 const long args[],
4797 int argcount,
4798 const char *intermed UNUSED,
4799 char command,
4800 void *user)
4801{
4802 term_T *term = (term_T *)user;
4803 char buf[100];
4804 int len;
4805 int x = 0;
4806 int y = 0;
4807 win_T *wp;
4808
4809 // We recognize only CSI 13 t
4810 if (command != 't' || argcount != 1 || args[0] != 13)
4811 return 0; // not handled
4812
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004813 // When getting the window position is not possible or it fails it results
4814 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004815#if defined(FEAT_GUI) \
4816 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4817 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004818 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004819#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004820
4821 FOR_ALL_WINDOWS(wp)
4822 if (wp->w_buffer == term->tl_buffer)
4823 break;
4824 if (wp != NULL)
4825 {
4826#ifdef FEAT_GUI
4827 if (gui.in_use)
4828 {
4829 x += wp->w_wincol * gui.char_width;
4830 y += W_WINROW(wp) * gui.char_height;
4831 }
4832 else
4833#endif
4834 {
4835 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004836 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004837 x += wp->w_wincol * 7;
4838 y += W_WINROW(wp) * 10;
4839 }
4840 }
4841
4842 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4843 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4844 (char_u *)buf, len, NULL);
4845 return 1;
4846}
4847
Bram Moolenaard8637282020-05-20 18:41:41 +02004848static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004849 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004850 parse_csi, // csi
4851 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004852 NULL, // dcs
4853 NULL, // apc
4854 NULL, // pm
4855 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004856};
4857
4858/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004859 * Use Vim's allocation functions for vterm so profiling works.
4860 */
4861 static void *
4862vterm_malloc(size_t size, void *data UNUSED)
4863{
Bram Moolenaar88137392021-11-12 16:01:15 +00004864 // make sure that the length is not zero
4865 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004866}
4867
4868 static void
4869vterm_memfree(void *ptr, void *data UNUSED)
4870{
4871 vim_free(ptr);
4872}
4873
4874static VTermAllocatorFunctions vterm_allocator = {
4875 &vterm_malloc,
4876 &vterm_memfree
4877};
4878
4879/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004880 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004881 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004882 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004883 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004884create_vterm(term_T *term, int rows, int cols)
4885{
4886 VTerm *vterm;
4887 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004888 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004889 VTermValue value;
4890
Bram Moolenaar756ef112018-04-10 12:04:27 +02004891 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004892 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004893 if (vterm == NULL)
4894 return FAIL;
4895
4896 // Allocate screen and state here, so we can bail out if that fails.
4897 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004898 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004899 if (state == NULL || screen == NULL)
4900 {
4901 vterm_free(vterm);
4902 return FAIL;
4903 }
4904
Bram Moolenaar52acb112018-03-18 19:20:22 +01004905 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004906 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004907 vterm_set_utf8(vterm, 1);
4908
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004909 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004910
4911 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004912 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004913 &term->tl_default_color.fg,
4914 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004915
Bram Moolenaar9e587872019-05-13 20:27:23 +02004916 if (t_colors < 16)
4917 // Less than 16 colors: assume that bold means using a bright color for
4918 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004919 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4920
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004921 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004922 vterm_screen_reset(screen, 1 /* hard */);
4923
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004924 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004925 vterm_screen_enable_altscreen(screen, 1);
4926
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004927 // For unix do not use a blinking cursor. In an xterm this causes the
4928 // cursor to blink if it's blinking in the xterm.
4929 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004930#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004931 if (GetCaretBlinkTime() == INFINITE)
4932 value.boolean = 0;
4933 else
4934 value.boolean = 1;
4935#else
4936 value.boolean = 0;
4937#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004938 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004939 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004940
4941 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004942}
4943
4944/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004945 * Reset the terminal palette to its default value.
4946 */
4947 static void
4948term_reset_palette(VTerm *vterm)
4949{
4950 VTermState *state = vterm_obtain_state(vterm);
4951 int index;
4952
4953 for (index = 0; index < 16; index++)
4954 {
4955 VTermColor color;
4956
4957 color.type = VTERM_COLOR_INDEXED;
4958 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4959 &color.index);
4960 // The first valid index starts at 1.
4961 color.index -= 1;
4962
4963 vterm_state_set_palette_color(state, index, &color);
4964 }
4965}
4966
4967 static void
4968term_update_palette(term_T *term)
4969{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004970#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004971 if (term_use_palette()
4972 && (term->tl_palette != NULL
4973 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004974 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004975 {
4976 if (term->tl_palette != NULL)
4977 set_vterm_palette(term->tl_vterm, term->tl_palette);
4978 else
4979 init_vterm_ansi_colors(term->tl_vterm);
4980 }
4981 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004982#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004983 term_reset_palette(term->tl_vterm);
4984}
4985
4986/*
4987 * Called when option 'termguicolors' is changed.
4988 */
4989 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004990term_update_palette_all(void)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004991{
4992 term_T *term;
4993
4994 FOR_ALL_TERMS(term)
4995 {
4996 if (term->tl_vterm == NULL)
4997 continue;
4998 term_update_palette(term);
4999 }
5000}
5001
5002/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005003 * Called when option 'background' or 'termguicolors' was set,
5004 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02005005 */
5006 void
5007term_update_colors_all(void)
5008{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005009 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02005010
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005011 FOR_ALL_TERMS(term)
5012 {
5013 if (term->tl_vterm == NULL)
5014 continue;
5015 init_default_colors(term);
5016 vterm_state_set_default_colors(
5017 vterm_obtain_state(term->tl_vterm),
5018 &term->tl_default_color.fg,
5019 &term->tl_default_color.bg);
5020 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005021}
5022
5023/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005024 * Return the text to show for the buffer name and status.
5025 */
5026 char_u *
5027term_get_status_text(term_T *term)
5028{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005029 if (term->tl_status_text != NULL)
5030 return term->tl_status_text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005031
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005032 char_u *txt;
5033 size_t len;
5034 char_u *fname;
5035
5036 if (term->tl_normal_mode)
5037 {
5038 if (term_job_running(term))
5039 txt = (char_u *)_("Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005040 else
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005041 txt = (char_u *)_("Terminal-finished");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005042 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005043 else if (term->tl_title != NULL)
5044 txt = term->tl_title;
5045 else if (term_none_open(term))
5046 txt = (char_u *)_("active");
5047 else if (term_job_running(term))
5048 txt = (char_u *)_("running");
5049 else
5050 txt = (char_u *)_("finished");
5051 fname = buf_get_fname(term->tl_buffer);
5052 len = 9 + STRLEN(fname) + STRLEN(txt);
5053 term->tl_status_text = alloc(len);
5054 if (term->tl_status_text != NULL)
5055 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
5056 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005057 return term->tl_status_text;
5058}
5059
5060/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00005061 * Clear the cached value of the status text.
5062 */
5063 void
5064term_clear_status_text(term_T *term)
5065{
5066 VIM_CLEAR(term->tl_status_text);
5067}
5068
5069/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005070 * Mark references in jobs of terminals.
5071 */
5072 int
5073set_ref_in_term(int copyID)
5074{
5075 int abort = FALSE;
5076 term_T *term;
5077 typval_T tv;
5078
Bram Moolenaar75a1a942019-06-20 03:45:36 +02005079 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005080 if (term->tl_job != NULL)
5081 {
5082 tv.v_type = VAR_JOB;
5083 tv.vval.v_job = term->tl_job;
Yegappan Lakshmanan9cb865e2025-03-23 16:42:16 +01005084 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005085 }
5086 return abort;
5087}
5088
5089/*
5090 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005091 * Returns NULL when the buffer is not for a terminal window and logs a message
5092 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005093 */
5094 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005095term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005096{
5097 buf_T *buf;
5098
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005099 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01005100 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005101 --emsg_off;
5102 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005103 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01005104 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005105 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005106 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005107 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005108 return buf;
5109}
5110
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005111 static void
5112clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005113{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005114 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005115 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
5116 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005117}
5118
5119 static void
5120dump_term_color(FILE *fd, VTermColor *color)
5121{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005122 int index;
5123
5124 if (VTERM_COLOR_IS_INDEXED(color))
5125 index = color->index + 1;
5126 else if (color->type == 0)
5127 // use RGB values
5128 index = 255;
5129 else
5130 // default color
5131 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005132 fprintf(fd, "%02x%02x%02x%d",
5133 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005134 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005135}
5136
5137/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005138 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01005139 *
5140 * Each screen cell in full is:
5141 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5142 * {characters} is a space for an empty cell
5143 * For a double-width character "+" is changed to "*" and the next cell is
5144 * skipped.
5145 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5146 * when "&" use the same as the previous cell.
5147 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5148 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5149 * {color-idx} is a number from 0 to 255
5150 *
5151 * Screen cell with same width, attributes and color as the previous one:
5152 * |{characters}
5153 *
5154 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5155 *
5156 * Repeating the previous screen cell:
5157 * @{count}
5158 */
5159 void
5160f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5161{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005162 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005163 term_T *term;
5164 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005165 int max_height = 0;
5166 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005167 stat_T st;
5168 FILE *fd;
5169 VTermPos pos;
5170 VTermScreen *screen;
5171 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005172 VTermState *state;
5173 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005174
5175 if (check_restricted() || check_secure())
5176 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005177
5178 if (in_vim9script()
5179 && (check_for_buffer_arg(argvars, 0) == FAIL
5180 || check_for_string_arg(argvars, 1) == FAIL
5181 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5182 return;
5183
5184 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005185 if (buf == NULL)
5186 return;
5187 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005188 if (term->tl_vterm == NULL)
5189 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005190 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005191 return;
5192 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005193
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005194 if (argvars[2].v_type != VAR_UNKNOWN)
5195 {
5196 dict_T *d;
5197
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005198 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005199 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005200 d = argvars[2].vval.v_dict;
5201 if (d != NULL)
5202 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005203 max_height = dict_get_number(d, "rows");
5204 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005205 }
5206 }
5207
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005208 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005209 if (fname == NULL)
5210 return;
5211 if (mch_stat((char *)fname, &st) >= 0)
5212 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005213 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005214 return;
5215 }
5216
Bram Moolenaard96ff162018-02-18 22:13:29 +01005217 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5218 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005219 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005220 return;
5221 }
5222
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005223 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005224
5225 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005226 state = vterm_obtain_state(term->tl_vterm);
5227 vterm_state_get_cursorpos(state, &cursor_pos);
5228
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005229 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5230 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005231 {
5232 int repeat = 0;
5233
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005234 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5235 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005236 {
5237 VTermScreenCell cell;
5238 int same_attr;
5239 int same_chars = TRUE;
5240 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005241 int is_cursor_pos = (pos.col == cursor_pos.col
5242 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005243
5244 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005245 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005246
5247 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5248 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005249 int c = cell.chars[i];
5250 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005251 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005252
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005253 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005254 if (i == 0)
5255 {
5256 c = (c == NUL) ? ' ' : c;
5257 pc = (pc == NUL) ? ' ' : pc;
5258 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005259 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005260 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005261 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005262 break;
5263 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005264 same_attr = vtermAttr2hl(&cell.attrs)
5265 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005266 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5267 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005268 if (same_chars && cell.width == prev_cell.width && same_attr
5269 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005270 {
5271 ++repeat;
5272 }
5273 else
5274 {
5275 if (repeat > 0)
5276 {
5277 fprintf(fd, "@%d", repeat);
5278 repeat = 0;
5279 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005280 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005281
5282 if (cell.chars[0] == NUL)
5283 fputs(" ", fd);
5284 else
5285 {
5286 char_u charbuf[10];
5287 int len;
5288
5289 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5290 && cell.chars[i] != NUL; ++i)
5291 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005292 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005293 fwrite(charbuf, len, 1, fd);
5294 }
5295 }
5296
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005297 // When only the characters differ we don't write anything, the
5298 // following "|", "@" or NL will indicate using the same
5299 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005300 if (cell.width != prev_cell.width || !same_attr)
5301 {
5302 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005303 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005304 else
5305 fputs("+", fd);
5306
5307 if (same_attr)
5308 {
5309 fputs("&", fd);
5310 }
5311 else
5312 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005313 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005314 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005315 fputs("&", fd);
5316 else
5317 {
5318 fputs("#", fd);
5319 dump_term_color(fd, &cell.fg);
5320 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005321 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005322 fputs("&", fd);
5323 else
5324 {
5325 fputs("#", fd);
5326 dump_term_color(fd, &cell.bg);
5327 }
5328 }
5329 }
5330
5331 prev_cell = cell;
5332 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005333
5334 if (cell.width == 2)
5335 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005336 }
5337 if (repeat > 0)
5338 fprintf(fd, "@%d", repeat);
5339 fputs("\n", fd);
5340 }
5341
5342 fclose(fd);
5343}
5344
5345/*
5346 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5347 */
5348 static void
5349dump_is_corrupt(garray_T *gap)
5350{
5351 ga_concat(gap, (char_u *)"CORRUPT");
5352}
5353
5354 static void
5355append_cell(garray_T *gap, cellattr_T *cell)
5356{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005357 if (ga_grow(gap, 1) == FAIL)
5358 return;
5359
5360 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5361 ++gap->ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005362}
5363
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005364 static void
5365clear_cellattr(cellattr_T *cell)
5366{
5367 CLEAR_FIELD(*cell);
5368 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5369 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5370}
5371
Bram Moolenaard96ff162018-02-18 22:13:29 +01005372/*
5373 * Read the dump file from "fd" and append lines to the current buffer.
5374 * Return the cell width of the longest line.
5375 */
5376 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005377read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005378{
5379 int c;
5380 garray_T ga_text;
5381 garray_T ga_cell;
5382 char_u *prev_char = NULL;
5383 int attr = 0;
5384 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005385 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005386 term_T *term = curbuf->b_term;
5387 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005388 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005389
5390 ga_init2(&ga_text, 1, 90);
5391 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005392 clear_cellattr(&cell);
5393 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005394 cursor_pos->row = -1;
5395 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005396
5397 c = fgetc(fd);
5398 for (;;)
5399 {
5400 if (c == EOF)
5401 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005402 if (c == '\r')
5403 {
5404 // DOS line endings? Ignore.
5405 c = fgetc(fd);
5406 }
5407 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005408 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005409 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005410 if (ga_text.ga_data == NULL)
5411 dump_is_corrupt(&ga_text);
5412 if (ga_grow(&term->tl_scrollback, 1) == OK)
5413 {
5414 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5415 + term->tl_scrollback.ga_len;
5416
5417 if (max_cells < ga_cell.ga_len)
5418 max_cells = ga_cell.ga_len;
5419 line->sb_cols = ga_cell.ga_len;
5420 line->sb_cells = ga_cell.ga_data;
5421 line->sb_fill_attr = term->tl_default_color;
5422 ++term->tl_scrollback.ga_len;
5423 ga_init(&ga_cell);
5424
5425 ga_append(&ga_text, NUL);
5426 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5427 ga_text.ga_len, FALSE);
5428 }
5429 else
5430 ga_clear(&ga_cell);
5431 ga_text.ga_len = 0;
5432
5433 c = fgetc(fd);
5434 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005435 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005436 {
5437 int prev_len = ga_text.ga_len;
5438
Bram Moolenaar9271d052018-02-25 21:39:46 +01005439 if (c == '>')
5440 {
5441 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005442 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005443 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5444 cursor_pos->col = ga_cell.ga_len;
5445 }
5446
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005447 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005448 c = fgetc(fd);
5449 if (c != EOF)
5450 ga_append(&ga_text, c);
5451 for (;;)
5452 {
5453 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005454 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005455 || c == EOF || c == '\n')
5456 break;
5457 ga_append(&ga_text, c);
5458 }
5459
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005460 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005461 vim_free(prev_char);
5462 if (ga_text.ga_data != NULL)
5463 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5464 ga_text.ga_len - prev_len);
5465
Bram Moolenaar9271d052018-02-25 21:39:46 +01005466 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005467 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005468 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005469 }
5470 else if (c == '+' || c == '*')
5471 {
5472 int is_bg;
5473
5474 cell.width = c == '+' ? 1 : 2;
5475
5476 c = fgetc(fd);
5477 if (c == '&')
5478 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005479 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005480 c = fgetc(fd);
5481 }
Keith Thompson184f71c2024-01-04 21:19:04 +01005482 else if (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005483 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005484 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005485 attr = 0;
Keith Thompson184f71c2024-01-04 21:19:04 +01005486 while (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005487 {
5488 attr = attr * 10 + (c - '0');
5489 c = fgetc(fd);
5490 }
5491 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005492
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005493 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005494 for (is_bg = 0; is_bg <= 1; ++is_bg)
5495 {
5496 if (c == '&')
5497 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005498 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005499 c = fgetc(fd);
5500 }
5501 else if (c == '#')
5502 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005503 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005504
5505 c = fgetc(fd);
5506 red = hex2nr(c);
5507 c = fgetc(fd);
5508 red = (red << 4) + hex2nr(c);
5509 c = fgetc(fd);
5510 green = hex2nr(c);
5511 c = fgetc(fd);
5512 green = (green << 4) + hex2nr(c);
5513 c = fgetc(fd);
5514 blue = hex2nr(c);
5515 c = fgetc(fd);
5516 blue = (blue << 4) + hex2nr(c);
5517 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005518 if (!SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005519 dump_is_corrupt(&ga_text);
Keith Thompson184f71c2024-01-04 21:19:04 +01005520 while (SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005521 {
5522 index = index * 10 + (c - '0');
5523 c = fgetc(fd);
5524 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005525 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005526 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005527 type = VTERM_COLOR_RGB;
5528 if (index == 0)
5529 {
5530 if (is_bg)
5531 type |= VTERM_COLOR_DEFAULT_BG;
5532 else
5533 type |= VTERM_COLOR_DEFAULT_FG;
5534 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005535 }
5536 else
5537 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005538 type = VTERM_COLOR_INDEXED;
5539 index -= 1;
5540 }
5541 if (is_bg)
5542 {
5543 cell.bg.type = type;
5544 cell.bg.red = red;
5545 cell.bg.green = green;
5546 cell.bg.blue = blue;
5547 cell.bg.index = index;
5548 }
5549 else
5550 {
5551 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005552 cell.fg.red = red;
5553 cell.fg.green = green;
5554 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005555 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005556 }
5557 }
5558 else
5559 dump_is_corrupt(&ga_text);
5560 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005561 }
5562 else
5563 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005564 }
5565 else
5566 dump_is_corrupt(&ga_text);
5567
5568 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005569 if (cell.width == 2)
5570 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005571 }
5572 else if (c == '@')
5573 {
5574 if (prev_char == NULL)
5575 dump_is_corrupt(&ga_text);
5576 else
5577 {
5578 int count = 0;
5579
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005580 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005581 for (;;)
5582 {
5583 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005584 if (!SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005585 break;
5586 count = count * 10 + (c - '0');
5587 }
5588
5589 while (count-- > 0)
5590 {
5591 ga_concat(&ga_text, prev_char);
5592 append_cell(&ga_cell, &cell);
5593 }
5594 }
5595 }
5596 else
5597 {
5598 dump_is_corrupt(&ga_text);
5599 c = fgetc(fd);
5600 }
5601 }
5602
5603 if (ga_text.ga_len > 0)
5604 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005605 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005606 dump_is_corrupt(&ga_text);
5607 ga_append(&ga_text, NUL);
5608 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5609 ga_text.ga_len, FALSE);
5610 }
5611
5612 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005613 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005614 vim_free(prev_char);
5615
5616 return max_cells;
5617}
5618
5619/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005620 * Return an allocated string with at least "text_width" "=" characters and
5621 * "fname" inserted in the middle.
5622 */
5623 static char_u *
5624get_separator(int text_width, char_u *fname)
5625{
5626 int width = MAX(text_width, curwin->w_width);
5627 char_u *textline;
5628 int fname_size;
5629 char_u *p = fname;
5630 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005631 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005632
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005633 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005634 if (textline == NULL)
5635 return NULL;
5636
5637 fname_size = vim_strsize(fname);
5638 if (fname_size < width - 8)
5639 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005640 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005641 width = MAX(text_width, fname_size + 8);
5642 }
5643 else if (fname_size > width - 8)
5644 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005645 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005646 p = gettail(fname);
5647 fname_size = vim_strsize(p);
5648 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005649 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005650 while (fname_size > width - 8)
5651 {
5652 p += (*mb_ptr2len)(p);
5653 fname_size = vim_strsize(p);
5654 }
5655
5656 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5657 textline[i] = '=';
5658 textline[i++] = ' ';
5659
5660 STRCPY(textline + i, p);
5661 off = STRLEN(textline);
5662 textline[off] = ' ';
5663 for (i = 1; i < (width - fname_size) / 2; ++i)
5664 textline[off + i] = '=';
5665 textline[off + i] = NUL;
5666
5667 return textline;
5668}
5669
5670/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005671 * Common for "term_dumpdiff()" and "term_dumpload()".
5672 */
5673 static void
5674term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5675{
5676 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005677 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005678 char_u buf1[NUMBUFLEN];
5679 char_u buf2[NUMBUFLEN];
5680 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005681 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005682 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005683 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005684 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005685 char_u *textline = NULL;
5686
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005687 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005688 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005689 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005690 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005691 if (fname1 == NULL || (do_diff && fname2 == NULL))
5692 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005693 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005694 return;
5695 }
5696 fd1 = mch_fopen((char *)fname1, READBIN);
5697 if (fd1 == NULL)
5698 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005699 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005700 return;
5701 }
5702 if (do_diff)
5703 {
5704 fd2 = mch_fopen((char *)fname2, READBIN);
5705 if (fd2 == NULL)
5706 {
5707 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005708 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005709 return;
5710 }
5711 }
5712
5713 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005714 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5715 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5716 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5717 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5718 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005719
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005720 if (opt.jo_term_name == NULL)
5721 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005722 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005723
Bram Moolenaar51e14382019-05-25 20:21:28 +02005724 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005725 if (fname_tofree != NULL)
5726 {
5727 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5728 opt.jo_term_name = fname_tofree;
5729 }
5730 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005731
Bram Moolenaar87abab92019-06-03 21:14:59 +02005732 if (opt.jo_bufnr_buf != NULL)
5733 {
5734 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5735
5736 // With "bufnr" argument: enter the window with this buffer and make it
5737 // empty.
5738 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005739 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005740 else
5741 {
5742 buf = curbuf;
5743 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005744 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005745 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005746 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005747 }
5748 }
5749 else
5750 // Create a new terminal window.
5751 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5752
Bram Moolenaard96ff162018-02-18 22:13:29 +01005753 if (buf != NULL && buf->b_term != NULL)
5754 {
5755 int i;
5756 linenr_T bot_lnum;
5757 linenr_T lnum;
5758 term_T *term = buf->b_term;
5759 int width;
5760 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005761 VTermPos cursor_pos1;
5762 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005763
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005764 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005765
Bram Moolenaard96ff162018-02-18 22:13:29 +01005766 rettv->vval.v_number = buf->b_fnum;
5767
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005768 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005769 width = read_dump_file(fd1, &cursor_pos1);
5770
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005771 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005772 if (cursor_pos1.row >= 0)
5773 {
5774 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5775 coladvance(cursor_pos1.col);
5776 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005777
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005778 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005779 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005780
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005781 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005782 if (!do_diff)
5783 goto theend;
5784
5785 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5786
Bram Moolenaar4a696342018-04-05 18:45:26 +02005787 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005788 if (textline == NULL)
5789 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005790 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5791 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5792 vim_free(textline);
5793
5794 textline = get_separator(width, fname2);
5795 if (textline == NULL)
5796 goto theend;
5797 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5798 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005799 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005800
5801 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005802 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005803 if (width2 > width)
5804 {
5805 vim_free(textline);
5806 textline = alloc(width2 + 1);
5807 if (textline == NULL)
5808 goto theend;
5809 width = width2;
5810 textline[width] = NUL;
5811 }
5812 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5813
5814 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5815 {
5816 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5817 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005818 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005819 for (i = 0; i < width; ++i)
5820 textline[i] = '-';
5821 }
5822 else
5823 {
5824 char_u *line1;
5825 char_u *line2;
5826 char_u *p1;
5827 char_u *p2;
5828 int col;
5829 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5830 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5831 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5832 ->sb_cells;
5833
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005834 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005835 line1 = vim_strsave(ml_get(lnum));
5836 if (line1 == NULL)
5837 break;
5838 p1 = line1;
5839
5840 line2 = ml_get(lnum + bot_lnum);
5841 p2 = line2;
5842 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5843 {
5844 int len1 = utfc_ptr2len(p1);
5845 int len2 = utfc_ptr2len(p2);
5846
5847 textline[col] = ' ';
5848 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005849 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005850 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005851 else if (lnum == cursor_pos1.row + 1
5852 && col == cursor_pos1.col
5853 && (cursor_pos1.row != cursor_pos2.row
5854 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005855 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005856 textline[col] = '>';
5857 else if (lnum == cursor_pos2.row + 1
5858 && col == cursor_pos2.col
5859 && (cursor_pos1.row != cursor_pos2.row
5860 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005861 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005862 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005863 else if (cellattr1 != NULL && cellattr2 != NULL)
5864 {
5865 if ((cellattr1 + col)->width
5866 != (cellattr2 + col)->width)
5867 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005868 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005869 &(cellattr2 + col)->fg))
5870 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005871 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005872 &(cellattr2 + col)->bg))
5873 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005874 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5875 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005876 textline[col] = 'a';
5877 }
5878 p1 += len1;
5879 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005880 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005881 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005882
5883 while (col < width)
5884 {
5885 if (*p1 == NUL && *p2 == NUL)
5886 textline[col] = '?';
5887 else if (*p1 == NUL)
5888 {
5889 textline[col] = '+';
5890 p2 += utfc_ptr2len(p2);
5891 }
5892 else
5893 {
5894 textline[col] = '-';
5895 p1 += utfc_ptr2len(p1);
5896 }
5897 ++col;
5898 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005899
5900 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005901 }
5902 if (add_empty_scrollback(term, &term->tl_default_color,
5903 term->tl_top_diff_rows) == OK)
5904 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5905 ++bot_lnum;
5906 }
5907
5908 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5909 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005910 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005911 for (i = 0; i < width; ++i)
5912 textline[i] = '+';
5913 if (add_empty_scrollback(term, &term->tl_default_color,
5914 term->tl_top_diff_rows) == OK)
5915 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5916 ++lnum;
5917 ++bot_lnum;
5918 }
5919
5920 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005921
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005922 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005923 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005924 }
5925
5926theend:
5927 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005928 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005929 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005930 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005931 fclose(fd2);
5932}
5933
5934/*
5935 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5936 * bottom files.
5937 * Return FAIL when this is not possible.
5938 */
5939 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005940term_swap_diff(void)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005941{
5942 term_T *term = curbuf->b_term;
5943 linenr_T line_count;
5944 linenr_T top_rows;
5945 linenr_T bot_rows;
5946 linenr_T bot_start;
5947 linenr_T lnum;
5948 char_u *p;
5949 sb_line_T *sb_line;
5950
5951 if (term == NULL
5952 || !term_is_finished(curbuf)
5953 || term->tl_top_diff_rows == 0
5954 || term->tl_scrollback.ga_len == 0)
5955 return FAIL;
5956
5957 line_count = curbuf->b_ml.ml_line_count;
5958 top_rows = term->tl_top_diff_rows;
5959 bot_rows = term->tl_bot_diff_rows;
5960 bot_start = line_count - bot_rows;
5961 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5962
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005963 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005964 for (lnum = 1; lnum <= top_rows; ++lnum)
5965 {
5966 p = vim_strsave(ml_get(1));
5967 if (p == NULL)
5968 return OK;
5969 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005970 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005971 vim_free(p);
5972 }
5973
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005974 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005975 for (lnum = 1; lnum <= bot_rows; ++lnum)
5976 {
5977 p = vim_strsave(ml_get(bot_start + lnum));
5978 if (p == NULL)
5979 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005980 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005981 ml_append(lnum - 1, p, 0, FALSE);
5982 vim_free(p);
5983 }
5984
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005985 // move top title to bottom
5986 p = vim_strsave(ml_get(bot_rows + 1));
5987 if (p == NULL)
5988 return OK;
5989 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005990 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005991 vim_free(p);
5992
5993 // move bottom title to top
5994 p = vim_strsave(ml_get(line_count - top_rows));
5995 if (p == NULL)
5996 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005997 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005998 ml_append(bot_rows, p, 0, FALSE);
5999 vim_free(p);
6000
Bram Moolenaard96ff162018-02-18 22:13:29 +01006001 if (top_rows == bot_rows)
6002 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006003 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01006004 for (lnum = 0; lnum < top_rows; ++lnum)
6005 {
6006 sb_line_T temp;
6007
6008 temp = *(sb_line + lnum);
6009 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
6010 *(sb_line + bot_start + lnum) = temp;
6011 }
6012 }
6013 else
6014 {
6015 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006016 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006017
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006018 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01006019 if (temp != NULL)
6020 {
6021 mch_memmove(temp, term->tl_scrollback.ga_data, size);
6022 mch_memmove(term->tl_scrollback.ga_data,
6023 temp + bot_start,
6024 sizeof(sb_line_T) * bot_rows);
6025 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
6026 temp + top_rows,
6027 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
6028 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
6029 + line_count - top_rows,
6030 temp,
6031 sizeof(sb_line_T) * top_rows);
6032 vim_free(temp);
6033 }
6034 }
6035
6036 term->tl_top_diff_rows = bot_rows;
6037 term->tl_bot_diff_rows = top_rows;
6038
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006039 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006040 return OK;
6041}
6042
6043/*
6044 * "term_dumpdiff(filename, filename, options)" function
6045 */
6046 void
6047f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
6048{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02006049 if (in_vim9script()
6050 && (check_for_string_arg(argvars, 0) == FAIL
6051 || check_for_string_arg(argvars, 1) == FAIL
6052 || check_for_opt_dict_arg(argvars, 2) == FAIL))
6053 return;
6054
Bram Moolenaard96ff162018-02-18 22:13:29 +01006055 term_load_dump(argvars, rettv, TRUE);
6056}
6057
6058/*
6059 * "term_dumpload(filename, options)" function
6060 */
6061 void
6062f_term_dumpload(typval_T *argvars, typval_T *rettv)
6063{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006064 if (in_vim9script()
6065 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02006066 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006067 return;
6068
Bram Moolenaard96ff162018-02-18 22:13:29 +01006069 term_load_dump(argvars, rettv, FALSE);
6070}
6071
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006072/*
6073 * "term_getaltscreen(buf)" function
6074 */
6075 void
6076f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
6077{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006078 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006079
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006080 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6081 return;
6082
6083 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006084 if (buf == NULL)
6085 return;
6086 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
6087}
6088
6089/*
6090 * "term_getattr(attr, name)" function
6091 */
6092 void
6093f_term_getattr(typval_T *argvars, typval_T *rettv)
6094{
6095 int attr;
6096 size_t i;
6097 char_u *name;
6098
6099 static struct {
6100 char *name;
6101 int attr;
6102 } attrs[] = {
6103 {"bold", HL_BOLD},
6104 {"italic", HL_ITALIC},
6105 {"underline", HL_UNDERLINE},
6106 {"strike", HL_STRIKETHROUGH},
6107 {"reverse", HL_INVERSE},
6108 };
6109
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02006110 if (in_vim9script()
6111 && (check_for_number_arg(argvars, 0) == FAIL
6112 || check_for_string_arg(argvars, 1) == FAIL))
6113 return;
6114
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006115 attr = tv_get_number(&argvars[0]);
6116 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006117 if (name == NULL)
6118 return;
6119
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02006120 if (attr > HL_ALL)
6121 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02006122 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006123 if (STRCMP(name, attrs[i].name) == 0)
6124 {
6125 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
6126 break;
6127 }
6128}
6129
6130/*
6131 * "term_getcursor(buf)" function
6132 */
6133 void
6134f_term_getcursor(typval_T *argvars, typval_T *rettv)
6135{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006136 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006137 term_T *term;
6138 list_T *l;
6139 dict_T *d;
6140
6141 if (rettv_list_alloc(rettv) == FAIL)
6142 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006143
6144 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6145 return;
6146
6147 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006148 if (buf == NULL)
6149 return;
6150 term = buf->b_term;
6151
6152 l = rettv->vval.v_list;
6153 list_append_number(l, term->tl_cursor_pos.row + 1);
6154 list_append_number(l, term->tl_cursor_pos.col + 1);
6155
6156 d = dict_alloc();
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00006157 if (d == NULL)
6158 return;
6159
6160 dict_add_number(d, "visible", term->tl_cursor_visible);
6161 dict_add_number(d, "blink", blink_state_is_inverted()
6162 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6163 dict_add_number(d, "shape", term->tl_cursor_shape);
6164 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
6165 list_append_dict(l, d);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006166}
6167
6168/*
6169 * "term_getjob(buf)" function
6170 */
6171 void
6172f_term_getjob(typval_T *argvars, typval_T *rettv)
6173{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006174 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006175
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006176 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6177 return;
6178
6179 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006180 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006181 {
Ernie Raela78eb252024-06-13 17:24:54 +02006182 if (in_vim9script())
6183 {
6184 rettv->v_type = VAR_JOB;
6185 rettv->vval.v_job = NULL;
6186 }
6187 else
6188 {
6189 rettv->v_type = VAR_SPECIAL;
6190 rettv->vval.v_number = VVAL_NULL;
6191 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006192 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006193 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006194
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006195 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006196 rettv->vval.v_job = buf->b_term->tl_job;
6197 if (rettv->vval.v_job != NULL)
6198 ++rettv->vval.v_job->jv_refcount;
6199}
6200
6201 static int
6202get_row_number(typval_T *tv, term_T *term)
6203{
6204 if (tv->v_type == VAR_STRING
6205 && tv->vval.v_string != NULL
6206 && STRCMP(tv->vval.v_string, ".") == 0)
6207 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006208 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006209}
6210
6211/*
6212 * "term_getline(buf, row)" function
6213 */
6214 void
6215f_term_getline(typval_T *argvars, typval_T *rettv)
6216{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006217 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006218 term_T *term;
6219 int row;
6220
6221 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006222
6223 if (in_vim9script()
6224 && (check_for_buffer_arg(argvars, 0) == FAIL
6225 || check_for_lnum_arg(argvars, 1) == FAIL))
6226 return;
6227
6228 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006229 if (buf == NULL)
6230 return;
6231 term = buf->b_term;
6232 row = get_row_number(&argvars[1], term);
6233
6234 if (term->tl_vterm == NULL)
6235 {
6236 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6237
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006238 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006239 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6240 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6241 }
6242 else
6243 {
6244 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6245 VTermRect rect;
6246 int len;
6247 char_u *p;
6248
6249 if (row < 0 || row >= term->tl_rows)
6250 return;
6251 len = term->tl_cols * MB_MAXBYTES + 1;
6252 p = alloc(len);
6253 if (p == NULL)
6254 return;
6255 rettv->vval.v_string = p;
6256
6257 rect.start_col = 0;
6258 rect.end_col = term->tl_cols;
6259 rect.start_row = row;
6260 rect.end_row = row + 1;
6261 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6262 }
6263}
6264
6265/*
6266 * "term_getscrolled(buf)" function
6267 */
6268 void
6269f_term_getscrolled(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
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006273 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6274 return;
6275
6276 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006277 if (buf == NULL)
6278 return;
6279 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6280}
6281
6282/*
6283 * "term_getsize(buf)" function
6284 */
6285 void
6286f_term_getsize(typval_T *argvars, typval_T *rettv)
6287{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006288 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006289 list_T *l;
6290
6291 if (rettv_list_alloc(rettv) == FAIL)
6292 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006293
6294 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6295 return;
6296
6297 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006298 if (buf == NULL)
6299 return;
6300
6301 l = rettv->vval.v_list;
6302 list_append_number(l, buf->b_term->tl_rows);
6303 list_append_number(l, buf->b_term->tl_cols);
6304}
6305
6306/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006307 * "term_setsize(buf, rows, cols)" function
6308 */
6309 void
Dominique Pellé0268ff32024-07-28 21:12:20 +02006310f_term_setsize(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006311{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006312 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006313 term_T *term;
6314 varnumber_T rows, cols;
6315
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006316 if (in_vim9script()
6317 && (check_for_buffer_arg(argvars, 0) == FAIL
6318 || check_for_number_arg(argvars, 1) == FAIL
6319 || check_for_number_arg(argvars, 2) == FAIL))
6320 return;
6321
6322 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006323 if (buf == NULL)
6324 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006325 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006326 return;
6327 }
6328 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006329 return;
6330 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006331 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006332 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006333 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006334 cols = cols <= 0 ? term->tl_cols : cols;
6335 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006336 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006337
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006338 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006339 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6340 term_report_winsize(term, term->tl_rows, term->tl_cols);
6341}
6342
6343/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006344 * "term_getstatus(buf)" function
6345 */
6346 void
6347f_term_getstatus(typval_T *argvars, typval_T *rettv)
6348{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006349 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006350 term_T *term;
6351 char_u val[100];
6352
6353 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006354
6355 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6356 return;
6357
6358 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006359 if (buf == NULL)
6360 return;
6361 term = buf->b_term;
6362
6363 if (term_job_running(term))
6364 STRCPY(val, "running");
6365 else
6366 STRCPY(val, "finished");
6367 if (term->tl_normal_mode)
6368 STRCAT(val, ",normal");
6369 rettv->vval.v_string = vim_strsave(val);
6370}
6371
6372/*
6373 * "term_gettitle(buf)" function
6374 */
6375 void
6376f_term_gettitle(typval_T *argvars, typval_T *rettv)
6377{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006378 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006379
6380 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006381
6382 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6383 return;
6384
6385 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006386 if (buf == NULL)
6387 return;
6388
6389 if (buf->b_term->tl_title != NULL)
6390 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6391}
6392
6393/*
6394 * "term_gettty(buf)" function
6395 */
6396 void
6397f_term_gettty(typval_T *argvars, typval_T *rettv)
6398{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006399 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006400 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006401 int num = 0;
6402
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006403 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006404 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006405 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6406 return;
6407
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006408 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006409 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006410 if (buf == NULL)
6411 return;
6412 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006413 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006414
6415 switch (num)
6416 {
6417 case 0:
6418 if (buf->b_term->tl_job != NULL)
6419 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006420 break;
6421 case 1:
6422 if (buf->b_term->tl_job != NULL)
6423 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006424 break;
6425 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006426 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006427 return;
6428 }
6429 if (p != NULL)
6430 rettv->vval.v_string = vim_strsave(p);
6431}
6432
6433/*
6434 * "term_list()" function
6435 */
6436 void
6437f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6438{
6439 term_T *tp;
6440 list_T *l;
6441
6442 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6443 return;
6444
6445 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006446 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006447 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006448 if (list_append_number(l,
6449 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6450 return;
6451}
6452
6453/*
6454 * "term_scrape(buf, row)" function
6455 */
6456 void
6457f_term_scrape(typval_T *argvars, typval_T *rettv)
6458{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006459 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006460 VTermScreen *screen = NULL;
6461 VTermPos pos;
6462 list_T *l;
6463 term_T *term;
6464 char_u *p;
6465 sb_line_T *line;
6466
6467 if (rettv_list_alloc(rettv) == FAIL)
6468 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006469
6470 if (in_vim9script()
6471 && (check_for_buffer_arg(argvars, 0) == FAIL
6472 || check_for_lnum_arg(argvars, 1) == FAIL))
6473 return;
6474
6475 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006476 if (buf == NULL)
6477 return;
6478 term = buf->b_term;
6479
6480 l = rettv->vval.v_list;
6481 pos.row = get_row_number(&argvars[1], term);
6482
6483 if (term->tl_vterm != NULL)
6484 {
6485 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006486 if (screen == NULL) // can't really happen
6487 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006488 p = NULL;
6489 line = NULL;
6490 }
6491 else
6492 {
6493 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6494
6495 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6496 return;
6497 p = ml_get_buf(buf, lnum + 1, FALSE);
6498 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6499 }
6500
6501 for (pos.col = 0; pos.col < term->tl_cols; )
6502 {
6503 dict_T *dcell;
6504 int width;
6505 VTermScreenCellAttrs attrs;
6506 VTermColor fg, bg;
6507 char_u rgb[8];
6508 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6509 int off = 0;
6510 int i;
6511
6512 if (screen == NULL)
6513 {
6514 cellattr_T *cellattr;
6515 int len;
6516
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006517 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006518 if (pos.col >= line->sb_cols)
6519 break;
6520 cellattr = line->sb_cells + pos.col;
6521 width = cellattr->width;
6522 attrs = cellattr->attrs;
6523 fg = cellattr->fg;
6524 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006525 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006526 mch_memmove(mbs, p, len);
6527 mbs[len] = NUL;
6528 p += len;
6529 }
6530 else
6531 {
6532 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006533
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006534 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6535 break;
6536 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6537 {
6538 if (cell.chars[i] == 0)
6539 break;
6540 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6541 }
6542 mbs[off] = NUL;
6543 width = cell.width;
6544 attrs = cell.attrs;
6545 fg = cell.fg;
6546 bg = cell.bg;
6547 }
6548 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006549 if (dcell == NULL)
6550 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006551 list_append_dict(l, dcell);
6552
Bram Moolenaare0be1672018-07-08 16:50:37 +02006553 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006554
6555 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6556 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006557 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006558 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6559 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006560 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006561
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006562 dict_add_number(dcell, "attr",
6563 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006564 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006565
6566 ++pos.col;
6567 if (width == 2)
6568 ++pos.col;
6569 }
6570}
6571
6572/*
6573 * "term_sendkeys(buf, keys)" function
6574 */
6575 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006576f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006577{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006578 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006579 char_u *msg;
6580 term_T *term;
6581
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006582 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006583 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006584 || check_for_string_arg(argvars, 1) == FAIL))
6585 return;
6586
6587 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006588 if (buf == NULL)
6589 return;
6590
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006591 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006592 if (msg == NULL)
6593 return;
6594 term = buf->b_term;
6595 if (term->tl_vterm == NULL)
6596 return;
6597
6598 while (*msg != NUL)
6599 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006600 int c;
6601
6602 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6603 {
6604 c = TO_SPECIAL(msg[1], msg[2]);
6605 msg += 3;
6606 }
6607 else
6608 {
6609 c = PTR2CHAR(msg);
6610 msg += MB_CPTR2LEN(msg);
6611 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006612 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006613 }
6614}
6615
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006616#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6617/*
6618 * "term_getansicolors(buf)" function
6619 */
6620 void
6621f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6622{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006623 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006624 term_T *term;
6625 VTermState *state;
6626 VTermColor color;
6627 char_u hexbuf[10];
6628 int index;
6629 list_T *list;
6630
6631 if (rettv_list_alloc(rettv) == FAIL)
6632 return;
6633
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006634 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6635 return;
6636
6637 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006638 if (buf == NULL)
6639 return;
6640 term = buf->b_term;
6641 if (term->tl_vterm == NULL)
6642 return;
6643
6644 list = rettv->vval.v_list;
6645 state = vterm_obtain_state(term->tl_vterm);
6646 for (index = 0; index < 16; index++)
6647 {
6648 vterm_state_get_palette_color(state, index, &color);
6649 sprintf((char *)hexbuf, "#%02x%02x%02x",
6650 color.red, color.green, color.blue);
6651 if (list_append_string(list, hexbuf, 7) == FAIL)
6652 return;
6653 }
6654}
6655
6656/*
6657 * "term_setansicolors(buf, list)" function
6658 */
6659 void
6660f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6661{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006662 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006663 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006664 listitem_T *li;
6665 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006666
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006667 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006668 && (check_for_buffer_arg(argvars, 0) == FAIL
6669 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006670 return;
6671
6672 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006673 if (buf == NULL)
6674 return;
6675 term = buf->b_term;
6676 if (term->tl_vterm == NULL)
6677 return;
6678
Bram Moolenaard83392a2022-09-01 12:22:46 +01006679 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006680 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006681
LemonBoyb2b3acb2022-05-20 10:10:34 +01006682 if (argvars[1].vval.v_list->lv_first == &range_list_item
6683 || argvars[1].vval.v_list->lv_len != 16)
6684 {
Bram Moolenaar23919542023-05-05 22:12:22 +01006685 semsg(_(e_invalid_value_for_argument_str), "\"colors\"");
LemonBoyb2b3acb2022-05-20 10:10:34 +01006686 return;
6687 }
6688
6689 if (term->tl_palette == NULL)
6690 term->tl_palette = ALLOC_MULT(long_u, 16);
6691 if (term->tl_palette == NULL)
6692 return;
6693
6694 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6695 {
6696 char_u *color_name;
6697 guicolor_T guicolor;
6698
6699 color_name = tv_get_string_chk(&li->li_tv);
6700 if (color_name == NULL)
6701 return;
6702
6703 guicolor = GUI_GET_COLOR(color_name);
6704 if (guicolor == INVALCOLOR)
6705 {
6706 semsg(_(e_cannot_allocate_color_str), color_name);
6707 return;
6708 }
6709
6710 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6711 }
6712
6713 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006714}
6715#endif
6716
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006717/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006718 * "term_setapi(buf, api)" function
6719 */
6720 void
6721f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6722{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006723 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006724 term_T *term;
6725 char_u *api;
6726
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006727 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006728 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006729 || check_for_string_arg(argvars, 1) == FAIL))
6730 return;
6731
6732 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006733 if (buf == NULL)
6734 return;
6735 term = buf->b_term;
6736 vim_free(term->tl_api);
6737 api = tv_get_string_chk(&argvars[1]);
6738 if (api != NULL)
6739 term->tl_api = vim_strsave(api);
6740 else
6741 term->tl_api = NULL;
6742}
6743
6744/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006745 * "term_setrestore(buf, command)" function
6746 */
6747 void
6748f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6749{
6750#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006751 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006752 term_T *term;
6753 char_u *cmd;
6754
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006755 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006756 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006757 || check_for_string_arg(argvars, 1) == FAIL))
6758 return;
6759
6760 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006761 if (buf == NULL)
6762 return;
6763 term = buf->b_term;
6764 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006765 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006766 if (cmd != NULL)
6767 term->tl_command = vim_strsave(cmd);
6768 else
6769 term->tl_command = NULL;
6770#endif
6771}
6772
6773/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006774 * "term_setkill(buf, how)" function
6775 */
6776 void
6777f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6778{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006779 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006780 term_T *term;
6781 char_u *how;
6782
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006783 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006784 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006785 || check_for_string_arg(argvars, 1) == FAIL))
6786 return;
6787
6788 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006789 if (buf == NULL)
6790 return;
6791 term = buf->b_term;
6792 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006793 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006794 if (how != NULL)
6795 term->tl_kill = vim_strsave(how);
6796 else
6797 term->tl_kill = NULL;
6798}
6799
6800/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006801 * "term_start(command, options)" function
6802 */
6803 void
6804f_term_start(typval_T *argvars, typval_T *rettv)
6805{
6806 jobopt_T opt;
6807 buf_T *buf;
6808
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006809 if (in_vim9script()
6810 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6811 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6812 return;
6813
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006814 init_job_options(&opt);
6815 if (argvars[1].v_type != VAR_UNKNOWN
6816 && get_job_options(&argvars[1], &opt,
6817 JO_TIMEOUT_ALL + JO_STOPONEXIT
6818 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6819 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6820 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6821 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006822 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006823 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006824 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006825 return;
6826
Bram Moolenaar13568252018-03-16 20:46:58 +01006827 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006828
6829 if (buf != NULL && buf->b_term != NULL)
6830 rettv->vval.v_number = buf->b_fnum;
6831}
6832
6833/*
6834 * "term_wait" function
6835 */
6836 void
6837f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6838{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006839 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006840
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006841 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006842 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006843 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006844 return;
6845
6846 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006847 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006848 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006849 if (buf->b_term->tl_job == NULL)
6850 {
6851 ch_log(NULL, "term_wait(): no job to wait for");
6852 return;
6853 }
6854 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006855 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006856 return;
6857
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006858 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006859 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006860 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6861 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006862 // The job is dead, keep reading channel I/O until the channel is
6863 // closed. buf->b_term may become NULL if the terminal was closed while
6864 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006865 ch_log(NULL, "term_wait(): waiting for channel to close");
6866 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6867 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006868 term_flush_messages();
6869
Bram Moolenaard45aa552018-05-21 22:50:29 +02006870 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006871 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006872 // If the terminal is closed when the channel is closed the
6873 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006874 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006875 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6876 // came here from a close callback, only wait one time
6877 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006878 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006879
6880 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006881 }
6882 else
6883 {
6884 long wait = 10L;
6885
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006886 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006887
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006888 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006889 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006890 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006891 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006892
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006893 // Flushing messages on channels is hopefully sufficient.
6894 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006895 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006896 }
6897}
6898
6899/*
6900 * Called when a channel has sent all the lines to a terminal.
6901 * Send a CTRL-D to mark the end of the text.
6902 */
6903 void
6904term_send_eof(channel_T *ch)
6905{
6906 term_T *term;
6907
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006908 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006909 if (term->tl_job == ch->ch_job)
6910 {
6911 if (term->tl_eof_chars != NULL)
6912 {
6913 channel_send(ch, PART_IN, term->tl_eof_chars,
6914 (int)STRLEN(term->tl_eof_chars), NULL);
6915 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6916 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006917# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006918 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006919 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006920 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6921# endif
6922 }
6923}
6924
Bram Moolenaar113e1072019-01-20 15:30:40 +01006925#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006926 job_T *
6927term_getjob(term_T *term)
6928{
6929 return term != NULL ? term->tl_job : NULL;
6930}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006931#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006932
Bram Moolenaar4f974752019-02-17 17:44:42 +01006933# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006934
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006935///////////////////////////////////////
6936// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006937#ifdef PROTO
6938typedef int COORD;
6939typedef int DWORD;
6940typedef int HANDLE;
6941typedef int *DWORD_PTR;
6942typedef int HPCON;
6943typedef int HRESULT;
6944typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006945typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006946typedef int PSIZE_T;
6947typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006948typedef int BOOL;
6949# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006950#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006951
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006952HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6953HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6954HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006955BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6956BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6957void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006958
6959 static int
6960dyn_conpty_init(int verbose)
6961{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006962 static HMODULE hKerneldll = NULL;
6963 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006964 static struct
6965 {
6966 char *name;
6967 FARPROC *ptr;
6968 } conpty_entry[] =
6969 {
6970 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6971 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6972 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6973 {"InitializeProcThreadAttributeList",
6974 (FARPROC*)&pInitializeProcThreadAttributeList},
6975 {"UpdateProcThreadAttribute",
6976 (FARPROC*)&pUpdateProcThreadAttribute},
6977 {"DeleteProcThreadAttributeList",
6978 (FARPROC*)&pDeleteProcThreadAttributeList},
6979 {NULL, NULL}
6980 };
6981
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006982 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006983 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006984 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006985 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006986 return FAIL;
6987 }
6988
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006989 // No need to initialize twice.
6990 if (hKerneldll)
6991 return OK;
6992
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006993 hKerneldll = vimLoadLib("kernel32.dll");
6994 for (i = 0; conpty_entry[i].name != NULL
6995 && conpty_entry[i].ptr != NULL; ++i)
6996 {
6997 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6998 conpty_entry[i].name)) == NULL)
6999 {
7000 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007001 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007002 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007003 return FAIL;
7004 }
7005 }
7006
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007007 return OK;
7008}
7009
7010 static int
7011conpty_term_and_job_init(
7012 term_T *term,
7013 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007014 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007015 jobopt_T *opt,
7016 jobopt_T *orig_opt)
7017{
7018 WCHAR *cmd_wchar = NULL;
7019 WCHAR *cmd_wchar_copy = NULL;
7020 WCHAR *cwd_wchar = NULL;
7021 WCHAR *env_wchar = NULL;
7022 channel_T *channel = NULL;
7023 job_T *job = NULL;
7024 HANDLE jo = NULL;
7025 garray_T ga_cmd, ga_env;
7026 char_u *cmd = NULL;
7027 HRESULT hr;
7028 COORD consize;
7029 SIZE_T breq;
7030 PROCESS_INFORMATION proc_info;
7031 HANDLE i_theirs = NULL;
7032 HANDLE o_theirs = NULL;
7033 HANDLE i_ours = NULL;
7034 HANDLE o_ours = NULL;
7035
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007036 ga_init2(&ga_cmd, sizeof(char*), 20);
7037 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007038
7039 if (argvar->v_type == VAR_STRING)
7040 {
7041 cmd = argvar->vval.v_string;
7042 }
7043 else if (argvar->v_type == VAR_LIST)
7044 {
7045 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
7046 goto failed;
7047 cmd = ga_cmd.ga_data;
7048 }
7049 if (cmd == NULL || *cmd == NUL)
7050 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007051 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007052 goto failed;
7053 }
7054
7055 term->tl_arg0_cmd = vim_strsave(cmd);
7056
7057 cmd_wchar = enc_to_utf16(cmd, NULL);
7058
7059 if (cmd_wchar != NULL)
7060 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007061 // Request by CreateProcessW
7062 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007063 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007064 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
7065 }
7066
7067 ga_clear(&ga_cmd);
7068 if (cmd_wchar == NULL)
7069 goto failed;
7070 if (opt->jo_cwd != NULL)
7071 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
7072
7073 win32_build_env(opt->jo_env, &ga_env, TRUE);
7074 env_wchar = ga_env.ga_data;
7075
7076 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
7077 goto failed;
7078 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
7079 goto failed;
7080
7081 consize.X = term->tl_cols;
7082 consize.Y = term->tl_rows;
7083 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
7084 &term->tl_conpty);
7085 if (FAILED(hr))
7086 goto failed;
7087
7088 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
7089
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007090 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007091 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007092 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007093 if (!term->tl_siex.lpAttributeList)
7094 goto failed;
7095 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
7096 0, &breq))
7097 goto failed;
7098 if (!pUpdateProcThreadAttribute(
7099 term->tl_siex.lpAttributeList, 0,
7100 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
7101 sizeof(HPCON), NULL, NULL))
7102 goto failed;
7103
7104 channel = add_channel();
7105 if (channel == NULL)
7106 goto failed;
7107
7108 job = job_alloc();
7109 if (job == NULL)
7110 goto failed;
7111 if (argvar->v_type == VAR_STRING)
7112 {
7113 int argc;
7114
7115 build_argv_from_string(cmd, &job->jv_argv, &argc);
7116 }
7117 else
7118 {
7119 int argc;
7120
7121 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7122 }
7123
7124 if (opt->jo_set & JO_IN_BUF)
7125 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7126
7127 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
7128 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02007129 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007130 env_wchar, cwd_wchar,
7131 &term->tl_siex.StartupInfo, &proc_info))
7132 goto failed;
7133
7134 CloseHandle(i_theirs);
7135 CloseHandle(o_theirs);
7136
7137 channel_set_pipes(channel,
7138 (sock_T)i_ours,
7139 (sock_T)o_ours,
7140 (sock_T)o_ours);
7141
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007142 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007143 channel->ch_write_text_mode = TRUE;
7144
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007145 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007146 channel->ch_anonymous_pipe = TRUE;
7147
7148 jo = CreateJobObject(NULL, NULL);
7149 if (jo == NULL)
7150 goto failed;
7151
7152 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7153 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007154 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007155 CloseHandle(jo);
7156 jo = NULL;
7157 }
7158
7159 ResumeThread(proc_info.hThread);
7160 CloseHandle(proc_info.hThread);
7161
7162 vim_free(cmd_wchar);
7163 vim_free(cmd_wchar_copy);
7164 vim_free(cwd_wchar);
7165 vim_free(env_wchar);
7166
7167 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7168 goto failed;
7169
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007170#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007171 if (term_use_palette())
7172 {
7173 if (term->tl_palette != NULL)
7174 set_vterm_palette(term->tl_vterm, term->tl_palette);
7175 else
7176 init_vterm_ansi_colors(term->tl_vterm);
7177 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007178#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007179
7180 channel_set_job(channel, job, opt);
7181 job_set_options(job, opt);
7182
7183 job->jv_channel = channel;
7184 job->jv_proc_info = proc_info;
7185 job->jv_job_object = jo;
7186 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007187 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007188 ++job->jv_refcount;
7189 term->tl_job = job;
7190
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007191 // Redirecting stdout and stderr doesn't work at the job level. Instead
7192 // open the file here and handle it in. opt->jo_io was changed in
7193 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007194 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7195 {
7196 char_u *fname = opt->jo_io_name[PART_OUT];
7197
7198 ch_log(channel, "Opening output file %s", fname);
7199 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7200 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007201 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007202 }
7203
7204 return OK;
7205
7206failed:
7207 ga_clear(&ga_cmd);
7208 ga_clear(&ga_env);
7209 vim_free(cmd_wchar);
7210 vim_free(cmd_wchar_copy);
7211 vim_free(cwd_wchar);
7212 if (channel != NULL)
7213 channel_clear(channel);
7214 if (job != NULL)
7215 {
7216 job->jv_channel = NULL;
7217 job_cleanup(job);
7218 }
7219 term->tl_job = NULL;
7220 if (jo != NULL)
7221 CloseHandle(jo);
7222
7223 if (term->tl_siex.lpAttributeList != NULL)
7224 {
7225 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7226 vim_free(term->tl_siex.lpAttributeList);
7227 }
7228 term->tl_siex.lpAttributeList = NULL;
7229 if (o_theirs != NULL)
7230 CloseHandle(o_theirs);
7231 if (o_ours != NULL)
7232 CloseHandle(o_ours);
7233 if (i_ours != NULL)
7234 CloseHandle(i_ours);
7235 if (i_theirs != NULL)
7236 CloseHandle(i_theirs);
7237 if (term->tl_conpty != NULL)
7238 pClosePseudoConsole(term->tl_conpty);
7239 term->tl_conpty = NULL;
7240 return FAIL;
7241}
7242
7243 static void
7244conpty_term_report_winsize(term_T *term, int rows, int cols)
7245{
7246 COORD consize;
7247
7248 consize.X = cols;
7249 consize.Y = rows;
7250 pResizePseudoConsole(term->tl_conpty, consize);
7251}
7252
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007253 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007254term_free_conpty(term_T *term)
7255{
7256 if (term->tl_siex.lpAttributeList != NULL)
7257 {
7258 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7259 vim_free(term->tl_siex.lpAttributeList);
7260 }
7261 term->tl_siex.lpAttributeList = NULL;
7262 if (term->tl_conpty != NULL)
7263 pClosePseudoConsole(term->tl_conpty);
7264 term->tl_conpty = NULL;
7265}
7266
7267 int
7268use_conpty(void)
7269{
7270 return has_conpty;
7271}
7272
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007273# ifndef PROTO
7274
7275#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7276#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007277#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007278
7279void* (*winpty_config_new)(UINT64, void*);
7280void* (*winpty_open)(void*, void*);
7281void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7282BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7283void (*winpty_config_set_mouse_mode)(void*, int);
7284void (*winpty_config_set_initial_size)(void*, int, int);
7285LPCWSTR (*winpty_conin_name)(void*);
7286LPCWSTR (*winpty_conout_name)(void*);
7287LPCWSTR (*winpty_conerr_name)(void*);
7288void (*winpty_free)(void*);
7289void (*winpty_config_free)(void*);
7290void (*winpty_spawn_config_free)(void*);
7291void (*winpty_error_free)(void*);
7292LPCWSTR (*winpty_error_msg)(void*);
7293BOOL (*winpty_set_size)(void*, int, int, void*);
7294HANDLE (*winpty_agent_process)(void*);
7295
7296#define WINPTY_DLL "winpty.dll"
7297
7298static HINSTANCE hWinPtyDLL = NULL;
7299# endif
7300
7301 static int
7302dyn_winpty_init(int verbose)
7303{
7304 int i;
7305 static struct
7306 {
7307 char *name;
7308 FARPROC *ptr;
7309 } winpty_entry[] =
7310 {
7311 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7312 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7313 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7314 {"winpty_config_set_mouse_mode",
7315 (FARPROC*)&winpty_config_set_mouse_mode},
7316 {"winpty_config_set_initial_size",
7317 (FARPROC*)&winpty_config_set_initial_size},
7318 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7319 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7320 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7321 {"winpty_free", (FARPROC*)&winpty_free},
7322 {"winpty_open", (FARPROC*)&winpty_open},
7323 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7324 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7325 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7326 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7327 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7328 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7329 {NULL, NULL}
7330 };
7331
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007332 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007333 if (hWinPtyDLL)
7334 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007335 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7336 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007337 if (*p_winptydll != NUL)
7338 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7339 if (!hWinPtyDLL)
7340 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7341 if (!hWinPtyDLL)
7342 {
7343 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007344 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007345 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7346 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007347 return FAIL;
7348 }
7349 for (i = 0; winpty_entry[i].name != NULL
7350 && winpty_entry[i].ptr != NULL; ++i)
7351 {
7352 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7353 winpty_entry[i].name)) == NULL)
7354 {
7355 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007356 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007357 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007358 return FAIL;
7359 }
7360 }
7361
7362 return OK;
7363}
7364
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007365 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007366winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007367 term_T *term,
7368 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007369 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007370 jobopt_T *opt,
7371 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007372{
7373 WCHAR *cmd_wchar = NULL;
7374 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007375 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007376 channel_T *channel = NULL;
7377 job_T *job = NULL;
7378 DWORD error;
7379 HANDLE jo = NULL;
7380 HANDLE child_process_handle;
7381 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007382 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007383 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007384 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007385 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007386
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007387 ga_init2(&ga_cmd, sizeof(char*), 20);
7388 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007389
7390 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007391 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007392 cmd = argvar->vval.v_string;
7393 }
7394 else if (argvar->v_type == VAR_LIST)
7395 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007396 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007397 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007398 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007399 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007400 if (cmd == NULL || *cmd == NUL)
7401 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007402 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007403 goto failed;
7404 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007405
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007406 term->tl_arg0_cmd = vim_strsave(cmd);
7407
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007408 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007409 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007410 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007411 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007412 if (opt->jo_cwd != NULL)
7413 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007414
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007415 win32_build_env(opt->jo_env, &ga_env, TRUE);
7416 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007417
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007418 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7419 if (term->tl_winpty_config == NULL)
7420 goto failed;
7421
7422 winpty_config_set_mouse_mode(term->tl_winpty_config,
7423 WINPTY_MOUSE_MODE_FORCE);
7424 winpty_config_set_initial_size(term->tl_winpty_config,
7425 term->tl_cols, term->tl_rows);
7426 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7427 if (term->tl_winpty == NULL)
7428 goto failed;
7429
7430 spawn_config = winpty_spawn_config_new(
7431 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7432 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7433 NULL,
7434 cmd_wchar,
7435 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007436 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007437 &winpty_err);
7438 if (spawn_config == NULL)
7439 goto failed;
7440
7441 channel = add_channel();
7442 if (channel == NULL)
7443 goto failed;
7444
7445 job = job_alloc();
7446 if (job == NULL)
7447 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007448 if (argvar->v_type == VAR_STRING)
7449 {
7450 int argc;
7451
7452 build_argv_from_string(cmd, &job->jv_argv, &argc);
7453 }
7454 else
7455 {
7456 int argc;
7457
7458 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7459 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007460
7461 if (opt->jo_set & JO_IN_BUF)
7462 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7463
7464 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7465 &child_thread_handle, &error, &winpty_err))
7466 goto failed;
7467
7468 channel_set_pipes(channel,
7469 (sock_T)CreateFileW(
7470 winpty_conin_name(term->tl_winpty),
7471 GENERIC_WRITE, 0, NULL,
7472 OPEN_EXISTING, 0, NULL),
7473 (sock_T)CreateFileW(
7474 winpty_conout_name(term->tl_winpty),
7475 GENERIC_READ, 0, NULL,
7476 OPEN_EXISTING, 0, NULL),
7477 (sock_T)CreateFileW(
7478 winpty_conerr_name(term->tl_winpty),
7479 GENERIC_READ, 0, NULL,
7480 OPEN_EXISTING, 0, NULL));
7481
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007482 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007483 channel->ch_write_text_mode = TRUE;
7484
7485 jo = CreateJobObject(NULL, NULL);
7486 if (jo == NULL)
7487 goto failed;
7488
7489 if (!AssignProcessToJobObject(jo, child_process_handle))
7490 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007491 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007492 CloseHandle(jo);
7493 jo = NULL;
7494 }
7495
7496 winpty_spawn_config_free(spawn_config);
7497 vim_free(cmd_wchar);
7498 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007499 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007500
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007501 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7502 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007503
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007504#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007505 if (term_use_palette())
7506 {
7507 if (term->tl_palette != NULL)
7508 set_vterm_palette(term->tl_vterm, term->tl_palette);
7509 else
7510 init_vterm_ansi_colors(term->tl_vterm);
7511 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007512#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007513
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007514 channel_set_job(channel, job, opt);
7515 job_set_options(job, opt);
7516
7517 job->jv_channel = channel;
7518 job->jv_proc_info.hProcess = child_process_handle;
7519 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7520 job->jv_job_object = jo;
7521 job->jv_status = JOB_STARTED;
7522 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007523 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007524 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007525 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007526 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007527 ++job->jv_refcount;
7528 term->tl_job = job;
7529
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007530 // Redirecting stdout and stderr doesn't work at the job level. Instead
7531 // open the file here and handle it in. opt->jo_io was changed in
7532 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007533 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7534 {
7535 char_u *fname = opt->jo_io_name[PART_OUT];
7536
7537 ch_log(channel, "Opening output file %s", fname);
7538 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7539 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007540 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007541 }
7542
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007543 return OK;
7544
7545failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007546 ga_clear(&ga_cmd);
7547 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007548 vim_free(cmd_wchar);
7549 vim_free(cwd_wchar);
7550 if (spawn_config != NULL)
7551 winpty_spawn_config_free(spawn_config);
7552 if (channel != NULL)
7553 channel_clear(channel);
7554 if (job != NULL)
7555 {
7556 job->jv_channel = NULL;
7557 job_cleanup(job);
7558 }
7559 term->tl_job = NULL;
7560 if (jo != NULL)
7561 CloseHandle(jo);
7562 if (term->tl_winpty != NULL)
7563 winpty_free(term->tl_winpty);
7564 term->tl_winpty = NULL;
7565 if (term->tl_winpty_config != NULL)
7566 winpty_config_free(term->tl_winpty_config);
7567 term->tl_winpty_config = NULL;
7568 if (winpty_err != NULL)
7569 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007570 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007571 (short_u *)winpty_error_msg(winpty_err), NULL);
7572
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007573 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007574 winpty_error_free(winpty_err);
7575 }
7576 return FAIL;
7577}
7578
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007579/*
7580 * Create a new terminal of "rows" by "cols" cells.
7581 * Store a reference in "term".
7582 * Return OK or FAIL.
7583 */
7584 static int
7585term_and_job_init(
7586 term_T *term,
7587 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007588 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007589 jobopt_T *opt,
7590 jobopt_T *orig_opt)
7591{
7592 int use_winpty = FALSE;
7593 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007594 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007595
7596 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7597 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7598
7599 if (!has_winpty && !has_conpty)
7600 // If neither is available give the errors for winpty, since when
7601 // conpty is not available it can't be installed either.
7602 return dyn_winpty_init(TRUE);
7603
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007604 if (opt->jo_tty_type != NUL)
7605 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007606
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007607 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007608 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007609 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007610 use_conpty = TRUE;
7611 else if (has_winpty)
7612 use_winpty = TRUE;
7613 // else: error
7614 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007615 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007616 {
7617 if (has_winpty)
7618 use_winpty = TRUE;
7619 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007620 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007621 {
7622 if (has_conpty)
7623 use_conpty = TRUE;
7624 else
7625 return dyn_conpty_init(TRUE);
7626 }
7627
7628 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007629 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007630
7631 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007632 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007633
7634 // error
7635 return dyn_winpty_init(TRUE);
7636}
7637
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007638 static int
7639create_pty_only(term_T *term, jobopt_T *options)
7640{
7641 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7642 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7643 char in_name[80], out_name[80];
7644 channel_T *channel = NULL;
7645
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007646 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7647 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007648
7649 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7650 GetCurrentProcessId(),
7651 curbuf->b_fnum);
7652 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7653 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7654 PIPE_UNLIMITED_INSTANCES,
7655 0, 0, NMPWAIT_NOWAIT, NULL);
7656 if (hPipeIn == INVALID_HANDLE_VALUE)
7657 goto failed;
7658
7659 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7660 GetCurrentProcessId(),
7661 curbuf->b_fnum);
7662 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7663 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7664 PIPE_UNLIMITED_INSTANCES,
7665 0, 0, 0, NULL);
7666 if (hPipeOut == INVALID_HANDLE_VALUE)
7667 goto failed;
7668
7669 ConnectNamedPipe(hPipeIn, NULL);
7670 ConnectNamedPipe(hPipeOut, NULL);
7671
7672 term->tl_job = job_alloc();
7673 if (term->tl_job == NULL)
7674 goto failed;
7675 ++term->tl_job->jv_refcount;
7676
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007677 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007678 term->tl_job->jv_status = JOB_FINISHED;
7679
7680 channel = add_channel();
7681 if (channel == NULL)
7682 goto failed;
7683 term->tl_job->jv_channel = channel;
7684 channel->ch_keep_open = TRUE;
7685 channel->ch_named_pipe = TRUE;
7686
7687 channel_set_pipes(channel,
7688 (sock_T)hPipeIn,
7689 (sock_T)hPipeOut,
7690 (sock_T)hPipeOut);
7691 channel_set_job(channel, term->tl_job, options);
7692 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7693 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7694
7695 return OK;
7696
7697failed:
7698 if (hPipeIn != NULL)
7699 CloseHandle(hPipeIn);
7700 if (hPipeOut != NULL)
7701 CloseHandle(hPipeOut);
7702 return FAIL;
7703}
7704
7705/*
7706 * Free the terminal emulator part of "term".
7707 */
7708 static void
7709term_free_vterm(term_T *term)
7710{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007711 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007712 if (term->tl_winpty != NULL)
7713 winpty_free(term->tl_winpty);
7714 term->tl_winpty = NULL;
7715 if (term->tl_winpty_config != NULL)
7716 winpty_config_free(term->tl_winpty_config);
7717 term->tl_winpty_config = NULL;
7718 if (term->tl_vterm != NULL)
7719 vterm_free(term->tl_vterm);
7720 term->tl_vterm = NULL;
7721}
7722
7723/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007724 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007725 */
7726 static void
7727term_report_winsize(term_T *term, int rows, int cols)
7728{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007729 if (term->tl_conpty)
7730 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007731 if (term->tl_winpty)
7732 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7733}
7734
7735 int
7736terminal_enabled(void)
7737{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007738 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007739}
7740
7741# else
7742
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007743///////////////////////////////////////
7744// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007745
7746/*
7747 * Create a new terminal of "rows" by "cols" cells.
7748 * Start job for "cmd".
7749 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007750 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007751 * Return OK or FAIL.
7752 */
7753 static int
7754term_and_job_init(
7755 term_T *term,
7756 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007757 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007758 jobopt_T *opt,
7759 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007760{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007761 term->tl_arg0_cmd = NULL;
7762
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007763 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7764 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007765
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007766#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007767 if (term_use_palette())
7768 {
7769 if (term->tl_palette != NULL)
7770 set_vterm_palette(term->tl_vterm, term->tl_palette);
7771 else
7772 init_vterm_ansi_colors(term->tl_vterm);
7773 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007774#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007775
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007776 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007777 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007778 if (term->tl_job != NULL)
7779 ++term->tl_job->jv_refcount;
7780
7781 return term->tl_job != NULL
7782 && term->tl_job->jv_channel != NULL
7783 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7784}
7785
7786 static int
7787create_pty_only(term_T *term, jobopt_T *opt)
7788{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007789 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7790 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007791
7792 term->tl_job = job_alloc();
7793 if (term->tl_job == NULL)
7794 return FAIL;
7795 ++term->tl_job->jv_refcount;
7796
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007797 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007798 term->tl_job->jv_status = JOB_FINISHED;
7799
7800 return mch_create_pty_channel(term->tl_job, opt);
7801}
7802
7803/*
7804 * Free the terminal emulator part of "term".
7805 */
7806 static void
7807term_free_vterm(term_T *term)
7808{
7809 if (term->tl_vterm != NULL)
7810 vterm_free(term->tl_vterm);
7811 term->tl_vterm = NULL;
7812}
7813
7814/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007815 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007816 */
7817 static void
7818term_report_winsize(term_T *term, int rows, int cols)
7819{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007820 // Use an ioctl() to report the new window size to the job.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007821 if (term->tl_job == NULL || term->tl_job->jv_channel == NULL)
7822 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007823
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007824 int fd = -1;
7825 int part;
7826
7827 for (part = PART_OUT; part < PART_COUNT; ++part)
7828 {
7829 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
7830 if (mch_isatty(fd))
7831 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007832 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007833 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7834 mch_signal_job(term->tl_job, (char_u *)"winch");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007835}
7836
7837# endif
7838
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007839#endif // FEAT_TERMINAL