blob: 648fc7872897641318801fbfb66dd5d8eede358f [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020039 */
40
41#include "vim.h"
42
43#if defined(FEAT_TERMINAL) || defined(PROTO)
44
45#ifndef MIN
46# define MIN(x,y) ((x) < (y) ? (x) : (y))
47#endif
48#ifndef MAX
49# define MAX(x,y) ((x) > (y) ? (x) : (y))
50#endif
51
52#include "libvterm/include/vterm.h"
53
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010054// This is VTermScreenCell without the characters, thus much smaller.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055typedef struct {
56 VTermScreenCellAttrs attrs;
57 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010058 VTermColor fg;
59 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060} cellattr_T;
61
62typedef struct sb_line_S {
Bram Moolenaar29ae2232019-02-14 21:22:01 +010063 int sb_cols; // can differ per line
64 cellattr_T *sb_cells; // allocated
65 cellattr_T sb_fill_attr; // for short line
66 char_u *sb_text; // for tl_scrollback_postponed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067} sb_line_T;
68
Bram Moolenaar4f974752019-02-17 17:44:42 +010069#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010070# ifndef HPCON
71# define HPCON VOID*
72# endif
73# ifndef EXTENDED_STARTUPINFO_PRESENT
74# define EXTENDED_STARTUPINFO_PRESENT 0x00080000
75# endif
76# ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
77# define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE 0x00020016
78# endif
79typedef struct _DYN_STARTUPINFOEXW
80{
81 STARTUPINFOW StartupInfo;
82 LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
83} DYN_STARTUPINFOEXW, *PDYN_STARTUPINFOEXW;
84#endif
85
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010086// typedef term_T in structs.h
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020087struct terminal_S {
88 term_T *tl_next;
89
90 VTerm *tl_vterm;
91 job_T *tl_job;
92 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010093#if defined(FEAT_GUI)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010094 int tl_system; // when non-zero used for :!cmd output
95 int tl_toprow; // row with first line of system terminal
Bram Moolenaar13568252018-03-16 20:46:58 +010096#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010098 // Set when setting the size of a vterm, reset after redrawing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020099 int tl_vterm_size_changed;
100
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100101 int tl_normal_mode; // TRUE: Terminal-Normal mode
Bram Moolenaareea32af2021-11-21 14:51:13 +0000102 int tl_channel_closing;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200103 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200104 int tl_channel_recently_closed; // still need to handle tl_finish
105
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100106 int tl_finish;
107#define TL_FINISH_UNSET NUL
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100108#define TL_FINISH_CLOSE 'c' // ++close or :terminal without argument
109#define TL_FINISH_NOCLOSE 'n' // ++noclose
110#define TL_FINISH_OPEN 'o' // ++open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200111 char_u *tl_opencmd;
112 char_u *tl_eof_chars;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200113 char_u *tl_api; // prefix for terminal API function
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200114
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100115 char_u *tl_arg0_cmd; // To format the status bar
116
Bram Moolenaar4f974752019-02-17 17:44:42 +0100117#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200118 void *tl_winpty_config;
119 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200120
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100121 HPCON tl_conpty;
122 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
123
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200124 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200125#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100126#if defined(FEAT_SESSION)
127 char_u *tl_command;
128#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100129 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100131 // last known vterm size
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200132 int tl_rows;
133 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200134
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100135 char_u *tl_title; // NULL or allocated
136 char_u *tl_status_text; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200137
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100138 // Range of screen rows to update. Zero based.
139 int tl_dirty_row_start; // MAX_ROW if nothing dirty
140 int tl_dirty_row_end; // row below last one to update
141 int tl_dirty_snapshot; // text updated after making snapshot
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200142#ifdef FEAT_TIMERS
143 int tl_timer_set;
144 proftime_T tl_timer_due;
145#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100146 int tl_postponed_scroll; // to be scrolled up
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200148 garray_T tl_scrollback;
149 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100150 garray_T tl_scrollback_postponed;
151
Bram Moolenaar83d47902020-03-26 20:34:00 +0100152 char_u *tl_highlight_name; // replaces "Terminal"; allocated
153
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200154 cellattr_T tl_default_color;
155
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100156 linenr_T tl_top_diff_rows; // rows of top diff file or zero
157 linenr_T tl_bot_diff_rows; // rows of bottom diff file
Bram Moolenaard96ff162018-02-18 22:13:29 +0100158
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200159 VTermPos tl_cursor_pos;
160 int tl_cursor_visible;
161 int tl_cursor_blink;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100162 int tl_cursor_shape; // 1: block, 2: underline, 3: bar
163 char_u *tl_cursor_color; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200164
LemonBoyb2b3acb2022-05-20 10:10:34 +0100165 long_u *tl_palette; // array of 16 colors specified by term_start, can
166 // be NULL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167 int tl_using_altscreen;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200168 garray_T tl_osc_buf; // incomplete OSC string
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200169};
170
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100171#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
172#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200173
174/*
175 * List of all active terminals.
176 */
177static term_T *first_term = NULL;
178
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100179// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200180static term_T *in_terminal_loop = NULL;
181
Bram Moolenaar4f974752019-02-17 17:44:42 +0100182#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100183static BOOL has_winpty = FALSE;
184static BOOL has_conpty = FALSE;
185#endif
186
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100187#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188#define KEY_BUF_LEN 200
189
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200190#define FOR_ALL_TERMS(term) \
191 for ((term) = first_term; (term) != NULL; (term) = (term)->tl_next)
192
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193/*
194 * Functions with separate implementation for MS-Windows and Unix-like systems.
195 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200196static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200197static int create_pty_only(term_T *term, jobopt_T *opt);
198static void term_report_winsize(term_T *term, int rows, int cols);
199static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100200#ifdef FEAT_GUI
201static void update_system_term(term_T *term);
202#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200203
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100204static void handle_postponed_scrollback(term_T *term);
205
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100206// The character that we know (or assume) that the terminal expects for the
207// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200208static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200209
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100210// Store the last set and the desired cursor properties, so that we only update
211// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200212static char_u *last_set_cursor_color = NULL;
213static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100214static int last_set_cursor_shape = -1;
215static int desired_cursor_shape = -1;
216static int last_set_cursor_blink = -1;
217static int desired_cursor_blink = -1;
218
219
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100220///////////////////////////////////////
221// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200222
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200223 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200224cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
225{
226 if (lhs_color != NULL && rhs_color != NULL)
227 return STRCMP(lhs_color, rhs_color) == 0;
228 return lhs_color == NULL && rhs_color == NULL;
229}
230
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200231 static void
232cursor_color_copy(char_u **to_color, char_u *from_color)
233{
234 // Avoid a free & alloc if the value is already right.
235 if (cursor_color_equal(*to_color, from_color))
236 return;
237 vim_free(*to_color);
238 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
239}
240
241 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200242cursor_color_get(char_u *color)
243{
244 return (color == NULL) ? (char_u *)"" : color;
245}
246
247
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200248/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200249 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200250 * current window.
251 * Sets "rows" and/or "cols" to zero when it should follow the window size.
252 * Return TRUE if the size is the minimum size: "24*80".
253 */
254 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200255parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200256{
257 int minsize = FALSE;
258
259 *rows = 0;
260 *cols = 0;
261
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000262 if (*wp->w_p_tws == NUL)
263 return FALSE;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200264
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000265 char_u *p = vim_strchr(wp->w_p_tws, 'x');
266
267 // Syntax of value was already checked when it's set.
268 if (p == NULL)
269 {
270 minsize = TRUE;
271 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200272 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000273 *rows = atoi((char *)wp->w_p_tws);
274 *cols = atoi((char *)p + 1);
Christian Brabandtceee7a82023-09-21 16:55:06 +0200275 if (*rows > VTERM_MAX_ROWS)
276 *rows = VTERM_MAX_ROWS;
277 if (*cols > VTERM_MAX_COLS)
278 *cols = VTERM_MAX_COLS;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200279 return minsize;
280}
281
282/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200283 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200284 */
285 static void
Bram Moolenaarb936b792020-09-04 18:34:09 +0200286set_term_and_win_size(term_T *term, jobopt_T *opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200287{
Bram Moolenaarb936b792020-09-04 18:34:09 +0200288 int rows, cols;
289 int minsize;
290
Bram Moolenaar13568252018-03-16 20:46:58 +0100291#ifdef FEAT_GUI
292 if (term->tl_system)
293 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100294 // Use the whole screen for the system command. However, it will start
295 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100296 term->tl_rows = Rows;
297 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200298 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100299 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100300#endif
Bram Moolenaarb936b792020-09-04 18:34:09 +0200301 term->tl_rows = curwin->w_height;
302 term->tl_cols = curwin->w_width;
303
304 minsize = parse_termwinsize(curwin, &rows, &cols);
305 if (minsize)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200306 {
Bram Moolenaarb936b792020-09-04 18:34:09 +0200307 if (term->tl_rows < rows)
308 term->tl_rows = rows;
309 if (term->tl_cols < cols)
310 term->tl_cols = cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200312 if ((opt->jo_set2 & JO2_TERM_ROWS))
313 term->tl_rows = opt->jo_term_rows;
314 else if (rows != 0)
315 term->tl_rows = rows;
316 if ((opt->jo_set2 & JO2_TERM_COLS))
317 term->tl_cols = opt->jo_term_cols;
318 else if (cols != 0)
319 term->tl_cols = cols;
320
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200321 if (!opt->jo_hidden)
Bram Moolenaarb936b792020-09-04 18:34:09 +0200322 {
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200323 if (term->tl_rows != curwin->w_height)
324 win_setheight_win(term->tl_rows, curwin);
325 if (term->tl_cols != curwin->w_width)
326 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaarb936b792020-09-04 18:34:09 +0200327
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200328 // Set 'winsize' now to avoid a resize at the next redraw.
329 if (!minsize && *curwin->w_p_tws != NUL)
330 {
331 char_u buf[100];
332
333 vim_snprintf((char *)buf, 100, "%dx%d",
334 term->tl_rows, term->tl_cols);
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100335 set_option_value_give_err((char_u *)"termwinsize",
336 0L, buf, OPT_LOCAL);
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200337 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200338 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200339}
340
341/*
342 * Initialize job options for a terminal job.
343 * Caller may overrule some of them.
344 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100345 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346init_job_options(jobopt_T *opt)
347{
348 clear_job_options(opt);
349
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100350 opt->jo_mode = CH_MODE_RAW;
351 opt->jo_out_mode = CH_MODE_RAW;
352 opt->jo_err_mode = CH_MODE_RAW;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200353 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
354}
355
356/*
357 * Set job options mandatory for a terminal job.
358 */
359 static void
360setup_job_options(jobopt_T *opt, int rows, int cols)
361{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100362#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100363 // Win32: Redirecting the job output won't work, thus always connect stdout
364 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200365 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200366#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200367 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100368 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200369 opt->jo_io[PART_OUT] = JIO_BUFFER;
370 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
371 opt->jo_modifiable[PART_OUT] = 0;
372 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
373 }
374
Bram Moolenaar4f974752019-02-17 17:44:42 +0100375#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100376 // Win32: Redirecting the job output won't work, thus always connect stderr
377 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200378 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200379#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200380 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100381 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200382 opt->jo_io[PART_ERR] = JIO_BUFFER;
383 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
384 opt->jo_modifiable[PART_ERR] = 0;
385 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
386 }
387
388 opt->jo_pty = TRUE;
389 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
390 opt->jo_term_rows = rows;
391 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
392 opt->jo_term_cols = cols;
393}
394
395/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200396 * Flush messages on channels.
397 */
398 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +0000399term_flush_messages(void)
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200400{
401 mch_check_messages();
402 parse_queued_messages();
403}
404
405/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100406 * Close a terminal buffer (and its window). Used when creating the terminal
407 * fails.
408 */
409 static void
410term_close_buffer(buf_T *buf, buf_T *old_curbuf)
411{
412 free_terminal(buf);
413 if (old_curbuf != NULL)
414 {
415 --curbuf->b_nwindows;
416 curbuf = old_curbuf;
417 curwin->w_buffer = curbuf;
418 ++curbuf->b_nwindows;
419 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100420 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100421
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100422 // Wiping out the buffer will also close the window and call
423 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100424 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
425}
426
427/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100429 * Use either "argvar" or "argv", the other must be NULL.
430 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
431 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200432 * Returns NULL when failed.
433 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100434 buf_T *
435term_start(
436 typval_T *argvar,
437 char **argv,
438 jobopt_T *opt,
439 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200440{
441 exarg_T split_ea;
442 win_T *old_curwin = curwin;
443 term_T *term;
444 buf_T *old_curbuf = NULL;
445 int res;
446 buf_T *newbuf;
Bram Moolenaare1004402020-10-24 20:49:43 +0200447 int vertical = opt->jo_vertical || (cmdmod.cmod_split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200448 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200449
450 if (check_restricted() || check_secure())
451 return NULL;
Bram Moolenaare5b44862021-05-30 13:54:03 +0200452 if (cmdwin_type != 0)
453 {
454 emsg(_(e_cannot_open_terminal_from_command_line_window));
455 return NULL;
456 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200457
458 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
459 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
460 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100461 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
462 || (argvar != NULL
463 && argvar->v_type == VAR_LIST
464 && argvar->vval.v_list != NULL
465 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200466 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000467 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200468 return NULL;
469 }
470
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200471 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200472 if (term == NULL)
473 return NULL;
474 term->tl_dirty_row_end = MAX_ROW;
475 term->tl_cursor_visible = TRUE;
476 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
477 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100478#ifdef FEAT_GUI
479 term->tl_system = (flags & TERM_START_SYSTEM);
480#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200481 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100482 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200483 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200484
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200485 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200486 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200487 if (opt->jo_curwin)
488 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100489 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100490 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200491 {
492 no_write_message();
493 vim_free(term);
494 return NULL;
495 }
496 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200497 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
498 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
499 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200500 {
501 vim_free(term);
502 return NULL;
503 }
504 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100505 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200506 {
507 buf_T *buf;
508
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100509 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100510 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200511 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
512 BLN_NEW | BLN_LISTED);
513 if (buf == NULL || ml_open(buf) == FAIL)
514 {
515 vim_free(term);
516 return NULL;
517 }
518 old_curbuf = curbuf;
519 --curbuf->b_nwindows;
520 curbuf = buf;
521 curwin->w_buffer = buf;
522 ++curbuf->b_nwindows;
523 }
524 else
525 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100526 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200527 split_ea.cmdidx = CMD_new;
528 split_ea.cmd = (char_u *)"new";
529 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100530 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200531 {
532 split_ea.line2 = opt->jo_term_rows;
533 split_ea.addr_count = 1;
534 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100535 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200536 {
537 split_ea.line2 = opt->jo_term_cols;
538 split_ea.addr_count = 1;
539 }
540
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200541 int cmod_split_modified = FALSE;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100542 if (vertical)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200543 {
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200544 if (!(cmdmod.cmod_split & WSP_VERT))
545 cmod_split_modified = TRUE;
Bram Moolenaare1004402020-10-24 20:49:43 +0200546 cmdmod.cmod_split |= WSP_VERT;
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200547 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200548 ex_splitview(&split_ea);
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200549 if (cmod_split_modified)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200550 cmdmod.cmod_split &= ~WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200551 if (curwin == old_curwin)
552 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100553 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200554 vim_free(term);
555 return NULL;
556 }
557 }
558 term->tl_buffer = curbuf;
559 curbuf->b_term = term;
560
561 if (!opt->jo_hidden)
562 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100563 // Only one size was taken care of with :new, do the other one. With
564 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100565 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200566 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100567 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 win_setwidth(opt->jo_term_cols);
569 }
570
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100571 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200572 term->tl_next = first_term;
573 first_term = term;
574
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100575 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
576
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200577 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100578 {
579 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200580 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100581 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100582 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100583 {
584 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100585 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100586 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200587 else
588 {
589 int i;
590 size_t len;
591 char_u *cmd, *p;
592
593 if (argvar->v_type == VAR_STRING)
594 {
595 cmd = argvar->vval.v_string;
596 if (cmd == NULL)
597 cmd = (char_u *)"";
598 else if (STRCMP(cmd, "NONE") == 0)
599 cmd = (char_u *)"pty";
600 }
601 else if (argvar->v_type != VAR_LIST
602 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100603 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100604 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200605 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
606 cmd = (char_u*)"";
607
608 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200609 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200610
611 for (i = 0; p != NULL; ++i)
612 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100613 // Prepend a ! to the command name to avoid the buffer name equals
614 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200615 if (i == 0)
616 vim_snprintf((char *)p, len, "!%s", cmd);
617 else
618 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
619 if (buflist_findname(p) == NULL)
620 {
621 vim_free(curbuf->b_ffname);
622 curbuf->b_ffname = p;
623 break;
624 }
625 }
626 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100627 vim_free(curbuf->b_sfname);
628 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200629 curbuf->b_fname = curbuf->b_ffname;
630
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100631 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
632
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200633 if (opt->jo_term_opencmd != NULL)
634 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
635
636 if (opt->jo_eof_chars != NULL)
637 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
638
639 set_string_option_direct((char_u *)"buftype", -1,
640 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200641 // Avoid that 'buftype' is reset when this buffer is entered.
642 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200643
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100644 // Mark the buffer as not modifiable. It can only be made modifiable after
645 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200646 curbuf->b_p_ma = FALSE;
647
Bram Moolenaarb936b792020-09-04 18:34:09 +0200648 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100649#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200650 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
651#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200652 setup_job_options(opt, term->tl_rows, term->tl_cols);
653
Bram Moolenaar13568252018-03-16 20:46:58 +0100654 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100655 return curbuf;
656
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100657#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100658 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100659 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100660 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100661 else if (argvar->v_type == VAR_STRING)
662 {
663 char_u *cmd = argvar->vval.v_string;
664
665 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
666 term->tl_command = vim_strsave(cmd);
667 }
668 else if (argvar->v_type == VAR_LIST
669 && argvar->vval.v_list != NULL
670 && argvar->vval.v_list->lv_len > 0)
671 {
672 garray_T ga;
673 listitem_T *item;
674
675 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200676 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100677 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100678 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100679 char_u *p;
680
681 if (s == NULL)
682 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100683 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100684 if (p == NULL)
685 break;
686 ga_concat(&ga, p);
687 vim_free(p);
688 ga_append(&ga, ' ');
689 }
690 if (item == NULL)
691 {
692 ga_append(&ga, NUL);
693 term->tl_command = ga.ga_data;
694 }
695 else
696 ga_clear(&ga);
697 }
698#endif
699
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100700 if (opt->jo_term_kill != NULL)
701 {
702 char_u *p = skiptowhite(opt->jo_term_kill);
703
704 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
705 }
706
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200707 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100708 {
709 char_u *p = skiptowhite(opt->jo_term_api);
710
711 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
712 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200713 else
714 term->tl_api = vim_strsave((char_u *)"Tapi_");
715
Bram Moolenaar83d47902020-03-26 20:34:00 +0100716 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
717 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
718
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100719#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100720 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
721 if (opt->jo_set2 & JO2_ANSI_COLORS)
722 {
723 term->tl_palette = ALLOC_MULT(long_u, 16);
724 if (term->tl_palette == NULL)
725 {
726 vim_free(term);
727 return NULL;
728 }
729 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
730 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100731#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100732
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100733 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100734 if (argv == NULL
735 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200736 && argvar->vval.v_string != NULL
737 && STRCMP(argvar->vval.v_string, "NONE") == 0)
738 res = create_pty_only(term, opt);
739 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200740 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200741
742 newbuf = curbuf;
743 if (res == OK)
744 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100745 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200746 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
747 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100748#ifdef FEAT_GUI
749 if (term->tl_system)
750 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100751 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100752 term->tl_toprow = msg_row + 1;
753 term->tl_dirty_row_end = 0;
754 }
755#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200756
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100757 // Make sure we don't get stuck on sending keys to the job, it leads to
758 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200759 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
760
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200761 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200762 {
763 --curbuf->b_nwindows;
764 curbuf = old_curbuf;
765 curwin->w_buffer = curbuf;
766 ++curbuf->b_nwindows;
767 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000768 else if (vgetc_busy
769#ifdef FEAT_TIMERS
770 || timer_busy
771#endif
772 || input_busy)
773 {
774 char_u ignore[4];
775
776 // When waiting for input need to return and possibly end up in
777 // terminal_loop() instead.
778 ignore[0] = K_SPECIAL;
779 ignore[1] = KS_EXTRA;
780 ignore[2] = KE_IGNORE;
781 ignore[3] = NUL;
782 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
783 typebuf_was_filled = TRUE;
784 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200785 }
786 else
787 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100788 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200789 return NULL;
790 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100791
Bram Moolenaar13568252018-03-16 20:46:58 +0100792 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200793 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
794 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200795 return newbuf;
796}
797
798/*
799 * ":terminal": open a terminal window and execute a job in it.
800 */
801 void
802ex_terminal(exarg_T *eap)
803{
804 typval_T argvar[2];
805 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100806 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200807 char_u *cmd;
808 char_u *tofree = NULL;
809
810 init_job_options(&opt);
811
812 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100813 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200814 {
815 char_u *p, *ep;
816
817 cmd += 2;
818 p = skiptowhite(cmd);
819 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200820 if (ep != NULL)
821 {
822 if (ep < p)
823 p = ep;
824 else
825 ep = NULL;
826 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200827
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200828 // Note: Keep this in sync with get_terminalopt_name.
829
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200830# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
831 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
832 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200833 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200834 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100835 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200836 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200837 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200838 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200839 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200840 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200841 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200842 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100843 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100844 else if (OPTARG_HAS("shell"))
845 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200846 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100847 {
848 opt.jo_set2 |= JO2_TERM_KILL;
849 opt.jo_term_kill = ep + 1;
850 p = skiptowhite(cmd);
851 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200852 else if (OPTARG_HAS("api"))
853 {
854 opt.jo_set2 |= JO2_TERM_API;
855 if (ep != NULL)
856 {
857 opt.jo_term_api = ep + 1;
858 p = skiptowhite(cmd);
859 }
860 else
861 opt.jo_term_api = NULL;
862 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100863 else if (OPTARG_HAS("rows") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200864 {
865 opt.jo_set2 |= JO2_TERM_ROWS;
866 opt.jo_term_rows = atoi((char *)ep + 1);
867 p = skiptowhite(cmd);
868 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100869 else if (OPTARG_HAS("cols") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200870 {
871 opt.jo_set2 |= JO2_TERM_COLS;
872 opt.jo_term_cols = atoi((char *)ep + 1);
873 p = skiptowhite(cmd);
874 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200875 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200876 {
877 char_u *buf = NULL;
878 char_u *keys;
879
Bram Moolenaar21109272020-01-30 16:27:20 +0100880 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200881 p = skiptowhite(cmd);
882 *p = NUL;
zeertzjq7e0bae02023-08-11 23:15:38 +0200883 keys = replace_termcodes(ep + 1, &buf, 0,
Bram Moolenaar459fd782019-10-13 16:43:39 +0200884 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200885 opt.jo_set2 |= JO2_EOF_CHARS;
886 opt.jo_eof_chars = vim_strsave(keys);
887 vim_free(buf);
888 *p = ' ';
889 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100890#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100891 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
892 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100893 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100894 int tty_type = NUL;
895
896 p = skiptowhite(cmd);
897 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
898 tty_type = 'w';
899 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
900 tty_type = 'c';
901 else
902 {
Bram Moolenaar50809a42023-05-20 16:39:07 +0100903 semsg(_(e_invalid_value_for_argument_str), "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100904 goto theend;
905 }
906 opt.jo_set2 |= JO2_TTY_TYPE;
907 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100908 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100909#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200910 else
911 {
912 if (*p)
913 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000914 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100915 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200916 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200917# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200918 cmd = skipwhite(p);
919 }
920 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100921 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100922 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200923 tofree = cmd = vim_strsave(p_sh);
924
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100925 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100926 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200927 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100928 }
929
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200930 if (eap->addr_count > 0)
931 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100932 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200933 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
934 opt.jo_io[PART_IN] = JIO_BUFFER;
935 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
936 opt.jo_in_top = eap->line1;
937 opt.jo_in_bot = eap->line2;
938 }
939
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100940 if (opt_shell && tofree == NULL)
941 {
942#ifdef UNIX
943 char **argv = NULL;
944 char_u *tofree1 = NULL;
945 char_u *tofree2 = NULL;
946
947 // :term ++shell command
948 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
949 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100950 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100951 vim_free(tofree1);
952 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100953 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100954#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100955# ifdef MSWIN
956 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
957 char_u *newcmd;
958
959 newcmd = alloc(cmdlen);
960 if (newcmd == NULL)
961 goto theend;
962 tofree = newcmd;
963 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
964 cmd = newcmd;
965# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000966 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100967 goto theend;
968# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100969#endif
970 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100971 argvar[0].v_type = VAR_STRING;
972 argvar[0].vval.v_string = cmd;
973 argvar[1].v_type = VAR_UNKNOWN;
974 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100975
976theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100977 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200978 vim_free(opt.jo_eof_chars);
979}
980
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200981 static char_u *
982get_terminalopt_name(expand_T *xp UNUSED, int idx)
983{
984 // Note: Keep this in sync with ex_terminal.
985 static char *(p_termopt_values[]) =
986 {
987 "close",
988 "noclose",
989 "open",
990 "curwin",
991 "hidden",
992 "norestore",
993 "shell",
994 "kill=",
995 "rows=",
996 "cols=",
997 "eof=",
998 "type=",
999 "api=",
1000 };
1001
1002 if (idx < (int)ARRAY_LENGTH(p_termopt_values))
1003 return (char_u*)p_termopt_values[idx];
1004 return NULL;
1005}
1006
1007 static char_u *
1008get_termkill_name(expand_T *xp UNUSED, int idx)
1009{
1010 // These are platform-specific values used for job_stop(). They are defined
1011 // in each platform's mch_signal_job(). Just use a unified auto-complete
1012 // list for simplicity.
1013 static char *(p_termkill_values[]) =
1014 {
1015 "term",
1016 "hup",
1017 "quit",
1018 "int",
1019 "kill",
1020 "winch",
1021 };
1022
1023 if (idx < (int)ARRAY_LENGTH(p_termkill_values))
1024 return (char_u*)p_termkill_values[idx];
1025 return NULL;
1026}
1027
1028/*
1029 * Command-line expansion for :terminal [options]
1030 */
1031 int
1032expand_terminal_opt(
1033 char_u *pat,
1034 expand_T *xp,
1035 regmatch_T *rmp,
1036 char_u ***matches,
1037 int *numMatches)
1038{
1039 if (xp->xp_pattern > xp->xp_line && *(xp->xp_pattern-1) == '=')
1040 {
1041 char_u *(*cb)(expand_T *, int) = NULL;
1042
1043 char_u *name_end = xp->xp_pattern - 1;
1044 if (name_end - xp->xp_line >= 4
1045 && STRNCMP(name_end - 4, "kill", 4) == 0)
1046 cb = get_termkill_name;
1047
1048 if (cb != NULL)
1049 {
1050 return ExpandGeneric(
1051 pat,
1052 xp,
1053 rmp,
1054 matches,
1055 numMatches,
1056 cb,
1057 FALSE);
1058 }
1059 return FAIL;
1060 }
1061 return ExpandGeneric(
1062 pat,
1063 xp,
1064 rmp,
1065 matches,
1066 numMatches,
1067 get_terminalopt_name,
1068 FALSE);
1069}
1070
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001071#if defined(FEAT_SESSION) || defined(PROTO)
1072/*
1073 * Write a :terminal command to the session file to restore the terminal in
1074 * window "wp".
1075 * Return FAIL if writing fails.
1076 */
1077 int
Bram Moolenaar0e655112020-09-11 20:36:36 +02001078term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001079{
Bram Moolenaar0e655112020-09-11 20:36:36 +02001080 const int bufnr = wp->w_buffer->b_fnum;
1081 term_T *term = wp->w_buffer->b_term;
1082
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001083 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001084 {
1085 // There are multiple views into this terminal buffer. We don't want to
1086 // create the terminal multiple times. If it's the first time, create,
1087 // otherwise link to the first buffer.
1088 char id_as_str[NUMBUFLEN];
1089 hashitem_T *entry;
1090
1091 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
1092
1093 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
1094 if (!HASHITEM_EMPTY(entry))
1095 {
1096 // we've already opened this terminal buffer
1097 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
1098 return FAIL;
1099 return put_eol(fd);
1100 }
1101 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001102
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001103 // Create the terminal and run the command. This is not without
1104 // risk, but let's assume the user only creates a session when this
1105 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001106 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1107 term->tl_cols, term->tl_rows) < 0)
1108 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001109#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001110 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1111 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001112#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001113 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1114 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001115 if (put_eol(fd) != OK)
1116 return FAIL;
1117
1118 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1119 return FAIL;
1120
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001121 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001122 {
1123 char *hash_key = alloc(NUMBUFLEN);
1124
1125 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00001126 hash_add(terminal_bufs, (char_u *)hash_key, "terminal session");
Bram Moolenaar0e655112020-09-11 20:36:36 +02001127 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001128
1129 return put_eol(fd);
1130}
1131
1132/*
1133 * Return TRUE if "buf" has a terminal that should be restored.
1134 */
1135 int
1136term_should_restore(buf_T *buf)
1137{
1138 term_T *term = buf->b_term;
1139
1140 return term != NULL && (term->tl_command == NULL
1141 || STRCMP(term->tl_command, "NONE") != 0);
1142}
1143#endif
1144
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001145/*
1146 * Free the scrollback buffer for "term".
1147 */
1148 static void
1149free_scrollback(term_T *term)
1150{
1151 int i;
1152
1153 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1154 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1155 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001156 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1157 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1158 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001159}
1160
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001161
1162// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001163static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001164
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001165/*
1166 * Free a terminal and everything it refers to.
1167 * Kills the job if there is one.
1168 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001169 * The actual terminal structure is freed later in free_unused_terminals(),
1170 * because callbacks may wipe out a buffer while the terminal is still
1171 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001172 */
1173 void
1174free_terminal(buf_T *buf)
1175{
1176 term_T *term = buf->b_term;
1177 term_T *tp;
1178
1179 if (term == NULL)
1180 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001181
1182 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001183 if (first_term == term)
1184 first_term = term->tl_next;
1185 else
1186 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1187 if (tp->tl_next == term)
1188 {
1189 tp->tl_next = term->tl_next;
1190 break;
1191 }
1192
1193 if (term->tl_job != NULL)
1194 {
1195 if (term->tl_job->jv_status != JOB_ENDED
1196 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001197 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001198 job_stop(term->tl_job, NULL, "kill");
1199 job_unref(term->tl_job);
1200 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001201 term->tl_next = terminals_to_free;
1202 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001203
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001204 buf->b_term = NULL;
1205 if (in_terminal_loop == term)
1206 in_terminal_loop = NULL;
1207}
1208
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001209 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00001210free_unused_terminals(void)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001211{
1212 while (terminals_to_free != NULL)
1213 {
1214 term_T *term = terminals_to_free;
1215
1216 terminals_to_free = term->tl_next;
1217
1218 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001219 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001220
1221 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001222 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001223 vim_free(term->tl_title);
1224#ifdef FEAT_SESSION
1225 vim_free(term->tl_command);
1226#endif
1227 vim_free(term->tl_kill);
1228 vim_free(term->tl_status_text);
1229 vim_free(term->tl_opencmd);
1230 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001231 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001232#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001233 if (term->tl_out_fd != NULL)
1234 fclose(term->tl_out_fd);
1235#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001236 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001237 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001238 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001239 vim_free(term);
1240 }
1241}
1242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001243/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001244 * Get the part that is connected to the tty. Normally this is PART_IN, but
1245 * when writing buffer lines to the job it can be another. This makes it
1246 * possible to do "1,5term vim -".
1247 */
1248 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001249get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001250{
1251#ifdef UNIX
1252 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1253 int i;
1254
1255 for (i = 0; i < 3; ++i)
1256 {
1257 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1258
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001259 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001260 return parts[i];
1261 }
1262#endif
1263 return PART_IN;
1264}
1265
1266/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001267 * Read any vterm output and send it on the channel.
1268 */
1269 static void
1270term_forward_output(term_T *term)
1271{
1272 VTerm *vterm = term->tl_vterm;
1273 char buf[KEY_BUF_LEN];
1274 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1275
1276 if (curlen > 0)
1277 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1278 (char_u *)buf, (int)curlen, NULL);
1279}
1280
1281/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001282 * Write job output "msg[len]" to the vterm.
1283 */
1284 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001285term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001286{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001287 char_u *msg = msg_arg;
1288 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001289 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001290 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001291 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1292
1293 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1294 // the end.
1295 if (len > limit)
1296 {
1297 char_u *p = msg + len - limit;
1298
1299 p -= (*mb_head_off)(msg, p);
1300 len -= p - msg;
1301 msg = p;
1302 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001303
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001304 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001305
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001306 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001307 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001308 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001309
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001310 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001311 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1312}
1313
1314 static void
Bram Moolenaar58806c12023-04-29 14:26:02 +01001315position_cursor(win_T *wp, VTermPos *pos)
1316{
1317 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1318 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1319#ifdef FEAT_PROP_POPUP
1320 if (popup_is_popup(wp))
1321 {
1322 wp->w_wrow += popup_top_extra(wp);
1323 wp->w_wcol += popup_left_extra(wp);
1324 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
1325 }
1326 else
1327 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
1328#endif
1329 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1330}
1331
1332 static void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001333update_cursor(term_T *term, int redraw)
1334{
1335 if (term->tl_normal_mode)
1336 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001337#ifdef FEAT_GUI
1338 if (term->tl_system)
1339 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1340 term->tl_cursor_pos.col);
1341 else
1342#endif
Bram Moolenaar58806c12023-04-29 14:26:02 +01001343 if (!term_job_running(term))
1344 // avoid the cursor positioned below the last used line
Bram Moolenaar13568252018-03-16 20:46:58 +01001345 setcursor();
Bram Moolenaar58806c12023-04-29 14:26:02 +01001346 else
1347 {
1348 // do not use the window cursor position
1349 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1350 windgoto(W_WINROW(curwin) + curwin->w_wrow,
1351 curwin->w_wincol + curwin->w_wcol);
1352 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001353 if (redraw)
1354 {
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001355 aco_save_T aco;
1356
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001357 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1358 cursor_on();
1359 out_flush();
1360#ifdef FEAT_GUI
1361 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001362 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001363 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001364 gui_mch_flush();
1365 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001366#endif
Bram Moolenaar24fe33a2022-11-24 00:09:02 +00001367 // Make sure an invoked autocmd doesn't delete the buffer (and the
1368 // terminal) under our fingers.
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001369 ++term->tl_buffer->b_locked;
1370
1371 // save and restore curwin and curbuf, in case the autocmd changes them
1372 aucmd_prepbuf(&aco, curbuf);
1373 apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, FALSE, term->tl_buffer);
1374 aucmd_restbuf(&aco);
1375
1376 --term->tl_buffer->b_locked;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001377 }
1378}
1379
1380/*
1381 * Invoked when "msg" output from a job was received. Write it to the terminal
1382 * of "buffer".
1383 */
1384 void
1385write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1386{
1387 size_t len = STRLEN(msg);
1388 term_T *term = buffer->b_term;
1389
Bram Moolenaar4f974752019-02-17 17:44:42 +01001390#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001391 // Win32: Cannot redirect output of the job, intercept it here and write to
1392 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001393 if (term->tl_out_fd != NULL)
1394 {
1395 ch_log(channel, "Writing %d bytes to output file", (int)len);
1396 fwrite(msg, len, 1, term->tl_out_fd);
1397 return;
1398 }
1399#endif
1400
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001401 if (term->tl_vterm == NULL)
1402 {
1403 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1404 return;
1405 }
1406 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001407 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001408 term_write_job_output(term, msg, len);
1409
Bram Moolenaar13568252018-03-16 20:46:58 +01001410#ifdef FEAT_GUI
1411 if (term->tl_system)
1412 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001413 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001414 update_system_term(term);
1415 update_cursor(term, TRUE);
1416 }
1417 else
1418#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001419 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1420 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001421 if (!term->tl_normal_mode)
1422 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001423 // Don't use update_screen() when editing the command line, it gets
1424 // cleared.
1425 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001426 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001427 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001428 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001429 update_screen(UPD_VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001430 // update_screen() can be slow, check the terminal wasn't closed
1431 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001432 if (buffer == curbuf && curbuf->b_term != NULL)
1433 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001434 }
1435 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001436 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001437 }
1438}
1439
1440/*
1441 * Send a mouse position and click to the vterm
1442 */
1443 static int
1444term_send_mouse(VTerm *vterm, int button, int pressed)
1445{
1446 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001447 int row = mouse_row - W_WINROW(curwin);
1448 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001449
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001450#ifdef FEAT_PROP_POPUP
1451 if (popup_is_popup(curwin))
1452 {
1453 row -= popup_top_extra(curwin);
1454 col -= popup_left_extra(curwin);
1455 }
1456#endif
1457 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001458 if (button != 0)
1459 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001460 return TRUE;
1461}
1462
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001463static int enter_mouse_col = -1;
1464static int enter_mouse_row = -1;
1465
1466/*
1467 * Handle a mouse click, drag or release.
1468 * Return TRUE when a mouse event is sent to the terminal.
1469 */
1470 static int
1471term_mouse_click(VTerm *vterm, int key)
1472{
1473#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001474 // For modeless selection mouse drag and release events are ignored, unless
1475 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001476 static int ignore_drag_release = TRUE;
1477 VTermMouseState mouse_state;
1478
1479 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1480 if (mouse_state.flags == 0)
1481 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001482 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001483 switch (key)
1484 {
1485 case K_LEFTDRAG:
1486 case K_LEFTRELEASE:
1487 case K_RIGHTDRAG:
1488 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001489 // Ignore drag and release events when the button-down wasn't
1490 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001491 if (ignore_drag_release)
1492 {
1493 int save_mouse_col, save_mouse_row;
1494
1495 if (enter_mouse_col < 0)
1496 break;
1497
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001498 // mouse click in the window gave us focus, handle that
1499 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001500 save_mouse_col = mouse_col;
1501 save_mouse_row = mouse_row;
1502 mouse_col = enter_mouse_col;
1503 mouse_row = enter_mouse_row;
1504 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1505 mouse_col = save_mouse_col;
1506 mouse_row = save_mouse_row;
1507 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001508 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001509 case K_LEFTMOUSE:
1510 case K_RIGHTMOUSE:
1511 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1512 ignore_drag_release = TRUE;
1513 else
1514 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001515 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001516 if (clip_star.available)
1517 {
1518 int button, is_click, is_drag;
1519
1520 button = get_mouse_button(KEY2TERMCAP1(key),
1521 &is_click, &is_drag);
1522 if (mouse_model_popup() && button == MOUSE_LEFT
1523 && (mod_mask & MOD_MASK_SHIFT))
1524 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001525 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001526 button = MOUSE_RIGHT;
1527 mod_mask &= ~MOD_MASK_SHIFT;
1528 }
1529 clip_modeless(button, is_click, is_drag);
1530 }
1531 break;
1532
1533 case K_MIDDLEMOUSE:
1534 if (clip_star.available)
1535 insert_reg('*', TRUE);
1536 break;
1537 }
1538 enter_mouse_col = -1;
1539 return FALSE;
1540 }
1541#endif
1542 enter_mouse_col = -1;
1543
1544 switch (key)
1545 {
1546 case K_LEFTMOUSE:
1547 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1548 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1549 case K_LEFTRELEASE:
1550 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1551 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1552 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1553 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1554 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1555 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1556 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1557 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1558 }
1559 return TRUE;
1560}
1561
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001562/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001563 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1564 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001565 * Return the number of bytes in "buf".
1566 */
1567 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001568term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001569{
1570 VTerm *vterm = term->tl_vterm;
1571 VTermKey key = VTERM_KEY_NONE;
1572 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001573 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001574
1575 switch (c)
1576 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001577 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001578
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001579 // don't use VTERM_KEY_BACKSPACE, it always
1580 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001581 case K_BS: c = term_backspace_char; break;
1582
1583 case ESC: key = VTERM_KEY_ESCAPE; break;
1584 case K_DEL: key = VTERM_KEY_DEL; break;
1585 case K_DOWN: key = VTERM_KEY_DOWN; break;
1586 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1587 key = VTERM_KEY_DOWN; break;
1588 case K_END: key = VTERM_KEY_END; break;
1589 case K_S_END: mod = VTERM_MOD_SHIFT;
1590 key = VTERM_KEY_END; break;
1591 case K_C_END: mod = VTERM_MOD_CTRL;
1592 key = VTERM_KEY_END; break;
1593 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1594 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1595 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1596 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1597 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1598 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1599 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1600 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1601 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1602 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1603 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1604 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1605 case K_HOME: key = VTERM_KEY_HOME; break;
1606 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1607 key = VTERM_KEY_HOME; break;
1608 case K_C_HOME: mod = VTERM_MOD_CTRL;
1609 key = VTERM_KEY_HOME; break;
1610 case K_INS: key = VTERM_KEY_INS; break;
1611 case K_K0: key = VTERM_KEY_KP_0; break;
1612 case K_K1: key = VTERM_KEY_KP_1; break;
1613 case K_K2: key = VTERM_KEY_KP_2; break;
1614 case K_K3: key = VTERM_KEY_KP_3; break;
1615 case K_K4: key = VTERM_KEY_KP_4; break;
1616 case K_K5: key = VTERM_KEY_KP_5; break;
1617 case K_K6: key = VTERM_KEY_KP_6; break;
1618 case K_K7: key = VTERM_KEY_KP_7; break;
1619 case K_K8: key = VTERM_KEY_KP_8; break;
1620 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001621 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001622 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001623 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001624 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001625 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1626 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1628 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001629 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1630 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001631 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1632 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1633 case K_LEFT: key = VTERM_KEY_LEFT; break;
1634 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1635 key = VTERM_KEY_LEFT; break;
1636 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1637 key = VTERM_KEY_LEFT; break;
1638 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1639 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1640 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1641 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1642 key = VTERM_KEY_RIGHT; break;
1643 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1644 key = VTERM_KEY_RIGHT; break;
1645 case K_UP: key = VTERM_KEY_UP; break;
1646 case K_S_UP: mod = VTERM_MOD_SHIFT;
1647 key = VTERM_KEY_UP; break;
1648 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001649 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1650 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001651
Bram Moolenaara42ad572017-11-16 13:08:04 +01001652 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1653 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001654 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1655 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001656
1657 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001658 case K_LEFTMOUSE_NM:
1659 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001660 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001661 case K_LEFTRELEASE_NM:
1662 case K_MOUSEMOVE:
1663 case K_MIDDLEMOUSE:
1664 case K_MIDDLEDRAG:
1665 case K_MIDDLERELEASE:
1666 case K_RIGHTMOUSE:
1667 case K_RIGHTDRAG:
1668 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1669 return 0;
1670 other = TRUE;
1671 break;
1672
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001673 case K_X1MOUSE: /* TODO */ return 0;
1674 case K_X1DRAG: /* TODO */ return 0;
1675 case K_X1RELEASE: /* TODO */ return 0;
1676 case K_X2MOUSE: /* TODO */ return 0;
1677 case K_X2DRAG: /* TODO */ return 0;
1678 case K_X2RELEASE: /* TODO */ return 0;
1679
1680 case K_IGNORE: return 0;
1681 case K_NOP: return 0;
1682 case K_UNDO: return 0;
1683 case K_HELP: return 0;
1684 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1685 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1686 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1687 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1688 case K_SELECT: return 0;
1689#ifdef FEAT_GUI
1690 case K_VER_SCROLLBAR: return 0;
1691 case K_HOR_SCROLLBAR: return 0;
1692#endif
1693#ifdef FEAT_GUI_TABLINE
1694 case K_TABLINE: return 0;
1695 case K_TABMENU: return 0;
1696#endif
1697#ifdef FEAT_NETBEANS_INTG
1698 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1699#endif
1700#ifdef FEAT_DND
1701 case K_DROP: return 0;
1702#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001703 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001704 case K_PS: vterm_keyboard_start_paste(vterm);
1705 other = TRUE;
1706 break;
1707 case K_PE: vterm_keyboard_end_paste(vterm);
1708 other = TRUE;
1709 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001710 }
1711
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001712 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001713 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001714 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001715 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001716 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001717 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001718 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001719
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001720 // Ctrl-Shift-i may have the key "I" instead of "i", but for the kitty
1721 // keyboard protocol should use "i". Applies to all ascii letters.
1722 if (ASCII_ISUPPER(c)
Bram Moolenaarebed1b02022-11-24 14:05:19 +00001723 && vterm_is_kitty_keyboard(vterm)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001724 && mod == (VTERM_MOD_CTRL | VTERM_MOD_SHIFT))
1725 c = TOLOWER_ASC(c);
1726
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001727 /*
1728 * Convert special keys to vterm keys:
1729 * - Write keys to vterm: vterm_keyboard_key()
1730 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001731 */
1732 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001733 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001735 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001736 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001737 vterm_keyboard_unichar(vterm, c, mod);
1738
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001739 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001740 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1741}
1742
1743/*
1744 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001745 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001746 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001747 */
1748 static int
1749term_job_running_check(term_T *term, int check_job_status)
1750{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001751 // Also consider the job finished when the channel is closed, to avoid a
1752 // race condition when updating the title.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001753 if (term == NULL
1754 || term->tl_job == NULL
1755 || !channel_is_open(term->tl_job->jv_channel))
1756 return FALSE;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001757
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001758 job_T *job = term->tl_job;
1759
1760 // Careful: Checking the job status may invoke callbacks, which close
1761 // the buffer and terminate "term". However, "job" will not be freed
1762 // yet.
1763 if (check_job_status)
1764 job_status(job);
1765 return (job->jv_status == JOB_STARTED
1766 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001767}
1768
1769/*
1770 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001771 */
1772 int
1773term_job_running(term_T *term)
1774{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001775 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001776}
1777
1778/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001779 * Return TRUE if the job for "term" is still running, ignoring the job was
1780 * "NONE".
1781 */
1782 int
1783term_job_running_not_none(term_T *term)
1784{
1785 return term_job_running(term) && !term_none_open(term);
1786}
1787
1788/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001789 * Return TRUE if "term" has an active channel and used ":term NONE".
1790 */
1791 int
1792term_none_open(term_T *term)
1793{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001794 // Also consider the job finished when the channel is closed, to avoid a
1795 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001796 return term != NULL
1797 && term->tl_job != NULL
1798 && channel_is_open(term->tl_job->jv_channel)
1799 && term->tl_job->jv_channel->ch_keep_open;
1800}
1801
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001802//
1803// Used to confirm whether we would like to kill a terminal.
1804// Return OK when the user confirms to kill it.
1805// Return FAIL if the user selects otherwise.
1806//
1807 int
1808term_confirm_stop(buf_T *buf)
1809{
1810 char_u buff[DIALOG_MSG_SIZE];
1811 int ret;
1812
1813 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1814 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1815 if (ret == VIM_YES)
1816 return OK;
1817 else
1818 return FAIL;
1819}
1820
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001821/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001822 * Used when exiting: kill the job in "buf" if so desired.
1823 * Return OK when the job finished.
1824 * Return FAIL when the job is still running.
1825 */
1826 int
1827term_try_stop_job(buf_T *buf)
1828{
1829 int count;
1830 char *how = (char *)buf->b_term->tl_kill;
1831
1832#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001833 if ((how == NULL || *how == NUL)
1834 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001835 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001836 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001837 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001838 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001839 return FAIL;
1840 }
1841#endif
1842 if (how == NULL || *how == NUL)
1843 return FAIL;
1844
1845 job_stop(buf->b_term->tl_job, NULL, how);
1846
Bram Moolenaar9172d232019-01-29 23:06:54 +01001847 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001848 for (count = 0; count < 100; ++count)
1849 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001850 job_T *job;
1851
1852 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001853 if (!buf_valid(buf)
1854 || buf->b_term == NULL
1855 || buf->b_term->tl_job == NULL)
1856 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001857 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001858
Bram Moolenaar9172d232019-01-29 23:06:54 +01001859 // Call job_status() to update jv_status. It may cause the job to be
1860 // cleaned up but it won't be freed.
1861 job_status(job);
1862 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001863 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001864
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001865 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001866 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001867 }
1868 return FAIL;
1869}
1870
1871/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001872 * Add the last line of the scrollback buffer to the buffer in the window.
1873 */
1874 static void
1875add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1876{
1877 buf_T *buf = term->tl_buffer;
1878 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1879 linenr_T lnum = buf->b_ml.ml_line_count;
1880
Bram Moolenaar4f974752019-02-17 17:44:42 +01001881#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001882 if (!enc_utf8 && enc_codepage > 0)
1883 {
1884 WCHAR *ret = NULL;
1885 int length = 0;
1886
1887 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1888 &ret, &length);
1889 if (ret != NULL)
1890 {
1891 WideCharToMultiByte_alloc(enc_codepage, 0,
1892 ret, length, (char **)&text, &len, 0, 0);
1893 vim_free(ret);
1894 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1895 vim_free(text);
1896 }
1897 }
1898 else
1899#endif
1900 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1901 if (empty)
1902 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001903 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001904 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001905 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001906 curbuf = curwin->w_buffer;
1907 }
1908}
1909
1910 static void
1911cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1912{
1913 attr->width = cell->width;
1914 attr->attrs = cell->attrs;
1915 attr->fg = cell->fg;
1916 attr->bg = cell->bg;
1917}
1918
1919 static int
1920equal_celattr(cellattr_T *a, cellattr_T *b)
1921{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001922 // We only compare the RGB colors, ignoring the ANSI index and type.
1923 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001924 return a->fg.red == b->fg.red
1925 && a->fg.green == b->fg.green
1926 && a->fg.blue == b->fg.blue
1927 && a->bg.red == b->bg.red
1928 && a->bg.green == b->bg.green
1929 && a->bg.blue == b->bg.blue;
1930}
1931
Bram Moolenaard96ff162018-02-18 22:13:29 +01001932/*
1933 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1934 * line at this position. Otherwise at the end.
1935 */
1936 static int
1937add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1938{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001939 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
1940 return FALSE;
1941
1942 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1943 + term->tl_scrollback.ga_len;
1944
1945 if (lnum > 0)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001946 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001947 int i;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001948
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001949 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001950 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001951 *line = *(line - 1);
1952 --line;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001953 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01001954 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001955 line->sb_cols = 0;
1956 line->sb_cells = NULL;
1957 line->sb_fill_attr = *fill_attr;
1958 ++term->tl_scrollback.ga_len;
1959 return OK;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001960}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001961
1962/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001963 * Remove the terminal contents from the scrollback and the buffer.
1964 * Used before adding a new scrollback line or updating the buffer for lines
1965 * displayed in the terminal.
1966 */
1967 static void
1968cleanup_scrollback(term_T *term)
1969{
1970 sb_line_T *line;
1971 garray_T *gap;
1972
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001973 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001974 gap = &term->tl_scrollback;
1975 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1976 && gap->ga_len > 0)
1977 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001978 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001979 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1980 vim_free(line->sb_cells);
1981 --gap->ga_len;
1982 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001983 curbuf = curwin->w_buffer;
1984 if (curbuf == term->tl_buffer)
1985 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001986}
1987
1988/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001989 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001990 */
1991 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001992update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001994 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001995 int len;
1996 int lines_skipped = 0;
1997 VTermPos pos;
1998 VTermScreenCell cell;
1999 cellattr_T fill_attr, new_fill_attr;
2000 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002001
2002 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
2003 "Adding terminal window snapshot to buffer");
2004
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002005 // First remove the lines that were appended before, they might be
2006 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002007 cleanup_scrollback(term);
2008
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002009 screen = vterm_obtain_screen(term->tl_vterm);
2010 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
2012 {
2013 len = 0;
2014 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
2015 if (vterm_screen_get_cell(screen, pos, &cell) != 0
2016 && cell.chars[0] != NUL)
2017 {
2018 len = pos.col + 1;
2019 new_fill_attr = term->tl_default_color;
2020 }
2021 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002022 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002023 cell2cellattr(&cell, &new_fill_attr);
2024
2025 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
2026 ++lines_skipped;
2027 else
2028 {
2029 while (lines_skipped > 0)
2030 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002031 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002032 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002033 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002034 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002035 }
2036
2037 if (len == 0)
2038 p = NULL;
2039 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002040 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002041 if ((p != NULL || len == 0)
2042 && ga_grow(&term->tl_scrollback, 1) == OK)
2043 {
2044 garray_T ga;
2045 int width;
2046 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
2047 + term->tl_scrollback.ga_len;
2048
2049 ga_init2(&ga, 1, 100);
2050 for (pos.col = 0; pos.col < len; pos.col += width)
2051 {
2052 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2053 {
2054 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02002055 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002056 if (ga_grow(&ga, 1) == OK)
2057 ga.ga_len += utf_char2bytes(' ',
2058 (char_u *)ga.ga_data + ga.ga_len);
2059 }
2060 else
2061 {
2062 width = cell.width;
2063
2064 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01002065 if (width == 2)
2066 // second cell of double-width character has the
2067 // same attributes.
2068 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002069
Bram Moolenaara79fd562018-12-20 20:47:32 +01002070 // Each character can be up to 6 bytes.
2071 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002072 {
2073 int i;
2074 int c;
2075
2076 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
2077 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2078 (char_u *)ga.ga_data + ga.ga_len);
2079 }
2080 }
2081 }
2082 line->sb_cols = len;
2083 line->sb_cells = p;
2084 line->sb_fill_attr = new_fill_attr;
2085 fill_attr = new_fill_attr;
2086 ++term->tl_scrollback.ga_len;
2087
2088 if (ga_grow(&ga, 1) == FAIL)
2089 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2090 else
2091 {
2092 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2093 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2094 }
2095 ga_clear(&ga);
2096 }
2097 else
2098 vim_free(p);
2099 }
2100 }
2101
Bram Moolenaarf3aea592018-11-11 22:18:21 +01002102 // Add trailing empty lines.
2103 for (pos.row = term->tl_scrollback.ga_len;
2104 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
2105 ++pos.row)
2106 {
2107 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
2108 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2109 }
2110
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002111 term->tl_dirty_snapshot = FALSE;
2112#ifdef FEAT_TIMERS
2113 term->tl_timer_set = FALSE;
2114#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002115}
2116
2117/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002118 * Loop over all windows in the current tab, and also curwin, which is not
2119 * encountered when using a terminal in a popup window.
2120 * Return TRUE if "*wp" was set to the next window.
2121 */
2122 static int
2123for_all_windows_and_curwin(win_T **wp, int *did_curwin)
2124{
2125 if (*wp == NULL)
2126 *wp = firstwin;
2127 else if ((*wp)->w_next != NULL)
2128 *wp = (*wp)->w_next;
2129 else if (!*did_curwin)
2130 *wp = curwin;
2131 else
2132 return FALSE;
2133 if (*wp == curwin)
2134 *did_curwin = TRUE;
2135 return TRUE;
2136}
2137
2138/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002139 * If needed, add the current lines of the terminal to scrollback and to the
2140 * buffer. Called after the job has ended and when switching to
2141 * Terminal-Normal mode.
2142 * When "redraw" is TRUE redraw the windows that show the terminal.
2143 */
2144 static void
2145may_move_terminal_to_buffer(term_T *term, int redraw)
2146{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002147 if (term->tl_vterm == NULL)
2148 return;
2149
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002150 // Update the snapshot only if something changes or the buffer does not
2151 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002152 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2153 <= term->tl_scrollback_scrolled)
2154 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002155
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002156 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002157 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2158 &term->tl_default_color.fg, &term->tl_default_color.bg);
2159
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002160 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002161 {
2162 win_T *wp = NULL;
2163 int did_curwin = FALSE;
2164
2165 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002167 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002168 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002169 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2170 wp->w_cursor.col = 0;
2171 wp->w_valid = 0;
2172 if (wp->w_cursor.lnum >= wp->w_height)
2173 {
2174 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002176 if (wp->w_topline < min_topline)
2177 wp->w_topline = min_topline;
2178 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002179 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002180 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002181 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002182 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002183}
2184
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002185#if defined(FEAT_TIMERS) || defined(PROTO)
2186/*
2187 * Check if any terminal timer expired. If so, copy text from the terminal to
2188 * the buffer.
2189 * Return the time until the next timer will expire.
2190 */
2191 int
2192term_check_timers(int next_due_arg, proftime_T *now)
2193{
2194 term_T *term;
2195 int next_due = next_due_arg;
2196
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002197 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002198 {
2199 if (term->tl_timer_set && !term->tl_normal_mode)
2200 {
2201 long this_due = proftime_time_left(&term->tl_timer_due, now);
2202
2203 if (this_due <= 1)
2204 {
2205 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002206 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002207 }
2208 else if (next_due == -1 || next_due > this_due)
2209 next_due = this_due;
2210 }
2211 }
2212
2213 return next_due;
2214}
2215#endif
2216
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002217/*
2218 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2219 * otherwise end it.
2220 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002221 static void
2222set_terminal_mode(term_T *term, int normal_mode)
2223{
2224 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002225 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002226 if (!normal_mode)
2227 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002228 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002229 if (term->tl_buffer == curbuf)
2230 maketitle();
2231}
2232
2233/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002234 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002235 * Move the vterm contents into the scrollback buffer and free the vterm.
2236 */
2237 static void
2238cleanup_vterm(term_T *term)
2239{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002240 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002241 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002242 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002243 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002244}
2245
2246/*
2247 * Switch from Terminal-Job mode to Terminal-Normal mode.
2248 * Suspends updating the terminal window.
2249 */
2250 static void
2251term_enter_normal_mode(void)
2252{
2253 term_T *term = curbuf->b_term;
2254
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002255 set_terminal_mode(term, TRUE);
2256
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002257 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002258 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002259
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002260 // Move the window cursor to the position of the cursor in the
2261 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2263 + term->tl_cursor_pos.row + 1;
2264 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002265 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2266 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002267 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002268
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002269 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002270 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2271}
2272
2273/*
2274 * Returns TRUE if the current window contains a terminal and we are in
2275 * Terminal-Normal mode.
2276 */
2277 int
2278term_in_normal_mode(void)
2279{
2280 term_T *term = curbuf->b_term;
2281
2282 return term != NULL && term->tl_normal_mode;
2283}
2284
2285/*
2286 * Switch from Terminal-Normal mode to Terminal-Job mode.
2287 * Restores updating the terminal window.
2288 */
2289 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002290term_enter_job_mode(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002291{
2292 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002293
2294 set_terminal_mode(term, FALSE);
2295
2296 if (term->tl_channel_closed)
2297 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002298 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002299#ifdef FEAT_PROP_POPUP
2300 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002301 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002302#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002303}
2304
2305/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002306 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2307 * modifiers into a basic key. However, we may only find out after calling
2308 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2309 * "no_reduce_keys" before using it.
2310 */
2311typedef enum {
2312 NRKS_NONE, // initial value
2313 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2314 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2315 // check_no_reduce_keys(), must be decremented.
2316} reduce_key_state_T;
2317
2318static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2319
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002320/*
2321 * Return TRUE if the term is using modifyOtherKeys level 2 or the kitty
2322 * keyboard protocol.
2323 */
2324 static int
2325vterm_using_key_protocol(void)
2326{
2327 return curbuf->b_term != NULL
2328 && curbuf->b_term->tl_vterm != NULL
2329 && (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm)
2330 || vterm_is_kitty_keyboard(curbuf->b_term->tl_vterm));
2331}
2332
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002333 void
2334check_no_reduce_keys(void)
2335{
2336 if (no_reduce_key_state != NRKS_CHECK
2337 || no_reduce_keys >= 1
2338 || curbuf->b_term == NULL
2339 || curbuf->b_term->tl_vterm == NULL)
2340 return;
2341
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002342 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002343 {
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002344 // "modify_other_keys" or kitty keyboard protocol was enabled while
2345 // waiting.
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002346 no_reduce_key_state = NRKS_SET;
2347 ++no_reduce_keys;
2348 }
2349}
2350
2351/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002352 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002353 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002354 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002355 */
2356 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002357term_vgetc(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358{
2359 int c;
2360 int save_State = State;
2361
Bram Moolenaar24959102022-05-07 20:01:16 +01002362 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002363 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002364#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002365 ctrl_break_was_pressed = FALSE;
2366#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002367
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002368 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002369 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002370 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002371 no_reduce_key_state = NRKS_SET;
2372 }
2373 else
2374 {
2375 no_reduce_key_state = NRKS_CHECK;
2376 }
2377
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002378 c = vgetc();
2379 got_int = FALSE;
2380 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002381
2382 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002383 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002384 no_reduce_key_state = NRKS_NONE;
2385
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002386 return c;
2387}
2388
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002389static int mouse_was_outside = FALSE;
2390
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002391/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002392 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002393 * Return FAIL when the key needs to be handled in Normal mode.
2394 * Return OK when the key was dropped or sent to the terminal.
2395 */
2396 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002397send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002398{
2399 char msg[KEY_BUF_LEN];
2400 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002401 int dragging_outside = FALSE;
2402
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002403 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002404 switch (c)
2405 {
2406 case NUL:
2407 case K_ZERO:
2408 if (typed)
2409 stuffcharReadbuff(c);
2410 return FAIL;
2411
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002412 case K_TABLINE:
2413 stuffcharReadbuff(c);
2414 return FAIL;
2415
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002416 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002417 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002418 return FAIL;
2419
2420 case K_LEFTDRAG:
2421 case K_MIDDLEDRAG:
2422 case K_RIGHTDRAG:
2423 case K_X1DRAG:
2424 case K_X2DRAG:
2425 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002426 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002427 case K_LEFTMOUSE:
2428 case K_LEFTMOUSE_NM:
2429 case K_LEFTRELEASE:
2430 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002431 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002432 case K_MIDDLEMOUSE:
2433 case K_MIDDLERELEASE:
2434 case K_RIGHTMOUSE:
2435 case K_RIGHTRELEASE:
2436 case K_X1MOUSE:
2437 case K_X1RELEASE:
2438 case K_X2MOUSE:
2439 case K_X2RELEASE:
2440
2441 case K_MOUSEUP:
2442 case K_MOUSEDOWN:
2443 case K_MOUSELEFT:
2444 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002445 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002446 int row = mouse_row;
2447 int col = mouse_col;
2448
2449#ifdef FEAT_PROP_POPUP
2450 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002451 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002452 row -= popup_top_extra(curwin);
2453 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002454 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002455#endif
2456 if (row < W_WINROW(curwin)
2457 || row >= (W_WINROW(curwin) + curwin->w_height)
2458 || col < curwin->w_wincol
2459 || col >= W_ENDCOL(curwin)
2460 || dragging_outside)
2461 {
2462 // click or scroll outside the current window or on status
2463 // line or vertical separator
2464 if (typed)
2465 {
2466 stuffcharReadbuff(c);
2467 mouse_was_outside = TRUE;
2468 }
2469 return FAIL;
2470 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002471 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002472 break;
2473
2474 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002475 case K_SCRIPT_COMMAND:
2476 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002477 }
2478 if (typed)
2479 mouse_was_outside = FALSE;
2480
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002481 // Convert the typed key to a sequence of bytes for the job.
2482 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002483 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002484 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002485 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2486 (char_u *)msg, (int)len, NULL);
2487
2488 return OK;
2489}
2490
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002491/*
2492 * Handle CTRL-W "": send register contents to the job.
2493 */
2494 static void
2495term_paste_register(int prev_c UNUSED)
2496{
2497 int c;
2498 list_T *l;
2499 listitem_T *item;
2500 long reglen = 0;
2501 int type;
2502
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 if (add_to_showcmd(prev_c))
2504 if (add_to_showcmd('"'))
2505 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002506
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002507 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002508 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002509
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002510 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002511 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002512 return;
2513
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002514 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002515 if (c == '=' && get_expr_register() != '=')
2516 return;
2517 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002518 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002519 return;
2520
2521 l = (list_T *)get_reg_contents(c, GREG_LIST);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002522 if (l == NULL)
2523 return;
2524
2525 type = get_reg_type(c, &reglen);
2526 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002527 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002528 char_u *s = tv_get_string(&item->li_tv);
2529#ifdef MSWIN
2530 char_u *tmp = s;
2531
2532 if (!enc_utf8 && enc_codepage > 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002533 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002534 WCHAR *ret = NULL;
2535 int length = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002536
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002537 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2538 (int)STRLEN(s), &ret, &length);
2539 if (ret != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002540 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002541 WideCharToMultiByte_alloc(CP_UTF8, 0,
2542 ret, length, (char **)&s, &length, 0, 0);
2543 vim_free(ret);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002544 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002545 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002546#endif
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002547 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2548 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002549#ifdef MSWIN
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002550 if (tmp != s)
2551 vim_free(s);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002552#endif
2553
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002554 if (item->li_next != NULL || type == MLINE)
2555 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2556 (char_u *)"\r", 1, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002557 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002558 list_free(l);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002559}
2560
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002561/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002562 * Return TRUE when waiting for a character in the terminal, the cursor of the
2563 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002564 */
2565 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002566terminal_is_active(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002567{
2568 return in_terminal_loop != NULL;
2569}
2570
Bram Moolenaar83d47902020-03-26 20:34:00 +01002571/*
dundargocc57b5bc2022-11-02 13:30:51 +00002572 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002573 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002574 static int
2575term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002576{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002577 char_u *name;
2578
2579 if (wp != NULL && *wp->w_p_wcr != NUL)
2580 name = wp->w_p_wcr;
2581 else if (term->tl_highlight_name != NULL)
2582 name = term->tl_highlight_name;
2583 else
2584 name = (char_u*)"Terminal";
2585
2586 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002587}
2588
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002589#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002590 cursorentry_T *
2591term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2592{
2593 term_T *term = in_terminal_loop;
2594 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002595 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002596 guicolor_T term_fg = INVALCOLOR;
2597 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002598
Bram Moolenaara80faa82020-04-12 19:37:17 +02002599 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002600 entry.shape = entry.mshape =
2601 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2602 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2603 SHAPE_BLOCK;
2604 entry.percentage = 20;
2605 if (term->tl_cursor_blink)
2606 {
2607 entry.blinkwait = 700;
2608 entry.blinkon = 400;
2609 entry.blinkoff = 250;
2610 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002611
Bram Moolenaar83d47902020-03-26 20:34:00 +01002612 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002613 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002614 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002615 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002616 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002617 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002618 else
2619 *fg = gui.back_pixel;
2620
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002621 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002622 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002623 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002624 *bg = term_fg;
2625 else
2626 *bg = gui.norm_pixel;
2627 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002628 else
2629 *bg = color_name2handle(term->tl_cursor_color);
2630 entry.name = "n";
2631 entry.used_for = SHAPE_CURSOR;
2632
2633 return &entry;
2634}
2635#endif
2636
Bram Moolenaard317b382018-02-08 22:33:31 +01002637 static void
2638may_output_cursor_props(void)
2639{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002640 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002641 || last_set_cursor_shape != desired_cursor_shape
2642 || last_set_cursor_blink != desired_cursor_blink)
2643 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002644 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002645 last_set_cursor_shape = desired_cursor_shape;
2646 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002647 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002648 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002649 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002650 ui_cursor_shape_forced(TRUE);
2651 else
2652 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2653 }
2654}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002655
Bram Moolenaard317b382018-02-08 22:33:31 +01002656/*
2657 * Set the cursor color and shape, if not last set to these.
2658 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002659 static void
2660may_set_cursor_props(term_T *term)
2661{
2662#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002663 // For the GUI the cursor properties are obtained with
2664 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002665 if (gui.in_use)
2666 return;
2667#endif
2668 if (in_terminal_loop == term)
2669 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002670 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002671 desired_cursor_shape = term->tl_cursor_shape;
2672 desired_cursor_blink = term->tl_cursor_blink;
2673 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002674 }
2675}
2676
Bram Moolenaard317b382018-02-08 22:33:31 +01002677/*
2678 * Reset the desired cursor properties and restore them when needed.
2679 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002680 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002681prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002682{
2683#ifdef FEAT_GUI
2684 if (gui.in_use)
2685 return;
2686#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002687 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002688 desired_cursor_shape = -1;
2689 desired_cursor_blink = -1;
2690 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002691}
2692
2693/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002694 * Returns TRUE if the current window contains a terminal and we are sending
2695 * keys to the job.
2696 * If "check_job_status" is TRUE update the job status.
2697 */
2698 static int
2699term_use_loop_check(int check_job_status)
2700{
2701 term_T *term = curbuf->b_term;
2702
2703 return term != NULL
2704 && !term->tl_normal_mode
2705 && term->tl_vterm != NULL
2706 && term_job_running_check(term, check_job_status);
2707}
2708
2709/*
2710 * Returns TRUE if the current window contains a terminal and we are sending
2711 * keys to the job.
2712 */
2713 int
2714term_use_loop(void)
2715{
2716 return term_use_loop_check(FALSE);
2717}
2718
2719/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002720 * Called when entering a window with the mouse. If this is a terminal window
2721 * we may want to change state.
2722 */
2723 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002724term_win_entered(void)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002725{
2726 term_T *term = curbuf->b_term;
2727
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002728 if (term == NULL)
2729 return;
2730
2731 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002732 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002733 reset_VIsual_and_resel();
2734 if (State & MODE_INSERT)
2735 stop_insert_mode = TRUE;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002736 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002737 mouse_was_outside = FALSE;
2738 enter_mouse_col = mouse_col;
2739 enter_mouse_row = mouse_row;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002740}
2741
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002742 void
2743term_focus_change(int in_focus)
2744{
2745 term_T *term = curbuf->b_term;
2746
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002747 if (term == NULL || term->tl_vterm == NULL)
2748 return;
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002749
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002750 VTermState *state = vterm_obtain_state(term->tl_vterm);
2751
2752 if (in_focus)
2753 vterm_state_focus_in(state);
2754 else
2755 vterm_state_focus_out(state);
2756 term_forward_output(term);
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002757}
2758
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002759/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002760 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2761 * Return the Ctrl-key value in that case.
2762 */
2763 static int
2764raw_c_to_ctrl(int c)
2765{
2766 if ((mod_mask & MOD_MASK_CTRL)
2767 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2768 return c & 0x1f;
2769 return c;
2770}
2771
2772/*
2773 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002774 * Also when the Kitty keyboard protocol is used.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002775 * May set "mod_mask".
2776 */
2777 static int
2778ctrl_to_raw_c(int c)
2779{
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002780 if (c < 0x20 && vterm_using_key_protocol())
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002781 {
2782 mod_mask |= MOD_MASK_CTRL;
2783 return c + '@';
2784 }
2785 return c;
2786}
2787
2788/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002789 * Wait for input and send it to the job.
2790 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2791 * when there is no more typahead.
2792 * Return when the start of a CTRL-W command is typed or anything else that
2793 * should be handled as a Normal mode command.
2794 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2795 * the terminal was closed.
2796 */
2797 int
2798terminal_loop(int blocking)
2799{
2800 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002801 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002802 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002803 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002804#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002805 int tty_fd = curbuf->b_term->tl_job->jv_channel
2806 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002807#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002808 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002809
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002810 // Remember the terminal we are sending keys to. However, the terminal
2811 // might be closed while waiting for a character, e.g. typing "exit" in a
2812 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2813 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002814 in_terminal_loop = curbuf->b_term;
2815
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002816 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002817 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002818 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002819 if (termwinkey == Ctrl_W)
2820 termwinkey = 0;
2821 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002822 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002823 may_set_cursor_props(curbuf->b_term);
2824
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002825 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002826 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002827#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002828 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002829#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002830 // TODO: skip screen update when handling a sequence of keys.
2831 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002832 while (must_redraw != 0)
2833 if (update_screen(0) == FAIL)
2834 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002835 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002836 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002837 break;
2838
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002839 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002840 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002841
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002842 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002843 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002844 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002845 // Job finished while waiting for a character. Push back the
2846 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002847 if (raw_c != K_IGNORE)
2848 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002849 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002850 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002851 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002852 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002853 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002854
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002855#ifdef UNIX
2856 /*
2857 * The shell or another program may change the tty settings. Getting
2858 * them for every typed character is a bit of overhead, but it's needed
2859 * for the first character typed, e.g. when Vim starts in a shell.
2860 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002861 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002862 {
2863 ttyinfo_T info;
2864
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002865 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002866 if (get_tty_info(tty_fd, &info) == OK)
2867 term_backspace_char = info.backspace;
2868 }
2869#endif
2870
Bram Moolenaar4f974752019-02-17 17:44:42 +01002871#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002872 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2873 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002874 if (ctrl_break_was_pressed)
2875 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2876#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002877 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2878 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002879 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002880#ifdef FEAT_GUI
2881 && !curbuf->b_term->tl_system
2882#endif
2883 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002884 {
2885 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002886 int prev_raw_c = raw_c;
2887 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002889 if (add_to_showcmd(c))
2890 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002891
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002892 raw_c = term_vgetc();
2893 c = raw_c_to_ctrl(raw_c);
2894
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002895 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002896
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002897 if (!term_use_loop_check(TRUE)
2898 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002899 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002900 break;
2901
2902 if (prev_c == Ctrl_BSL)
2903 {
2904 if (c == Ctrl_N)
2905 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002906 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002907 term_enter_normal_mode();
2908 ret = FAIL;
2909 goto theend;
2910 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002911 // Send both keys to the terminal, first one here, second one
2912 // below.
2913 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2914 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002915 }
2916 else if (c == Ctrl_C)
2917 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002918 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002919 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2920 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002921 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002923 // "CTRL-W .": send CTRL-W to the job
2924 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002925 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002926 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002927 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002928 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002929 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002930 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002931 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002932 else if (c == 'N')
2933 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002934 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002935 term_enter_normal_mode();
2936 ret = FAIL;
2937 goto theend;
2938 }
2939 else if (c == '"')
2940 {
2941 term_paste_register(prev_c);
2942 continue;
2943 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002944 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002945 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002946 // space for CTRL-W, modifier, multi-byte char and NUL
2947 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002948
2949 // Put the command into the typeahead buffer, when using the
2950 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2951 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002952 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002953 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002954 ret = OK;
2955 goto theend;
2956 }
2957 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002958# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002959 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002960 {
2961 WCHAR wc;
2962 char_u mb[3];
2963
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002964 mb[0] = (unsigned)raw_c >> 8;
2965 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002966 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002967 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002968 }
2969# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002970 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002971 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002972 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002973 // We are sure to come back here, don't reset the cursor color
2974 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002975 restore_cursor = FALSE;
2976
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002977 ret = OK;
2978 goto theend;
2979 }
2980 }
2981 ret = FAIL;
2982
2983theend:
2984 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002985 if (restore_cursor)
2986 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002987
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002988 // Move a snapshot of the screen contents to the buffer, so that completion
2989 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002990 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2991 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002992
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002993 return ret;
2994}
2995
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002996 static void
2997may_toggle_cursor(term_T *term)
2998{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002999 if (in_terminal_loop != term)
3000 return;
3001
3002 if (term->tl_cursor_visible)
3003 cursor_on();
3004 else
3005 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003006}
3007
3008/*
3009 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01003010 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003011 */
3012 static int
3013color2index(VTermColor *color, int fg, int *boldp)
3014{
3015 int red = color->red;
3016 int blue = color->blue;
3017 int green = color->green;
3018
LemonBoyb2b3acb2022-05-20 10:10:34 +01003019 *boldp = FALSE;
3020
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003021 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003022 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01003023
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003024 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003025 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003026 // Use the color as-is if possible, give up otherwise.
3027 if (color->index < t_colors)
3028 return color->index + 1;
3029 // 8-color terminals can actually display twice as many colors by
3030 // setting the high-intensity/bold bit.
3031 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003032 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003033 *boldp = TRUE;
3034 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003035 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01003036 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003037 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01003038
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003039 if (t_colors >= 256)
3040 {
3041 if (red == blue && red == green)
3042 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003043 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003044 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003045 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
3046 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
3047 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003048 int i;
3049
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003050 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003051 return 17; // 00/00/00
3052 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003053 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003054 for (i = 0; i < 23; ++i)
3055 if (red < cutoff[i])
3056 return i + 233;
3057 return 256;
3058 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003059 {
3060 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
3061 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003062
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003063 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003064 for (ri = 0; ri < 5; ++ri)
3065 if (red < cutoff[ri])
3066 break;
3067 for (gi = 0; gi < 5; ++gi)
3068 if (green < cutoff[gi])
3069 break;
3070 for (bi = 0; bi < 5; ++bi)
3071 if (blue < cutoff[bi])
3072 break;
3073 return 17 + ri * 36 + gi * 6 + bi;
3074 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003075 }
3076 return 0;
3077}
3078
3079/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01003080 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003081 */
3082 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003083vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003084{
3085 int attr = 0;
3086
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003087 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003088 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003089 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003090 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003091 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003092 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003093 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003094 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003095 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003096 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003097 return attr;
3098}
3099
3100/*
3101 * Store Vterm attributes in "cell" from highlight flags.
3102 */
3103 static void
3104hl2vtermAttr(int attr, cellattr_T *cell)
3105{
Bram Moolenaara80faa82020-04-12 19:37:17 +02003106 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003107 if (attr & HL_BOLD)
3108 cell->attrs.bold = 1;
3109 if (attr & HL_UNDERLINE)
3110 cell->attrs.underline = 1;
3111 if (attr & HL_ITALIC)
3112 cell->attrs.italic = 1;
3113 if (attr & HL_STRIKETHROUGH)
3114 cell->attrs.strike = 1;
3115 if (attr & HL_INVERSE)
3116 cell->attrs.reverse = 1;
3117}
3118
3119/*
3120 * Convert the attributes of a vterm cell into an attribute index.
3121 */
3122 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003123cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003124 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003125 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003126 VTermScreenCellAttrs *cellattrs,
3127 VTermColor *cellfg,
3128 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003129{
3130 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003131 VTermColor *fg = cellfg;
3132 VTermColor *bg = cellbg;
3133 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3134 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3135
3136 if (is_default_fg || is_default_bg)
3137 {
3138 if (wp != NULL && *wp->w_p_wcr != NUL)
3139 {
3140 if (is_default_fg)
3141 fg = &wp->w_term_wincolor.fg;
3142 if (is_default_bg)
3143 bg = &wp->w_term_wincolor.bg;
3144 }
3145 else
3146 {
3147 if (is_default_fg)
3148 fg = &term->tl_default_color.fg;
3149 if (is_default_bg)
3150 bg = &term->tl_default_color.bg;
3151 }
3152 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153
3154#ifdef FEAT_GUI
3155 if (gui.in_use)
3156 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003157 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3158 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3159 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003160 }
3161 else
3162#endif
3163#ifdef FEAT_TERMGUICOLORS
3164 if (p_tgc)
3165 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003166 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3167 ? INVALCOLOR
3168 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3169 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3170 ? INVALCOLOR
3171 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3172 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003173 }
3174 else
3175#endif
3176 {
3177 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003178 int ctermfg = color2index(fg, TRUE, &bold);
3179 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003180
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003181 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003182 if (bold == TRUE)
3183 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003184
3185 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003186 }
3187 return 0;
3188}
3189
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003190 static void
3191set_dirty_snapshot(term_T *term)
3192{
3193 term->tl_dirty_snapshot = TRUE;
3194#ifdef FEAT_TIMERS
3195 if (!term->tl_normal_mode)
3196 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003197 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003198 profile_setlimit(100L, &term->tl_timer_due);
3199 term->tl_timer_set = TRUE;
3200 }
3201#endif
3202}
3203
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003204 static int
3205handle_damage(VTermRect rect, void *user)
3206{
3207 term_T *term = (term_T *)user;
3208
3209 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3210 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003211 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003212 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003213 return 1;
3214}
3215
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003216 static void
3217term_scroll_up(term_T *term, int start_row, int count)
3218{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003219 win_T *wp = NULL;
3220 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003221 VTermColor fg, bg;
3222 VTermScreenCellAttrs attr;
3223 int clear_attr;
3224
Bram Moolenaara80faa82020-04-12 19:37:17 +02003225 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003226
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003227 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003228 {
3229 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003230 {
3231 // Set the color to clear lines with.
3232 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3233 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003234 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003235 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003236 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003237 }
3238}
3239
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003240 static int
3241handle_moverect(VTermRect dest, VTermRect src, void *user)
3242{
3243 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003244 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003245
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003246 // Scrolling up is done much more efficiently by deleting lines instead of
3247 // redrawing the text. But avoid doing this multiple times, postpone until
3248 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003249 if (dest.start_col == src.start_col
3250 && dest.end_col == src.end_col
3251 && dest.start_row < src.start_row)
3252 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003253 if (dest.start_row == 0)
3254 term->tl_postponed_scroll += count;
3255 else
3256 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003257 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003258
3259 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3260 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003261 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003262
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003263 // Note sure if the scrolling will work correctly, let's do a complete
3264 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003265 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003266 return 1;
3267}
3268
3269 static int
3270handle_movecursor(
3271 VTermPos pos,
3272 VTermPos oldpos UNUSED,
3273 int visible,
3274 void *user)
3275{
3276 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003277 win_T *wp = NULL;
3278 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003279
3280 term->tl_cursor_pos = pos;
3281 term->tl_cursor_visible = visible;
3282
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003283 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003284 {
3285 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003286 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003287 }
3288 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003289 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003290
3291 return 1;
3292}
3293
3294 static int
3295handle_settermprop(
3296 VTermProp prop,
3297 VTermValue *value,
3298 void *user)
3299{
3300 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003301 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003302
3303 switch (prop)
3304 {
3305 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003306 if (disable_vterm_title_for_testing)
3307 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003308 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003309 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003310 if (strval == NULL)
3311 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003312 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003313 // a blank title isn't useful, make it empty, so that "running" is
3314 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003315 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003316 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003317 // Same as blank
3318 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003319 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003320 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3321 term->tl_title = NULL;
3322 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003323 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003324 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003325#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003326 else if (!enc_utf8 && enc_codepage > 0)
3327 {
3328 WCHAR *ret = NULL;
3329 int length = 0;
3330
3331 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003332 (char*)value->string.str,
3333 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003334 if (ret != NULL)
3335 {
3336 WideCharToMultiByte_alloc(enc_codepage, 0,
3337 ret, length, (char**)&term->tl_title,
3338 &length, 0, 0);
3339 vim_free(ret);
3340 }
3341 }
3342#endif
3343 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003344 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003345 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003346 strval = NULL;
3347 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003348 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003349 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003350 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003351 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003352 curwin->w_redr_status = TRUE;
3353 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003354 break;
3355
3356 case VTERM_PROP_CURSORVISIBLE:
3357 term->tl_cursor_visible = value->boolean;
3358 may_toggle_cursor(term);
3359 out_flush();
3360 break;
3361
3362 case VTERM_PROP_CURSORBLINK:
3363 term->tl_cursor_blink = value->boolean;
3364 may_set_cursor_props(term);
3365 break;
3366
3367 case VTERM_PROP_CURSORSHAPE:
3368 term->tl_cursor_shape = value->number;
3369 may_set_cursor_props(term);
3370 break;
3371
3372 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003373 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003374 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003375 if (strval == NULL)
3376 break;
3377 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003378 may_set_cursor_props(term);
3379 break;
3380
3381 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003382 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003383 term->tl_using_altscreen = value->boolean;
3384 break;
3385
3386 default:
3387 break;
3388 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003389 vim_free(strval);
3390
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003391 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003392 return 1;
3393}
3394
3395/*
3396 * The job running in the terminal resized the terminal.
3397 */
3398 static int
3399handle_resize(int rows, int cols, void *user)
3400{
3401 term_T *term = (term_T *)user;
3402 win_T *wp;
3403
3404 term->tl_rows = rows;
3405 term->tl_cols = cols;
3406 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003407 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003408 term->tl_vterm_size_changed = FALSE;
3409 else
3410 {
3411 FOR_ALL_WINDOWS(wp)
3412 {
3413 if (wp->w_buffer == term->tl_buffer)
3414 {
3415 win_setheight_win(rows, wp);
3416 win_setwidth_win(cols, wp);
3417 }
3418 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003419 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003420 }
3421 return 1;
3422}
3423
3424/*
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003425 * If the number of lines that are stored goes over 'termwinscroll' then
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003426 * delete the first 10%.
3427 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3428 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003429 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003430 static void
3431limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003432{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003433 if (gap->ga_len < term->tl_buffer->b_p_twsl)
3434 return;
3435
3436 int todo = term->tl_buffer->b_p_twsl / 10;
3437 int i;
3438
3439 curbuf = term->tl_buffer;
3440 for (i = 0; i < todo; ++i)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003441 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003442 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003443 if (update_buffer)
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003444 ml_delete(1);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003445 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003446 curbuf = curwin->w_buffer;
3447
3448 gap->ga_len -= todo;
3449 mch_memmove(gap->ga_data,
3450 (sb_line_T *)gap->ga_data + todo,
3451 sizeof(sb_line_T) * gap->ga_len);
3452 if (update_buffer)
3453 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003454}
3455
3456/*
3457 * Handle a line that is pushed off the top of the screen.
3458 */
3459 static int
3460handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3461{
3462 term_T *term = (term_T *)user;
3463 garray_T *gap;
3464 int update_buffer;
3465
3466 if (term->tl_normal_mode)
3467 {
3468 // In Terminal-Normal mode the user interacts with the buffer, thus we
3469 // must not change it. Postpone adding the scrollback lines.
3470 gap = &term->tl_scrollback_postponed;
3471 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003472 }
3473 else
3474 {
3475 // First remove the lines that were appended before, the pushed line
3476 // goes above it.
3477 cleanup_scrollback(term);
3478 gap = &term->tl_scrollback;
3479 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003480 }
3481
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003482 limit_scrollback(term, gap, update_buffer);
3483
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003484 if (ga_grow(gap, 1) == FAIL)
3485 return 0;
3486
3487 cellattr_T *p = NULL;
3488 int len = 0;
3489 int i;
3490 int c;
3491 int col;
3492 int text_len;
3493 char_u *text;
3494 sb_line_T *line;
3495 garray_T ga;
3496 cellattr_T fill_attr = term->tl_default_color;
3497
3498 // do not store empty cells at the end
3499 for (i = 0; i < cols; ++i)
3500 if (cells[i].chars[0] != 0)
3501 len = i + 1;
3502 else
3503 cell2cellattr(&cells[i], &fill_attr);
3504
3505 ga_init2(&ga, 1, 100);
3506 if (len > 0)
3507 p = ALLOC_MULT(cellattr_T, len);
3508 if (p != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003509 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003510 for (col = 0; col < len; col += cells[col].width)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003511 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003512 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003513 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003514 ga.ga_len = 0;
3515 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003516 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003517 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3518 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3519 (char_u *)ga.ga_data + ga.ga_len);
3520 cell2cellattr(&cells[col], &p[col]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003521 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003522 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003523 if (ga_grow(&ga, 1) == FAIL)
3524 {
3525 if (update_buffer)
3526 text = (char_u *)"";
3527 else
3528 text = vim_strsave((char_u *)"");
3529 text_len = 0;
3530 }
3531 else
3532 {
3533 text = ga.ga_data;
3534 text_len = ga.ga_len;
3535 *(text + text_len) = NUL;
3536 }
3537 if (update_buffer)
3538 add_scrollback_line_to_buffer(term, text, text_len);
3539
3540 line = (sb_line_T *)gap->ga_data + gap->ga_len;
3541 line->sb_cols = len;
3542 line->sb_cells = p;
3543 line->sb_fill_attr = fill_attr;
3544 if (update_buffer)
3545 {
3546 line->sb_text = NULL;
3547 ++term->tl_scrollback_scrolled;
3548 ga_clear(&ga); // free the text
3549 }
3550 else
3551 {
3552 line->sb_text = text;
3553 ga_init(&ga); // text is kept in tl_scrollback_postponed
3554 }
3555 ++gap->ga_len;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003556 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003557}
3558
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003559/*
3560 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3561 * received and stored in tl_scrollback_postponed.
3562 */
3563 static void
3564handle_postponed_scrollback(term_T *term)
3565{
3566 int i;
3567
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003568 if (term->tl_scrollback_postponed.ga_len == 0)
3569 return;
3570 ch_log(NULL, "Moving postponed scrollback to scrollback");
3571
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003572 // First remove the lines that were appended before, the pushed lines go
3573 // above it.
3574 cleanup_scrollback(term);
3575
3576 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3577 {
3578 char_u *text;
3579 sb_line_T *pp_line;
3580 sb_line_T *line;
3581
3582 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3583 break;
3584 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3585
3586 text = pp_line->sb_text;
3587 if (text == NULL)
3588 text = (char_u *)"";
3589 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3590 vim_free(pp_line->sb_text);
3591
3592 line = (sb_line_T *)term->tl_scrollback.ga_data
3593 + term->tl_scrollback.ga_len;
3594 line->sb_cols = pp_line->sb_cols;
3595 line->sb_cells = pp_line->sb_cells;
3596 line->sb_fill_attr = pp_line->sb_fill_attr;
3597 line->sb_text = NULL;
3598 ++term->tl_scrollback_scrolled;
3599 ++term->tl_scrollback.ga_len;
3600 }
3601
3602 ga_clear(&term->tl_scrollback_postponed);
3603 limit_scrollback(term, &term->tl_scrollback, TRUE);
3604}
3605
LemonBoy77771d32022-04-13 11:47:25 +01003606/*
3607 * Called when the terminal wants to ring the system bell.
3608 */
3609 static int
3610handle_bell(void *user UNUSED)
3611{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003612 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003613 return 0;
3614}
3615
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003616static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003617 handle_damage, // damage
3618 handle_moverect, // moverect
3619 handle_movecursor, // movecursor
3620 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003621 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003622 handle_resize, // resize
3623 handle_pushline, // sb_pushline
Bram Moolenaar6a12d262022-10-16 19:26:52 +01003624 NULL, // sb_popline
3625 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003626};
3627
3628/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003629 * Do the work after the channel of a terminal was closed.
3630 * Must be called only when updating_screen is FALSE.
3631 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3632 */
3633 static int
3634term_after_channel_closed(term_T *term)
3635{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003636 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003637 if (!term->tl_normal_mode)
3638 {
3639 int fnum = term->tl_buffer->b_fnum;
3640
3641 cleanup_vterm(term);
3642
3643 if (term->tl_finish == TL_FINISH_CLOSE)
3644 {
3645 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003646 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003647#ifdef FEAT_PROP_POPUP
3648 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003649
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003650 // If this was a terminal in a popup window, go back to the
3651 // previous window.
3652 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3653 {
3654 pwin = curwin;
3655 if (win_valid(prevwin))
3656 win_enter(prevwin, FALSE);
3657 }
3658 else
3659#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003660 // If this is the last normal window: exit Vim.
3661 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3662 {
3663 exarg_T ea;
3664
Bram Moolenaara80faa82020-04-12 19:37:17 +02003665 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003666 ex_quit(&ea);
3667 return TRUE;
3668 }
3669
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003670 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003671 ch_log(NULL, "terminal job finished, closing window");
3672 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaare76062c2022-11-28 18:51:43 +00003673 if (curbuf == term->tl_buffer)
3674 {
3675 // Avoid closing the window if we temporarily use it.
3676 if (is_aucmd_win(curwin))
3677 do_set_w_closing = TRUE;
3678 if (do_set_w_closing)
3679 curwin->w_closing = TRUE;
3680 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
3681 if (do_set_w_closing)
3682 curwin->w_closing = FALSE;
3683 aucmd_restbuf(&aco);
3684 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003685#ifdef FEAT_PROP_POPUP
3686 if (pwin != NULL)
3687 popup_close_with_retval(pwin, 0);
3688#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003689 return TRUE;
3690 }
3691 if (term->tl_finish == TL_FINISH_OPEN
3692 && term->tl_buffer->b_nwindows == 0)
3693 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003694 char *cmd = term->tl_opencmd == NULL
3695 ? "botright sbuf %d"
3696 : (char *)term->tl_opencmd;
3697 size_t len = strlen(cmd) + 50;
3698 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003699
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003700 if (buf != NULL)
3701 {
3702 ch_log(NULL, "terminal job finished, opening window");
3703 vim_snprintf(buf, len, cmd, fnum);
3704 do_cmdline_cmd((char_u *)buf);
3705 vim_free(buf);
3706 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003707 }
3708 else
3709 ch_log(NULL, "terminal job finished");
3710 }
3711
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003712 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003713 return FALSE;
3714}
3715
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003716#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3717/*
3718 * If the current window is a terminal in a popup window and the job has
3719 * finished, close the popup window and to back to the previous window.
3720 * Otherwise return FAIL.
3721 */
3722 int
3723may_close_term_popup(void)
3724{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003725 if (!popup_is_popup(curwin) || curbuf->b_term == NULL
3726 || term_job_running_not_none(curbuf->b_term))
3727 return FAIL;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003728
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003729 win_T *pwin = curwin;
3730
3731 if (win_valid(prevwin))
3732 win_enter(prevwin, FALSE);
3733 popup_close_with_retval(pwin, 0);
3734 return OK;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003735}
3736#endif
3737
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003738/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003739 * Called when a channel is going to be closed, before invoking the close
3740 * callback.
3741 */
3742 void
3743term_channel_closing(channel_T *ch)
3744{
3745 term_T *term;
3746
3747 for (term = first_term; term != NULL; term = term->tl_next)
3748 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3749 term->tl_channel_closing = TRUE;
3750}
3751
3752/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003753 * Called when a channel has been closed.
3754 * If this was a channel for a terminal window then finish it up.
3755 */
3756 void
3757term_channel_closed(channel_T *ch)
3758{
3759 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003760 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003761 int did_one = FALSE;
3762
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003763 for (term = first_term; term != NULL; term = next_term)
3764 {
3765 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003766 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003767 {
3768 term->tl_channel_closed = TRUE;
3769 did_one = TRUE;
3770
Bram Moolenaard23a8232018-02-10 18:45:26 +01003771 VIM_CLEAR(term->tl_title);
3772 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003773#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003774 if (term->tl_out_fd != NULL)
3775 {
3776 fclose(term->tl_out_fd);
3777 term->tl_out_fd = NULL;
3778 }
3779#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003780
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003781 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003782 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003783 // Cannot open or close windows now. Can happen when
3784 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003785 term->tl_channel_recently_closed = TRUE;
3786 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003787 }
3788
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003789 if (term_after_channel_closed(term))
3790 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003791 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003792 }
3793
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003794 if (did_one)
3795 {
3796 redraw_statuslines();
3797
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003798 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003799 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003800 typebuf_was_filled = TRUE;
3801
3802 term = curbuf->b_term;
3803 if (term != NULL)
3804 {
3805 if (term->tl_job == ch->ch_job)
3806 maketitle();
3807 update_cursor(term, term->tl_cursor_visible);
3808 }
3809 }
3810}
3811
3812/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003813 * To be called after resetting updating_screen: handle any terminal where the
3814 * channel was closed.
3815 */
3816 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003817term_check_channel_closed_recently(void)
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003818{
3819 term_T *term;
3820 term_T *next_term;
3821
3822 for (term = first_term; term != NULL; term = next_term)
3823 {
3824 next_term = term->tl_next;
3825 if (term->tl_channel_recently_closed)
3826 {
3827 term->tl_channel_recently_closed = FALSE;
3828 if (term_after_channel_closed(term))
3829 // start over, the list may have changed
3830 next_term = first_term;
3831 }
3832 }
3833}
3834
3835/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003836 * Fill one screen line from a line of the terminal.
3837 * Advances "pos" to past the last column.
3838 */
3839 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003840term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003841 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003842 win_T *wp,
3843 VTermScreen *screen,
3844 VTermPos *pos,
3845 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003846{
3847 int off = screen_get_current_line_off();
3848
3849 for (pos->col = 0; pos->col < max_col; )
3850 {
3851 VTermScreenCell cell;
3852 int c;
3853
3854 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003855 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003856
3857 c = cell.chars[0];
3858 if (c == NUL)
3859 {
3860 ScreenLines[off] = ' ';
3861 if (enc_utf8)
3862 ScreenLinesUC[off] = NUL;
3863 }
3864 else
3865 {
3866 if (enc_utf8)
3867 {
3868 int i;
3869
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003870 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003871 for (i = 0; i < Screen_mco
3872 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3873 {
3874 ScreenLinesC[i][off] = cell.chars[i + 1];
3875 if (cell.chars[i + 1] == 0)
3876 break;
3877 }
3878 if (c >= 0x80 || (Screen_mco > 0
3879 && ScreenLinesC[0][off] != 0))
3880 {
3881 ScreenLines[off] = ' ';
3882 ScreenLinesUC[off] = c;
3883 }
3884 else
3885 {
3886 ScreenLines[off] = c;
3887 ScreenLinesUC[off] = NUL;
3888 }
3889 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003890#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003891 else if (has_mbyte && c >= 0x80)
3892 {
3893 char_u mb[MB_MAXBYTES+1];
3894 WCHAR wc = c;
3895
3896 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3897 (char*)mb, 2, 0, 0) > 1)
3898 {
3899 ScreenLines[off] = mb[0];
3900 ScreenLines[off + 1] = mb[1];
3901 cell.width = mb_ptr2cells(mb);
3902 }
3903 else
3904 ScreenLines[off] = c;
3905 }
3906#endif
3907 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003908 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003909 ScreenLines[off] = c;
3910 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003911 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3912 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003913
3914 ++pos->col;
3915 ++off;
3916 if (cell.width == 2)
3917 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003918 // don't set the second byte to NUL for a DBCS encoding, it
3919 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003920 if (enc_utf8)
3921 {
3922 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003923 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003924 }
3925 else if (!has_mbyte)
3926 {
3927 // Can't show a double-width character with a single-byte
3928 // 'encoding', just use a space.
3929 ScreenLines[off] = ' ';
3930 ScreenAttrs[off] = ScreenAttrs[off - 1];
3931 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003932
3933 ++pos->col;
3934 ++off;
3935 }
3936 }
3937}
3938
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003939#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003940 static void
3941update_system_term(term_T *term)
3942{
3943 VTermPos pos;
3944 VTermScreen *screen;
3945
3946 if (term->tl_vterm == NULL)
3947 return;
3948 screen = vterm_obtain_screen(term->tl_vterm);
3949
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003950 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003951 while (term->tl_toprow > 0
3952 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3953 {
3954 int save_p_more = p_more;
3955
3956 p_more = FALSE;
3957 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003958 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003959 p_more = save_p_more;
3960 --term->tl_toprow;
3961 }
3962
3963 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3964 && pos.row < Rows; ++pos.row)
3965 {
3966 if (pos.row < term->tl_rows)
3967 {
3968 int max_col = MIN(Columns, term->tl_cols);
3969
Bram Moolenaar83d47902020-03-26 20:34:00 +01003970 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003971 }
3972 else
3973 pos.col = 0;
3974
zeertzjqd0c1b772024-03-16 15:03:33 +01003975 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, -1,
3976 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003977 }
3978
3979 term->tl_dirty_row_start = MAX_ROW;
3980 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003981}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003982#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003983
3984/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003985 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3986 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003987 * Terminal-Normal mode.
3988 */
3989 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003990term_do_update_window(win_T *wp)
3991{
3992 term_T *term = wp->w_buffer->b_term;
3993
3994 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3995}
3996
3997/*
3998 * Called to update a window that contains an active terminal.
3999 */
4000 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004001term_update_window(win_T *wp)
4002{
4003 term_T *term = wp->w_buffer->b_term;
4004 VTerm *vterm;
4005 VTermScreen *screen;
4006 VTermState *state;
4007 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004008 int rows, cols;
4009 int newrows, newcols;
4010 int minsize;
4011 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004012
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004013 vterm = term->tl_vterm;
4014 screen = vterm_obtain_screen(vterm);
4015 state = vterm_obtain_state(vterm);
4016
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004017 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
4018 // With UPD_SOME_VALID only redraw what was marked dirty.
4019 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004020 {
4021 term->tl_dirty_row_start = 0;
4022 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004023
4024 if (term->tl_postponed_scroll > 0
4025 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004026 // Scrolling is usually faster than redrawing, when there are only
4027 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004028 term_scroll_up(term, 0, term->tl_postponed_scroll);
4029 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004030 }
4031
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004032 /*
4033 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004034 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004035 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004036 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004037
Bram Moolenaar498c2562018-04-15 23:45:15 +02004038 newrows = 99999;
4039 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004040 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02004041 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004042 // Always use curwin, it may be a popup window.
4043 win_T *wwp = twp == NULL ? curwin : twp;
4044
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004045 // When more than one window shows the same terminal, use the
4046 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004047 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004048 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004049 newrows = MIN(newrows, wwp->w_height);
4050 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004051 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004052 if (twp == NULL)
4053 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004054 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02004055 if (newrows == 99999 || newcols == 99999)
4056 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02004057 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
4058 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
4059
Bram Moolenaareba13e42021-02-23 17:47:23 +01004060 // If no cell is visible there is no point in resizing. Also, vterm can't
4061 // handle a zero height.
4062 if (newrows == 0 || newcols == 0)
4063 return;
4064
Bram Moolenaar498c2562018-04-15 23:45:15 +02004065 if (term->tl_rows != newrows || term->tl_cols != newcols)
4066 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004067 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004068 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004069 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02004070 newrows);
4071 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02004072
4073 // Updating the terminal size will cause the snapshot to be cleared.
4074 // When not in terminal_loop() we need to restore it.
4075 if (term != in_terminal_loop)
4076 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004077 }
4078
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004079 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004080 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01004081 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004082
Bram Moolenaar3a497e12017-09-30 20:40:27 +02004083 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
4084 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004085 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004086 if (pos.row < term->tl_rows)
4087 {
Bram Moolenaar13568252018-03-16 20:46:58 +01004088 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004089
Bram Moolenaar83d47902020-03-26 20:34:00 +01004090 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004091 }
4092 else
4093 pos.col = 0;
4094
Bram Moolenaar510f0372022-07-04 17:46:22 +01004095 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01004096#ifdef FEAT_MENU
4097 + winbar_height(wp)
4098#endif
zeertzjqd0c1b772024-03-16 15:03:33 +01004099 , wp->w_wincol, pos.col, wp->w_width, -1,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004100#ifdef FEAT_PROP_POPUP
4101 popup_is_popup(wp) ? SLF_POPUP :
4102#endif
4103 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004104 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00004105}
4106
4107/*
4108 * Called after updating all windows: may reset dirty rows.
4109 */
4110 void
4111term_did_update_window(win_T *wp)
4112{
4113 term_T *term = wp->w_buffer->b_term;
4114
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004115 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode
4116 || wp->w_redr_type != 0)
4117 return;
4118
4119 term->tl_dirty_row_start = MAX_ROW;
4120 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004121}
4122
4123/*
4124 * Return TRUE if "wp" is a terminal window where the job has finished.
4125 */
4126 int
4127term_is_finished(buf_T *buf)
4128{
4129 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
4130}
4131
4132/*
4133 * Return TRUE if "wp" is a terminal window where the job has finished or we
4134 * are in Terminal-Normal mode, thus we show the buffer contents.
4135 */
4136 int
4137term_show_buffer(buf_T *buf)
4138{
4139 term_T *term = buf->b_term;
4140
4141 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4142}
4143
4144/*
4145 * The current buffer is going to be changed. If there is terminal
4146 * highlighting remove it now.
4147 */
4148 void
4149term_change_in_curbuf(void)
4150{
4151 term_T *term = curbuf->b_term;
4152
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004153 if (!term_is_finished(curbuf) || term->tl_scrollback.ga_len <= 0)
4154 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004155
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004156 free_scrollback(term);
4157 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
4158
4159 // The buffer is now like a normal buffer, it cannot be easily
4160 // abandoned when changed.
4161 set_string_option_direct((char_u *)"buftype", -1,
4162 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004163}
4164
4165/*
4166 * Get the screen attribute for a position in the buffer.
4167 * Use a negative "col" to get the filler background color.
4168 */
4169 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004170term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004171{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004172 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004173 term_T *term = buf->b_term;
4174 sb_line_T *line;
4175 cellattr_T *cellattr;
4176
4177 if (lnum > term->tl_scrollback.ga_len)
4178 cellattr = &term->tl_default_color;
4179 else
4180 {
4181 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4182 if (col < 0 || col >= line->sb_cols)
4183 cellattr = &line->sb_fill_attr;
4184 else
4185 cellattr = line->sb_cells + col;
4186 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004187 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004188}
4189
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004190/*
4191 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004192 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004193 */
4194 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004195cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004196{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004197 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4198 if (rgb->index == 0)
4199 rgb->type = VTERM_COLOR_RGB;
4200 else
4201 {
4202 rgb->type = VTERM_COLOR_INDEXED;
4203 --rgb->index;
4204 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004205}
4206
4207/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004208 * Initialize vterm color from the synID.
4209 * Returns TRUE if color is set to "fg" and "bg".
4210 * Otherwise returns FALSE.
4211 */
4212 static int
4213get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4214{
4215#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4216 // Use the actual color for the GUI and when 'termguicolors' is set.
4217 if (0
4218# ifdef FEAT_GUI
4219 || gui.in_use
4220# endif
4221# ifdef FEAT_TERMGUICOLORS
4222 || p_tgc
4223# ifdef FEAT_VTP
4224 // Finally get INVALCOLOR on this execution path
4225 || (!p_tgc && t_colors >= 256)
4226# endif
4227# endif
4228 )
4229 {
4230 guicolor_T fg_rgb = INVALCOLOR;
4231 guicolor_T bg_rgb = INVALCOLOR;
4232
4233 if (id > 0)
4234 syn_id2colors(id, &fg_rgb, &bg_rgb);
4235
4236 if (fg_rgb != INVALCOLOR)
4237 {
4238 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4239 fg->red = (unsigned)(rgb >> 16);
4240 fg->green = (unsigned)(rgb >> 8) & 255;
4241 fg->blue = (unsigned)rgb & 255;
4242 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4243 }
4244 else
4245 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4246
4247 if (bg_rgb != INVALCOLOR)
4248 {
4249 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4250 bg->red = (unsigned)(rgb >> 16);
4251 bg->green = (unsigned)(rgb >> 8) & 255;
4252 bg->blue = (unsigned)rgb & 255;
4253 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4254 }
4255 else
4256 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4257
4258 return TRUE;
4259 }
4260 else
4261#endif
4262 if (t_colors >= 16)
4263 {
4264 int cterm_fg = -1;
4265 int cterm_bg = -1;
4266
4267 if (id > 0)
4268 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4269
4270 if (cterm_fg >= 0)
4271 {
4272 cterm_color2vterm(cterm_fg, fg);
4273 fg->type |= VTERM_COLOR_DEFAULT_FG;
4274 }
4275 else
4276 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4277
4278 if (cterm_bg >= 0)
4279 {
4280 cterm_color2vterm(cterm_bg, bg);
4281 bg->type |= VTERM_COLOR_DEFAULT_BG;
4282 }
4283 else
4284 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4285
4286 return TRUE;
4287 }
4288
4289 return FALSE;
4290}
4291
4292 void
4293term_reset_wincolor(win_T *wp)
4294{
4295 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4296 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4297}
4298
4299/*
4300 * Cache the color of 'wincolor'.
4301 */
4302 void
4303term_update_wincolor(win_T *wp)
4304{
4305 int id = 0;
4306
4307 if (*wp->w_p_wcr != NUL)
4308 id = syn_name2id(wp->w_p_wcr);
4309 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4310 &wp->w_term_wincolor.bg))
4311 term_reset_wincolor(wp);
4312}
4313
4314/*
4315 * Called when option 'termguicolors' was set,
4316 * or when any highlight is changed.
4317 */
4318 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004319term_update_wincolor_all(void)
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004320{
4321 win_T *wp = NULL;
4322 int did_curwin = FALSE;
4323
4324 while (for_all_windows_and_curwin(&wp, &did_curwin))
4325 term_update_wincolor(wp);
4326}
4327
4328/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004329 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004330 */
4331 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004332init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004333{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004334 VTermColor *fg, *bg;
4335 int fgval, bgval;
4336 int id;
4337
Bram Moolenaara80faa82020-04-12 19:37:17 +02004338 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004339 term->tl_default_color.width = 1;
4340 fg = &term->tl_default_color.fg;
4341 bg = &term->tl_default_color.bg;
4342
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004343 // Vterm uses a default black background. Set it to white when
4344 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004345 if (*p_bg == 'l')
4346 {
4347 fgval = 0;
4348 bgval = 255;
4349 }
4350 else
4351 {
4352 fgval = 255;
4353 bgval = 0;
4354 }
4355 fg->red = fg->green = fg->blue = fgval;
4356 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004357 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4358 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004359
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004360 // The highlight group overrules the defaults.
4361 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004362
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004363 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004364 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004365#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004366 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004367#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004368
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004369 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004370 if (cterm_normal_fg_color > 0)
4371 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004372 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004373# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4374# ifdef VIMDLL
4375 if (!gui.in_use)
4376# endif
4377 {
4378 tmp = fg->red;
4379 fg->red = fg->blue;
4380 fg->blue = tmp;
4381 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004382# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004383 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004384# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004385 else
4386 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004387# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004388
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004389 if (cterm_normal_bg_color > 0)
4390 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004391 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004392# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4393# ifdef VIMDLL
4394 if (!gui.in_use)
4395# endif
4396 {
4397 tmp = fg->red;
4398 fg->red = fg->blue;
4399 fg->blue = tmp;
4400 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004401# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004402 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004403# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004404 else
4405 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004406# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004407 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004408}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004409
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004410#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4411/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004412 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4413 * "ansi_colors" argument in term_start()) shall be applied.
4414 */
4415 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004416term_use_palette(void)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004417{
4418 if (0
4419#ifdef FEAT_GUI
4420 || gui.in_use
4421#endif
4422#ifdef FEAT_TERMGUICOLORS
4423 || p_tgc
4424#endif
4425 )
4426 return TRUE;
4427 return FALSE;
4428}
4429
4430/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004431 * Set the 16 ANSI colors from array of RGB values
4432 */
4433 static void
4434set_vterm_palette(VTerm *vterm, long_u *rgb)
4435{
4436 int index = 0;
4437 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004438
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004439 for (; index < 16; index++)
4440 {
4441 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004442
Millyb771b6b2021-11-23 12:07:25 +00004443 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004444 color.red = (unsigned)(rgb[index] >> 16);
4445 color.green = (unsigned)(rgb[index] >> 8) & 255;
4446 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004447 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004448 vterm_state_set_palette_color(state, index, &color);
4449 }
4450}
4451
4452/*
4453 * Set the ANSI color palette from a list of colors
4454 */
4455 static int
4456set_ansi_colors_list(VTerm *vterm, list_T *list)
4457{
4458 int n = 0;
4459 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004460 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004461
Bram Moolenaarb0992022020-01-30 14:55:42 +01004462 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004463 {
4464 char_u *color_name;
4465 guicolor_T guicolor;
4466
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004467 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004468 if (color_name == NULL)
4469 return FAIL;
4470
4471 guicolor = GUI_GET_COLOR(color_name);
4472 if (guicolor == INVALCOLOR)
4473 return FAIL;
4474
4475 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4476 }
4477
4478 if (n != 16 || li != NULL)
4479 return FAIL;
4480
4481 set_vterm_palette(vterm, rgb);
4482
4483 return OK;
4484}
4485
4486/*
4487 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4488 */
4489 static void
4490init_vterm_ansi_colors(VTerm *vterm)
4491{
4492 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4493
LemonBoyb2b3acb2022-05-20 10:10:34 +01004494 if (var == NULL)
4495 return;
4496
4497 if (var->di_tv.v_type != VAR_LIST
4498 || var->di_tv.vval.v_list == NULL
4499 || var->di_tv.vval.v_list->lv_first == &range_list_item
4500 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004501 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004502}
4503#endif
4504
Bram Moolenaar52acb112018-03-18 19:20:22 +01004505/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004506 * Handles a "drop" command from the job in the terminal.
4507 * "item" is the file name, "item->li_next" may have options.
4508 */
4509 static void
4510handle_drop_command(listitem_T *item)
4511{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004512 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004513 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004514 int bufnr;
4515 win_T *wp;
4516 tabpage_T *tp;
4517 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004518 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004519
4520 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4521 FOR_ALL_TAB_WINDOWS(tp, wp)
4522 {
4523 if (wp->w_buffer->b_fnum == bufnr)
4524 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004525 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004526 goto_tabpage_win(tp, wp);
4527 return;
4528 }
4529 }
4530
Bram Moolenaara80faa82020-04-12 19:37:17 +02004531 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004532
4533 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4534 && opt_item->li_tv.vval.v_dict != NULL)
4535 {
4536 dict_T *dict = opt_item->li_tv.vval.v_dict;
4537 char_u *p;
4538
Bram Moolenaard61efa52022-07-23 09:52:04 +01004539 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004540 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004541 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004542 if (p != NULL)
4543 {
4544 if (check_ff_value(p) == FAIL)
4545 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4546 else
4547 ea.force_ff = *p;
4548 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004549 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004550 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004551 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004552 if (p != NULL)
4553 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004554 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004555 if (ea.cmd != NULL)
4556 {
4557 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4558 ea.force_enc = 11;
4559 tofree = ea.cmd;
4560 }
4561 }
4562
Bram Moolenaard61efa52022-07-23 09:52:04 +01004563 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004564 if (p != NULL)
4565 get_bad_opt(p, &ea);
4566
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004567 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004568 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004569 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004570 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004571 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004572 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004573 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004574 ea.force_bin = FORCE_NOBIN;
4575 }
4576
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004577 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004578 if (ea.cmd == NULL)
4579 ea.cmd = (char_u *)"split";
4580 ea.arg = fname;
4581 ea.cmdidx = CMD_split;
4582 ex_splitview(&ea);
4583
4584 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004585}
4586
4587/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004588 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4589 */
4590 static int
4591is_permitted_term_api(char_u *func, char_u *pat)
4592{
4593 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4594}
4595
4596/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004597 * Handles a function call from the job running in a terminal.
4598 * "item" is the function name, "item->li_next" has the arguments.
4599 */
4600 static void
4601handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4602{
4603 char_u *func;
4604 typval_T argvars[2];
4605 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004606 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004607
4608 if (item->li_next == NULL)
4609 {
4610 ch_log(channel, "Missing function arguments for call");
4611 return;
4612 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004613 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004614
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004615 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004616 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004617 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004618 return;
4619 }
4620
4621 argvars[0].v_type = VAR_NUMBER;
4622 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4623 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004624 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004625 funcexe.fe_firstline = 1L;
4626 funcexe.fe_lastline = 1L;
4627 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004628 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004629 {
4630 clear_tv(&rettv);
4631 ch_log(channel, "Function %s called", func);
4632 }
4633 else
4634 ch_log(channel, "Calling function %s failed", func);
4635}
4636
4637/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004638 * URL decoding (also know as Percent-encoding).
4639 *
4640 * Note this function currently is only used for decoding shell's
4641 * OSC 7 escape sequence which we can assume all bytes are valid
4642 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4643 * encoding bytes like 0xfe, 0xff.
4644 */
4645 static size_t
4646url_decode(const char *src, const size_t len, char_u *dst)
4647{
4648 size_t i = 0, j = 0;
4649
4650 while (i < len)
4651 {
4652 if (src[i] == '%' && i + 2 < len)
4653 {
4654 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4655 j++;
4656 i += 3;
4657 }
4658 else
4659 {
4660 dst[j] = src[i];
4661 i++;
4662 j++;
4663 }
4664 }
4665 dst[j] = '\0';
4666 return j;
4667}
4668
4669/*
4670 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4671 *
4672 * The OSC 7 sequence has the format of
4673 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4674 * and what VTerm provides via VTermStringFragment is
4675 * "file://HOSTNAME/CURRENT/DIR"
4676 */
4677 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004678sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004679{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004680 int offset = 7; // len of "file://" is 7
4681 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004682 char_u *new_dir;
4683
4684 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004685 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004686 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004687 ++offset;
4688 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004689 }
4690
Bram Moolenaar474ad392022-08-21 11:37:17 +01004691 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004692 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004693 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004694 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004695 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004696 }
4697
Bram Moolenaar474ad392022-08-21 11:37:17 +01004698 new_dir = alloc(gap->ga_len - offset + 1);
4699 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004700 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4701 vim_free(new_dir);
4702}
4703
4704/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004705 * Called by libvterm when it cannot recognize an OSC sequence.
4706 * We recognize a terminal API command.
4707 */
4708 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004709parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004710{
4711 term_T *term = (term_T *)user;
4712 js_read_T reader;
4713 typval_T tv;
4714 channel_T *channel = term->tl_job == NULL ? NULL
4715 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004716 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004717
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004718 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004719 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004720 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004721
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004722 // Concatenate what was received until the final piece is found.
4723 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4724 {
4725 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004726 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004727 }
4728 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004729 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004730 if (!frag.final)
4731 return 1;
4732
4733 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004734
4735 if (command == 7)
4736 {
4737 sync_shell_dir(gap);
4738 ga_clear(gap);
4739 return 1;
4740 }
4741
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004742 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004743 reader.js_fill = NULL;
4744 reader.js_used = 0;
4745 if (json_decode(&reader, &tv, 0) == OK
4746 && tv.v_type == VAR_LIST
4747 && tv.vval.v_list != NULL)
4748 {
4749 listitem_T *item = tv.vval.v_list->lv_first;
4750
4751 if (item == NULL)
4752 ch_log(channel, "Missing command");
4753 else
4754 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004755 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004756
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004757 // Make sure an invoked command doesn't delete the buffer (and the
4758 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004759 ++term->tl_buffer->b_locked;
4760
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004761 item = item->li_next;
4762 if (item == NULL)
4763 ch_log(channel, "Missing argument for %s", cmd);
4764 else if (STRCMP(cmd, "drop") == 0)
4765 handle_drop_command(item);
4766 else if (STRCMP(cmd, "call") == 0)
4767 handle_call_command(term, channel, item);
4768 else
4769 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004770 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004771 }
4772 }
4773 else
4774 ch_log(channel, "Invalid JSON received");
4775
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004776 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004777 clear_tv(&tv);
4778 return 1;
4779}
4780
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004781/*
4782 * Called by libvterm when it cannot recognize a CSI sequence.
4783 * We recognize the window position report.
4784 */
4785 static int
4786parse_csi(
4787 const char *leader UNUSED,
4788 const long args[],
4789 int argcount,
4790 const char *intermed UNUSED,
4791 char command,
4792 void *user)
4793{
4794 term_T *term = (term_T *)user;
4795 char buf[100];
4796 int len;
4797 int x = 0;
4798 int y = 0;
4799 win_T *wp;
4800
4801 // We recognize only CSI 13 t
4802 if (command != 't' || argcount != 1 || args[0] != 13)
4803 return 0; // not handled
4804
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004805 // When getting the window position is not possible or it fails it results
4806 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004807#if defined(FEAT_GUI) \
4808 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4809 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004810 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004811#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004812
4813 FOR_ALL_WINDOWS(wp)
4814 if (wp->w_buffer == term->tl_buffer)
4815 break;
4816 if (wp != NULL)
4817 {
4818#ifdef FEAT_GUI
4819 if (gui.in_use)
4820 {
4821 x += wp->w_wincol * gui.char_width;
4822 y += W_WINROW(wp) * gui.char_height;
4823 }
4824 else
4825#endif
4826 {
4827 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004828 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004829 x += wp->w_wincol * 7;
4830 y += W_WINROW(wp) * 10;
4831 }
4832 }
4833
4834 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4835 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4836 (char_u *)buf, len, NULL);
4837 return 1;
4838}
4839
Bram Moolenaard8637282020-05-20 18:41:41 +02004840static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004841 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004842 parse_csi, // csi
4843 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004844 NULL, // dcs
4845 NULL, // apc
4846 NULL, // pm
4847 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004848};
4849
4850/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004851 * Use Vim's allocation functions for vterm so profiling works.
4852 */
4853 static void *
4854vterm_malloc(size_t size, void *data UNUSED)
4855{
Bram Moolenaar88137392021-11-12 16:01:15 +00004856 // make sure that the length is not zero
4857 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004858}
4859
4860 static void
4861vterm_memfree(void *ptr, void *data UNUSED)
4862{
4863 vim_free(ptr);
4864}
4865
4866static VTermAllocatorFunctions vterm_allocator = {
4867 &vterm_malloc,
4868 &vterm_memfree
4869};
4870
4871/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004872 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004873 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004874 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004875 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004876create_vterm(term_T *term, int rows, int cols)
4877{
4878 VTerm *vterm;
4879 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004880 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004881 VTermValue value;
4882
Bram Moolenaar756ef112018-04-10 12:04:27 +02004883 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004884 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004885 if (vterm == NULL)
4886 return FAIL;
4887
4888 // Allocate screen and state here, so we can bail out if that fails.
4889 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004890 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004891 if (state == NULL || screen == NULL)
4892 {
4893 vterm_free(vterm);
4894 return FAIL;
4895 }
4896
Bram Moolenaar52acb112018-03-18 19:20:22 +01004897 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004898 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004899 vterm_set_utf8(vterm, 1);
4900
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004901 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004902
4903 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004904 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004905 &term->tl_default_color.fg,
4906 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004907
Bram Moolenaar9e587872019-05-13 20:27:23 +02004908 if (t_colors < 16)
4909 // Less than 16 colors: assume that bold means using a bright color for
4910 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004911 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4912
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004913 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004914 vterm_screen_reset(screen, 1 /* hard */);
4915
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004916 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004917 vterm_screen_enable_altscreen(screen, 1);
4918
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004919 // For unix do not use a blinking cursor. In an xterm this causes the
4920 // cursor to blink if it's blinking in the xterm.
4921 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004922#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004923 if (GetCaretBlinkTime() == INFINITE)
4924 value.boolean = 0;
4925 else
4926 value.boolean = 1;
4927#else
4928 value.boolean = 0;
4929#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004930 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004931 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004932
4933 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004934}
4935
4936/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004937 * Reset the terminal palette to its default value.
4938 */
4939 static void
4940term_reset_palette(VTerm *vterm)
4941{
4942 VTermState *state = vterm_obtain_state(vterm);
4943 int index;
4944
4945 for (index = 0; index < 16; index++)
4946 {
4947 VTermColor color;
4948
4949 color.type = VTERM_COLOR_INDEXED;
4950 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4951 &color.index);
4952 // The first valid index starts at 1.
4953 color.index -= 1;
4954
4955 vterm_state_set_palette_color(state, index, &color);
4956 }
4957}
4958
4959 static void
4960term_update_palette(term_T *term)
4961{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004962#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004963 if (term_use_palette()
4964 && (term->tl_palette != NULL
4965 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004966 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004967 {
4968 if (term->tl_palette != NULL)
4969 set_vterm_palette(term->tl_vterm, term->tl_palette);
4970 else
4971 init_vterm_ansi_colors(term->tl_vterm);
4972 }
4973 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004974#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004975 term_reset_palette(term->tl_vterm);
4976}
4977
4978/*
4979 * Called when option 'termguicolors' is changed.
4980 */
4981 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004982term_update_palette_all(void)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004983{
4984 term_T *term;
4985
4986 FOR_ALL_TERMS(term)
4987 {
4988 if (term->tl_vterm == NULL)
4989 continue;
4990 term_update_palette(term);
4991 }
4992}
4993
4994/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004995 * Called when option 'background' or 'termguicolors' was set,
4996 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02004997 */
4998 void
4999term_update_colors_all(void)
5000{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005001 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02005002
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005003 FOR_ALL_TERMS(term)
5004 {
5005 if (term->tl_vterm == NULL)
5006 continue;
5007 init_default_colors(term);
5008 vterm_state_set_default_colors(
5009 vterm_obtain_state(term->tl_vterm),
5010 &term->tl_default_color.fg,
5011 &term->tl_default_color.bg);
5012 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005013}
5014
5015/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005016 * Return the text to show for the buffer name and status.
5017 */
5018 char_u *
5019term_get_status_text(term_T *term)
5020{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005021 if (term->tl_status_text != NULL)
5022 return term->tl_status_text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005023
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005024 char_u *txt;
5025 size_t len;
5026 char_u *fname;
5027
5028 if (term->tl_normal_mode)
5029 {
5030 if (term_job_running(term))
5031 txt = (char_u *)_("Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005032 else
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005033 txt = (char_u *)_("Terminal-finished");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005034 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005035 else if (term->tl_title != NULL)
5036 txt = term->tl_title;
5037 else if (term_none_open(term))
5038 txt = (char_u *)_("active");
5039 else if (term_job_running(term))
5040 txt = (char_u *)_("running");
5041 else
5042 txt = (char_u *)_("finished");
5043 fname = buf_get_fname(term->tl_buffer);
5044 len = 9 + STRLEN(fname) + STRLEN(txt);
5045 term->tl_status_text = alloc(len);
5046 if (term->tl_status_text != NULL)
5047 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
5048 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005049 return term->tl_status_text;
5050}
5051
5052/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00005053 * Clear the cached value of the status text.
5054 */
5055 void
5056term_clear_status_text(term_T *term)
5057{
5058 VIM_CLEAR(term->tl_status_text);
5059}
5060
5061/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005062 * Mark references in jobs of terminals.
5063 */
5064 int
5065set_ref_in_term(int copyID)
5066{
5067 int abort = FALSE;
5068 term_T *term;
5069 typval_T tv;
5070
Bram Moolenaar75a1a942019-06-20 03:45:36 +02005071 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005072 if (term->tl_job != NULL)
5073 {
5074 tv.v_type = VAR_JOB;
5075 tv.vval.v_job = term->tl_job;
5076 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
5077 }
5078 return abort;
5079}
5080
5081/*
5082 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005083 * Returns NULL when the buffer is not for a terminal window and logs a message
5084 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005085 */
5086 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005087term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005088{
5089 buf_T *buf;
5090
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005091 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01005092 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005093 --emsg_off;
5094 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005095 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01005096 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005097 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005098 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005099 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005100 return buf;
5101}
5102
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005103 static void
5104clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005105{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005106 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005107 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
5108 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005109}
5110
5111 static void
5112dump_term_color(FILE *fd, VTermColor *color)
5113{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005114 int index;
5115
5116 if (VTERM_COLOR_IS_INDEXED(color))
5117 index = color->index + 1;
5118 else if (color->type == 0)
5119 // use RGB values
5120 index = 255;
5121 else
5122 // default color
5123 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005124 fprintf(fd, "%02x%02x%02x%d",
5125 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005126 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005127}
5128
5129/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005130 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01005131 *
5132 * Each screen cell in full is:
5133 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5134 * {characters} is a space for an empty cell
5135 * For a double-width character "+" is changed to "*" and the next cell is
5136 * skipped.
5137 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5138 * when "&" use the same as the previous cell.
5139 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5140 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5141 * {color-idx} is a number from 0 to 255
5142 *
5143 * Screen cell with same width, attributes and color as the previous one:
5144 * |{characters}
5145 *
5146 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5147 *
5148 * Repeating the previous screen cell:
5149 * @{count}
5150 */
5151 void
5152f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5153{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005154 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005155 term_T *term;
5156 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005157 int max_height = 0;
5158 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005159 stat_T st;
5160 FILE *fd;
5161 VTermPos pos;
5162 VTermScreen *screen;
5163 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005164 VTermState *state;
5165 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005166
5167 if (check_restricted() || check_secure())
5168 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005169
5170 if (in_vim9script()
5171 && (check_for_buffer_arg(argvars, 0) == FAIL
5172 || check_for_string_arg(argvars, 1) == FAIL
5173 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5174 return;
5175
5176 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005177 if (buf == NULL)
5178 return;
5179 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005180 if (term->tl_vterm == NULL)
5181 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005182 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005183 return;
5184 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005185
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005186 if (argvars[2].v_type != VAR_UNKNOWN)
5187 {
5188 dict_T *d;
5189
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005190 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005191 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005192 d = argvars[2].vval.v_dict;
5193 if (d != NULL)
5194 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005195 max_height = dict_get_number(d, "rows");
5196 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005197 }
5198 }
5199
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005200 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005201 if (fname == NULL)
5202 return;
5203 if (mch_stat((char *)fname, &st) >= 0)
5204 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005205 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005206 return;
5207 }
5208
Bram Moolenaard96ff162018-02-18 22:13:29 +01005209 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5210 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005211 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005212 return;
5213 }
5214
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005215 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005216
5217 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005218 state = vterm_obtain_state(term->tl_vterm);
5219 vterm_state_get_cursorpos(state, &cursor_pos);
5220
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005221 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5222 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005223 {
5224 int repeat = 0;
5225
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005226 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5227 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005228 {
5229 VTermScreenCell cell;
5230 int same_attr;
5231 int same_chars = TRUE;
5232 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005233 int is_cursor_pos = (pos.col == cursor_pos.col
5234 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005235
5236 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005237 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005238
5239 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5240 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005241 int c = cell.chars[i];
5242 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005243 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005244
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005245 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005246 if (i == 0)
5247 {
5248 c = (c == NUL) ? ' ' : c;
5249 pc = (pc == NUL) ? ' ' : pc;
5250 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005251 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005252 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005253 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005254 break;
5255 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005256 same_attr = vtermAttr2hl(&cell.attrs)
5257 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005258 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5259 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005260 if (same_chars && cell.width == prev_cell.width && same_attr
5261 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005262 {
5263 ++repeat;
5264 }
5265 else
5266 {
5267 if (repeat > 0)
5268 {
5269 fprintf(fd, "@%d", repeat);
5270 repeat = 0;
5271 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005272 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005273
5274 if (cell.chars[0] == NUL)
5275 fputs(" ", fd);
5276 else
5277 {
5278 char_u charbuf[10];
5279 int len;
5280
5281 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5282 && cell.chars[i] != NUL; ++i)
5283 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005284 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005285 fwrite(charbuf, len, 1, fd);
5286 }
5287 }
5288
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005289 // When only the characters differ we don't write anything, the
5290 // following "|", "@" or NL will indicate using the same
5291 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005292 if (cell.width != prev_cell.width || !same_attr)
5293 {
5294 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005295 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005296 else
5297 fputs("+", fd);
5298
5299 if (same_attr)
5300 {
5301 fputs("&", fd);
5302 }
5303 else
5304 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005305 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005306 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005307 fputs("&", fd);
5308 else
5309 {
5310 fputs("#", fd);
5311 dump_term_color(fd, &cell.fg);
5312 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005313 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005314 fputs("&", fd);
5315 else
5316 {
5317 fputs("#", fd);
5318 dump_term_color(fd, &cell.bg);
5319 }
5320 }
5321 }
5322
5323 prev_cell = cell;
5324 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005325
5326 if (cell.width == 2)
5327 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005328 }
5329 if (repeat > 0)
5330 fprintf(fd, "@%d", repeat);
5331 fputs("\n", fd);
5332 }
5333
5334 fclose(fd);
5335}
5336
5337/*
5338 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5339 */
5340 static void
5341dump_is_corrupt(garray_T *gap)
5342{
5343 ga_concat(gap, (char_u *)"CORRUPT");
5344}
5345
5346 static void
5347append_cell(garray_T *gap, cellattr_T *cell)
5348{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005349 if (ga_grow(gap, 1) == FAIL)
5350 return;
5351
5352 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5353 ++gap->ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005354}
5355
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005356 static void
5357clear_cellattr(cellattr_T *cell)
5358{
5359 CLEAR_FIELD(*cell);
5360 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5361 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5362}
5363
Bram Moolenaard96ff162018-02-18 22:13:29 +01005364/*
5365 * Read the dump file from "fd" and append lines to the current buffer.
5366 * Return the cell width of the longest line.
5367 */
5368 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005369read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005370{
5371 int c;
5372 garray_T ga_text;
5373 garray_T ga_cell;
5374 char_u *prev_char = NULL;
5375 int attr = 0;
5376 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005377 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005378 term_T *term = curbuf->b_term;
5379 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005380 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005381
5382 ga_init2(&ga_text, 1, 90);
5383 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005384 clear_cellattr(&cell);
5385 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005386 cursor_pos->row = -1;
5387 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005388
5389 c = fgetc(fd);
5390 for (;;)
5391 {
5392 if (c == EOF)
5393 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005394 if (c == '\r')
5395 {
5396 // DOS line endings? Ignore.
5397 c = fgetc(fd);
5398 }
5399 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005400 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005401 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005402 if (ga_text.ga_data == NULL)
5403 dump_is_corrupt(&ga_text);
5404 if (ga_grow(&term->tl_scrollback, 1) == OK)
5405 {
5406 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5407 + term->tl_scrollback.ga_len;
5408
5409 if (max_cells < ga_cell.ga_len)
5410 max_cells = ga_cell.ga_len;
5411 line->sb_cols = ga_cell.ga_len;
5412 line->sb_cells = ga_cell.ga_data;
5413 line->sb_fill_attr = term->tl_default_color;
5414 ++term->tl_scrollback.ga_len;
5415 ga_init(&ga_cell);
5416
5417 ga_append(&ga_text, NUL);
5418 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5419 ga_text.ga_len, FALSE);
5420 }
5421 else
5422 ga_clear(&ga_cell);
5423 ga_text.ga_len = 0;
5424
5425 c = fgetc(fd);
5426 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005427 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005428 {
5429 int prev_len = ga_text.ga_len;
5430
Bram Moolenaar9271d052018-02-25 21:39:46 +01005431 if (c == '>')
5432 {
5433 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005434 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005435 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5436 cursor_pos->col = ga_cell.ga_len;
5437 }
5438
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005439 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005440 c = fgetc(fd);
5441 if (c != EOF)
5442 ga_append(&ga_text, c);
5443 for (;;)
5444 {
5445 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005446 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005447 || c == EOF || c == '\n')
5448 break;
5449 ga_append(&ga_text, c);
5450 }
5451
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005452 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005453 vim_free(prev_char);
5454 if (ga_text.ga_data != NULL)
5455 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5456 ga_text.ga_len - prev_len);
5457
Bram Moolenaar9271d052018-02-25 21:39:46 +01005458 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005459 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005460 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005461 }
5462 else if (c == '+' || c == '*')
5463 {
5464 int is_bg;
5465
5466 cell.width = c == '+' ? 1 : 2;
5467
5468 c = fgetc(fd);
5469 if (c == '&')
5470 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005471 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005472 c = fgetc(fd);
5473 }
Keith Thompson184f71c2024-01-04 21:19:04 +01005474 else if (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005475 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005476 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005477 attr = 0;
Keith Thompson184f71c2024-01-04 21:19:04 +01005478 while (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005479 {
5480 attr = attr * 10 + (c - '0');
5481 c = fgetc(fd);
5482 }
5483 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005484
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005485 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005486 for (is_bg = 0; is_bg <= 1; ++is_bg)
5487 {
5488 if (c == '&')
5489 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005490 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005491 c = fgetc(fd);
5492 }
5493 else if (c == '#')
5494 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005495 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005496
5497 c = fgetc(fd);
5498 red = hex2nr(c);
5499 c = fgetc(fd);
5500 red = (red << 4) + hex2nr(c);
5501 c = fgetc(fd);
5502 green = hex2nr(c);
5503 c = fgetc(fd);
5504 green = (green << 4) + hex2nr(c);
5505 c = fgetc(fd);
5506 blue = hex2nr(c);
5507 c = fgetc(fd);
5508 blue = (blue << 4) + hex2nr(c);
5509 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005510 if (!SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005511 dump_is_corrupt(&ga_text);
Keith Thompson184f71c2024-01-04 21:19:04 +01005512 while (SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005513 {
5514 index = index * 10 + (c - '0');
5515 c = fgetc(fd);
5516 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005517 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005518 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005519 type = VTERM_COLOR_RGB;
5520 if (index == 0)
5521 {
5522 if (is_bg)
5523 type |= VTERM_COLOR_DEFAULT_BG;
5524 else
5525 type |= VTERM_COLOR_DEFAULT_FG;
5526 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005527 }
5528 else
5529 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005530 type = VTERM_COLOR_INDEXED;
5531 index -= 1;
5532 }
5533 if (is_bg)
5534 {
5535 cell.bg.type = type;
5536 cell.bg.red = red;
5537 cell.bg.green = green;
5538 cell.bg.blue = blue;
5539 cell.bg.index = index;
5540 }
5541 else
5542 {
5543 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005544 cell.fg.red = red;
5545 cell.fg.green = green;
5546 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005547 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005548 }
5549 }
5550 else
5551 dump_is_corrupt(&ga_text);
5552 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005553 }
5554 else
5555 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005556 }
5557 else
5558 dump_is_corrupt(&ga_text);
5559
5560 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005561 if (cell.width == 2)
5562 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005563 }
5564 else if (c == '@')
5565 {
5566 if (prev_char == NULL)
5567 dump_is_corrupt(&ga_text);
5568 else
5569 {
5570 int count = 0;
5571
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005572 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005573 for (;;)
5574 {
5575 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005576 if (!SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005577 break;
5578 count = count * 10 + (c - '0');
5579 }
5580
5581 while (count-- > 0)
5582 {
5583 ga_concat(&ga_text, prev_char);
5584 append_cell(&ga_cell, &cell);
5585 }
5586 }
5587 }
5588 else
5589 {
5590 dump_is_corrupt(&ga_text);
5591 c = fgetc(fd);
5592 }
5593 }
5594
5595 if (ga_text.ga_len > 0)
5596 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005597 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005598 dump_is_corrupt(&ga_text);
5599 ga_append(&ga_text, NUL);
5600 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5601 ga_text.ga_len, FALSE);
5602 }
5603
5604 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005605 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005606 vim_free(prev_char);
5607
5608 return max_cells;
5609}
5610
5611/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005612 * Return an allocated string with at least "text_width" "=" characters and
5613 * "fname" inserted in the middle.
5614 */
5615 static char_u *
5616get_separator(int text_width, char_u *fname)
5617{
5618 int width = MAX(text_width, curwin->w_width);
5619 char_u *textline;
5620 int fname_size;
5621 char_u *p = fname;
5622 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005623 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005624
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005625 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005626 if (textline == NULL)
5627 return NULL;
5628
5629 fname_size = vim_strsize(fname);
5630 if (fname_size < width - 8)
5631 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005632 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005633 width = MAX(text_width, fname_size + 8);
5634 }
5635 else if (fname_size > width - 8)
5636 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005637 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005638 p = gettail(fname);
5639 fname_size = vim_strsize(p);
5640 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005641 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005642 while (fname_size > width - 8)
5643 {
5644 p += (*mb_ptr2len)(p);
5645 fname_size = vim_strsize(p);
5646 }
5647
5648 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5649 textline[i] = '=';
5650 textline[i++] = ' ';
5651
5652 STRCPY(textline + i, p);
5653 off = STRLEN(textline);
5654 textline[off] = ' ';
5655 for (i = 1; i < (width - fname_size) / 2; ++i)
5656 textline[off + i] = '=';
5657 textline[off + i] = NUL;
5658
5659 return textline;
5660}
5661
5662/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005663 * Common for "term_dumpdiff()" and "term_dumpload()".
5664 */
5665 static void
5666term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5667{
5668 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005669 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005670 char_u buf1[NUMBUFLEN];
5671 char_u buf2[NUMBUFLEN];
5672 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005673 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005674 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005675 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005676 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005677 char_u *textline = NULL;
5678
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005679 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005680 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005681 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005682 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005683 if (fname1 == NULL || (do_diff && fname2 == NULL))
5684 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005685 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005686 return;
5687 }
5688 fd1 = mch_fopen((char *)fname1, READBIN);
5689 if (fd1 == NULL)
5690 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005691 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005692 return;
5693 }
5694 if (do_diff)
5695 {
5696 fd2 = mch_fopen((char *)fname2, READBIN);
5697 if (fd2 == NULL)
5698 {
5699 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005700 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005701 return;
5702 }
5703 }
5704
5705 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005706 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5707 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5708 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5709 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5710 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005711
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005712 if (opt.jo_term_name == NULL)
5713 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005714 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005715
Bram Moolenaar51e14382019-05-25 20:21:28 +02005716 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005717 if (fname_tofree != NULL)
5718 {
5719 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5720 opt.jo_term_name = fname_tofree;
5721 }
5722 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005723
Bram Moolenaar87abab92019-06-03 21:14:59 +02005724 if (opt.jo_bufnr_buf != NULL)
5725 {
5726 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5727
5728 // With "bufnr" argument: enter the window with this buffer and make it
5729 // empty.
5730 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005731 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005732 else
5733 {
5734 buf = curbuf;
5735 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005736 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005737 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005738 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005739 }
5740 }
5741 else
5742 // Create a new terminal window.
5743 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5744
Bram Moolenaard96ff162018-02-18 22:13:29 +01005745 if (buf != NULL && buf->b_term != NULL)
5746 {
5747 int i;
5748 linenr_T bot_lnum;
5749 linenr_T lnum;
5750 term_T *term = buf->b_term;
5751 int width;
5752 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005753 VTermPos cursor_pos1;
5754 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005755
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005756 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005757
Bram Moolenaard96ff162018-02-18 22:13:29 +01005758 rettv->vval.v_number = buf->b_fnum;
5759
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005760 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005761 width = read_dump_file(fd1, &cursor_pos1);
5762
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005763 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005764 if (cursor_pos1.row >= 0)
5765 {
5766 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5767 coladvance(cursor_pos1.col);
5768 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005769
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005770 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005771 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005772
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005773 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005774 if (!do_diff)
5775 goto theend;
5776
5777 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5778
Bram Moolenaar4a696342018-04-05 18:45:26 +02005779 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005780 if (textline == NULL)
5781 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005782 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5783 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5784 vim_free(textline);
5785
5786 textline = get_separator(width, fname2);
5787 if (textline == NULL)
5788 goto theend;
5789 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5790 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005791 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005792
5793 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005794 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005795 if (width2 > width)
5796 {
5797 vim_free(textline);
5798 textline = alloc(width2 + 1);
5799 if (textline == NULL)
5800 goto theend;
5801 width = width2;
5802 textline[width] = NUL;
5803 }
5804 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5805
5806 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5807 {
5808 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5809 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005810 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005811 for (i = 0; i < width; ++i)
5812 textline[i] = '-';
5813 }
5814 else
5815 {
5816 char_u *line1;
5817 char_u *line2;
5818 char_u *p1;
5819 char_u *p2;
5820 int col;
5821 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5822 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5823 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5824 ->sb_cells;
5825
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005826 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005827 line1 = vim_strsave(ml_get(lnum));
5828 if (line1 == NULL)
5829 break;
5830 p1 = line1;
5831
5832 line2 = ml_get(lnum + bot_lnum);
5833 p2 = line2;
5834 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5835 {
5836 int len1 = utfc_ptr2len(p1);
5837 int len2 = utfc_ptr2len(p2);
5838
5839 textline[col] = ' ';
5840 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005841 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005842 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005843 else if (lnum == cursor_pos1.row + 1
5844 && col == cursor_pos1.col
5845 && (cursor_pos1.row != cursor_pos2.row
5846 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005847 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005848 textline[col] = '>';
5849 else if (lnum == cursor_pos2.row + 1
5850 && col == cursor_pos2.col
5851 && (cursor_pos1.row != cursor_pos2.row
5852 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005853 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005854 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005855 else if (cellattr1 != NULL && cellattr2 != NULL)
5856 {
5857 if ((cellattr1 + col)->width
5858 != (cellattr2 + col)->width)
5859 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005860 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005861 &(cellattr2 + col)->fg))
5862 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005863 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005864 &(cellattr2 + col)->bg))
5865 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005866 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5867 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005868 textline[col] = 'a';
5869 }
5870 p1 += len1;
5871 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005872 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005873 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005874
5875 while (col < width)
5876 {
5877 if (*p1 == NUL && *p2 == NUL)
5878 textline[col] = '?';
5879 else if (*p1 == NUL)
5880 {
5881 textline[col] = '+';
5882 p2 += utfc_ptr2len(p2);
5883 }
5884 else
5885 {
5886 textline[col] = '-';
5887 p1 += utfc_ptr2len(p1);
5888 }
5889 ++col;
5890 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005891
5892 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005893 }
5894 if (add_empty_scrollback(term, &term->tl_default_color,
5895 term->tl_top_diff_rows) == OK)
5896 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5897 ++bot_lnum;
5898 }
5899
5900 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5901 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005902 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005903 for (i = 0; i < width; ++i)
5904 textline[i] = '+';
5905 if (add_empty_scrollback(term, &term->tl_default_color,
5906 term->tl_top_diff_rows) == OK)
5907 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5908 ++lnum;
5909 ++bot_lnum;
5910 }
5911
5912 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005913
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005914 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005915 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005916 }
5917
5918theend:
5919 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005920 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005921 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005922 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005923 fclose(fd2);
5924}
5925
5926/*
5927 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5928 * bottom files.
5929 * Return FAIL when this is not possible.
5930 */
5931 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005932term_swap_diff(void)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005933{
5934 term_T *term = curbuf->b_term;
5935 linenr_T line_count;
5936 linenr_T top_rows;
5937 linenr_T bot_rows;
5938 linenr_T bot_start;
5939 linenr_T lnum;
5940 char_u *p;
5941 sb_line_T *sb_line;
5942
5943 if (term == NULL
5944 || !term_is_finished(curbuf)
5945 || term->tl_top_diff_rows == 0
5946 || term->tl_scrollback.ga_len == 0)
5947 return FAIL;
5948
5949 line_count = curbuf->b_ml.ml_line_count;
5950 top_rows = term->tl_top_diff_rows;
5951 bot_rows = term->tl_bot_diff_rows;
5952 bot_start = line_count - bot_rows;
5953 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5954
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005955 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005956 for (lnum = 1; lnum <= top_rows; ++lnum)
5957 {
5958 p = vim_strsave(ml_get(1));
5959 if (p == NULL)
5960 return OK;
5961 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005962 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005963 vim_free(p);
5964 }
5965
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005966 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005967 for (lnum = 1; lnum <= bot_rows; ++lnum)
5968 {
5969 p = vim_strsave(ml_get(bot_start + lnum));
5970 if (p == NULL)
5971 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005972 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005973 ml_append(lnum - 1, p, 0, FALSE);
5974 vim_free(p);
5975 }
5976
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005977 // move top title to bottom
5978 p = vim_strsave(ml_get(bot_rows + 1));
5979 if (p == NULL)
5980 return OK;
5981 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005982 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005983 vim_free(p);
5984
5985 // move bottom title to top
5986 p = vim_strsave(ml_get(line_count - top_rows));
5987 if (p == NULL)
5988 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005989 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005990 ml_append(bot_rows, p, 0, FALSE);
5991 vim_free(p);
5992
Bram Moolenaard96ff162018-02-18 22:13:29 +01005993 if (top_rows == bot_rows)
5994 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005995 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005996 for (lnum = 0; lnum < top_rows; ++lnum)
5997 {
5998 sb_line_T temp;
5999
6000 temp = *(sb_line + lnum);
6001 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
6002 *(sb_line + bot_start + lnum) = temp;
6003 }
6004 }
6005 else
6006 {
6007 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006008 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006009
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006010 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01006011 if (temp != NULL)
6012 {
6013 mch_memmove(temp, term->tl_scrollback.ga_data, size);
6014 mch_memmove(term->tl_scrollback.ga_data,
6015 temp + bot_start,
6016 sizeof(sb_line_T) * bot_rows);
6017 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
6018 temp + top_rows,
6019 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
6020 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
6021 + line_count - top_rows,
6022 temp,
6023 sizeof(sb_line_T) * top_rows);
6024 vim_free(temp);
6025 }
6026 }
6027
6028 term->tl_top_diff_rows = bot_rows;
6029 term->tl_bot_diff_rows = top_rows;
6030
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006031 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006032 return OK;
6033}
6034
6035/*
6036 * "term_dumpdiff(filename, filename, options)" function
6037 */
6038 void
6039f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
6040{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02006041 if (in_vim9script()
6042 && (check_for_string_arg(argvars, 0) == FAIL
6043 || check_for_string_arg(argvars, 1) == FAIL
6044 || check_for_opt_dict_arg(argvars, 2) == FAIL))
6045 return;
6046
Bram Moolenaard96ff162018-02-18 22:13:29 +01006047 term_load_dump(argvars, rettv, TRUE);
6048}
6049
6050/*
6051 * "term_dumpload(filename, options)" function
6052 */
6053 void
6054f_term_dumpload(typval_T *argvars, typval_T *rettv)
6055{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006056 if (in_vim9script()
6057 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02006058 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006059 return;
6060
Bram Moolenaard96ff162018-02-18 22:13:29 +01006061 term_load_dump(argvars, rettv, FALSE);
6062}
6063
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006064/*
6065 * "term_getaltscreen(buf)" function
6066 */
6067 void
6068f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
6069{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006070 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006071
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006072 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6073 return;
6074
6075 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006076 if (buf == NULL)
6077 return;
6078 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
6079}
6080
6081/*
6082 * "term_getattr(attr, name)" function
6083 */
6084 void
6085f_term_getattr(typval_T *argvars, typval_T *rettv)
6086{
6087 int attr;
6088 size_t i;
6089 char_u *name;
6090
6091 static struct {
6092 char *name;
6093 int attr;
6094 } attrs[] = {
6095 {"bold", HL_BOLD},
6096 {"italic", HL_ITALIC},
6097 {"underline", HL_UNDERLINE},
6098 {"strike", HL_STRIKETHROUGH},
6099 {"reverse", HL_INVERSE},
6100 };
6101
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02006102 if (in_vim9script()
6103 && (check_for_number_arg(argvars, 0) == FAIL
6104 || check_for_string_arg(argvars, 1) == FAIL))
6105 return;
6106
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006107 attr = tv_get_number(&argvars[0]);
6108 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006109 if (name == NULL)
6110 return;
6111
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02006112 if (attr > HL_ALL)
6113 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02006114 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006115 if (STRCMP(name, attrs[i].name) == 0)
6116 {
6117 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
6118 break;
6119 }
6120}
6121
6122/*
6123 * "term_getcursor(buf)" function
6124 */
6125 void
6126f_term_getcursor(typval_T *argvars, typval_T *rettv)
6127{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006128 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006129 term_T *term;
6130 list_T *l;
6131 dict_T *d;
6132
6133 if (rettv_list_alloc(rettv) == FAIL)
6134 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006135
6136 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6137 return;
6138
6139 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006140 if (buf == NULL)
6141 return;
6142 term = buf->b_term;
6143
6144 l = rettv->vval.v_list;
6145 list_append_number(l, term->tl_cursor_pos.row + 1);
6146 list_append_number(l, term->tl_cursor_pos.col + 1);
6147
6148 d = dict_alloc();
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00006149 if (d == NULL)
6150 return;
6151
6152 dict_add_number(d, "visible", term->tl_cursor_visible);
6153 dict_add_number(d, "blink", blink_state_is_inverted()
6154 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6155 dict_add_number(d, "shape", term->tl_cursor_shape);
6156 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
6157 list_append_dict(l, d);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006158}
6159
6160/*
6161 * "term_getjob(buf)" function
6162 */
6163 void
6164f_term_getjob(typval_T *argvars, typval_T *rettv)
6165{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006166 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006167
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006168 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6169 return;
6170
6171 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006172 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006173 {
Ernie Raela78eb252024-06-13 17:24:54 +02006174 if (in_vim9script())
6175 {
6176 rettv->v_type = VAR_JOB;
6177 rettv->vval.v_job = NULL;
6178 }
6179 else
6180 {
6181 rettv->v_type = VAR_SPECIAL;
6182 rettv->vval.v_number = VVAL_NULL;
6183 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006184 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006185 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006186
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006187 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006188 rettv->vval.v_job = buf->b_term->tl_job;
6189 if (rettv->vval.v_job != NULL)
6190 ++rettv->vval.v_job->jv_refcount;
6191}
6192
6193 static int
6194get_row_number(typval_T *tv, term_T *term)
6195{
6196 if (tv->v_type == VAR_STRING
6197 && tv->vval.v_string != NULL
6198 && STRCMP(tv->vval.v_string, ".") == 0)
6199 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006200 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006201}
6202
6203/*
6204 * "term_getline(buf, row)" function
6205 */
6206 void
6207f_term_getline(typval_T *argvars, typval_T *rettv)
6208{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006209 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006210 term_T *term;
6211 int row;
6212
6213 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006214
6215 if (in_vim9script()
6216 && (check_for_buffer_arg(argvars, 0) == FAIL
6217 || check_for_lnum_arg(argvars, 1) == FAIL))
6218 return;
6219
6220 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006221 if (buf == NULL)
6222 return;
6223 term = buf->b_term;
6224 row = get_row_number(&argvars[1], term);
6225
6226 if (term->tl_vterm == NULL)
6227 {
6228 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6229
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006230 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006231 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6232 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6233 }
6234 else
6235 {
6236 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6237 VTermRect rect;
6238 int len;
6239 char_u *p;
6240
6241 if (row < 0 || row >= term->tl_rows)
6242 return;
6243 len = term->tl_cols * MB_MAXBYTES + 1;
6244 p = alloc(len);
6245 if (p == NULL)
6246 return;
6247 rettv->vval.v_string = p;
6248
6249 rect.start_col = 0;
6250 rect.end_col = term->tl_cols;
6251 rect.start_row = row;
6252 rect.end_row = row + 1;
6253 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6254 }
6255}
6256
6257/*
6258 * "term_getscrolled(buf)" function
6259 */
6260 void
6261f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6262{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006263 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006264
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006265 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6266 return;
6267
6268 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006269 if (buf == NULL)
6270 return;
6271 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6272}
6273
6274/*
6275 * "term_getsize(buf)" function
6276 */
6277 void
6278f_term_getsize(typval_T *argvars, typval_T *rettv)
6279{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006280 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006281 list_T *l;
6282
6283 if (rettv_list_alloc(rettv) == FAIL)
6284 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006285
6286 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6287 return;
6288
6289 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006290 if (buf == NULL)
6291 return;
6292
6293 l = rettv->vval.v_list;
6294 list_append_number(l, buf->b_term->tl_rows);
6295 list_append_number(l, buf->b_term->tl_cols);
6296}
6297
6298/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006299 * "term_setsize(buf, rows, cols)" function
6300 */
6301 void
6302f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6303{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006304 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006305 term_T *term;
6306 varnumber_T rows, cols;
6307
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006308 if (in_vim9script()
6309 && (check_for_buffer_arg(argvars, 0) == FAIL
6310 || check_for_number_arg(argvars, 1) == FAIL
6311 || check_for_number_arg(argvars, 2) == FAIL))
6312 return;
6313
6314 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006315 if (buf == NULL)
6316 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006317 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006318 return;
6319 }
6320 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006321 return;
6322 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006323 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006324 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006325 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006326 cols = cols <= 0 ? term->tl_cols : cols;
6327 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006328 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006329
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006330 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006331 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6332 term_report_winsize(term, term->tl_rows, term->tl_cols);
6333}
6334
6335/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006336 * "term_getstatus(buf)" function
6337 */
6338 void
6339f_term_getstatus(typval_T *argvars, typval_T *rettv)
6340{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006341 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006342 term_T *term;
6343 char_u val[100];
6344
6345 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006346
6347 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6348 return;
6349
6350 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006351 if (buf == NULL)
6352 return;
6353 term = buf->b_term;
6354
6355 if (term_job_running(term))
6356 STRCPY(val, "running");
6357 else
6358 STRCPY(val, "finished");
6359 if (term->tl_normal_mode)
6360 STRCAT(val, ",normal");
6361 rettv->vval.v_string = vim_strsave(val);
6362}
6363
6364/*
6365 * "term_gettitle(buf)" function
6366 */
6367 void
6368f_term_gettitle(typval_T *argvars, typval_T *rettv)
6369{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006370 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006371
6372 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006373
6374 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6375 return;
6376
6377 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006378 if (buf == NULL)
6379 return;
6380
6381 if (buf->b_term->tl_title != NULL)
6382 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6383}
6384
6385/*
6386 * "term_gettty(buf)" function
6387 */
6388 void
6389f_term_gettty(typval_T *argvars, typval_T *rettv)
6390{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006391 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006392 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006393 int num = 0;
6394
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006395 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006396 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006397 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6398 return;
6399
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006400 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006401 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006402 if (buf == NULL)
6403 return;
6404 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006405 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006406
6407 switch (num)
6408 {
6409 case 0:
6410 if (buf->b_term->tl_job != NULL)
6411 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006412 break;
6413 case 1:
6414 if (buf->b_term->tl_job != NULL)
6415 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006416 break;
6417 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006418 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006419 return;
6420 }
6421 if (p != NULL)
6422 rettv->vval.v_string = vim_strsave(p);
6423}
6424
6425/*
6426 * "term_list()" function
6427 */
6428 void
6429f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6430{
6431 term_T *tp;
6432 list_T *l;
6433
6434 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6435 return;
6436
6437 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006438 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006439 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006440 if (list_append_number(l,
6441 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6442 return;
6443}
6444
6445/*
6446 * "term_scrape(buf, row)" function
6447 */
6448 void
6449f_term_scrape(typval_T *argvars, typval_T *rettv)
6450{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006451 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006452 VTermScreen *screen = NULL;
6453 VTermPos pos;
6454 list_T *l;
6455 term_T *term;
6456 char_u *p;
6457 sb_line_T *line;
6458
6459 if (rettv_list_alloc(rettv) == FAIL)
6460 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006461
6462 if (in_vim9script()
6463 && (check_for_buffer_arg(argvars, 0) == FAIL
6464 || check_for_lnum_arg(argvars, 1) == FAIL))
6465 return;
6466
6467 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006468 if (buf == NULL)
6469 return;
6470 term = buf->b_term;
6471
6472 l = rettv->vval.v_list;
6473 pos.row = get_row_number(&argvars[1], term);
6474
6475 if (term->tl_vterm != NULL)
6476 {
6477 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006478 if (screen == NULL) // can't really happen
6479 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006480 p = NULL;
6481 line = NULL;
6482 }
6483 else
6484 {
6485 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6486
6487 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6488 return;
6489 p = ml_get_buf(buf, lnum + 1, FALSE);
6490 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6491 }
6492
6493 for (pos.col = 0; pos.col < term->tl_cols; )
6494 {
6495 dict_T *dcell;
6496 int width;
6497 VTermScreenCellAttrs attrs;
6498 VTermColor fg, bg;
6499 char_u rgb[8];
6500 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6501 int off = 0;
6502 int i;
6503
6504 if (screen == NULL)
6505 {
6506 cellattr_T *cellattr;
6507 int len;
6508
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006509 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006510 if (pos.col >= line->sb_cols)
6511 break;
6512 cellattr = line->sb_cells + pos.col;
6513 width = cellattr->width;
6514 attrs = cellattr->attrs;
6515 fg = cellattr->fg;
6516 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006517 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006518 mch_memmove(mbs, p, len);
6519 mbs[len] = NUL;
6520 p += len;
6521 }
6522 else
6523 {
6524 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006525
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006526 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6527 break;
6528 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6529 {
6530 if (cell.chars[i] == 0)
6531 break;
6532 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6533 }
6534 mbs[off] = NUL;
6535 width = cell.width;
6536 attrs = cell.attrs;
6537 fg = cell.fg;
6538 bg = cell.bg;
6539 }
6540 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006541 if (dcell == NULL)
6542 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006543 list_append_dict(l, dcell);
6544
Bram Moolenaare0be1672018-07-08 16:50:37 +02006545 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006546
6547 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6548 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006549 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006550 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6551 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006552 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006553
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006554 dict_add_number(dcell, "attr",
6555 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006556 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006557
6558 ++pos.col;
6559 if (width == 2)
6560 ++pos.col;
6561 }
6562}
6563
6564/*
6565 * "term_sendkeys(buf, keys)" function
6566 */
6567 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006568f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006569{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006570 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006571 char_u *msg;
6572 term_T *term;
6573
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006574 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006575 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006576 || check_for_string_arg(argvars, 1) == FAIL))
6577 return;
6578
6579 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006580 if (buf == NULL)
6581 return;
6582
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006583 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006584 if (msg == NULL)
6585 return;
6586 term = buf->b_term;
6587 if (term->tl_vterm == NULL)
6588 return;
6589
6590 while (*msg != NUL)
6591 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006592 int c;
6593
6594 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6595 {
6596 c = TO_SPECIAL(msg[1], msg[2]);
6597 msg += 3;
6598 }
6599 else
6600 {
6601 c = PTR2CHAR(msg);
6602 msg += MB_CPTR2LEN(msg);
6603 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006604 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006605 }
6606}
6607
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006608#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6609/*
6610 * "term_getansicolors(buf)" function
6611 */
6612 void
6613f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6614{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006615 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006616 term_T *term;
6617 VTermState *state;
6618 VTermColor color;
6619 char_u hexbuf[10];
6620 int index;
6621 list_T *list;
6622
6623 if (rettv_list_alloc(rettv) == FAIL)
6624 return;
6625
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006626 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6627 return;
6628
6629 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006630 if (buf == NULL)
6631 return;
6632 term = buf->b_term;
6633 if (term->tl_vterm == NULL)
6634 return;
6635
6636 list = rettv->vval.v_list;
6637 state = vterm_obtain_state(term->tl_vterm);
6638 for (index = 0; index < 16; index++)
6639 {
6640 vterm_state_get_palette_color(state, index, &color);
6641 sprintf((char *)hexbuf, "#%02x%02x%02x",
6642 color.red, color.green, color.blue);
6643 if (list_append_string(list, hexbuf, 7) == FAIL)
6644 return;
6645 }
6646}
6647
6648/*
6649 * "term_setansicolors(buf, list)" function
6650 */
6651 void
6652f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6653{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006654 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006655 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006656 listitem_T *li;
6657 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006658
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006659 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006660 && (check_for_buffer_arg(argvars, 0) == FAIL
6661 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006662 return;
6663
6664 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006665 if (buf == NULL)
6666 return;
6667 term = buf->b_term;
6668 if (term->tl_vterm == NULL)
6669 return;
6670
Bram Moolenaard83392a2022-09-01 12:22:46 +01006671 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006672 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006673
LemonBoyb2b3acb2022-05-20 10:10:34 +01006674 if (argvars[1].vval.v_list->lv_first == &range_list_item
6675 || argvars[1].vval.v_list->lv_len != 16)
6676 {
Bram Moolenaar23919542023-05-05 22:12:22 +01006677 semsg(_(e_invalid_value_for_argument_str), "\"colors\"");
LemonBoyb2b3acb2022-05-20 10:10:34 +01006678 return;
6679 }
6680
6681 if (term->tl_palette == NULL)
6682 term->tl_palette = ALLOC_MULT(long_u, 16);
6683 if (term->tl_palette == NULL)
6684 return;
6685
6686 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6687 {
6688 char_u *color_name;
6689 guicolor_T guicolor;
6690
6691 color_name = tv_get_string_chk(&li->li_tv);
6692 if (color_name == NULL)
6693 return;
6694
6695 guicolor = GUI_GET_COLOR(color_name);
6696 if (guicolor == INVALCOLOR)
6697 {
6698 semsg(_(e_cannot_allocate_color_str), color_name);
6699 return;
6700 }
6701
6702 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6703 }
6704
6705 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006706}
6707#endif
6708
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006709/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006710 * "term_setapi(buf, api)" function
6711 */
6712 void
6713f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6714{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006715 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006716 term_T *term;
6717 char_u *api;
6718
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006719 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006720 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006721 || check_for_string_arg(argvars, 1) == FAIL))
6722 return;
6723
6724 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006725 if (buf == NULL)
6726 return;
6727 term = buf->b_term;
6728 vim_free(term->tl_api);
6729 api = tv_get_string_chk(&argvars[1]);
6730 if (api != NULL)
6731 term->tl_api = vim_strsave(api);
6732 else
6733 term->tl_api = NULL;
6734}
6735
6736/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006737 * "term_setrestore(buf, command)" function
6738 */
6739 void
6740f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6741{
6742#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006743 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006744 term_T *term;
6745 char_u *cmd;
6746
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006747 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006748 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006749 || check_for_string_arg(argvars, 1) == FAIL))
6750 return;
6751
6752 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006753 if (buf == NULL)
6754 return;
6755 term = buf->b_term;
6756 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006757 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006758 if (cmd != NULL)
6759 term->tl_command = vim_strsave(cmd);
6760 else
6761 term->tl_command = NULL;
6762#endif
6763}
6764
6765/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006766 * "term_setkill(buf, how)" function
6767 */
6768 void
6769f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6770{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006771 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006772 term_T *term;
6773 char_u *how;
6774
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006775 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006776 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006777 || check_for_string_arg(argvars, 1) == FAIL))
6778 return;
6779
6780 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006781 if (buf == NULL)
6782 return;
6783 term = buf->b_term;
6784 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006785 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006786 if (how != NULL)
6787 term->tl_kill = vim_strsave(how);
6788 else
6789 term->tl_kill = NULL;
6790}
6791
6792/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006793 * "term_start(command, options)" function
6794 */
6795 void
6796f_term_start(typval_T *argvars, typval_T *rettv)
6797{
6798 jobopt_T opt;
6799 buf_T *buf;
6800
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006801 if (in_vim9script()
6802 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6803 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6804 return;
6805
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006806 init_job_options(&opt);
6807 if (argvars[1].v_type != VAR_UNKNOWN
6808 && get_job_options(&argvars[1], &opt,
6809 JO_TIMEOUT_ALL + JO_STOPONEXIT
6810 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6811 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6812 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6813 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006814 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006815 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006816 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006817 return;
6818
Bram Moolenaar13568252018-03-16 20:46:58 +01006819 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006820
6821 if (buf != NULL && buf->b_term != NULL)
6822 rettv->vval.v_number = buf->b_fnum;
6823}
6824
6825/*
6826 * "term_wait" function
6827 */
6828 void
6829f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6830{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006831 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006832
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006833 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006834 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006835 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006836 return;
6837
6838 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006839 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006840 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006841 if (buf->b_term->tl_job == NULL)
6842 {
6843 ch_log(NULL, "term_wait(): no job to wait for");
6844 return;
6845 }
6846 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006847 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006848 return;
6849
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006850 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006851 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006852 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6853 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006854 // The job is dead, keep reading channel I/O until the channel is
6855 // closed. buf->b_term may become NULL if the terminal was closed while
6856 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006857 ch_log(NULL, "term_wait(): waiting for channel to close");
6858 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6859 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006860 term_flush_messages();
6861
Bram Moolenaard45aa552018-05-21 22:50:29 +02006862 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006863 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006864 // If the terminal is closed when the channel is closed the
6865 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006866 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006867 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6868 // came here from a close callback, only wait one time
6869 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006870 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006871
6872 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006873 }
6874 else
6875 {
6876 long wait = 10L;
6877
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006878 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006879
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006880 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006881 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006882 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006883 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006884
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006885 // Flushing messages on channels is hopefully sufficient.
6886 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006887 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006888 }
6889}
6890
6891/*
6892 * Called when a channel has sent all the lines to a terminal.
6893 * Send a CTRL-D to mark the end of the text.
6894 */
6895 void
6896term_send_eof(channel_T *ch)
6897{
6898 term_T *term;
6899
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006900 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006901 if (term->tl_job == ch->ch_job)
6902 {
6903 if (term->tl_eof_chars != NULL)
6904 {
6905 channel_send(ch, PART_IN, term->tl_eof_chars,
6906 (int)STRLEN(term->tl_eof_chars), NULL);
6907 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6908 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006909# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006910 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006911 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006912 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6913# endif
6914 }
6915}
6916
Bram Moolenaar113e1072019-01-20 15:30:40 +01006917#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006918 job_T *
6919term_getjob(term_T *term)
6920{
6921 return term != NULL ? term->tl_job : NULL;
6922}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006923#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006924
Bram Moolenaar4f974752019-02-17 17:44:42 +01006925# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006926
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006927///////////////////////////////////////
6928// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006929#ifdef PROTO
6930typedef int COORD;
6931typedef int DWORD;
6932typedef int HANDLE;
6933typedef int *DWORD_PTR;
6934typedef int HPCON;
6935typedef int HRESULT;
6936typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006937typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006938typedef int PSIZE_T;
6939typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006940typedef int BOOL;
6941# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006942#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006943
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006944HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6945HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6946HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006947BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6948BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6949void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006950
6951 static int
6952dyn_conpty_init(int verbose)
6953{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006954 static HMODULE hKerneldll = NULL;
6955 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006956 static struct
6957 {
6958 char *name;
6959 FARPROC *ptr;
6960 } conpty_entry[] =
6961 {
6962 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6963 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6964 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6965 {"InitializeProcThreadAttributeList",
6966 (FARPROC*)&pInitializeProcThreadAttributeList},
6967 {"UpdateProcThreadAttribute",
6968 (FARPROC*)&pUpdateProcThreadAttribute},
6969 {"DeleteProcThreadAttributeList",
6970 (FARPROC*)&pDeleteProcThreadAttributeList},
6971 {NULL, NULL}
6972 };
6973
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006974 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006975 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006976 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006977 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006978 return FAIL;
6979 }
6980
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006981 // No need to initialize twice.
6982 if (hKerneldll)
6983 return OK;
6984
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006985 hKerneldll = vimLoadLib("kernel32.dll");
6986 for (i = 0; conpty_entry[i].name != NULL
6987 && conpty_entry[i].ptr != NULL; ++i)
6988 {
6989 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6990 conpty_entry[i].name)) == NULL)
6991 {
6992 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006993 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006994 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006995 return FAIL;
6996 }
6997 }
6998
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006999 return OK;
7000}
7001
7002 static int
7003conpty_term_and_job_init(
7004 term_T *term,
7005 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007006 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007007 jobopt_T *opt,
7008 jobopt_T *orig_opt)
7009{
7010 WCHAR *cmd_wchar = NULL;
7011 WCHAR *cmd_wchar_copy = NULL;
7012 WCHAR *cwd_wchar = NULL;
7013 WCHAR *env_wchar = NULL;
7014 channel_T *channel = NULL;
7015 job_T *job = NULL;
7016 HANDLE jo = NULL;
7017 garray_T ga_cmd, ga_env;
7018 char_u *cmd = NULL;
7019 HRESULT hr;
7020 COORD consize;
7021 SIZE_T breq;
7022 PROCESS_INFORMATION proc_info;
7023 HANDLE i_theirs = NULL;
7024 HANDLE o_theirs = NULL;
7025 HANDLE i_ours = NULL;
7026 HANDLE o_ours = NULL;
7027
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007028 ga_init2(&ga_cmd, sizeof(char*), 20);
7029 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007030
7031 if (argvar->v_type == VAR_STRING)
7032 {
7033 cmd = argvar->vval.v_string;
7034 }
7035 else if (argvar->v_type == VAR_LIST)
7036 {
7037 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
7038 goto failed;
7039 cmd = ga_cmd.ga_data;
7040 }
7041 if (cmd == NULL || *cmd == NUL)
7042 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007043 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007044 goto failed;
7045 }
7046
7047 term->tl_arg0_cmd = vim_strsave(cmd);
7048
7049 cmd_wchar = enc_to_utf16(cmd, NULL);
7050
7051 if (cmd_wchar != NULL)
7052 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007053 // Request by CreateProcessW
7054 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007055 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007056 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
7057 }
7058
7059 ga_clear(&ga_cmd);
7060 if (cmd_wchar == NULL)
7061 goto failed;
7062 if (opt->jo_cwd != NULL)
7063 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
7064
7065 win32_build_env(opt->jo_env, &ga_env, TRUE);
7066 env_wchar = ga_env.ga_data;
7067
7068 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
7069 goto failed;
7070 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
7071 goto failed;
7072
7073 consize.X = term->tl_cols;
7074 consize.Y = term->tl_rows;
7075 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
7076 &term->tl_conpty);
7077 if (FAILED(hr))
7078 goto failed;
7079
7080 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
7081
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007082 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007083 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007084 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007085 if (!term->tl_siex.lpAttributeList)
7086 goto failed;
7087 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
7088 0, &breq))
7089 goto failed;
7090 if (!pUpdateProcThreadAttribute(
7091 term->tl_siex.lpAttributeList, 0,
7092 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
7093 sizeof(HPCON), NULL, NULL))
7094 goto failed;
7095
7096 channel = add_channel();
7097 if (channel == NULL)
7098 goto failed;
7099
7100 job = job_alloc();
7101 if (job == NULL)
7102 goto failed;
7103 if (argvar->v_type == VAR_STRING)
7104 {
7105 int argc;
7106
7107 build_argv_from_string(cmd, &job->jv_argv, &argc);
7108 }
7109 else
7110 {
7111 int argc;
7112
7113 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7114 }
7115
7116 if (opt->jo_set & JO_IN_BUF)
7117 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7118
7119 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
7120 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02007121 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007122 env_wchar, cwd_wchar,
7123 &term->tl_siex.StartupInfo, &proc_info))
7124 goto failed;
7125
7126 CloseHandle(i_theirs);
7127 CloseHandle(o_theirs);
7128
7129 channel_set_pipes(channel,
7130 (sock_T)i_ours,
7131 (sock_T)o_ours,
7132 (sock_T)o_ours);
7133
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007134 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007135 channel->ch_write_text_mode = TRUE;
7136
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007137 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007138 channel->ch_anonymous_pipe = TRUE;
7139
7140 jo = CreateJobObject(NULL, NULL);
7141 if (jo == NULL)
7142 goto failed;
7143
7144 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7145 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007146 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007147 CloseHandle(jo);
7148 jo = NULL;
7149 }
7150
7151 ResumeThread(proc_info.hThread);
7152 CloseHandle(proc_info.hThread);
7153
7154 vim_free(cmd_wchar);
7155 vim_free(cmd_wchar_copy);
7156 vim_free(cwd_wchar);
7157 vim_free(env_wchar);
7158
7159 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7160 goto failed;
7161
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007162#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007163 if (term_use_palette())
7164 {
7165 if (term->tl_palette != NULL)
7166 set_vterm_palette(term->tl_vterm, term->tl_palette);
7167 else
7168 init_vterm_ansi_colors(term->tl_vterm);
7169 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007170#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007171
7172 channel_set_job(channel, job, opt);
7173 job_set_options(job, opt);
7174
7175 job->jv_channel = channel;
7176 job->jv_proc_info = proc_info;
7177 job->jv_job_object = jo;
7178 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007179 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007180 ++job->jv_refcount;
7181 term->tl_job = job;
7182
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007183 // Redirecting stdout and stderr doesn't work at the job level. Instead
7184 // open the file here and handle it in. opt->jo_io was changed in
7185 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007186 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7187 {
7188 char_u *fname = opt->jo_io_name[PART_OUT];
7189
7190 ch_log(channel, "Opening output file %s", fname);
7191 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7192 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007193 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007194 }
7195
7196 return OK;
7197
7198failed:
7199 ga_clear(&ga_cmd);
7200 ga_clear(&ga_env);
7201 vim_free(cmd_wchar);
7202 vim_free(cmd_wchar_copy);
7203 vim_free(cwd_wchar);
7204 if (channel != NULL)
7205 channel_clear(channel);
7206 if (job != NULL)
7207 {
7208 job->jv_channel = NULL;
7209 job_cleanup(job);
7210 }
7211 term->tl_job = NULL;
7212 if (jo != NULL)
7213 CloseHandle(jo);
7214
7215 if (term->tl_siex.lpAttributeList != NULL)
7216 {
7217 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7218 vim_free(term->tl_siex.lpAttributeList);
7219 }
7220 term->tl_siex.lpAttributeList = NULL;
7221 if (o_theirs != NULL)
7222 CloseHandle(o_theirs);
7223 if (o_ours != NULL)
7224 CloseHandle(o_ours);
7225 if (i_ours != NULL)
7226 CloseHandle(i_ours);
7227 if (i_theirs != NULL)
7228 CloseHandle(i_theirs);
7229 if (term->tl_conpty != NULL)
7230 pClosePseudoConsole(term->tl_conpty);
7231 term->tl_conpty = NULL;
7232 return FAIL;
7233}
7234
7235 static void
7236conpty_term_report_winsize(term_T *term, int rows, int cols)
7237{
7238 COORD consize;
7239
7240 consize.X = cols;
7241 consize.Y = rows;
7242 pResizePseudoConsole(term->tl_conpty, consize);
7243}
7244
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007245 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007246term_free_conpty(term_T *term)
7247{
7248 if (term->tl_siex.lpAttributeList != NULL)
7249 {
7250 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7251 vim_free(term->tl_siex.lpAttributeList);
7252 }
7253 term->tl_siex.lpAttributeList = NULL;
7254 if (term->tl_conpty != NULL)
7255 pClosePseudoConsole(term->tl_conpty);
7256 term->tl_conpty = NULL;
7257}
7258
7259 int
7260use_conpty(void)
7261{
7262 return has_conpty;
7263}
7264
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007265# ifndef PROTO
7266
7267#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7268#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007269#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007270
7271void* (*winpty_config_new)(UINT64, void*);
7272void* (*winpty_open)(void*, void*);
7273void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7274BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7275void (*winpty_config_set_mouse_mode)(void*, int);
7276void (*winpty_config_set_initial_size)(void*, int, int);
7277LPCWSTR (*winpty_conin_name)(void*);
7278LPCWSTR (*winpty_conout_name)(void*);
7279LPCWSTR (*winpty_conerr_name)(void*);
7280void (*winpty_free)(void*);
7281void (*winpty_config_free)(void*);
7282void (*winpty_spawn_config_free)(void*);
7283void (*winpty_error_free)(void*);
7284LPCWSTR (*winpty_error_msg)(void*);
7285BOOL (*winpty_set_size)(void*, int, int, void*);
7286HANDLE (*winpty_agent_process)(void*);
7287
7288#define WINPTY_DLL "winpty.dll"
7289
7290static HINSTANCE hWinPtyDLL = NULL;
7291# endif
7292
7293 static int
7294dyn_winpty_init(int verbose)
7295{
7296 int i;
7297 static struct
7298 {
7299 char *name;
7300 FARPROC *ptr;
7301 } winpty_entry[] =
7302 {
7303 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7304 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7305 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7306 {"winpty_config_set_mouse_mode",
7307 (FARPROC*)&winpty_config_set_mouse_mode},
7308 {"winpty_config_set_initial_size",
7309 (FARPROC*)&winpty_config_set_initial_size},
7310 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7311 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7312 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7313 {"winpty_free", (FARPROC*)&winpty_free},
7314 {"winpty_open", (FARPROC*)&winpty_open},
7315 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7316 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7317 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7318 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7319 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7320 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7321 {NULL, NULL}
7322 };
7323
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007324 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007325 if (hWinPtyDLL)
7326 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007327 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7328 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007329 if (*p_winptydll != NUL)
7330 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7331 if (!hWinPtyDLL)
7332 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7333 if (!hWinPtyDLL)
7334 {
7335 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007336 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007337 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7338 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007339 return FAIL;
7340 }
7341 for (i = 0; winpty_entry[i].name != NULL
7342 && winpty_entry[i].ptr != NULL; ++i)
7343 {
7344 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7345 winpty_entry[i].name)) == NULL)
7346 {
7347 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007348 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007349 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007350 return FAIL;
7351 }
7352 }
7353
7354 return OK;
7355}
7356
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007357 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007358winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007359 term_T *term,
7360 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007361 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007362 jobopt_T *opt,
7363 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007364{
7365 WCHAR *cmd_wchar = NULL;
7366 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007367 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007368 channel_T *channel = NULL;
7369 job_T *job = NULL;
7370 DWORD error;
7371 HANDLE jo = NULL;
7372 HANDLE child_process_handle;
7373 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007374 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007375 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007376 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007377 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007378
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007379 ga_init2(&ga_cmd, sizeof(char*), 20);
7380 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007381
7382 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007383 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007384 cmd = argvar->vval.v_string;
7385 }
7386 else if (argvar->v_type == VAR_LIST)
7387 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007388 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007389 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007390 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007391 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007392 if (cmd == NULL || *cmd == NUL)
7393 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007394 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007395 goto failed;
7396 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007397
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007398 term->tl_arg0_cmd = vim_strsave(cmd);
7399
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007400 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007401 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007402 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007403 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007404 if (opt->jo_cwd != NULL)
7405 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007406
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007407 win32_build_env(opt->jo_env, &ga_env, TRUE);
7408 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007409
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007410 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7411 if (term->tl_winpty_config == NULL)
7412 goto failed;
7413
7414 winpty_config_set_mouse_mode(term->tl_winpty_config,
7415 WINPTY_MOUSE_MODE_FORCE);
7416 winpty_config_set_initial_size(term->tl_winpty_config,
7417 term->tl_cols, term->tl_rows);
7418 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7419 if (term->tl_winpty == NULL)
7420 goto failed;
7421
7422 spawn_config = winpty_spawn_config_new(
7423 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7424 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7425 NULL,
7426 cmd_wchar,
7427 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007428 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007429 &winpty_err);
7430 if (spawn_config == NULL)
7431 goto failed;
7432
7433 channel = add_channel();
7434 if (channel == NULL)
7435 goto failed;
7436
7437 job = job_alloc();
7438 if (job == NULL)
7439 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007440 if (argvar->v_type == VAR_STRING)
7441 {
7442 int argc;
7443
7444 build_argv_from_string(cmd, &job->jv_argv, &argc);
7445 }
7446 else
7447 {
7448 int argc;
7449
7450 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7451 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007452
7453 if (opt->jo_set & JO_IN_BUF)
7454 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7455
7456 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7457 &child_thread_handle, &error, &winpty_err))
7458 goto failed;
7459
7460 channel_set_pipes(channel,
7461 (sock_T)CreateFileW(
7462 winpty_conin_name(term->tl_winpty),
7463 GENERIC_WRITE, 0, NULL,
7464 OPEN_EXISTING, 0, NULL),
7465 (sock_T)CreateFileW(
7466 winpty_conout_name(term->tl_winpty),
7467 GENERIC_READ, 0, NULL,
7468 OPEN_EXISTING, 0, NULL),
7469 (sock_T)CreateFileW(
7470 winpty_conerr_name(term->tl_winpty),
7471 GENERIC_READ, 0, NULL,
7472 OPEN_EXISTING, 0, NULL));
7473
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007474 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007475 channel->ch_write_text_mode = TRUE;
7476
7477 jo = CreateJobObject(NULL, NULL);
7478 if (jo == NULL)
7479 goto failed;
7480
7481 if (!AssignProcessToJobObject(jo, child_process_handle))
7482 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007483 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007484 CloseHandle(jo);
7485 jo = NULL;
7486 }
7487
7488 winpty_spawn_config_free(spawn_config);
7489 vim_free(cmd_wchar);
7490 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007491 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007492
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007493 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7494 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007495
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007496#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007497 if (term_use_palette())
7498 {
7499 if (term->tl_palette != NULL)
7500 set_vterm_palette(term->tl_vterm, term->tl_palette);
7501 else
7502 init_vterm_ansi_colors(term->tl_vterm);
7503 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007504#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007505
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007506 channel_set_job(channel, job, opt);
7507 job_set_options(job, opt);
7508
7509 job->jv_channel = channel;
7510 job->jv_proc_info.hProcess = child_process_handle;
7511 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7512 job->jv_job_object = jo;
7513 job->jv_status = JOB_STARTED;
7514 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007515 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007516 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007517 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007518 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007519 ++job->jv_refcount;
7520 term->tl_job = job;
7521
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007522 // Redirecting stdout and stderr doesn't work at the job level. Instead
7523 // open the file here and handle it in. opt->jo_io was changed in
7524 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007525 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7526 {
7527 char_u *fname = opt->jo_io_name[PART_OUT];
7528
7529 ch_log(channel, "Opening output file %s", fname);
7530 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7531 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007532 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007533 }
7534
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007535 return OK;
7536
7537failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007538 ga_clear(&ga_cmd);
7539 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007540 vim_free(cmd_wchar);
7541 vim_free(cwd_wchar);
7542 if (spawn_config != NULL)
7543 winpty_spawn_config_free(spawn_config);
7544 if (channel != NULL)
7545 channel_clear(channel);
7546 if (job != NULL)
7547 {
7548 job->jv_channel = NULL;
7549 job_cleanup(job);
7550 }
7551 term->tl_job = NULL;
7552 if (jo != NULL)
7553 CloseHandle(jo);
7554 if (term->tl_winpty != NULL)
7555 winpty_free(term->tl_winpty);
7556 term->tl_winpty = NULL;
7557 if (term->tl_winpty_config != NULL)
7558 winpty_config_free(term->tl_winpty_config);
7559 term->tl_winpty_config = NULL;
7560 if (winpty_err != NULL)
7561 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007562 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007563 (short_u *)winpty_error_msg(winpty_err), NULL);
7564
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007565 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007566 winpty_error_free(winpty_err);
7567 }
7568 return FAIL;
7569}
7570
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007571/*
7572 * Create a new terminal of "rows" by "cols" cells.
7573 * Store a reference in "term".
7574 * Return OK or FAIL.
7575 */
7576 static int
7577term_and_job_init(
7578 term_T *term,
7579 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007580 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007581 jobopt_T *opt,
7582 jobopt_T *orig_opt)
7583{
7584 int use_winpty = FALSE;
7585 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007586 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007587
7588 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7589 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7590
7591 if (!has_winpty && !has_conpty)
7592 // If neither is available give the errors for winpty, since when
7593 // conpty is not available it can't be installed either.
7594 return dyn_winpty_init(TRUE);
7595
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007596 if (opt->jo_tty_type != NUL)
7597 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007598
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007599 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007600 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007601 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007602 use_conpty = TRUE;
7603 else if (has_winpty)
7604 use_winpty = TRUE;
7605 // else: error
7606 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007607 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007608 {
7609 if (has_winpty)
7610 use_winpty = TRUE;
7611 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007612 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007613 {
7614 if (has_conpty)
7615 use_conpty = TRUE;
7616 else
7617 return dyn_conpty_init(TRUE);
7618 }
7619
7620 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007621 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007622
7623 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007624 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007625
7626 // error
7627 return dyn_winpty_init(TRUE);
7628}
7629
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007630 static int
7631create_pty_only(term_T *term, jobopt_T *options)
7632{
7633 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7634 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7635 char in_name[80], out_name[80];
7636 channel_T *channel = NULL;
7637
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007638 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7639 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007640
7641 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7642 GetCurrentProcessId(),
7643 curbuf->b_fnum);
7644 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7645 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7646 PIPE_UNLIMITED_INSTANCES,
7647 0, 0, NMPWAIT_NOWAIT, NULL);
7648 if (hPipeIn == INVALID_HANDLE_VALUE)
7649 goto failed;
7650
7651 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7652 GetCurrentProcessId(),
7653 curbuf->b_fnum);
7654 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7655 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7656 PIPE_UNLIMITED_INSTANCES,
7657 0, 0, 0, NULL);
7658 if (hPipeOut == INVALID_HANDLE_VALUE)
7659 goto failed;
7660
7661 ConnectNamedPipe(hPipeIn, NULL);
7662 ConnectNamedPipe(hPipeOut, NULL);
7663
7664 term->tl_job = job_alloc();
7665 if (term->tl_job == NULL)
7666 goto failed;
7667 ++term->tl_job->jv_refcount;
7668
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007669 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007670 term->tl_job->jv_status = JOB_FINISHED;
7671
7672 channel = add_channel();
7673 if (channel == NULL)
7674 goto failed;
7675 term->tl_job->jv_channel = channel;
7676 channel->ch_keep_open = TRUE;
7677 channel->ch_named_pipe = TRUE;
7678
7679 channel_set_pipes(channel,
7680 (sock_T)hPipeIn,
7681 (sock_T)hPipeOut,
7682 (sock_T)hPipeOut);
7683 channel_set_job(channel, term->tl_job, options);
7684 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7685 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7686
7687 return OK;
7688
7689failed:
7690 if (hPipeIn != NULL)
7691 CloseHandle(hPipeIn);
7692 if (hPipeOut != NULL)
7693 CloseHandle(hPipeOut);
7694 return FAIL;
7695}
7696
7697/*
7698 * Free the terminal emulator part of "term".
7699 */
7700 static void
7701term_free_vterm(term_T *term)
7702{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007703 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007704 if (term->tl_winpty != NULL)
7705 winpty_free(term->tl_winpty);
7706 term->tl_winpty = NULL;
7707 if (term->tl_winpty_config != NULL)
7708 winpty_config_free(term->tl_winpty_config);
7709 term->tl_winpty_config = NULL;
7710 if (term->tl_vterm != NULL)
7711 vterm_free(term->tl_vterm);
7712 term->tl_vterm = NULL;
7713}
7714
7715/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007716 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007717 */
7718 static void
7719term_report_winsize(term_T *term, int rows, int cols)
7720{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007721 if (term->tl_conpty)
7722 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007723 if (term->tl_winpty)
7724 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7725}
7726
7727 int
7728terminal_enabled(void)
7729{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007730 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007731}
7732
7733# else
7734
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007735///////////////////////////////////////
7736// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007737
7738/*
7739 * Create a new terminal of "rows" by "cols" cells.
7740 * Start job for "cmd".
7741 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007742 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007743 * Return OK or FAIL.
7744 */
7745 static int
7746term_and_job_init(
7747 term_T *term,
7748 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007749 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007750 jobopt_T *opt,
7751 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007752{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007753 term->tl_arg0_cmd = NULL;
7754
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007755 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7756 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007757
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007758#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007759 if (term_use_palette())
7760 {
7761 if (term->tl_palette != NULL)
7762 set_vterm_palette(term->tl_vterm, term->tl_palette);
7763 else
7764 init_vterm_ansi_colors(term->tl_vterm);
7765 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007766#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007767
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007768 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007769 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007770 if (term->tl_job != NULL)
7771 ++term->tl_job->jv_refcount;
7772
7773 return term->tl_job != NULL
7774 && term->tl_job->jv_channel != NULL
7775 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7776}
7777
7778 static int
7779create_pty_only(term_T *term, jobopt_T *opt)
7780{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007781 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7782 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007783
7784 term->tl_job = job_alloc();
7785 if (term->tl_job == NULL)
7786 return FAIL;
7787 ++term->tl_job->jv_refcount;
7788
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007789 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007790 term->tl_job->jv_status = JOB_FINISHED;
7791
7792 return mch_create_pty_channel(term->tl_job, opt);
7793}
7794
7795/*
7796 * Free the terminal emulator part of "term".
7797 */
7798 static void
7799term_free_vterm(term_T *term)
7800{
7801 if (term->tl_vterm != NULL)
7802 vterm_free(term->tl_vterm);
7803 term->tl_vterm = NULL;
7804}
7805
7806/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007807 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007808 */
7809 static void
7810term_report_winsize(term_T *term, int rows, int cols)
7811{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007812 // Use an ioctl() to report the new window size to the job.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007813 if (term->tl_job == NULL || term->tl_job->jv_channel == NULL)
7814 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007815
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007816 int fd = -1;
7817 int part;
7818
7819 for (part = PART_OUT; part < PART_COUNT; ++part)
7820 {
7821 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
7822 if (mch_isatty(fd))
7823 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007824 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007825 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7826 mch_signal_job(term->tl_job, (char_u *)"winch");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007827}
7828
7829# endif
7830
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007831#endif // FEAT_TERMINAL