blob: 9f94825705532eadd78ed2413762215b67dcfac4 [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020039 */
40
41#include "vim.h"
42
43#if defined(FEAT_TERMINAL) || defined(PROTO)
44
45#ifndef MIN
46# define MIN(x,y) ((x) < (y) ? (x) : (y))
47#endif
48#ifndef MAX
49# define MAX(x,y) ((x) > (y) ? (x) : (y))
50#endif
51
52#include "libvterm/include/vterm.h"
53
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010054// This is VTermScreenCell without the characters, thus much smaller.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055typedef struct {
Yegappan Lakshmanan562610c2025-05-04 21:05:51 +020056 VTermScreenCellAttrs attrs;
57 char width;
58 VTermColor fg;
59 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060} cellattr_T;
61
62typedef struct sb_line_S {
Bram Moolenaar29ae2232019-02-14 21:22:01 +010063 int sb_cols; // can differ per line
64 cellattr_T *sb_cells; // allocated
65 cellattr_T sb_fill_attr; // for short line
66 char_u *sb_text; // for tl_scrollback_postponed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067} sb_line_T;
68
Bram Moolenaar4f974752019-02-17 17:44:42 +010069#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010070# ifndef HPCON
71# define HPCON VOID*
72# endif
73# ifndef EXTENDED_STARTUPINFO_PRESENT
74# define EXTENDED_STARTUPINFO_PRESENT 0x00080000
75# endif
76# ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
77# define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE 0x00020016
78# endif
79typedef struct _DYN_STARTUPINFOEXW
80{
81 STARTUPINFOW StartupInfo;
82 LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
83} DYN_STARTUPINFOEXW, *PDYN_STARTUPINFOEXW;
84#endif
85
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010086// typedef term_T in structs.h
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020087struct terminal_S {
88 term_T *tl_next;
89
90 VTerm *tl_vterm;
91 job_T *tl_job;
92 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010093#if defined(FEAT_GUI)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010094 int tl_system; // when non-zero used for :!cmd output
95 int tl_toprow; // row with first line of system terminal
Bram Moolenaar13568252018-03-16 20:46:58 +010096#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010098 // Set when setting the size of a vterm, reset after redrawing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020099 int tl_vterm_size_changed;
100
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100101 int tl_normal_mode; // TRUE: Terminal-Normal mode
Bram Moolenaareea32af2021-11-21 14:51:13 +0000102 int tl_channel_closing;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200103 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200104 int tl_channel_recently_closed; // still need to handle tl_finish
105
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100106 int tl_finish;
107#define TL_FINISH_UNSET NUL
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100108#define TL_FINISH_CLOSE 'c' // ++close or :terminal without argument
109#define TL_FINISH_NOCLOSE 'n' // ++noclose
110#define TL_FINISH_OPEN 'o' // ++open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200111 char_u *tl_opencmd;
112 char_u *tl_eof_chars;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200113 char_u *tl_api; // prefix for terminal API function
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200114
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100115 char_u *tl_arg0_cmd; // To format the status bar
116
Bram Moolenaar4f974752019-02-17 17:44:42 +0100117#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200118 void *tl_winpty_config;
119 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200120
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100121 HPCON tl_conpty;
122 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
123
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200124 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200125#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100126#if defined(FEAT_SESSION)
127 char_u *tl_command;
128#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100129 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100131 // last known vterm size
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200132 int tl_rows;
133 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200134
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100135 char_u *tl_title; // NULL or allocated
136 char_u *tl_status_text; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200137
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100138 // Range of screen rows to update. Zero based.
139 int tl_dirty_row_start; // MAX_ROW if nothing dirty
140 int tl_dirty_row_end; // row below last one to update
141 int tl_dirty_snapshot; // text updated after making snapshot
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200142#ifdef FEAT_TIMERS
143 int tl_timer_set;
144 proftime_T tl_timer_due;
145#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100146 int tl_postponed_scroll; // to be scrolled up
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200148 garray_T tl_scrollback;
149 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100150 garray_T tl_scrollback_postponed;
151
Bram Moolenaar83d47902020-03-26 20:34:00 +0100152 char_u *tl_highlight_name; // replaces "Terminal"; allocated
153
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200154 cellattr_T tl_default_color;
155
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100156 linenr_T tl_top_diff_rows; // rows of top diff file or zero
157 linenr_T tl_bot_diff_rows; // rows of bottom diff file
Bram Moolenaard96ff162018-02-18 22:13:29 +0100158
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200159 VTermPos tl_cursor_pos;
160 int tl_cursor_visible;
161 int tl_cursor_blink;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100162 int tl_cursor_shape; // 1: block, 2: underline, 3: bar
163 char_u *tl_cursor_color; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200164
LemonBoyb2b3acb2022-05-20 10:10:34 +0100165 long_u *tl_palette; // array of 16 colors specified by term_start, can
166 // be NULL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167 int tl_using_altscreen;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200168 garray_T tl_osc_buf; // incomplete OSC string
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200169};
170
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100171#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
172#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200173
174/*
175 * List of all active terminals.
176 */
177static term_T *first_term = NULL;
178
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100179// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200180static term_T *in_terminal_loop = NULL;
181
Bram Moolenaar4f974752019-02-17 17:44:42 +0100182#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100183static BOOL has_winpty = FALSE;
184static BOOL has_conpty = FALSE;
185#endif
186
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100187#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188#define KEY_BUF_LEN 200
189
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200190#define FOR_ALL_TERMS(term) \
191 for ((term) = first_term; (term) != NULL; (term) = (term)->tl_next)
192
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193/*
194 * Functions with separate implementation for MS-Windows and Unix-like systems.
195 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200196static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200197static int create_pty_only(term_T *term, jobopt_T *opt);
198static void term_report_winsize(term_T *term, int rows, int cols);
199static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100200#ifdef FEAT_GUI
201static void update_system_term(term_T *term);
202#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200203
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100204static void handle_postponed_scrollback(term_T *term);
205
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100206// The character that we know (or assume) that the terminal expects for the
207// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200208static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200209
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100210// Store the last set and the desired cursor properties, so that we only update
211// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200212static char_u *last_set_cursor_color = NULL;
213static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100214static int last_set_cursor_shape = -1;
215static int desired_cursor_shape = -1;
216static int last_set_cursor_blink = -1;
217static int desired_cursor_blink = -1;
218
219
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100220///////////////////////////////////////
221// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200222
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200223 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200224cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
225{
226 if (lhs_color != NULL && rhs_color != NULL)
227 return STRCMP(lhs_color, rhs_color) == 0;
228 return lhs_color == NULL && rhs_color == NULL;
229}
230
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200231 static void
232cursor_color_copy(char_u **to_color, char_u *from_color)
233{
234 // Avoid a free & alloc if the value is already right.
235 if (cursor_color_equal(*to_color, from_color))
236 return;
237 vim_free(*to_color);
238 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
239}
240
241 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200242cursor_color_get(char_u *color)
243{
244 return (color == NULL) ? (char_u *)"" : color;
245}
246
247
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200248/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200249 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200250 * current window.
251 * Sets "rows" and/or "cols" to zero when it should follow the window size.
252 * Return TRUE if the size is the minimum size: "24*80".
253 */
254 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200255parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200256{
257 int minsize = FALSE;
258
259 *rows = 0;
260 *cols = 0;
261
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000262 if (*wp->w_p_tws == NUL)
263 return FALSE;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200264
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000265 char_u *p = vim_strchr(wp->w_p_tws, 'x');
266
267 // Syntax of value was already checked when it's set.
268 if (p == NULL)
269 {
270 minsize = TRUE;
271 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200272 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000273 *rows = atoi((char *)wp->w_p_tws);
274 *cols = atoi((char *)p + 1);
Christian Brabandtceee7a82023-09-21 16:55:06 +0200275 if (*rows > VTERM_MAX_ROWS)
276 *rows = VTERM_MAX_ROWS;
277 if (*cols > VTERM_MAX_COLS)
278 *cols = VTERM_MAX_COLS;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200279 return minsize;
280}
281
282/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200283 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200284 */
285 static void
Bram Moolenaarb936b792020-09-04 18:34:09 +0200286set_term_and_win_size(term_T *term, jobopt_T *opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200287{
Bram Moolenaarb936b792020-09-04 18:34:09 +0200288 int rows, cols;
289 int minsize;
290
Bram Moolenaar13568252018-03-16 20:46:58 +0100291#ifdef FEAT_GUI
292 if (term->tl_system)
293 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100294 // Use the whole screen for the system command. However, it will start
295 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100296 term->tl_rows = Rows;
297 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200298 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100299 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100300#endif
Bram Moolenaarb936b792020-09-04 18:34:09 +0200301 term->tl_rows = curwin->w_height;
302 term->tl_cols = curwin->w_width;
303
304 minsize = parse_termwinsize(curwin, &rows, &cols);
305 if (minsize)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200306 {
Bram Moolenaarb936b792020-09-04 18:34:09 +0200307 if (term->tl_rows < rows)
308 term->tl_rows = rows;
309 if (term->tl_cols < cols)
310 term->tl_cols = cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200312 if ((opt->jo_set2 & JO2_TERM_ROWS))
313 term->tl_rows = opt->jo_term_rows;
314 else if (rows != 0)
315 term->tl_rows = rows;
316 if ((opt->jo_set2 & JO2_TERM_COLS))
317 term->tl_cols = opt->jo_term_cols;
318 else if (cols != 0)
319 term->tl_cols = cols;
320
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200321 if (!opt->jo_hidden)
Bram Moolenaarb936b792020-09-04 18:34:09 +0200322 {
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200323 if (term->tl_rows != curwin->w_height)
324 win_setheight_win(term->tl_rows, curwin);
325 if (term->tl_cols != curwin->w_width)
326 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaarb936b792020-09-04 18:34:09 +0200327
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200328 // Set 'winsize' now to avoid a resize at the next redraw.
329 if (!minsize && *curwin->w_p_tws != NUL)
330 {
331 char_u buf[100];
332
333 vim_snprintf((char *)buf, 100, "%dx%d",
334 term->tl_rows, term->tl_cols);
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100335 set_option_value_give_err((char_u *)"termwinsize",
336 0L, buf, OPT_LOCAL);
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200337 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200338 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200339}
340
341/*
342 * Initialize job options for a terminal job.
343 * Caller may overrule some of them.
344 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100345 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346init_job_options(jobopt_T *opt)
347{
348 clear_job_options(opt);
349
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100350 opt->jo_mode = CH_MODE_RAW;
351 opt->jo_out_mode = CH_MODE_RAW;
352 opt->jo_err_mode = CH_MODE_RAW;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200353 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
354}
355
356/*
357 * Set job options mandatory for a terminal job.
358 */
359 static void
360setup_job_options(jobopt_T *opt, int rows, int cols)
361{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100362#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100363 // Win32: Redirecting the job output won't work, thus always connect stdout
364 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200365 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200366#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200367 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100368 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200369 opt->jo_io[PART_OUT] = JIO_BUFFER;
370 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
371 opt->jo_modifiable[PART_OUT] = 0;
372 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
373 }
374
Bram Moolenaar4f974752019-02-17 17:44:42 +0100375#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100376 // Win32: Redirecting the job output won't work, thus always connect stderr
377 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200378 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200379#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200380 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100381 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200382 opt->jo_io[PART_ERR] = JIO_BUFFER;
383 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
384 opt->jo_modifiable[PART_ERR] = 0;
385 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
386 }
387
388 opt->jo_pty = TRUE;
389 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
390 opt->jo_term_rows = rows;
391 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
392 opt->jo_term_cols = cols;
393}
394
395/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200396 * Flush messages on channels.
397 */
398 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +0000399term_flush_messages(void)
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200400{
401 mch_check_messages();
402 parse_queued_messages();
403}
404
405/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100406 * Close a terminal buffer (and its window). Used when creating the terminal
407 * fails.
408 */
409 static void
410term_close_buffer(buf_T *buf, buf_T *old_curbuf)
411{
412 free_terminal(buf);
413 if (old_curbuf != NULL)
414 {
415 --curbuf->b_nwindows;
416 curbuf = old_curbuf;
417 curwin->w_buffer = curbuf;
418 ++curbuf->b_nwindows;
419 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100420 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100421
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100422 // Wiping out the buffer will also close the window and call
423 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100424 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
425}
426
427/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100429 * Use either "argvar" or "argv", the other must be NULL.
430 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
431 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200432 * Returns NULL when failed.
433 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100434 buf_T *
435term_start(
436 typval_T *argvar,
437 char **argv,
438 jobopt_T *opt,
439 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200440{
441 exarg_T split_ea;
442 win_T *old_curwin = curwin;
443 term_T *term;
444 buf_T *old_curbuf = NULL;
445 int res;
446 buf_T *newbuf;
Bram Moolenaare1004402020-10-24 20:49:43 +0200447 int vertical = opt->jo_vertical || (cmdmod.cmod_split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200448 jobopt_T orig_opt; // only partly filled
Christian Brabandt991657e2024-10-15 20:31:14 +0200449 pos_T save_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200450
451 if (check_restricted() || check_secure())
452 return NULL;
Bram Moolenaare5b44862021-05-30 13:54:03 +0200453 if (cmdwin_type != 0)
454 {
455 emsg(_(e_cannot_open_terminal_from_command_line_window));
456 return NULL;
457 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200458
459 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
460 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
461 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100462 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
463 || (argvar != NULL
464 && argvar->v_type == VAR_LIST
465 && argvar->vval.v_list != NULL
466 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200467 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000468 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200469 return NULL;
470 }
471
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200472 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200473 if (term == NULL)
474 return NULL;
475 term->tl_dirty_row_end = MAX_ROW;
476 term->tl_cursor_visible = TRUE;
477 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
478 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100479#ifdef FEAT_GUI
480 term->tl_system = (flags & TERM_START_SYSTEM);
481#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200482 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100483 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200484 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200485
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200486 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200487 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200488 if (opt->jo_curwin)
489 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100490 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100491 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200492 {
493 no_write_message();
494 vim_free(term);
495 return NULL;
496 }
497 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200498 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
499 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
500 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200501 {
502 vim_free(term);
503 return NULL;
504 }
505 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100506 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200507 {
508 buf_T *buf;
509
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100510 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100511 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200512 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
513 BLN_NEW | BLN_LISTED);
514 if (buf == NULL || ml_open(buf) == FAIL)
515 {
516 vim_free(term);
517 return NULL;
518 }
519 old_curbuf = curbuf;
520 --curbuf->b_nwindows;
521 curbuf = buf;
Christian Brabandt991657e2024-10-15 20:31:14 +0200522 save_cursor = curwin->w_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200523 curwin->w_buffer = buf;
524 ++curbuf->b_nwindows;
525 }
526 else
527 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100528 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200529 split_ea.cmdidx = CMD_new;
530 split_ea.cmd = (char_u *)"new";
531 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100532 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200533 {
534 split_ea.line2 = opt->jo_term_rows;
535 split_ea.addr_count = 1;
536 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100537 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200538 {
539 split_ea.line2 = opt->jo_term_cols;
540 split_ea.addr_count = 1;
541 }
542
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200543 int cmod_split_modified = FALSE;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100544 if (vertical)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200545 {
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200546 if (!(cmdmod.cmod_split & WSP_VERT))
547 cmod_split_modified = TRUE;
Bram Moolenaare1004402020-10-24 20:49:43 +0200548 cmdmod.cmod_split |= WSP_VERT;
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200549 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200550 ex_splitview(&split_ea);
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200551 if (cmod_split_modified)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200552 cmdmod.cmod_split &= ~WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200553 if (curwin == old_curwin)
554 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100555 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200556 vim_free(term);
557 return NULL;
558 }
559 }
560 term->tl_buffer = curbuf;
561 curbuf->b_term = term;
562
563 if (!opt->jo_hidden)
564 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100565 // Only one size was taken care of with :new, do the other one. With
566 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100567 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100569 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200570 win_setwidth(opt->jo_term_cols);
571 }
572
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100573 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200574 term->tl_next = first_term;
575 first_term = term;
576
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100577 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
578
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200579 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100580 {
581 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200582 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100583 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100584 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100585 {
586 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100587 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100588 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200589 else
590 {
591 int i;
592 size_t len;
593 char_u *cmd, *p;
594
595 if (argvar->v_type == VAR_STRING)
596 {
597 cmd = argvar->vval.v_string;
598 if (cmd == NULL)
599 cmd = (char_u *)"";
600 else if (STRCMP(cmd, "NONE") == 0)
601 cmd = (char_u *)"pty";
602 }
603 else if (argvar->v_type != VAR_LIST
604 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100605 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100606 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200607 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
608 cmd = (char_u*)"";
609
610 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200611 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200612
613 for (i = 0; p != NULL; ++i)
614 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100615 // Prepend a ! to the command name to avoid the buffer name equals
616 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200617 if (i == 0)
618 vim_snprintf((char *)p, len, "!%s", cmd);
619 else
620 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
621 if (buflist_findname(p) == NULL)
622 {
623 vim_free(curbuf->b_ffname);
624 curbuf->b_ffname = p;
625 break;
626 }
627 }
628 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100629 vim_free(curbuf->b_sfname);
630 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200631 curbuf->b_fname = curbuf->b_ffname;
632
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100633 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
634
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200635 if (opt->jo_term_opencmd != NULL)
636 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
637
638 if (opt->jo_eof_chars != NULL)
639 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
640
641 set_string_option_direct((char_u *)"buftype", -1,
642 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200643 // Avoid that 'buftype' is reset when this buffer is entered.
644 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200645
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100646 // Mark the buffer as not modifiable. It can only be made modifiable after
647 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200648 curbuf->b_p_ma = FALSE;
649
Bram Moolenaarb936b792020-09-04 18:34:09 +0200650 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100651#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200652 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
653#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200654 setup_job_options(opt, term->tl_rows, term->tl_cols);
655
Bram Moolenaar13568252018-03-16 20:46:58 +0100656 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100657 return curbuf;
658
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100659#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100660 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100661 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100662 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100663 else if (argvar->v_type == VAR_STRING)
664 {
665 char_u *cmd = argvar->vval.v_string;
666
667 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
668 term->tl_command = vim_strsave(cmd);
669 }
670 else if (argvar->v_type == VAR_LIST
671 && argvar->vval.v_list != NULL
672 && argvar->vval.v_list->lv_len > 0)
673 {
674 garray_T ga;
675 listitem_T *item;
676
677 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200678 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100679 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100680 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100681 char_u *p;
682
683 if (s == NULL)
684 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100685 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100686 if (p == NULL)
687 break;
688 ga_concat(&ga, p);
689 vim_free(p);
690 ga_append(&ga, ' ');
691 }
692 if (item == NULL)
693 {
694 ga_append(&ga, NUL);
695 term->tl_command = ga.ga_data;
696 }
697 else
698 ga_clear(&ga);
699 }
700#endif
701
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100702 if (opt->jo_term_kill != NULL)
703 {
704 char_u *p = skiptowhite(opt->jo_term_kill);
705
706 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
707 }
708
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200709 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100710 {
711 char_u *p = skiptowhite(opt->jo_term_api);
712
713 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
714 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200715 else
716 term->tl_api = vim_strsave((char_u *)"Tapi_");
717
Bram Moolenaar83d47902020-03-26 20:34:00 +0100718 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
719 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
720
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100721#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100722 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
723 if (opt->jo_set2 & JO2_ANSI_COLORS)
724 {
725 term->tl_palette = ALLOC_MULT(long_u, 16);
726 if (term->tl_palette == NULL)
727 {
728 vim_free(term);
729 return NULL;
730 }
731 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
732 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100733#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100734
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100735 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100736 if (argv == NULL
737 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200738 && argvar->vval.v_string != NULL
739 && STRCMP(argvar->vval.v_string, "NONE") == 0)
740 res = create_pty_only(term, opt);
741 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200742 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200743
744 newbuf = curbuf;
745 if (res == OK)
746 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100747 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200748 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
749 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100750#ifdef FEAT_GUI
751 if (term->tl_system)
752 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100753 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100754 term->tl_toprow = msg_row + 1;
755 term->tl_dirty_row_end = 0;
756 }
757#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200758
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100759 // Make sure we don't get stuck on sending keys to the job, it leads to
760 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200761 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
762
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200763 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200764 {
765 --curbuf->b_nwindows;
766 curbuf = old_curbuf;
767 curwin->w_buffer = curbuf;
Christian Brabandt991657e2024-10-15 20:31:14 +0200768 curwin->w_cursor = save_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200769 ++curbuf->b_nwindows;
770 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000771 else if (vgetc_busy
772#ifdef FEAT_TIMERS
773 || timer_busy
774#endif
775 || input_busy)
776 {
777 char_u ignore[4];
778
779 // When waiting for input need to return and possibly end up in
780 // terminal_loop() instead.
781 ignore[0] = K_SPECIAL;
782 ignore[1] = KS_EXTRA;
783 ignore[2] = KE_IGNORE;
784 ignore[3] = NUL;
785 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
786 typebuf_was_filled = TRUE;
787 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788 }
789 else
790 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100791 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200792 return NULL;
793 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100794
Bram Moolenaar13568252018-03-16 20:46:58 +0100795 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200796 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
797 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200798 return newbuf;
799}
800
801/*
802 * ":terminal": open a terminal window and execute a job in it.
803 */
804 void
805ex_terminal(exarg_T *eap)
806{
807 typval_T argvar[2];
808 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100809 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200810 char_u *cmd;
811 char_u *tofree = NULL;
812
813 init_job_options(&opt);
814
815 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100816 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200817 {
818 char_u *p, *ep;
819
820 cmd += 2;
821 p = skiptowhite(cmd);
822 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200823 if (ep != NULL)
824 {
825 if (ep < p)
826 p = ep;
827 else
828 ep = NULL;
829 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200830
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200831 // Note: Keep this in sync with get_terminalopt_name.
832
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200833# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
834 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
835 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200836 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200837 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100838 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200839 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200840 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200841 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200842 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200843 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200844 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200845 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100846 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100847 else if (OPTARG_HAS("shell"))
848 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200849 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100850 {
851 opt.jo_set2 |= JO2_TERM_KILL;
852 opt.jo_term_kill = ep + 1;
853 p = skiptowhite(cmd);
854 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200855 else if (OPTARG_HAS("api"))
856 {
857 opt.jo_set2 |= JO2_TERM_API;
858 if (ep != NULL)
859 {
860 opt.jo_term_api = ep + 1;
861 p = skiptowhite(cmd);
862 }
863 else
864 opt.jo_term_api = NULL;
865 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100866 else if (OPTARG_HAS("rows") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200867 {
868 opt.jo_set2 |= JO2_TERM_ROWS;
869 opt.jo_term_rows = atoi((char *)ep + 1);
870 p = skiptowhite(cmd);
871 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100872 else if (OPTARG_HAS("cols") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200873 {
874 opt.jo_set2 |= JO2_TERM_COLS;
875 opt.jo_term_cols = atoi((char *)ep + 1);
876 p = skiptowhite(cmd);
877 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200878 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200879 {
880 char_u *buf = NULL;
881 char_u *keys;
882
Bram Moolenaar21109272020-01-30 16:27:20 +0100883 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200884 p = skiptowhite(cmd);
885 *p = NUL;
zeertzjq7e0bae02023-08-11 23:15:38 +0200886 keys = replace_termcodes(ep + 1, &buf, 0,
Bram Moolenaar459fd782019-10-13 16:43:39 +0200887 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200888 opt.jo_set2 |= JO2_EOF_CHARS;
889 opt.jo_eof_chars = vim_strsave(keys);
890 vim_free(buf);
891 *p = ' ';
892 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100893#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100894 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
895 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100896 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100897 int tty_type = NUL;
898
899 p = skiptowhite(cmd);
900 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
901 tty_type = 'w';
902 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
903 tty_type = 'c';
904 else
905 {
Bram Moolenaar50809a42023-05-20 16:39:07 +0100906 semsg(_(e_invalid_value_for_argument_str), "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100907 goto theend;
908 }
909 opt.jo_set2 |= JO2_TTY_TYPE;
910 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100911 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100912#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200913 else
914 {
915 if (*p)
916 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000917 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100918 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200919 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200920# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200921 cmd = skipwhite(p);
922 }
923 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100924 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100925 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200926 tofree = cmd = vim_strsave(p_sh);
927
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100928 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100929 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200930 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100931 }
932
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200933 if (eap->addr_count > 0)
934 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100935 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200936 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
937 opt.jo_io[PART_IN] = JIO_BUFFER;
938 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
939 opt.jo_in_top = eap->line1;
940 opt.jo_in_bot = eap->line2;
941 }
942
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100943 if (opt_shell && tofree == NULL)
944 {
945#ifdef UNIX
946 char **argv = NULL;
947 char_u *tofree1 = NULL;
948 char_u *tofree2 = NULL;
949
950 // :term ++shell command
951 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
952 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100953 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100954 vim_free(tofree1);
955 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100956 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100957#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100958# ifdef MSWIN
959 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
960 char_u *newcmd;
961
962 newcmd = alloc(cmdlen);
963 if (newcmd == NULL)
964 goto theend;
965 tofree = newcmd;
966 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
967 cmd = newcmd;
968# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000969 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100970 goto theend;
971# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100972#endif
973 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100974 argvar[0].v_type = VAR_STRING;
975 argvar[0].vval.v_string = cmd;
976 argvar[1].v_type = VAR_UNKNOWN;
977 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100978
979theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100980 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200981 vim_free(opt.jo_eof_chars);
982}
983
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200984 static char_u *
985get_terminalopt_name(expand_T *xp UNUSED, int idx)
986{
987 // Note: Keep this in sync with ex_terminal.
988 static char *(p_termopt_values[]) =
989 {
990 "close",
991 "noclose",
992 "open",
993 "curwin",
994 "hidden",
995 "norestore",
996 "shell",
997 "kill=",
998 "rows=",
999 "cols=",
1000 "eof=",
1001 "type=",
1002 "api=",
1003 };
1004
1005 if (idx < (int)ARRAY_LENGTH(p_termopt_values))
1006 return (char_u*)p_termopt_values[idx];
1007 return NULL;
1008}
1009
1010 static char_u *
1011get_termkill_name(expand_T *xp UNUSED, int idx)
1012{
1013 // These are platform-specific values used for job_stop(). They are defined
1014 // in each platform's mch_signal_job(). Just use a unified auto-complete
1015 // list for simplicity.
1016 static char *(p_termkill_values[]) =
1017 {
1018 "term",
1019 "hup",
1020 "quit",
1021 "int",
1022 "kill",
1023 "winch",
1024 };
1025
1026 if (idx < (int)ARRAY_LENGTH(p_termkill_values))
1027 return (char_u*)p_termkill_values[idx];
1028 return NULL;
1029}
1030
1031/*
1032 * Command-line expansion for :terminal [options]
1033 */
1034 int
1035expand_terminal_opt(
1036 char_u *pat,
1037 expand_T *xp,
1038 regmatch_T *rmp,
1039 char_u ***matches,
1040 int *numMatches)
1041{
1042 if (xp->xp_pattern > xp->xp_line && *(xp->xp_pattern-1) == '=')
1043 {
1044 char_u *(*cb)(expand_T *, int) = NULL;
1045
1046 char_u *name_end = xp->xp_pattern - 1;
1047 if (name_end - xp->xp_line >= 4
1048 && STRNCMP(name_end - 4, "kill", 4) == 0)
1049 cb = get_termkill_name;
1050
1051 if (cb != NULL)
1052 {
1053 return ExpandGeneric(
1054 pat,
1055 xp,
1056 rmp,
1057 matches,
1058 numMatches,
1059 cb,
1060 FALSE);
1061 }
1062 return FAIL;
1063 }
1064 return ExpandGeneric(
1065 pat,
1066 xp,
1067 rmp,
1068 matches,
1069 numMatches,
1070 get_terminalopt_name,
1071 FALSE);
1072}
1073
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001074#if defined(FEAT_SESSION) || defined(PROTO)
1075/*
1076 * Write a :terminal command to the session file to restore the terminal in
1077 * window "wp".
1078 * Return FAIL if writing fails.
1079 */
1080 int
Bram Moolenaar0e655112020-09-11 20:36:36 +02001081term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001082{
Bram Moolenaar0e655112020-09-11 20:36:36 +02001083 const int bufnr = wp->w_buffer->b_fnum;
1084 term_T *term = wp->w_buffer->b_term;
1085
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001086 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001087 {
1088 // There are multiple views into this terminal buffer. We don't want to
1089 // create the terminal multiple times. If it's the first time, create,
1090 // otherwise link to the first buffer.
1091 char id_as_str[NUMBUFLEN];
1092 hashitem_T *entry;
1093
1094 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
1095
1096 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
1097 if (!HASHITEM_EMPTY(entry))
1098 {
1099 // we've already opened this terminal buffer
1100 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
1101 return FAIL;
1102 return put_eol(fd);
1103 }
1104 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001105
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001106 // Create the terminal and run the command. This is not without
1107 // risk, but let's assume the user only creates a session when this
1108 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001109 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1110 term->tl_cols, term->tl_rows) < 0)
1111 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001112#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001113 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1114 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001115#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001116 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1117 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001118 if (put_eol(fd) != OK)
1119 return FAIL;
1120
1121 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1122 return FAIL;
1123
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001124 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001125 {
1126 char *hash_key = alloc(NUMBUFLEN);
1127
1128 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00001129 hash_add(terminal_bufs, (char_u *)hash_key, "terminal session");
Bram Moolenaar0e655112020-09-11 20:36:36 +02001130 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001131
1132 return put_eol(fd);
1133}
1134
1135/*
1136 * Return TRUE if "buf" has a terminal that should be restored.
1137 */
1138 int
1139term_should_restore(buf_T *buf)
1140{
1141 term_T *term = buf->b_term;
1142
1143 return term != NULL && (term->tl_command == NULL
1144 || STRCMP(term->tl_command, "NONE") != 0);
1145}
1146#endif
1147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001148/*
1149 * Free the scrollback buffer for "term".
1150 */
1151 static void
1152free_scrollback(term_T *term)
1153{
1154 int i;
1155
1156 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1157 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1158 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001159 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1160 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1161 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001162}
1163
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001164
1165// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001166static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001167
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001168/*
1169 * Free a terminal and everything it refers to.
1170 * Kills the job if there is one.
1171 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001172 * The actual terminal structure is freed later in free_unused_terminals(),
1173 * because callbacks may wipe out a buffer while the terminal is still
1174 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001175 */
1176 void
1177free_terminal(buf_T *buf)
1178{
1179 term_T *term = buf->b_term;
1180 term_T *tp;
1181
1182 if (term == NULL)
1183 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001184
1185 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001186 if (first_term == term)
1187 first_term = term->tl_next;
1188 else
1189 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1190 if (tp->tl_next == term)
1191 {
1192 tp->tl_next = term->tl_next;
1193 break;
1194 }
1195
1196 if (term->tl_job != NULL)
1197 {
1198 if (term->tl_job->jv_status != JOB_ENDED
1199 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001200 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001201 job_stop(term->tl_job, NULL, "kill");
1202 job_unref(term->tl_job);
1203 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001204 term->tl_next = terminals_to_free;
1205 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001206
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001207 buf->b_term = NULL;
1208 if (in_terminal_loop == term)
1209 in_terminal_loop = NULL;
1210}
1211
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001212 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00001213free_unused_terminals(void)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001214{
1215 while (terminals_to_free != NULL)
1216 {
1217 term_T *term = terminals_to_free;
1218
1219 terminals_to_free = term->tl_next;
1220
1221 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001222 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001223
1224 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001225 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001226 vim_free(term->tl_title);
1227#ifdef FEAT_SESSION
1228 vim_free(term->tl_command);
1229#endif
1230 vim_free(term->tl_kill);
1231 vim_free(term->tl_status_text);
1232 vim_free(term->tl_opencmd);
1233 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001234 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001235#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001236 if (term->tl_out_fd != NULL)
1237 fclose(term->tl_out_fd);
1238#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001239 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001240 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001241 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001242 vim_free(term);
1243 }
1244}
1245
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001246/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001247 * Get the part that is connected to the tty. Normally this is PART_IN, but
1248 * when writing buffer lines to the job it can be another. This makes it
1249 * possible to do "1,5term vim -".
1250 */
1251 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001252get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001253{
1254#ifdef UNIX
1255 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1256 int i;
1257
1258 for (i = 0; i < 3; ++i)
1259 {
1260 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1261
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001262 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001263 return parts[i];
1264 }
1265#endif
1266 return PART_IN;
1267}
1268
1269/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001270 * Read any vterm output and send it on the channel.
1271 */
1272 static void
1273term_forward_output(term_T *term)
1274{
1275 VTerm *vterm = term->tl_vterm;
1276 char buf[KEY_BUF_LEN];
1277 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1278
1279 if (curlen > 0)
1280 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1281 (char_u *)buf, (int)curlen, NULL);
1282}
1283
1284/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001285 * Write job output "msg[len]" to the vterm.
1286 */
1287 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001288term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001289{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001290 char_u *msg = msg_arg;
1291 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001292 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001293 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001294 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1295
1296 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1297 // the end.
1298 if (len > limit)
1299 {
1300 char_u *p = msg + len - limit;
1301
1302 p -= (*mb_head_off)(msg, p);
1303 len -= p - msg;
1304 msg = p;
1305 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001306
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001307 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001308
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001309 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001310 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001311 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001312
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001313 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001314 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1315}
1316
1317 static void
Bram Moolenaar58806c12023-04-29 14:26:02 +01001318position_cursor(win_T *wp, VTermPos *pos)
1319{
1320 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1321 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1322#ifdef FEAT_PROP_POPUP
1323 if (popup_is_popup(wp))
1324 {
1325 wp->w_wrow += popup_top_extra(wp);
1326 wp->w_wcol += popup_left_extra(wp);
1327 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
1328 }
1329 else
1330 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
1331#endif
1332 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1333}
1334
1335 static void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001336update_cursor(term_T *term, int redraw)
1337{
1338 if (term->tl_normal_mode)
1339 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001340#ifdef FEAT_GUI
1341 if (term->tl_system)
1342 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1343 term->tl_cursor_pos.col);
1344 else
1345#endif
Bram Moolenaar58806c12023-04-29 14:26:02 +01001346 if (!term_job_running(term))
1347 // avoid the cursor positioned below the last used line
Bram Moolenaar13568252018-03-16 20:46:58 +01001348 setcursor();
Bram Moolenaar58806c12023-04-29 14:26:02 +01001349 else
1350 {
1351 // do not use the window cursor position
1352 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1353 windgoto(W_WINROW(curwin) + curwin->w_wrow,
1354 curwin->w_wincol + curwin->w_wcol);
1355 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001356 if (redraw)
1357 {
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001358 aco_save_T aco;
1359
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001360 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1361 cursor_on();
1362 out_flush();
1363#ifdef FEAT_GUI
1364 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001365 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001366 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001367 gui_mch_flush();
1368 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001369#endif
Bram Moolenaar24fe33a2022-11-24 00:09:02 +00001370 // Make sure an invoked autocmd doesn't delete the buffer (and the
1371 // terminal) under our fingers.
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001372 ++term->tl_buffer->b_locked;
1373
1374 // save and restore curwin and curbuf, in case the autocmd changes them
1375 aucmd_prepbuf(&aco, curbuf);
1376 apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, FALSE, term->tl_buffer);
1377 aucmd_restbuf(&aco);
1378
1379 --term->tl_buffer->b_locked;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001380 }
1381}
1382
1383/*
1384 * Invoked when "msg" output from a job was received. Write it to the terminal
1385 * of "buffer".
1386 */
1387 void
1388write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1389{
1390 size_t len = STRLEN(msg);
1391 term_T *term = buffer->b_term;
1392
Bram Moolenaar4f974752019-02-17 17:44:42 +01001393#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001394 // Win32: Cannot redirect output of the job, intercept it here and write to
1395 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001396 if (term->tl_out_fd != NULL)
1397 {
1398 ch_log(channel, "Writing %d bytes to output file", (int)len);
1399 fwrite(msg, len, 1, term->tl_out_fd);
1400 return;
1401 }
1402#endif
1403
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001404 if (term->tl_vterm == NULL)
1405 {
1406 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1407 return;
1408 }
1409 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001410 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001411 term_write_job_output(term, msg, len);
1412
Bram Moolenaar13568252018-03-16 20:46:58 +01001413#ifdef FEAT_GUI
1414 if (term->tl_system)
1415 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001416 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001417 update_system_term(term);
1418 update_cursor(term, TRUE);
1419 }
1420 else
1421#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001422 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1423 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001424 if (!term->tl_normal_mode)
1425 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001426 // Don't use update_screen() when editing the command line, it gets
1427 // cleared.
1428 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001429 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001430 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001431 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001432 update_screen(UPD_VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001433 // update_screen() can be slow, check the terminal wasn't closed
1434 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001435 if (buffer == curbuf && curbuf->b_term != NULL)
1436 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001437 }
1438 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001439 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001440 }
1441}
1442
1443/*
1444 * Send a mouse position and click to the vterm
1445 */
1446 static int
1447term_send_mouse(VTerm *vterm, int button, int pressed)
1448{
1449 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001450 int row = mouse_row - W_WINROW(curwin);
1451 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001452
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001453#ifdef FEAT_PROP_POPUP
1454 if (popup_is_popup(curwin))
1455 {
1456 row -= popup_top_extra(curwin);
1457 col -= popup_left_extra(curwin);
1458 }
1459#endif
1460 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001461 if (button != 0)
1462 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001463 return TRUE;
1464}
1465
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001466static int enter_mouse_col = -1;
1467static int enter_mouse_row = -1;
1468
1469/*
1470 * Handle a mouse click, drag or release.
1471 * Return TRUE when a mouse event is sent to the terminal.
1472 */
1473 static int
1474term_mouse_click(VTerm *vterm, int key)
1475{
1476#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001477 // For modeless selection mouse drag and release events are ignored, unless
1478 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001479 static int ignore_drag_release = TRUE;
1480 VTermMouseState mouse_state;
1481
1482 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1483 if (mouse_state.flags == 0)
1484 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001485 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001486 switch (key)
1487 {
1488 case K_LEFTDRAG:
1489 case K_LEFTRELEASE:
1490 case K_RIGHTDRAG:
1491 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001492 // Ignore drag and release events when the button-down wasn't
1493 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001494 if (ignore_drag_release)
1495 {
1496 int save_mouse_col, save_mouse_row;
1497
1498 if (enter_mouse_col < 0)
1499 break;
1500
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001501 // mouse click in the window gave us focus, handle that
1502 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001503 save_mouse_col = mouse_col;
1504 save_mouse_row = mouse_row;
1505 mouse_col = enter_mouse_col;
1506 mouse_row = enter_mouse_row;
1507 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1508 mouse_col = save_mouse_col;
1509 mouse_row = save_mouse_row;
1510 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001511 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001512 case K_LEFTMOUSE:
1513 case K_RIGHTMOUSE:
1514 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1515 ignore_drag_release = TRUE;
1516 else
1517 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001518 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001519 if (clip_star.available)
1520 {
1521 int button, is_click, is_drag;
1522
1523 button = get_mouse_button(KEY2TERMCAP1(key),
1524 &is_click, &is_drag);
1525 if (mouse_model_popup() && button == MOUSE_LEFT
1526 && (mod_mask & MOD_MASK_SHIFT))
1527 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001528 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001529 button = MOUSE_RIGHT;
1530 mod_mask &= ~MOD_MASK_SHIFT;
1531 }
1532 clip_modeless(button, is_click, is_drag);
1533 }
1534 break;
1535
1536 case K_MIDDLEMOUSE:
1537 if (clip_star.available)
1538 insert_reg('*', TRUE);
1539 break;
1540 }
1541 enter_mouse_col = -1;
1542 return FALSE;
1543 }
1544#endif
1545 enter_mouse_col = -1;
1546
1547 switch (key)
1548 {
1549 case K_LEFTMOUSE:
1550 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1551 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1552 case K_LEFTRELEASE:
1553 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1554 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1555 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1556 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1557 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1558 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1559 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1560 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1561 }
1562 return TRUE;
1563}
1564
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001565/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001566 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1567 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001568 * Return the number of bytes in "buf".
1569 */
1570 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001571term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001572{
1573 VTerm *vterm = term->tl_vterm;
1574 VTermKey key = VTERM_KEY_NONE;
1575 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001576 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001577
1578 switch (c)
1579 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001580 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001581
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001582 // don't use VTERM_KEY_BACKSPACE, it always
1583 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001584 case K_BS: c = term_backspace_char; break;
1585
1586 case ESC: key = VTERM_KEY_ESCAPE; break;
1587 case K_DEL: key = VTERM_KEY_DEL; break;
1588 case K_DOWN: key = VTERM_KEY_DOWN; break;
1589 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1590 key = VTERM_KEY_DOWN; break;
1591 case K_END: key = VTERM_KEY_END; break;
1592 case K_S_END: mod = VTERM_MOD_SHIFT;
1593 key = VTERM_KEY_END; break;
1594 case K_C_END: mod = VTERM_MOD_CTRL;
1595 key = VTERM_KEY_END; break;
1596 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1597 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1598 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1599 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1600 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1601 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1602 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1603 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1604 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1605 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1606 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1607 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1608 case K_HOME: key = VTERM_KEY_HOME; break;
1609 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1610 key = VTERM_KEY_HOME; break;
1611 case K_C_HOME: mod = VTERM_MOD_CTRL;
1612 key = VTERM_KEY_HOME; break;
1613 case K_INS: key = VTERM_KEY_INS; break;
1614 case K_K0: key = VTERM_KEY_KP_0; break;
1615 case K_K1: key = VTERM_KEY_KP_1; break;
1616 case K_K2: key = VTERM_KEY_KP_2; break;
1617 case K_K3: key = VTERM_KEY_KP_3; break;
1618 case K_K4: key = VTERM_KEY_KP_4; break;
1619 case K_K5: key = VTERM_KEY_KP_5; break;
1620 case K_K6: key = VTERM_KEY_KP_6; break;
1621 case K_K7: key = VTERM_KEY_KP_7; break;
1622 case K_K8: key = VTERM_KEY_KP_8; break;
1623 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001624 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001625 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001626 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001628 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1629 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001630 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1631 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001632 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1633 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001634 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1635 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1636 case K_LEFT: key = VTERM_KEY_LEFT; break;
1637 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1638 key = VTERM_KEY_LEFT; break;
1639 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1640 key = VTERM_KEY_LEFT; break;
1641 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1642 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1643 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1644 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1645 key = VTERM_KEY_RIGHT; break;
1646 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1647 key = VTERM_KEY_RIGHT; break;
1648 case K_UP: key = VTERM_KEY_UP; break;
1649 case K_S_UP: mod = VTERM_MOD_SHIFT;
1650 key = VTERM_KEY_UP; break;
1651 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001652 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1653 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001654
Bram Moolenaara42ad572017-11-16 13:08:04 +01001655 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1656 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001657 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1658 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001659
1660 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001661 case K_LEFTMOUSE_NM:
1662 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001663 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001664 case K_LEFTRELEASE_NM:
1665 case K_MOUSEMOVE:
1666 case K_MIDDLEMOUSE:
1667 case K_MIDDLEDRAG:
1668 case K_MIDDLERELEASE:
1669 case K_RIGHTMOUSE:
1670 case K_RIGHTDRAG:
1671 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1672 return 0;
1673 other = TRUE;
1674 break;
1675
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001676 case K_X1MOUSE: /* TODO */ return 0;
1677 case K_X1DRAG: /* TODO */ return 0;
1678 case K_X1RELEASE: /* TODO */ return 0;
1679 case K_X2MOUSE: /* TODO */ return 0;
1680 case K_X2DRAG: /* TODO */ return 0;
1681 case K_X2RELEASE: /* TODO */ return 0;
1682
1683 case K_IGNORE: return 0;
1684 case K_NOP: return 0;
1685 case K_UNDO: return 0;
1686 case K_HELP: return 0;
1687 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1688 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1689 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1690 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1691 case K_SELECT: return 0;
1692#ifdef FEAT_GUI
1693 case K_VER_SCROLLBAR: return 0;
1694 case K_HOR_SCROLLBAR: return 0;
1695#endif
1696#ifdef FEAT_GUI_TABLINE
1697 case K_TABLINE: return 0;
1698 case K_TABMENU: return 0;
1699#endif
1700#ifdef FEAT_NETBEANS_INTG
1701 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1702#endif
1703#ifdef FEAT_DND
1704 case K_DROP: return 0;
1705#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001706 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001707 case K_PS: vterm_keyboard_start_paste(vterm);
1708 other = TRUE;
1709 break;
1710 case K_PE: vterm_keyboard_end_paste(vterm);
1711 other = TRUE;
1712 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001713 }
1714
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001715 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001716 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001717 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001718 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001719 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001720 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001721 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001722
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001723 // Ctrl-Shift-i may have the key "I" instead of "i", but for the kitty
1724 // keyboard protocol should use "i". Applies to all ascii letters.
1725 if (ASCII_ISUPPER(c)
Bram Moolenaarebed1b02022-11-24 14:05:19 +00001726 && vterm_is_kitty_keyboard(vterm)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001727 && mod == (VTERM_MOD_CTRL | VTERM_MOD_SHIFT))
1728 c = TOLOWER_ASC(c);
1729
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001730 /*
1731 * Convert special keys to vterm keys:
1732 * - Write keys to vterm: vterm_keyboard_key()
1733 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 */
1735 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001736 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001737 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001738 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001739 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001740 vterm_keyboard_unichar(vterm, c, mod);
1741
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001742 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001743 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1744}
1745
1746/*
1747 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001748 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001749 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001750 */
1751 static int
1752term_job_running_check(term_T *term, int check_job_status)
1753{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001754 // Also consider the job finished when the channel is closed, to avoid a
1755 // race condition when updating the title.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001756 if (term == NULL
1757 || term->tl_job == NULL
1758 || !channel_is_open(term->tl_job->jv_channel))
1759 return FALSE;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001760
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001761 job_T *job = term->tl_job;
1762
1763 // Careful: Checking the job status may invoke callbacks, which close
1764 // the buffer and terminate "term". However, "job" will not be freed
1765 // yet.
1766 if (check_job_status)
1767 job_status(job);
1768 return (job->jv_status == JOB_STARTED
1769 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001770}
1771
1772/*
1773 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001774 */
1775 int
1776term_job_running(term_T *term)
1777{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001778 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001779}
1780
1781/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001782 * Return TRUE if the job for "term" is still running, ignoring the job was
1783 * "NONE".
1784 */
1785 int
1786term_job_running_not_none(term_T *term)
1787{
1788 return term_job_running(term) && !term_none_open(term);
1789}
1790
1791/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001792 * Return TRUE if "term" has an active channel and used ":term NONE".
1793 */
1794 int
1795term_none_open(term_T *term)
1796{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001797 // Also consider the job finished when the channel is closed, to avoid a
1798 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001799 return term != NULL
1800 && term->tl_job != NULL
1801 && channel_is_open(term->tl_job->jv_channel)
1802 && term->tl_job->jv_channel->ch_keep_open;
1803}
1804
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001805//
1806// Used to confirm whether we would like to kill a terminal.
1807// Return OK when the user confirms to kill it.
1808// Return FAIL if the user selects otherwise.
1809//
1810 int
1811term_confirm_stop(buf_T *buf)
1812{
1813 char_u buff[DIALOG_MSG_SIZE];
1814 int ret;
1815
1816 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1817 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1818 if (ret == VIM_YES)
1819 return OK;
1820 else
1821 return FAIL;
1822}
1823
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001825 * Used when exiting: kill the job in "buf" if so desired.
1826 * Return OK when the job finished.
1827 * Return FAIL when the job is still running.
1828 */
1829 int
1830term_try_stop_job(buf_T *buf)
1831{
1832 int count;
1833 char *how = (char *)buf->b_term->tl_kill;
1834
1835#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001836 if ((how == NULL || *how == NUL)
1837 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001838 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001839 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001840 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001841 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001842 return FAIL;
1843 }
1844#endif
1845 if (how == NULL || *how == NUL)
1846 return FAIL;
1847
1848 job_stop(buf->b_term->tl_job, NULL, how);
1849
Bram Moolenaar9172d232019-01-29 23:06:54 +01001850 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001851 for (count = 0; count < 100; ++count)
1852 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001853 job_T *job;
1854
1855 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001856 if (!buf_valid(buf)
1857 || buf->b_term == NULL
1858 || buf->b_term->tl_job == NULL)
1859 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001860 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001861
Bram Moolenaar9172d232019-01-29 23:06:54 +01001862 // Call job_status() to update jv_status. It may cause the job to be
1863 // cleaned up but it won't be freed.
1864 job_status(job);
1865 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001866 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001867
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001868 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001869 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001870 }
1871 return FAIL;
1872}
1873
1874/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875 * Add the last line of the scrollback buffer to the buffer in the window.
1876 */
1877 static void
1878add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1879{
1880 buf_T *buf = term->tl_buffer;
1881 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1882 linenr_T lnum = buf->b_ml.ml_line_count;
1883
Bram Moolenaar4f974752019-02-17 17:44:42 +01001884#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001885 if (!enc_utf8 && enc_codepage > 0)
1886 {
1887 WCHAR *ret = NULL;
1888 int length = 0;
1889
1890 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1891 &ret, &length);
1892 if (ret != NULL)
1893 {
1894 WideCharToMultiByte_alloc(enc_codepage, 0,
1895 ret, length, (char **)&text, &len, 0, 0);
1896 vim_free(ret);
1897 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1898 vim_free(text);
1899 }
1900 }
1901 else
1902#endif
1903 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1904 if (empty)
1905 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001906 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001907 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001908 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001909 curbuf = curwin->w_buffer;
1910 }
1911}
1912
1913 static void
1914cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1915{
1916 attr->width = cell->width;
1917 attr->attrs = cell->attrs;
1918 attr->fg = cell->fg;
1919 attr->bg = cell->bg;
1920}
1921
1922 static int
1923equal_celattr(cellattr_T *a, cellattr_T *b)
1924{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001925 // We only compare the RGB colors, ignoring the ANSI index and type.
1926 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001927 return a->fg.red == b->fg.red
1928 && a->fg.green == b->fg.green
1929 && a->fg.blue == b->fg.blue
1930 && a->bg.red == b->bg.red
1931 && a->bg.green == b->bg.green
1932 && a->bg.blue == b->bg.blue;
1933}
1934
Bram Moolenaard96ff162018-02-18 22:13:29 +01001935/*
1936 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1937 * line at this position. Otherwise at the end.
1938 */
1939 static int
1940add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1941{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001942 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
1943 return FALSE;
1944
1945 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1946 + term->tl_scrollback.ga_len;
1947
1948 if (lnum > 0)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001949 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001950 int i;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001951
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001952 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001953 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001954 *line = *(line - 1);
1955 --line;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001956 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01001957 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001958 line->sb_cols = 0;
1959 line->sb_cells = NULL;
1960 line->sb_fill_attr = *fill_attr;
1961 ++term->tl_scrollback.ga_len;
1962 return OK;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001963}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001964
1965/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001966 * Remove the terminal contents from the scrollback and the buffer.
1967 * Used before adding a new scrollback line or updating the buffer for lines
1968 * displayed in the terminal.
1969 */
1970 static void
1971cleanup_scrollback(term_T *term)
1972{
1973 sb_line_T *line;
1974 garray_T *gap;
1975
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001976 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001977 gap = &term->tl_scrollback;
1978 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1979 && gap->ga_len > 0)
1980 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001981 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001982 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1983 vim_free(line->sb_cells);
1984 --gap->ga_len;
1985 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001986 curbuf = curwin->w_buffer;
1987 if (curbuf == term->tl_buffer)
1988 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001989}
1990
1991/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001992 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993 */
1994 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001995update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001996{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001997 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001998 int len;
1999 int lines_skipped = 0;
2000 VTermPos pos;
2001 VTermScreenCell cell;
2002 cellattr_T fill_attr, new_fill_attr;
2003 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002004
2005 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
2006 "Adding terminal window snapshot to buffer");
2007
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002008 // First remove the lines that were appended before, they might be
2009 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002010 cleanup_scrollback(term);
2011
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002012 screen = vterm_obtain_screen(term->tl_vterm);
2013 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002014 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
2015 {
2016 len = 0;
2017 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
2018 if (vterm_screen_get_cell(screen, pos, &cell) != 0
2019 && cell.chars[0] != NUL)
2020 {
2021 len = pos.col + 1;
2022 new_fill_attr = term->tl_default_color;
2023 }
2024 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002025 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002026 cell2cellattr(&cell, &new_fill_attr);
2027
2028 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
2029 ++lines_skipped;
2030 else
2031 {
2032 while (lines_skipped > 0)
2033 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002034 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002035 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002036 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002037 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002038 }
2039
2040 if (len == 0)
2041 p = NULL;
2042 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002043 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002044 if ((p != NULL || len == 0)
2045 && ga_grow(&term->tl_scrollback, 1) == OK)
2046 {
2047 garray_T ga;
2048 int width;
2049 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
2050 + term->tl_scrollback.ga_len;
2051
2052 ga_init2(&ga, 1, 100);
2053 for (pos.col = 0; pos.col < len; pos.col += width)
2054 {
2055 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2056 {
2057 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02002058 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002059 if (ga_grow(&ga, 1) == OK)
2060 ga.ga_len += utf_char2bytes(' ',
2061 (char_u *)ga.ga_data + ga.ga_len);
2062 }
2063 else
2064 {
2065 width = cell.width;
2066
2067 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01002068 if (width == 2)
2069 // second cell of double-width character has the
2070 // same attributes.
2071 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002072
Bram Moolenaara79fd562018-12-20 20:47:32 +01002073 // Each character can be up to 6 bytes.
2074 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002075 {
2076 int i;
2077 int c;
2078
2079 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
2080 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2081 (char_u *)ga.ga_data + ga.ga_len);
2082 }
2083 }
2084 }
2085 line->sb_cols = len;
2086 line->sb_cells = p;
2087 line->sb_fill_attr = new_fill_attr;
2088 fill_attr = new_fill_attr;
2089 ++term->tl_scrollback.ga_len;
2090
2091 if (ga_grow(&ga, 1) == FAIL)
2092 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2093 else
2094 {
2095 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2096 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2097 }
2098 ga_clear(&ga);
2099 }
2100 else
2101 vim_free(p);
2102 }
2103 }
2104
Bram Moolenaarf3aea592018-11-11 22:18:21 +01002105 // Add trailing empty lines.
2106 for (pos.row = term->tl_scrollback.ga_len;
2107 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
2108 ++pos.row)
2109 {
2110 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
2111 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2112 }
2113
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002114 term->tl_dirty_snapshot = FALSE;
2115#ifdef FEAT_TIMERS
2116 term->tl_timer_set = FALSE;
2117#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002118}
2119
2120/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002121 * Loop over all windows in the current tab, and also curwin, which is not
2122 * encountered when using a terminal in a popup window.
2123 * Return TRUE if "*wp" was set to the next window.
2124 */
2125 static int
2126for_all_windows_and_curwin(win_T **wp, int *did_curwin)
2127{
2128 if (*wp == NULL)
2129 *wp = firstwin;
2130 else if ((*wp)->w_next != NULL)
2131 *wp = (*wp)->w_next;
2132 else if (!*did_curwin)
2133 *wp = curwin;
2134 else
2135 return FALSE;
2136 if (*wp == curwin)
2137 *did_curwin = TRUE;
2138 return TRUE;
2139}
2140
2141/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002142 * If needed, add the current lines of the terminal to scrollback and to the
2143 * buffer. Called after the job has ended and when switching to
2144 * Terminal-Normal mode.
2145 * When "redraw" is TRUE redraw the windows that show the terminal.
2146 */
2147 static void
2148may_move_terminal_to_buffer(term_T *term, int redraw)
2149{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002150 if (term->tl_vterm == NULL)
2151 return;
2152
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002153 // Update the snapshot only if something changes or the buffer does not
2154 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002155 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2156 <= term->tl_scrollback_scrolled)
2157 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002158
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002159 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002160 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2161 &term->tl_default_color.fg, &term->tl_default_color.bg);
2162
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002163 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002164 {
2165 win_T *wp = NULL;
2166 int did_curwin = FALSE;
2167
2168 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002169 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002170 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002171 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002172 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2173 wp->w_cursor.col = 0;
2174 wp->w_valid = 0;
2175 if (wp->w_cursor.lnum >= wp->w_height)
2176 {
2177 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002178
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002179 if (wp->w_topline < min_topline)
2180 wp->w_topline = min_topline;
2181 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002182 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002183 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002184 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002185 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002186}
2187
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002188#if defined(FEAT_TIMERS) || defined(PROTO)
2189/*
2190 * Check if any terminal timer expired. If so, copy text from the terminal to
2191 * the buffer.
2192 * Return the time until the next timer will expire.
2193 */
2194 int
2195term_check_timers(int next_due_arg, proftime_T *now)
2196{
2197 term_T *term;
2198 int next_due = next_due_arg;
2199
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002200 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002201 {
2202 if (term->tl_timer_set && !term->tl_normal_mode)
2203 {
2204 long this_due = proftime_time_left(&term->tl_timer_due, now);
2205
2206 if (this_due <= 1)
2207 {
2208 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002209 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002210 }
2211 else if (next_due == -1 || next_due > this_due)
2212 next_due = this_due;
2213 }
2214 }
2215
2216 return next_due;
2217}
2218#endif
2219
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002220/*
2221 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2222 * otherwise end it.
2223 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002224 static void
2225set_terminal_mode(term_T *term, int normal_mode)
2226{
2227 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002228 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002229 if (!normal_mode)
2230 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002231 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002232 if (term->tl_buffer == curbuf)
2233 maketitle();
2234}
2235
2236/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002237 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002238 * Move the vterm contents into the scrollback buffer and free the vterm.
2239 */
2240 static void
2241cleanup_vterm(term_T *term)
2242{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002243 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002244 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002245 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002246 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002247}
2248
2249/*
2250 * Switch from Terminal-Job mode to Terminal-Normal mode.
2251 * Suspends updating the terminal window.
2252 */
2253 static void
2254term_enter_normal_mode(void)
2255{
2256 term_T *term = curbuf->b_term;
2257
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002258 set_terminal_mode(term, TRUE);
2259
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002260 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002261 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002263 // Move the window cursor to the position of the cursor in the
2264 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002265 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2266 + term->tl_cursor_pos.row + 1;
2267 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002268 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2269 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002270 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002271
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002272 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002273 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2274}
2275
2276/*
2277 * Returns TRUE if the current window contains a terminal and we are in
2278 * Terminal-Normal mode.
2279 */
2280 int
2281term_in_normal_mode(void)
2282{
2283 term_T *term = curbuf->b_term;
2284
2285 return term != NULL && term->tl_normal_mode;
2286}
2287
2288/*
2289 * Switch from Terminal-Normal mode to Terminal-Job mode.
2290 * Restores updating the terminal window.
2291 */
2292 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002293term_enter_job_mode(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002294{
2295 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002296
2297 set_terminal_mode(term, FALSE);
2298
2299 if (term->tl_channel_closed)
2300 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002301 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002302#ifdef FEAT_PROP_POPUP
2303 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002304 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002305#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002306}
2307
2308/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002309 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2310 * modifiers into a basic key. However, we may only find out after calling
2311 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2312 * "no_reduce_keys" before using it.
2313 */
2314typedef enum {
2315 NRKS_NONE, // initial value
2316 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2317 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2318 // check_no_reduce_keys(), must be decremented.
2319} reduce_key_state_T;
2320
2321static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2322
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002323/*
2324 * Return TRUE if the term is using modifyOtherKeys level 2 or the kitty
2325 * keyboard protocol.
2326 */
2327 static int
2328vterm_using_key_protocol(void)
2329{
2330 return curbuf->b_term != NULL
2331 && curbuf->b_term->tl_vterm != NULL
2332 && (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm)
2333 || vterm_is_kitty_keyboard(curbuf->b_term->tl_vterm));
2334}
2335
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002336 void
2337check_no_reduce_keys(void)
2338{
2339 if (no_reduce_key_state != NRKS_CHECK
2340 || no_reduce_keys >= 1
2341 || curbuf->b_term == NULL
2342 || curbuf->b_term->tl_vterm == NULL)
2343 return;
2344
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002345 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002346 {
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002347 // "modify_other_keys" or kitty keyboard protocol was enabled while
2348 // waiting.
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002349 no_reduce_key_state = NRKS_SET;
2350 ++no_reduce_keys;
2351 }
2352}
2353
2354/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002355 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002356 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002357 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358 */
2359 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002360term_vgetc(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002361{
2362 int c;
2363 int save_State = State;
2364
Bram Moolenaar24959102022-05-07 20:01:16 +01002365 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002366 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002367#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002368 ctrl_break_was_pressed = FALSE;
2369#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002370
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002371 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002372 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002373 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002374 no_reduce_key_state = NRKS_SET;
2375 }
2376 else
2377 {
2378 no_reduce_key_state = NRKS_CHECK;
2379 }
2380
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002381 c = vgetc();
2382 got_int = FALSE;
2383 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002384
2385 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002386 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002387 no_reduce_key_state = NRKS_NONE;
2388
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002389 return c;
2390}
2391
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002392static int mouse_was_outside = FALSE;
2393
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002394/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002395 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002396 * Return FAIL when the key needs to be handled in Normal mode.
2397 * Return OK when the key was dropped or sent to the terminal.
2398 */
2399 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002400send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002401{
2402 char msg[KEY_BUF_LEN];
2403 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002404 int dragging_outside = FALSE;
2405
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002406 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002407 switch (c)
2408 {
2409 case NUL:
2410 case K_ZERO:
2411 if (typed)
2412 stuffcharReadbuff(c);
2413 return FAIL;
2414
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002415 case K_TABLINE:
2416 stuffcharReadbuff(c);
2417 return FAIL;
2418
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002419 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002420 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002421 return FAIL;
2422
2423 case K_LEFTDRAG:
2424 case K_MIDDLEDRAG:
2425 case K_RIGHTDRAG:
2426 case K_X1DRAG:
2427 case K_X2DRAG:
2428 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002429 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002430 case K_LEFTMOUSE:
2431 case K_LEFTMOUSE_NM:
2432 case K_LEFTRELEASE:
2433 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002434 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002435 case K_MIDDLEMOUSE:
2436 case K_MIDDLERELEASE:
2437 case K_RIGHTMOUSE:
2438 case K_RIGHTRELEASE:
2439 case K_X1MOUSE:
2440 case K_X1RELEASE:
2441 case K_X2MOUSE:
2442 case K_X2RELEASE:
2443
2444 case K_MOUSEUP:
2445 case K_MOUSEDOWN:
2446 case K_MOUSELEFT:
2447 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002448 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002449 int row = mouse_row;
2450 int col = mouse_col;
2451
2452#ifdef FEAT_PROP_POPUP
2453 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002454 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002455 row -= popup_top_extra(curwin);
2456 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002457 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002458#endif
2459 if (row < W_WINROW(curwin)
2460 || row >= (W_WINROW(curwin) + curwin->w_height)
2461 || col < curwin->w_wincol
2462 || col >= W_ENDCOL(curwin)
2463 || dragging_outside)
2464 {
2465 // click or scroll outside the current window or on status
2466 // line or vertical separator
2467 if (typed)
2468 {
2469 stuffcharReadbuff(c);
2470 mouse_was_outside = TRUE;
2471 }
2472 return FAIL;
2473 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002474 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002475 break;
2476
2477 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002478 case K_SCRIPT_COMMAND:
2479 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002480 }
2481 if (typed)
2482 mouse_was_outside = FALSE;
2483
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002484 // Convert the typed key to a sequence of bytes for the job.
2485 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002486 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002487 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002488 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2489 (char_u *)msg, (int)len, NULL);
2490
2491 return OK;
2492}
2493
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002494/*
2495 * Handle CTRL-W "": send register contents to the job.
2496 */
2497 static void
2498term_paste_register(int prev_c UNUSED)
2499{
2500 int c;
2501 list_T *l;
2502 listitem_T *item;
2503 long reglen = 0;
2504 int type;
2505
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002506 if (add_to_showcmd(prev_c))
2507 if (add_to_showcmd('"'))
2508 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002509
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002510 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002511 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002512
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002513 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002514 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002515 return;
2516
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002517 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002518 if (c == '=' && get_expr_register() != '=')
2519 return;
2520 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002521 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002522 return;
2523
2524 l = (list_T *)get_reg_contents(c, GREG_LIST);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002525 if (l == NULL)
2526 return;
2527
2528 type = get_reg_type(c, &reglen);
2529 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002530 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002531 char_u *s = tv_get_string(&item->li_tv);
2532#ifdef MSWIN
2533 char_u *tmp = s;
2534
2535 if (!enc_utf8 && enc_codepage > 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002536 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002537 WCHAR *ret = NULL;
2538 int length = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002540 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2541 (int)STRLEN(s), &ret, &length);
2542 if (ret != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002543 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002544 WideCharToMultiByte_alloc(CP_UTF8, 0,
2545 ret, length, (char **)&s, &length, 0, 0);
2546 vim_free(ret);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002547 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002548 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002549#endif
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002550 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2551 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002552#ifdef MSWIN
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002553 if (tmp != s)
2554 vim_free(s);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002555#endif
2556
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002557 if (item->li_next != NULL || type == MLINE)
2558 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2559 (char_u *)"\r", 1, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002560 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002561 list_free(l);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002562}
2563
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002564/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002565 * Return TRUE when waiting for a character in the terminal, the cursor of the
2566 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002567 */
2568 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002569terminal_is_active(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002570{
2571 return in_terminal_loop != NULL;
2572}
2573
Bram Moolenaar83d47902020-03-26 20:34:00 +01002574/*
dundargocc57b5bc2022-11-02 13:30:51 +00002575 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002576 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002577 static int
2578term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002579{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002580 char_u *name;
2581
2582 if (wp != NULL && *wp->w_p_wcr != NUL)
2583 name = wp->w_p_wcr;
2584 else if (term->tl_highlight_name != NULL)
2585 name = term->tl_highlight_name;
2586 else
2587 name = (char_u*)"Terminal";
2588
2589 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002590}
2591
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002592#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 cursorentry_T *
2594term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2595{
2596 term_T *term = in_terminal_loop;
2597 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002598 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002599 guicolor_T term_fg = INVALCOLOR;
2600 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002601
Bram Moolenaara80faa82020-04-12 19:37:17 +02002602 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002603 entry.shape = entry.mshape =
2604 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2605 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2606 SHAPE_BLOCK;
2607 entry.percentage = 20;
2608 if (term->tl_cursor_blink)
2609 {
2610 entry.blinkwait = 700;
2611 entry.blinkon = 400;
2612 entry.blinkoff = 250;
2613 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002614
Bram Moolenaar83d47902020-03-26 20:34:00 +01002615 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002616 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002617 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002618 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002619 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002620 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002621 else
2622 *fg = gui.back_pixel;
2623
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002624 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002625 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002626 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002627 *bg = term_fg;
2628 else
2629 *bg = gui.norm_pixel;
2630 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002631 else
2632 *bg = color_name2handle(term->tl_cursor_color);
2633 entry.name = "n";
2634 entry.used_for = SHAPE_CURSOR;
2635
2636 return &entry;
2637}
2638#endif
2639
Bram Moolenaard317b382018-02-08 22:33:31 +01002640 static void
2641may_output_cursor_props(void)
2642{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002643 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002644 || last_set_cursor_shape != desired_cursor_shape
2645 || last_set_cursor_blink != desired_cursor_blink)
2646 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002647 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002648 last_set_cursor_shape = desired_cursor_shape;
2649 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002650 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002651 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002652 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002653 ui_cursor_shape_forced(TRUE);
2654 else
2655 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2656 }
2657}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002658
Bram Moolenaard317b382018-02-08 22:33:31 +01002659/*
2660 * Set the cursor color and shape, if not last set to these.
2661 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002662 static void
2663may_set_cursor_props(term_T *term)
2664{
2665#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002666 // For the GUI the cursor properties are obtained with
2667 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002668 if (gui.in_use)
2669 return;
2670#endif
2671 if (in_terminal_loop == term)
2672 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002673 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002674 desired_cursor_shape = term->tl_cursor_shape;
2675 desired_cursor_blink = term->tl_cursor_blink;
2676 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002677 }
2678}
2679
Bram Moolenaard317b382018-02-08 22:33:31 +01002680/*
2681 * Reset the desired cursor properties and restore them when needed.
2682 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002683 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002684prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002685{
2686#ifdef FEAT_GUI
2687 if (gui.in_use)
2688 return;
2689#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002690 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002691 desired_cursor_shape = -1;
2692 desired_cursor_blink = -1;
2693 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002694}
2695
2696/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002697 * Returns TRUE if the current window contains a terminal and we are sending
2698 * keys to the job.
2699 * If "check_job_status" is TRUE update the job status.
2700 */
2701 static int
2702term_use_loop_check(int check_job_status)
2703{
2704 term_T *term = curbuf->b_term;
2705
2706 return term != NULL
2707 && !term->tl_normal_mode
2708 && term->tl_vterm != NULL
2709 && term_job_running_check(term, check_job_status);
2710}
2711
2712/*
2713 * Returns TRUE if the current window contains a terminal and we are sending
2714 * keys to the job.
2715 */
2716 int
2717term_use_loop(void)
2718{
2719 return term_use_loop_check(FALSE);
2720}
2721
2722/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002723 * Called when entering a window with the mouse. If this is a terminal window
2724 * we may want to change state.
2725 */
2726 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002727term_win_entered(void)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002728{
2729 term_T *term = curbuf->b_term;
2730
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002731 if (term == NULL)
2732 return;
2733
2734 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002735 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002736 reset_VIsual_and_resel();
2737 if (State & MODE_INSERT)
2738 stop_insert_mode = TRUE;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002739 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002740 mouse_was_outside = FALSE;
2741 enter_mouse_col = mouse_col;
2742 enter_mouse_row = mouse_row;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002743}
2744
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002745 void
2746term_focus_change(int in_focus)
2747{
2748 term_T *term = curbuf->b_term;
2749
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002750 if (term == NULL || term->tl_vterm == NULL)
2751 return;
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002752
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002753 VTermState *state = vterm_obtain_state(term->tl_vterm);
2754
2755 if (in_focus)
2756 vterm_state_focus_in(state);
2757 else
2758 vterm_state_focus_out(state);
2759 term_forward_output(term);
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002760}
2761
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002762/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002763 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2764 * Return the Ctrl-key value in that case.
2765 */
2766 static int
2767raw_c_to_ctrl(int c)
2768{
2769 if ((mod_mask & MOD_MASK_CTRL)
2770 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2771 return c & 0x1f;
2772 return c;
2773}
2774
2775/*
2776 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002777 * Also when the Kitty keyboard protocol is used.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002778 * May set "mod_mask".
2779 */
2780 static int
2781ctrl_to_raw_c(int c)
2782{
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002783 if (c < 0x20 && vterm_using_key_protocol())
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002784 {
2785 mod_mask |= MOD_MASK_CTRL;
2786 return c + '@';
2787 }
2788 return c;
2789}
2790
2791/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002792 * Wait for input and send it to the job.
2793 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2794 * when there is no more typahead.
2795 * Return when the start of a CTRL-W command is typed or anything else that
2796 * should be handled as a Normal mode command.
2797 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2798 * the terminal was closed.
2799 */
2800 int
2801terminal_loop(int blocking)
2802{
2803 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002804 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002805 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002806 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002807#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002808 int tty_fd = curbuf->b_term->tl_job->jv_channel
2809 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002810#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002811 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002812
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002813 // Remember the terminal we are sending keys to. However, the terminal
2814 // might be closed while waiting for a character, e.g. typing "exit" in a
2815 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2816 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002817 in_terminal_loop = curbuf->b_term;
2818
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002819 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002820 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002821 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002822 if (termwinkey == Ctrl_W)
2823 termwinkey = 0;
2824 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002825 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002826 may_set_cursor_props(curbuf->b_term);
2827
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002828 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002829 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002830#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002831 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002832#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002833 // TODO: skip screen update when handling a sequence of keys.
2834 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002835 while (must_redraw != 0)
2836 if (update_screen(0) == FAIL)
2837 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002838 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002839 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002840 break;
2841
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002842 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002843 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002844
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002845 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002846 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002847 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002848 // Job finished while waiting for a character. Push back the
2849 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002850 if (raw_c != K_IGNORE)
2851 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002852 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002853 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002854 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002855 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002856 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002857
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002858#ifdef UNIX
2859 /*
2860 * The shell or another program may change the tty settings. Getting
2861 * them for every typed character is a bit of overhead, but it's needed
2862 * for the first character typed, e.g. when Vim starts in a shell.
2863 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002864 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002865 {
2866 ttyinfo_T info;
2867
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002868 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002869 if (get_tty_info(tty_fd, &info) == OK)
2870 term_backspace_char = info.backspace;
2871 }
2872#endif
2873
Bram Moolenaar4f974752019-02-17 17:44:42 +01002874#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002875 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2876 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002877 if (ctrl_break_was_pressed)
2878 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2879#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002880 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2881 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002882 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002883#ifdef FEAT_GUI
2884 && !curbuf->b_term->tl_system
2885#endif
2886 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002887 {
2888 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002889 int prev_raw_c = raw_c;
2890 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002891
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002892 if (add_to_showcmd(c))
2893 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002894
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002895 raw_c = term_vgetc();
2896 c = raw_c_to_ctrl(raw_c);
2897
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002898 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002899
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002900 if (!term_use_loop_check(TRUE)
2901 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002902 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002903 break;
2904
2905 if (prev_c == Ctrl_BSL)
2906 {
2907 if (c == Ctrl_N)
2908 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002909 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002910 term_enter_normal_mode();
2911 ret = FAIL;
2912 goto theend;
2913 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002914 // Send both keys to the terminal, first one here, second one
2915 // below.
2916 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2917 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002918 }
2919 else if (c == Ctrl_C)
2920 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002921 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2923 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002924 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002926 // "CTRL-W .": send CTRL-W to the job
2927 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002928 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002929 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002930 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002931 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002932 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002933 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002934 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002935 else if (c == 'N')
2936 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002937 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002938 term_enter_normal_mode();
2939 ret = FAIL;
2940 goto theend;
2941 }
2942 else if (c == '"')
2943 {
2944 term_paste_register(prev_c);
2945 continue;
2946 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002947 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002948 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002949 // space for CTRL-W, modifier, multi-byte char and NUL
2950 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002951
2952 // Put the command into the typeahead buffer, when using the
2953 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2954 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002955 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002956 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002957 ret = OK;
2958 goto theend;
2959 }
2960 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002961# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002962 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002963 {
2964 WCHAR wc;
2965 char_u mb[3];
2966
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002967 mb[0] = (unsigned)raw_c >> 8;
2968 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002969 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002970 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002971 }
2972# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002973 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002974 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002975 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002976 // We are sure to come back here, don't reset the cursor color
2977 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002978 restore_cursor = FALSE;
2979
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002980 ret = OK;
2981 goto theend;
2982 }
2983 }
2984 ret = FAIL;
2985
2986theend:
2987 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002988 if (restore_cursor)
2989 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002990
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002991 // Move a snapshot of the screen contents to the buffer, so that completion
2992 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002993 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2994 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002995
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002996 return ret;
2997}
2998
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002999 static void
3000may_toggle_cursor(term_T *term)
3001{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003002 if (in_terminal_loop != term)
3003 return;
3004
3005 if (term->tl_cursor_visible)
3006 cursor_on();
3007 else
3008 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003009}
3010
3011/*
3012 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01003013 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003014 */
3015 static int
3016color2index(VTermColor *color, int fg, int *boldp)
3017{
3018 int red = color->red;
3019 int blue = color->blue;
3020 int green = color->green;
3021
LemonBoyb2b3acb2022-05-20 10:10:34 +01003022 *boldp = FALSE;
3023
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003024 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003025 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01003026
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003027 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003028 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003029 // Use the color as-is if possible, give up otherwise.
3030 if (color->index < t_colors)
3031 return color->index + 1;
3032 // 8-color terminals can actually display twice as many colors by
3033 // setting the high-intensity/bold bit.
3034 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003035 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003036 *boldp = TRUE;
3037 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003038 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01003039 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003040 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01003041
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003042 if (t_colors >= 256)
3043 {
3044 if (red == blue && red == green)
3045 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003046 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003047 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003048 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
3049 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
3050 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003051 int i;
3052
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003053 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003054 return 17; // 00/00/00
3055 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003056 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003057 for (i = 0; i < 23; ++i)
3058 if (red < cutoff[i])
3059 return i + 233;
3060 return 256;
3061 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003062 {
3063 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
3064 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003065
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003066 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003067 for (ri = 0; ri < 5; ++ri)
3068 if (red < cutoff[ri])
3069 break;
3070 for (gi = 0; gi < 5; ++gi)
3071 if (green < cutoff[gi])
3072 break;
3073 for (bi = 0; bi < 5; ++bi)
3074 if (blue < cutoff[bi])
3075 break;
3076 return 17 + ri * 36 + gi * 6 + bi;
3077 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003078 }
3079 return 0;
3080}
3081
3082/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01003083 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003084 */
3085 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003086vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003087{
3088 int attr = 0;
3089
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003090 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003091 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003092 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003093 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003094 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003096 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003098 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003099 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003100 return attr;
3101}
3102
3103/*
3104 * Store Vterm attributes in "cell" from highlight flags.
3105 */
3106 static void
3107hl2vtermAttr(int attr, cellattr_T *cell)
3108{
Bram Moolenaara80faa82020-04-12 19:37:17 +02003109 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003110 if (attr & HL_BOLD)
3111 cell->attrs.bold = 1;
3112 if (attr & HL_UNDERLINE)
3113 cell->attrs.underline = 1;
3114 if (attr & HL_ITALIC)
3115 cell->attrs.italic = 1;
3116 if (attr & HL_STRIKETHROUGH)
3117 cell->attrs.strike = 1;
3118 if (attr & HL_INVERSE)
3119 cell->attrs.reverse = 1;
3120}
3121
3122/*
3123 * Convert the attributes of a vterm cell into an attribute index.
3124 */
3125 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003126cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003127 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003128 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003129 VTermScreenCellAttrs *cellattrs,
3130 VTermColor *cellfg,
3131 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003132{
3133 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003134 VTermColor *fg = cellfg;
3135 VTermColor *bg = cellbg;
3136 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3137 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3138
3139 if (is_default_fg || is_default_bg)
3140 {
3141 if (wp != NULL && *wp->w_p_wcr != NUL)
3142 {
3143 if (is_default_fg)
3144 fg = &wp->w_term_wincolor.fg;
3145 if (is_default_bg)
3146 bg = &wp->w_term_wincolor.bg;
3147 }
3148 else
3149 {
3150 if (is_default_fg)
3151 fg = &term->tl_default_color.fg;
3152 if (is_default_bg)
3153 bg = &term->tl_default_color.bg;
3154 }
3155 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156
3157#ifdef FEAT_GUI
3158 if (gui.in_use)
3159 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003160 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3161 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3162 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003163 }
3164 else
3165#endif
3166#ifdef FEAT_TERMGUICOLORS
3167 if (p_tgc)
3168 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003169 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3170 ? INVALCOLOR
3171 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3172 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3173 ? INVALCOLOR
3174 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3175 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003176 }
3177 else
3178#endif
3179 {
3180 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003181 int ctermfg = color2index(fg, TRUE, &bold);
3182 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003183
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003184 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003185 if (bold == TRUE)
3186 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003187
3188 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003189 }
3190 return 0;
3191}
3192
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003193 static void
3194set_dirty_snapshot(term_T *term)
3195{
3196 term->tl_dirty_snapshot = TRUE;
3197#ifdef FEAT_TIMERS
3198 if (!term->tl_normal_mode)
3199 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003200 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003201 profile_setlimit(100L, &term->tl_timer_due);
3202 term->tl_timer_set = TRUE;
3203 }
3204#endif
3205}
3206
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003207 static int
3208handle_damage(VTermRect rect, void *user)
3209{
3210 term_T *term = (term_T *)user;
3211
3212 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3213 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003214 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003215 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003216 return 1;
3217}
3218
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003219 static void
3220term_scroll_up(term_T *term, int start_row, int count)
3221{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003222 win_T *wp = NULL;
3223 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003224 VTermColor fg, bg;
3225 VTermScreenCellAttrs attr;
3226 int clear_attr;
3227
Bram Moolenaara80faa82020-04-12 19:37:17 +02003228 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003229
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003230 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003231 {
3232 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003233 {
3234 // Set the color to clear lines with.
3235 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3236 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003237 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003238 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003239 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003240 }
3241}
3242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003243 static int
3244handle_moverect(VTermRect dest, VTermRect src, void *user)
3245{
3246 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003247 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003248
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003249 // Scrolling up is done much more efficiently by deleting lines instead of
3250 // redrawing the text. But avoid doing this multiple times, postpone until
3251 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003252 if (dest.start_col == src.start_col
3253 && dest.end_col == src.end_col
3254 && dest.start_row < src.start_row)
3255 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003256 if (dest.start_row == 0)
3257 term->tl_postponed_scroll += count;
3258 else
3259 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003260 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003261
3262 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3263 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003264 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003265
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003266 // Note sure if the scrolling will work correctly, let's do a complete
3267 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003268 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003269 return 1;
3270}
3271
3272 static int
3273handle_movecursor(
3274 VTermPos pos,
3275 VTermPos oldpos UNUSED,
3276 int visible,
3277 void *user)
3278{
3279 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003280 win_T *wp = NULL;
3281 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003282
3283 term->tl_cursor_pos = pos;
3284 term->tl_cursor_visible = visible;
3285
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003286 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003287 {
3288 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003289 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003290 }
3291 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003292 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003293
3294 return 1;
3295}
3296
3297 static int
3298handle_settermprop(
3299 VTermProp prop,
3300 VTermValue *value,
3301 void *user)
3302{
3303 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003304 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003305
3306 switch (prop)
3307 {
3308 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003309 if (disable_vterm_title_for_testing)
3310 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003311 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003312 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003313 if (strval == NULL)
3314 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003315 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003316 // a blank title isn't useful, make it empty, so that "running" is
3317 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003318 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003319 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003320 // Same as blank
3321 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003322 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003323 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3324 term->tl_title = NULL;
3325 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003326 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003327 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003328#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003329 else if (!enc_utf8 && enc_codepage > 0)
3330 {
3331 WCHAR *ret = NULL;
3332 int length = 0;
3333
3334 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003335 (char*)value->string.str,
3336 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003337 if (ret != NULL)
3338 {
3339 WideCharToMultiByte_alloc(enc_codepage, 0,
3340 ret, length, (char**)&term->tl_title,
3341 &length, 0, 0);
3342 vim_free(ret);
3343 }
3344 }
3345#endif
3346 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003347 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003348 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003349 strval = NULL;
3350 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003351 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003352 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003353 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003354 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003355 curwin->w_redr_status = TRUE;
3356 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357 break;
3358
3359 case VTERM_PROP_CURSORVISIBLE:
3360 term->tl_cursor_visible = value->boolean;
3361 may_toggle_cursor(term);
3362 out_flush();
3363 break;
3364
3365 case VTERM_PROP_CURSORBLINK:
3366 term->tl_cursor_blink = value->boolean;
3367 may_set_cursor_props(term);
3368 break;
3369
3370 case VTERM_PROP_CURSORSHAPE:
3371 term->tl_cursor_shape = value->number;
3372 may_set_cursor_props(term);
3373 break;
3374
3375 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003376 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003377 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003378 if (strval == NULL)
3379 break;
3380 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003381 may_set_cursor_props(term);
3382 break;
3383
3384 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003385 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003386 term->tl_using_altscreen = value->boolean;
3387 break;
3388
3389 default:
3390 break;
3391 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003392 vim_free(strval);
3393
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003394 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003395 return 1;
3396}
3397
3398/*
3399 * The job running in the terminal resized the terminal.
3400 */
3401 static int
3402handle_resize(int rows, int cols, void *user)
3403{
3404 term_T *term = (term_T *)user;
3405 win_T *wp;
3406
3407 term->tl_rows = rows;
3408 term->tl_cols = cols;
3409 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003410 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003411 term->tl_vterm_size_changed = FALSE;
3412 else
3413 {
3414 FOR_ALL_WINDOWS(wp)
3415 {
3416 if (wp->w_buffer == term->tl_buffer)
3417 {
3418 win_setheight_win(rows, wp);
3419 win_setwidth_win(cols, wp);
3420 }
3421 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003422 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003423 }
3424 return 1;
3425}
3426
3427/*
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003428 * If the number of lines that are stored goes over 'termwinscroll' then
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003429 * delete the first 10%.
3430 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3431 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003432 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003433 static void
3434limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003435{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003436 if (gap->ga_len < term->tl_buffer->b_p_twsl)
3437 return;
3438
Milly6d5f4a02024-10-22 23:17:45 +02003439 int todo = MAX(term->tl_buffer->b_p_twsl / 10,
3440 gap->ga_len - term->tl_buffer->b_p_twsl);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003441 int i;
3442
3443 curbuf = term->tl_buffer;
3444 for (i = 0; i < todo; ++i)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003445 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003446 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003447 if (update_buffer)
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003448 ml_delete(1);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003449 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003450 curbuf = curwin->w_buffer;
3451
3452 gap->ga_len -= todo;
3453 mch_memmove(gap->ga_data,
3454 (sb_line_T *)gap->ga_data + todo,
3455 sizeof(sb_line_T) * gap->ga_len);
3456 if (update_buffer)
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003457 {
Hirohito Higashifa9753a2025-04-27 15:36:43 +02003458 win_T *curwin_save = curwin;
3459 win_T *wp = NULL;
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003460
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003461 term->tl_scrollback_scrolled -= todo;
Christian Brabandt1254e6d2024-07-29 21:19:51 +02003462
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003463 FOR_ALL_WINDOWS(wp)
3464 {
3465 if (wp->w_buffer == term->tl_buffer)
3466 {
3467 curwin = wp;
3468 check_cursor();
Hirohito Higashifa9753a2025-04-27 15:36:43 +02003469 update_topline();
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003470 }
3471 }
3472 curwin = curwin_save;
3473 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003474}
3475
3476/*
3477 * Handle a line that is pushed off the top of the screen.
3478 */
3479 static int
3480handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3481{
3482 term_T *term = (term_T *)user;
3483 garray_T *gap;
3484 int update_buffer;
3485
3486 if (term->tl_normal_mode)
3487 {
3488 // In Terminal-Normal mode the user interacts with the buffer, thus we
3489 // must not change it. Postpone adding the scrollback lines.
3490 gap = &term->tl_scrollback_postponed;
3491 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003492 }
3493 else
3494 {
3495 // First remove the lines that were appended before, the pushed line
3496 // goes above it.
3497 cleanup_scrollback(term);
3498 gap = &term->tl_scrollback;
3499 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003500 }
3501
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003502 limit_scrollback(term, gap, update_buffer);
3503
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003504 if (ga_grow(gap, 1) == FAIL)
3505 return 0;
3506
3507 cellattr_T *p = NULL;
3508 int len = 0;
3509 int i;
3510 int c;
3511 int col;
3512 int text_len;
3513 char_u *text;
3514 sb_line_T *line;
3515 garray_T ga;
3516 cellattr_T fill_attr = term->tl_default_color;
3517
3518 // do not store empty cells at the end
3519 for (i = 0; i < cols; ++i)
3520 if (cells[i].chars[0] != 0)
3521 len = i + 1;
3522 else
3523 cell2cellattr(&cells[i], &fill_attr);
3524
3525 ga_init2(&ga, 1, 100);
3526 if (len > 0)
3527 p = ALLOC_MULT(cellattr_T, len);
3528 if (p != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003529 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003530 for (col = 0; col < len; col += cells[col].width)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003531 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003532 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003533 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003534 ga.ga_len = 0;
3535 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003536 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003537 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3538 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3539 (char_u *)ga.ga_data + ga.ga_len);
3540 cell2cellattr(&cells[col], &p[col]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003541 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003542 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003543 if (ga_grow(&ga, 1) == FAIL)
3544 {
3545 if (update_buffer)
3546 text = (char_u *)"";
3547 else
3548 text = vim_strsave((char_u *)"");
3549 text_len = 0;
3550 }
3551 else
3552 {
3553 text = ga.ga_data;
3554 text_len = ga.ga_len;
3555 *(text + text_len) = NUL;
3556 }
3557 if (update_buffer)
3558 add_scrollback_line_to_buffer(term, text, text_len);
3559
3560 line = (sb_line_T *)gap->ga_data + gap->ga_len;
3561 line->sb_cols = len;
3562 line->sb_cells = p;
3563 line->sb_fill_attr = fill_attr;
3564 if (update_buffer)
3565 {
3566 line->sb_text = NULL;
3567 ++term->tl_scrollback_scrolled;
3568 ga_clear(&ga); // free the text
3569 }
3570 else
3571 {
3572 line->sb_text = text;
3573 ga_init(&ga); // text is kept in tl_scrollback_postponed
3574 }
3575 ++gap->ga_len;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003576 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003577}
3578
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003579/*
3580 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3581 * received and stored in tl_scrollback_postponed.
3582 */
3583 static void
3584handle_postponed_scrollback(term_T *term)
3585{
3586 int i;
3587
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003588 if (term->tl_scrollback_postponed.ga_len == 0)
3589 return;
3590 ch_log(NULL, "Moving postponed scrollback to scrollback");
3591
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003592 // First remove the lines that were appended before, the pushed lines go
3593 // above it.
3594 cleanup_scrollback(term);
3595
3596 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3597 {
3598 char_u *text;
3599 sb_line_T *pp_line;
3600 sb_line_T *line;
3601
3602 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3603 break;
3604 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3605
3606 text = pp_line->sb_text;
3607 if (text == NULL)
3608 text = (char_u *)"";
3609 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3610 vim_free(pp_line->sb_text);
3611
3612 line = (sb_line_T *)term->tl_scrollback.ga_data
3613 + term->tl_scrollback.ga_len;
3614 line->sb_cols = pp_line->sb_cols;
3615 line->sb_cells = pp_line->sb_cells;
3616 line->sb_fill_attr = pp_line->sb_fill_attr;
3617 line->sb_text = NULL;
3618 ++term->tl_scrollback_scrolled;
3619 ++term->tl_scrollback.ga_len;
3620 }
3621
3622 ga_clear(&term->tl_scrollback_postponed);
3623 limit_scrollback(term, &term->tl_scrollback, TRUE);
3624}
3625
LemonBoy77771d32022-04-13 11:47:25 +01003626/*
3627 * Called when the terminal wants to ring the system bell.
3628 */
3629 static int
3630handle_bell(void *user UNUSED)
3631{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003632 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003633 return 0;
3634}
3635
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003636static VTermScreenCallbacks screen_callbacks = {
Yegappan Lakshmanan562610c2025-05-04 21:05:51 +02003637 handle_damage, // damage
3638 handle_moverect, // moverect
3639 handle_movecursor, // movecursor
3640 handle_settermprop, // settermprop
3641 handle_bell, // bell
3642 handle_resize, // resize
3643 handle_pushline, // sb_pushline
3644 NULL, // sb_popline
3645 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003646};
3647
3648/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003649 * Do the work after the channel of a terminal was closed.
3650 * Must be called only when updating_screen is FALSE.
3651 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3652 */
3653 static int
3654term_after_channel_closed(term_T *term)
3655{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003656 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003657 if (!term->tl_normal_mode)
3658 {
3659 int fnum = term->tl_buffer->b_fnum;
3660
3661 cleanup_vterm(term);
3662
3663 if (term->tl_finish == TL_FINISH_CLOSE)
3664 {
3665 aco_save_T aco;
zeertzjqbc11f6d2024-08-16 21:11:31 +02003666 int do_set_w_locked = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003667#ifdef FEAT_PROP_POPUP
3668 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003669
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003670 // If this was a terminal in a popup window, go back to the
3671 // previous window.
3672 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3673 {
3674 pwin = curwin;
3675 if (win_valid(prevwin))
3676 win_enter(prevwin, FALSE);
3677 }
3678 else
3679#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003680 // If this is the last normal window: exit Vim.
3681 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3682 {
3683 exarg_T ea;
3684
Bram Moolenaara80faa82020-04-12 19:37:17 +02003685 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003686 ex_quit(&ea);
3687 return TRUE;
3688 }
3689
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003690 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003691 ch_log(NULL, "terminal job finished, closing window");
3692 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaare76062c2022-11-28 18:51:43 +00003693 if (curbuf == term->tl_buffer)
3694 {
3695 // Avoid closing the window if we temporarily use it.
3696 if (is_aucmd_win(curwin))
zeertzjqbc11f6d2024-08-16 21:11:31 +02003697 do_set_w_locked = TRUE;
3698 if (do_set_w_locked)
Christian Brabandt0a6e57b2024-08-15 22:15:28 +02003699 curwin->w_locked = TRUE;
Bram Moolenaare76062c2022-11-28 18:51:43 +00003700 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
zeertzjqbc11f6d2024-08-16 21:11:31 +02003701 if (do_set_w_locked)
Christian Brabandt0a6e57b2024-08-15 22:15:28 +02003702 curwin->w_locked = FALSE;
Bram Moolenaare76062c2022-11-28 18:51:43 +00003703 aucmd_restbuf(&aco);
3704 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003705#ifdef FEAT_PROP_POPUP
3706 if (pwin != NULL)
3707 popup_close_with_retval(pwin, 0);
3708#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003709 return TRUE;
3710 }
3711 if (term->tl_finish == TL_FINISH_OPEN
3712 && term->tl_buffer->b_nwindows == 0)
3713 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003714 char *cmd = term->tl_opencmd == NULL
3715 ? "botright sbuf %d"
3716 : (char *)term->tl_opencmd;
3717 size_t len = strlen(cmd) + 50;
3718 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003719
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003720 if (buf != NULL)
3721 {
3722 ch_log(NULL, "terminal job finished, opening window");
3723 vim_snprintf(buf, len, cmd, fnum);
3724 do_cmdline_cmd((char_u *)buf);
3725 vim_free(buf);
3726 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003727 }
3728 else
3729 ch_log(NULL, "terminal job finished");
3730 }
3731
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003732 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003733 return FALSE;
3734}
3735
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003736#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3737/*
3738 * If the current window is a terminal in a popup window and the job has
3739 * finished, close the popup window and to back to the previous window.
3740 * Otherwise return FAIL.
3741 */
3742 int
3743may_close_term_popup(void)
3744{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003745 if (!popup_is_popup(curwin) || curbuf->b_term == NULL
3746 || term_job_running_not_none(curbuf->b_term))
3747 return FAIL;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003748
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003749 win_T *pwin = curwin;
3750
3751 if (win_valid(prevwin))
3752 win_enter(prevwin, FALSE);
3753 popup_close_with_retval(pwin, 0);
3754 return OK;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003755}
3756#endif
3757
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003758/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003759 * Called when a channel is going to be closed, before invoking the close
3760 * callback.
3761 */
3762 void
3763term_channel_closing(channel_T *ch)
3764{
3765 term_T *term;
3766
3767 for (term = first_term; term != NULL; term = term->tl_next)
3768 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3769 term->tl_channel_closing = TRUE;
3770}
3771
3772/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003773 * Called when a channel has been closed.
3774 * If this was a channel for a terminal window then finish it up.
3775 */
3776 void
3777term_channel_closed(channel_T *ch)
3778{
3779 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003780 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003781 int did_one = FALSE;
3782
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003783 for (term = first_term; term != NULL; term = next_term)
3784 {
3785 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003786 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003787 {
3788 term->tl_channel_closed = TRUE;
3789 did_one = TRUE;
3790
Bram Moolenaard23a8232018-02-10 18:45:26 +01003791 VIM_CLEAR(term->tl_title);
3792 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003793#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003794 if (term->tl_out_fd != NULL)
3795 {
3796 fclose(term->tl_out_fd);
3797 term->tl_out_fd = NULL;
3798 }
3799#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003800
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003801 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003802 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003803 // Cannot open or close windows now. Can happen when
3804 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003805 term->tl_channel_recently_closed = TRUE;
3806 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003807 }
3808
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003809 if (term_after_channel_closed(term))
3810 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003811 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003812 }
3813
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003814 if (did_one)
3815 {
3816 redraw_statuslines();
3817
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003818 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003819 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003820 typebuf_was_filled = TRUE;
3821
3822 term = curbuf->b_term;
3823 if (term != NULL)
3824 {
3825 if (term->tl_job == ch->ch_job)
3826 maketitle();
3827 update_cursor(term, term->tl_cursor_visible);
3828 }
3829 }
3830}
3831
3832/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003833 * To be called after resetting updating_screen: handle any terminal where the
3834 * channel was closed.
3835 */
3836 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003837term_check_channel_closed_recently(void)
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003838{
3839 term_T *term;
3840 term_T *next_term;
3841
3842 for (term = first_term; term != NULL; term = next_term)
3843 {
3844 next_term = term->tl_next;
3845 if (term->tl_channel_recently_closed)
3846 {
3847 term->tl_channel_recently_closed = FALSE;
3848 if (term_after_channel_closed(term))
3849 // start over, the list may have changed
3850 next_term = first_term;
3851 }
3852 }
3853}
3854
3855/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003856 * Fill one screen line from a line of the terminal.
3857 * Advances "pos" to past the last column.
3858 */
3859 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003860term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003861 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003862 win_T *wp,
3863 VTermScreen *screen,
3864 VTermPos *pos,
3865 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003866{
3867 int off = screen_get_current_line_off();
3868
3869 for (pos->col = 0; pos->col < max_col; )
3870 {
3871 VTermScreenCell cell;
3872 int c;
3873
3874 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003875 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003876
3877 c = cell.chars[0];
3878 if (c == NUL)
3879 {
3880 ScreenLines[off] = ' ';
3881 if (enc_utf8)
3882 ScreenLinesUC[off] = NUL;
3883 }
3884 else
3885 {
3886 if (enc_utf8)
3887 {
3888 int i;
3889
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003890 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003891 for (i = 0; i < Screen_mco
3892 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3893 {
3894 ScreenLinesC[i][off] = cell.chars[i + 1];
3895 if (cell.chars[i + 1] == 0)
3896 break;
3897 }
3898 if (c >= 0x80 || (Screen_mco > 0
3899 && ScreenLinesC[0][off] != 0))
3900 {
3901 ScreenLines[off] = ' ';
3902 ScreenLinesUC[off] = c;
3903 }
3904 else
3905 {
3906 ScreenLines[off] = c;
3907 ScreenLinesUC[off] = NUL;
3908 }
3909 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003910#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003911 else if (has_mbyte && c >= 0x80)
3912 {
3913 char_u mb[MB_MAXBYTES+1];
3914 WCHAR wc = c;
3915
3916 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3917 (char*)mb, 2, 0, 0) > 1)
3918 {
3919 ScreenLines[off] = mb[0];
3920 ScreenLines[off + 1] = mb[1];
3921 cell.width = mb_ptr2cells(mb);
3922 }
3923 else
3924 ScreenLines[off] = c;
3925 }
3926#endif
3927 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003928 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003929 ScreenLines[off] = c;
3930 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003931 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3932 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003933
3934 ++pos->col;
3935 ++off;
3936 if (cell.width == 2)
3937 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003938 // don't set the second byte to NUL for a DBCS encoding, it
3939 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003940 if (enc_utf8)
3941 {
3942 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003943 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003944 }
3945 else if (!has_mbyte)
3946 {
3947 // Can't show a double-width character with a single-byte
3948 // 'encoding', just use a space.
3949 ScreenLines[off] = ' ';
3950 ScreenAttrs[off] = ScreenAttrs[off - 1];
3951 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003952
3953 ++pos->col;
3954 ++off;
3955 }
3956 }
3957}
3958
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003959#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003960 static void
3961update_system_term(term_T *term)
3962{
3963 VTermPos pos;
3964 VTermScreen *screen;
3965
3966 if (term->tl_vterm == NULL)
3967 return;
3968 screen = vterm_obtain_screen(term->tl_vterm);
3969
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003970 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003971 while (term->tl_toprow > 0
3972 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3973 {
3974 int save_p_more = p_more;
3975
3976 p_more = FALSE;
3977 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003978 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003979 p_more = save_p_more;
3980 --term->tl_toprow;
3981 }
3982
3983 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3984 && pos.row < Rows; ++pos.row)
3985 {
3986 if (pos.row < term->tl_rows)
3987 {
3988 int max_col = MIN(Columns, term->tl_cols);
3989
Bram Moolenaar83d47902020-03-26 20:34:00 +01003990 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003991 }
3992 else
3993 pos.col = 0;
3994
zeertzjqd0c1b772024-03-16 15:03:33 +01003995 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, -1,
3996 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003997 }
3998
3999 term->tl_dirty_row_start = MAX_ROW;
4000 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01004001}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01004002#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01004003
4004/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004005 * Return TRUE if window "wp" is to be redrawn with term_update_window().
4006 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004007 * Terminal-Normal mode.
4008 */
4009 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004010term_do_update_window(win_T *wp)
4011{
4012 term_T *term = wp->w_buffer->b_term;
4013
4014 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
4015}
4016
4017/*
4018 * Called to update a window that contains an active terminal.
4019 */
4020 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004021term_update_window(win_T *wp)
4022{
4023 term_T *term = wp->w_buffer->b_term;
4024 VTerm *vterm;
4025 VTermScreen *screen;
4026 VTermState *state;
4027 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004028 int rows, cols;
4029 int newrows, newcols;
4030 int minsize;
4031 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004032
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004033 vterm = term->tl_vterm;
4034 screen = vterm_obtain_screen(vterm);
4035 state = vterm_obtain_state(vterm);
4036
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004037 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
4038 // With UPD_SOME_VALID only redraw what was marked dirty.
4039 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004040 {
4041 term->tl_dirty_row_start = 0;
4042 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004043
4044 if (term->tl_postponed_scroll > 0
4045 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004046 // Scrolling is usually faster than redrawing, when there are only
4047 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004048 term_scroll_up(term, 0, term->tl_postponed_scroll);
4049 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004050 }
4051
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004052 /*
4053 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004054 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004055 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004056 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004057
Bram Moolenaar498c2562018-04-15 23:45:15 +02004058 newrows = 99999;
4059 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004060 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02004061 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004062 // Always use curwin, it may be a popup window.
4063 win_T *wwp = twp == NULL ? curwin : twp;
4064
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004065 // When more than one window shows the same terminal, use the
4066 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004067 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004068 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004069 newrows = MIN(newrows, wwp->w_height);
4070 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004071 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004072 if (twp == NULL)
4073 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004074 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02004075 if (newrows == 99999 || newcols == 99999)
4076 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02004077 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
4078 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
4079
Bram Moolenaareba13e42021-02-23 17:47:23 +01004080 // If no cell is visible there is no point in resizing. Also, vterm can't
4081 // handle a zero height.
4082 if (newrows == 0 || newcols == 0)
4083 return;
4084
Bram Moolenaar498c2562018-04-15 23:45:15 +02004085 if (term->tl_rows != newrows || term->tl_cols != newcols)
4086 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004087 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004088 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004089 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02004090 newrows);
4091 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02004092
4093 // Updating the terminal size will cause the snapshot to be cleared.
4094 // When not in terminal_loop() we need to restore it.
4095 if (term != in_terminal_loop)
4096 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004097 }
4098
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004099 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004100 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01004101 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004102
Bram Moolenaar3a497e12017-09-30 20:40:27 +02004103 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
4104 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004105 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004106 if (pos.row < term->tl_rows)
4107 {
Bram Moolenaar13568252018-03-16 20:46:58 +01004108 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004109
Bram Moolenaar83d47902020-03-26 20:34:00 +01004110 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004111 }
4112 else
4113 pos.col = 0;
4114
Bram Moolenaar510f0372022-07-04 17:46:22 +01004115 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01004116#ifdef FEAT_MENU
4117 + winbar_height(wp)
4118#endif
zeertzjqd0c1b772024-03-16 15:03:33 +01004119 , wp->w_wincol, pos.col, wp->w_width, -1,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004120#ifdef FEAT_PROP_POPUP
4121 popup_is_popup(wp) ? SLF_POPUP :
4122#endif
4123 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004124 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00004125}
4126
4127/*
4128 * Called after updating all windows: may reset dirty rows.
4129 */
4130 void
4131term_did_update_window(win_T *wp)
4132{
4133 term_T *term = wp->w_buffer->b_term;
4134
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004135 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode
4136 || wp->w_redr_type != 0)
4137 return;
4138
4139 term->tl_dirty_row_start = MAX_ROW;
4140 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004141}
4142
4143/*
4144 * Return TRUE if "wp" is a terminal window where the job has finished.
4145 */
4146 int
4147term_is_finished(buf_T *buf)
4148{
4149 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
4150}
4151
4152/*
4153 * Return TRUE if "wp" is a terminal window where the job has finished or we
4154 * are in Terminal-Normal mode, thus we show the buffer contents.
4155 */
4156 int
4157term_show_buffer(buf_T *buf)
4158{
4159 term_T *term = buf->b_term;
4160
4161 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4162}
4163
4164/*
4165 * The current buffer is going to be changed. If there is terminal
4166 * highlighting remove it now.
4167 */
4168 void
4169term_change_in_curbuf(void)
4170{
4171 term_T *term = curbuf->b_term;
4172
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004173 if (!term_is_finished(curbuf) || term->tl_scrollback.ga_len <= 0)
4174 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004175
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004176 free_scrollback(term);
4177 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
4178
4179 // The buffer is now like a normal buffer, it cannot be easily
4180 // abandoned when changed.
4181 set_string_option_direct((char_u *)"buftype", -1,
4182 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004183}
4184
4185/*
4186 * Get the screen attribute for a position in the buffer.
4187 * Use a negative "col" to get the filler background color.
4188 */
4189 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004190term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004191{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004192 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004193 term_T *term = buf->b_term;
4194 sb_line_T *line;
4195 cellattr_T *cellattr;
4196
4197 if (lnum > term->tl_scrollback.ga_len)
4198 cellattr = &term->tl_default_color;
4199 else
4200 {
4201 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4202 if (col < 0 || col >= line->sb_cols)
4203 cellattr = &line->sb_fill_attr;
4204 else
4205 cellattr = line->sb_cells + col;
4206 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004207 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004208}
4209
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004210/*
4211 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004212 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004213 */
4214 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004215cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004216{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004217 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4218 if (rgb->index == 0)
4219 rgb->type = VTERM_COLOR_RGB;
4220 else
4221 {
4222 rgb->type = VTERM_COLOR_INDEXED;
4223 --rgb->index;
4224 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004225}
4226
4227/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004228 * Initialize vterm color from the synID.
4229 * Returns TRUE if color is set to "fg" and "bg".
4230 * Otherwise returns FALSE.
4231 */
4232 static int
4233get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4234{
4235#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4236 // Use the actual color for the GUI and when 'termguicolors' is set.
4237 if (0
4238# ifdef FEAT_GUI
4239 || gui.in_use
4240# endif
4241# ifdef FEAT_TERMGUICOLORS
4242 || p_tgc
4243# ifdef FEAT_VTP
4244 // Finally get INVALCOLOR on this execution path
4245 || (!p_tgc && t_colors >= 256)
4246# endif
4247# endif
4248 )
4249 {
4250 guicolor_T fg_rgb = INVALCOLOR;
4251 guicolor_T bg_rgb = INVALCOLOR;
4252
4253 if (id > 0)
4254 syn_id2colors(id, &fg_rgb, &bg_rgb);
4255
4256 if (fg_rgb != INVALCOLOR)
4257 {
4258 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4259 fg->red = (unsigned)(rgb >> 16);
4260 fg->green = (unsigned)(rgb >> 8) & 255;
4261 fg->blue = (unsigned)rgb & 255;
4262 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4263 }
4264 else
4265 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4266
4267 if (bg_rgb != INVALCOLOR)
4268 {
4269 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4270 bg->red = (unsigned)(rgb >> 16);
4271 bg->green = (unsigned)(rgb >> 8) & 255;
4272 bg->blue = (unsigned)rgb & 255;
4273 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4274 }
4275 else
4276 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4277
4278 return TRUE;
4279 }
4280 else
4281#endif
4282 if (t_colors >= 16)
4283 {
4284 int cterm_fg = -1;
4285 int cterm_bg = -1;
4286
4287 if (id > 0)
4288 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4289
4290 if (cterm_fg >= 0)
4291 {
4292 cterm_color2vterm(cterm_fg, fg);
4293 fg->type |= VTERM_COLOR_DEFAULT_FG;
4294 }
4295 else
4296 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4297
4298 if (cterm_bg >= 0)
4299 {
4300 cterm_color2vterm(cterm_bg, bg);
4301 bg->type |= VTERM_COLOR_DEFAULT_BG;
4302 }
4303 else
4304 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4305
4306 return TRUE;
4307 }
4308
4309 return FALSE;
4310}
4311
4312 void
4313term_reset_wincolor(win_T *wp)
4314{
4315 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4316 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4317}
4318
4319/*
4320 * Cache the color of 'wincolor'.
4321 */
4322 void
4323term_update_wincolor(win_T *wp)
4324{
4325 int id = 0;
4326
4327 if (*wp->w_p_wcr != NUL)
4328 id = syn_name2id(wp->w_p_wcr);
4329 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4330 &wp->w_term_wincolor.bg))
4331 term_reset_wincolor(wp);
4332}
4333
4334/*
4335 * Called when option 'termguicolors' was set,
4336 * or when any highlight is changed.
4337 */
4338 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004339term_update_wincolor_all(void)
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004340{
4341 win_T *wp = NULL;
4342 int did_curwin = FALSE;
4343
4344 while (for_all_windows_and_curwin(&wp, &did_curwin))
4345 term_update_wincolor(wp);
4346}
4347
4348/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004349 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004350 */
4351 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004352init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004353{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004354 VTermColor *fg, *bg;
4355 int fgval, bgval;
4356 int id;
4357
Bram Moolenaara80faa82020-04-12 19:37:17 +02004358 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004359 term->tl_default_color.width = 1;
4360 fg = &term->tl_default_color.fg;
4361 bg = &term->tl_default_color.bg;
4362
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004363 // Vterm uses a default black background. Set it to white when
4364 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004365 if (*p_bg == 'l')
4366 {
4367 fgval = 0;
4368 bgval = 255;
4369 }
4370 else
4371 {
4372 fgval = 255;
4373 bgval = 0;
4374 }
4375 fg->red = fg->green = fg->blue = fgval;
4376 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004377 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4378 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004379
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004380 // The highlight group overrules the defaults.
4381 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004382
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004383 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004384 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004385#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004386 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004387#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004388
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004389 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004390 if (cterm_normal_fg_color > 0)
4391 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004392 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004393# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4394# ifdef VIMDLL
4395 if (!gui.in_use)
4396# endif
4397 {
4398 tmp = fg->red;
4399 fg->red = fg->blue;
4400 fg->blue = tmp;
4401 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004402# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004403 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004404# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004405 else
4406 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004407# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004408
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004409 if (cterm_normal_bg_color > 0)
4410 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004411 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004412# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4413# ifdef VIMDLL
4414 if (!gui.in_use)
4415# endif
4416 {
4417 tmp = fg->red;
4418 fg->red = fg->blue;
4419 fg->blue = tmp;
4420 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004421# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004422 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004423# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004424 else
4425 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004426# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004427 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004428}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004429
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004430#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4431/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004432 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4433 * "ansi_colors" argument in term_start()) shall be applied.
4434 */
4435 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004436term_use_palette(void)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004437{
4438 if (0
4439#ifdef FEAT_GUI
4440 || gui.in_use
4441#endif
4442#ifdef FEAT_TERMGUICOLORS
4443 || p_tgc
4444#endif
4445 )
4446 return TRUE;
4447 return FALSE;
4448}
4449
4450/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004451 * Set the 16 ANSI colors from array of RGB values
4452 */
4453 static void
4454set_vterm_palette(VTerm *vterm, long_u *rgb)
4455{
4456 int index = 0;
4457 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004458
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004459 for (; index < 16; index++)
4460 {
4461 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004462
Millyb771b6b2021-11-23 12:07:25 +00004463 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004464 color.red = (unsigned)(rgb[index] >> 16);
4465 color.green = (unsigned)(rgb[index] >> 8) & 255;
4466 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004467 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004468 vterm_state_set_palette_color(state, index, &color);
4469 }
4470}
4471
4472/*
4473 * Set the ANSI color palette from a list of colors
4474 */
4475 static int
4476set_ansi_colors_list(VTerm *vterm, list_T *list)
4477{
4478 int n = 0;
4479 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004480 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004481
Bram Moolenaarb0992022020-01-30 14:55:42 +01004482 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004483 {
4484 char_u *color_name;
4485 guicolor_T guicolor;
4486
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004487 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004488 if (color_name == NULL)
4489 return FAIL;
4490
4491 guicolor = GUI_GET_COLOR(color_name);
4492 if (guicolor == INVALCOLOR)
4493 return FAIL;
4494
4495 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4496 }
4497
4498 if (n != 16 || li != NULL)
4499 return FAIL;
4500
4501 set_vterm_palette(vterm, rgb);
4502
4503 return OK;
4504}
4505
4506/*
4507 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4508 */
4509 static void
4510init_vterm_ansi_colors(VTerm *vterm)
4511{
4512 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4513
LemonBoyb2b3acb2022-05-20 10:10:34 +01004514 if (var == NULL)
4515 return;
4516
4517 if (var->di_tv.v_type != VAR_LIST
4518 || var->di_tv.vval.v_list == NULL
4519 || var->di_tv.vval.v_list->lv_first == &range_list_item
4520 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004521 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004522}
4523#endif
4524
Bram Moolenaar52acb112018-03-18 19:20:22 +01004525/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004526 * Handles a "drop" command from the job in the terminal.
4527 * "item" is the file name, "item->li_next" may have options.
4528 */
4529 static void
4530handle_drop_command(listitem_T *item)
4531{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004532 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004533 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004534 int bufnr;
4535 win_T *wp;
4536 tabpage_T *tp;
4537 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004538 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004539
4540 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4541 FOR_ALL_TAB_WINDOWS(tp, wp)
4542 {
4543 if (wp->w_buffer->b_fnum == bufnr)
4544 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004545 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004546 goto_tabpage_win(tp, wp);
4547 return;
4548 }
4549 }
4550
Bram Moolenaara80faa82020-04-12 19:37:17 +02004551 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004552
4553 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4554 && opt_item->li_tv.vval.v_dict != NULL)
4555 {
4556 dict_T *dict = opt_item->li_tv.vval.v_dict;
4557 char_u *p;
4558
Bram Moolenaard61efa52022-07-23 09:52:04 +01004559 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004560 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004561 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004562 if (p != NULL)
4563 {
4564 if (check_ff_value(p) == FAIL)
4565 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4566 else
4567 ea.force_ff = *p;
4568 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004569 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004570 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004571 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004572 if (p != NULL)
4573 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004574 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004575 if (ea.cmd != NULL)
4576 {
4577 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4578 ea.force_enc = 11;
4579 tofree = ea.cmd;
4580 }
4581 }
4582
Bram Moolenaard61efa52022-07-23 09:52:04 +01004583 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004584 if (p != NULL)
4585 get_bad_opt(p, &ea);
4586
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004587 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004588 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004589 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004590 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004591 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004592 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004593 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004594 ea.force_bin = FORCE_NOBIN;
4595 }
4596
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004597 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004598 if (ea.cmd == NULL)
4599 ea.cmd = (char_u *)"split";
4600 ea.arg = fname;
4601 ea.cmdidx = CMD_split;
4602 ex_splitview(&ea);
4603
4604 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004605}
4606
4607/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004608 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4609 */
4610 static int
4611is_permitted_term_api(char_u *func, char_u *pat)
4612{
4613 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4614}
4615
4616/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004617 * Handles a function call from the job running in a terminal.
4618 * "item" is the function name, "item->li_next" has the arguments.
4619 */
4620 static void
4621handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4622{
4623 char_u *func;
4624 typval_T argvars[2];
4625 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004626 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004627
4628 if (item->li_next == NULL)
4629 {
4630 ch_log(channel, "Missing function arguments for call");
4631 return;
4632 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004633 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004634
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004635 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004636 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004637 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004638 return;
4639 }
4640
4641 argvars[0].v_type = VAR_NUMBER;
4642 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4643 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004644 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004645 funcexe.fe_firstline = 1L;
4646 funcexe.fe_lastline = 1L;
4647 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004648 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004649 {
4650 clear_tv(&rettv);
4651 ch_log(channel, "Function %s called", func);
4652 }
4653 else
4654 ch_log(channel, "Calling function %s failed", func);
4655}
4656
4657/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004658 * URL decoding (also know as Percent-encoding).
4659 *
4660 * Note this function currently is only used for decoding shell's
4661 * OSC 7 escape sequence which we can assume all bytes are valid
4662 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4663 * encoding bytes like 0xfe, 0xff.
4664 */
4665 static size_t
4666url_decode(const char *src, const size_t len, char_u *dst)
4667{
4668 size_t i = 0, j = 0;
4669
4670 while (i < len)
4671 {
4672 if (src[i] == '%' && i + 2 < len)
4673 {
4674 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4675 j++;
4676 i += 3;
4677 }
4678 else
4679 {
4680 dst[j] = src[i];
4681 i++;
4682 j++;
4683 }
4684 }
4685 dst[j] = '\0';
4686 return j;
4687}
4688
4689/*
4690 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4691 *
4692 * The OSC 7 sequence has the format of
4693 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4694 * and what VTerm provides via VTermStringFragment is
4695 * "file://HOSTNAME/CURRENT/DIR"
4696 */
4697 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004698sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004699{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004700 int offset = 7; // len of "file://" is 7
4701 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004702 char_u *new_dir;
4703
4704 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004705 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004706 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004707 ++offset;
4708 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004709 }
4710
Bram Moolenaar474ad392022-08-21 11:37:17 +01004711 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004712 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004713 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004714 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004715 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004716 }
4717
Bram Moolenaar474ad392022-08-21 11:37:17 +01004718 new_dir = alloc(gap->ga_len - offset + 1);
4719 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004720 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4721 vim_free(new_dir);
4722}
4723
4724/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004725 * Called by libvterm when it cannot recognize an OSC sequence.
4726 * We recognize a terminal API command.
4727 */
4728 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004729parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004730{
4731 term_T *term = (term_T *)user;
4732 js_read_T reader;
4733 typval_T tv;
4734 channel_T *channel = term->tl_job == NULL ? NULL
4735 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004736 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004737
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004738 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004739 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004740 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004741
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004742 // Concatenate what was received until the final piece is found.
4743 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4744 {
4745 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004746 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004747 }
4748 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004749 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004750 if (!frag.final)
4751 return 1;
4752
4753 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004754
4755 if (command == 7)
4756 {
4757 sync_shell_dir(gap);
4758 ga_clear(gap);
4759 return 1;
4760 }
4761
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004762 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004763 reader.js_fill = NULL;
4764 reader.js_used = 0;
4765 if (json_decode(&reader, &tv, 0) == OK
4766 && tv.v_type == VAR_LIST
4767 && tv.vval.v_list != NULL)
4768 {
4769 listitem_T *item = tv.vval.v_list->lv_first;
4770
4771 if (item == NULL)
4772 ch_log(channel, "Missing command");
4773 else
4774 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004775 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004776
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004777 // Make sure an invoked command doesn't delete the buffer (and the
4778 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004779 ++term->tl_buffer->b_locked;
4780
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004781 item = item->li_next;
4782 if (item == NULL)
4783 ch_log(channel, "Missing argument for %s", cmd);
4784 else if (STRCMP(cmd, "drop") == 0)
4785 handle_drop_command(item);
4786 else if (STRCMP(cmd, "call") == 0)
4787 handle_call_command(term, channel, item);
4788 else
4789 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004790 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004791 }
4792 }
4793 else
4794 ch_log(channel, "Invalid JSON received");
4795
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004796 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004797 clear_tv(&tv);
4798 return 1;
4799}
4800
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004801/*
4802 * Called by libvterm when it cannot recognize a CSI sequence.
4803 * We recognize the window position report.
4804 */
4805 static int
4806parse_csi(
4807 const char *leader UNUSED,
4808 const long args[],
4809 int argcount,
4810 const char *intermed UNUSED,
4811 char command,
4812 void *user)
4813{
4814 term_T *term = (term_T *)user;
4815 char buf[100];
4816 int len;
4817 int x = 0;
4818 int y = 0;
4819 win_T *wp;
4820
4821 // We recognize only CSI 13 t
4822 if (command != 't' || argcount != 1 || args[0] != 13)
4823 return 0; // not handled
4824
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004825 // When getting the window position is not possible or it fails it results
4826 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004827#if defined(FEAT_GUI) \
4828 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4829 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004830 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004831#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004832
4833 FOR_ALL_WINDOWS(wp)
4834 if (wp->w_buffer == term->tl_buffer)
4835 break;
4836 if (wp != NULL)
4837 {
4838#ifdef FEAT_GUI
4839 if (gui.in_use)
4840 {
4841 x += wp->w_wincol * gui.char_width;
4842 y += W_WINROW(wp) * gui.char_height;
4843 }
4844 else
4845#endif
4846 {
4847 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004848 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004849 x += wp->w_wincol * 7;
4850 y += W_WINROW(wp) * 10;
4851 }
4852 }
4853
4854 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4855 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4856 (char_u *)buf, len, NULL);
4857 return 1;
4858}
4859
Bram Moolenaard8637282020-05-20 18:41:41 +02004860static VTermStateFallbacks state_fallbacks = {
Yegappan Lakshmanan562610c2025-05-04 21:05:51 +02004861 NULL, // control
4862 parse_csi, // csi
4863 parse_osc, // osc
4864 NULL, // dcs
4865 NULL, // apc
4866 NULL, // pm
4867 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004868};
4869
4870/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004871 * Use Vim's allocation functions for vterm so profiling works.
4872 */
4873 static void *
4874vterm_malloc(size_t size, void *data UNUSED)
4875{
Bram Moolenaar88137392021-11-12 16:01:15 +00004876 // make sure that the length is not zero
4877 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004878}
4879
4880 static void
4881vterm_memfree(void *ptr, void *data UNUSED)
4882{
4883 vim_free(ptr);
4884}
4885
4886static VTermAllocatorFunctions vterm_allocator = {
4887 &vterm_malloc,
4888 &vterm_memfree
4889};
4890
4891/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004892 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004893 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004894 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004895 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004896create_vterm(term_T *term, int rows, int cols)
4897{
4898 VTerm *vterm;
4899 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004900 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004901 VTermValue value;
4902
Bram Moolenaar756ef112018-04-10 12:04:27 +02004903 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004904 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004905 if (vterm == NULL)
4906 return FAIL;
4907
4908 // Allocate screen and state here, so we can bail out if that fails.
4909 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004910 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004911 if (state == NULL || screen == NULL)
4912 {
4913 vterm_free(vterm);
4914 return FAIL;
4915 }
4916
Bram Moolenaar52acb112018-03-18 19:20:22 +01004917 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004918 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004919 vterm_set_utf8(vterm, 1);
4920
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004921 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004922
4923 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004924 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004925 &term->tl_default_color.fg,
4926 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004927
Bram Moolenaar9e587872019-05-13 20:27:23 +02004928 if (t_colors < 16)
4929 // Less than 16 colors: assume that bold means using a bright color for
4930 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004931 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4932
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004933 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004934 vterm_screen_reset(screen, 1 /* hard */);
4935
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004936 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004937 vterm_screen_enable_altscreen(screen, 1);
4938
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004939 // For unix do not use a blinking cursor. In an xterm this causes the
4940 // cursor to blink if it's blinking in the xterm.
4941 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004942#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004943 if (GetCaretBlinkTime() == INFINITE)
4944 value.boolean = 0;
4945 else
4946 value.boolean = 1;
4947#else
4948 value.boolean = 0;
4949#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004950 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004951 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004952
4953 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004954}
4955
4956/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004957 * Reset the terminal palette to its default value.
4958 */
4959 static void
4960term_reset_palette(VTerm *vterm)
4961{
4962 VTermState *state = vterm_obtain_state(vterm);
4963 int index;
4964
4965 for (index = 0; index < 16; index++)
4966 {
4967 VTermColor color;
4968
4969 color.type = VTERM_COLOR_INDEXED;
4970 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4971 &color.index);
4972 // The first valid index starts at 1.
4973 color.index -= 1;
4974
4975 vterm_state_set_palette_color(state, index, &color);
4976 }
4977}
4978
4979 static void
4980term_update_palette(term_T *term)
4981{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004982#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004983 if (term_use_palette()
4984 && (term->tl_palette != NULL
4985 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004986 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004987 {
4988 if (term->tl_palette != NULL)
4989 set_vterm_palette(term->tl_vterm, term->tl_palette);
4990 else
4991 init_vterm_ansi_colors(term->tl_vterm);
4992 }
4993 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004994#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004995 term_reset_palette(term->tl_vterm);
4996}
4997
4998/*
4999 * Called when option 'termguicolors' is changed.
5000 */
5001 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005002term_update_palette_all(void)
LemonBoyb2b3acb2022-05-20 10:10:34 +01005003{
5004 term_T *term;
5005
5006 FOR_ALL_TERMS(term)
5007 {
5008 if (term->tl_vterm == NULL)
5009 continue;
5010 term_update_palette(term);
5011 }
5012}
5013
5014/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005015 * Called when option 'background' or 'termguicolors' was set,
5016 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02005017 */
5018 void
5019term_update_colors_all(void)
5020{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005021 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02005022
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005023 FOR_ALL_TERMS(term)
5024 {
5025 if (term->tl_vterm == NULL)
5026 continue;
5027 init_default_colors(term);
5028 vterm_state_set_default_colors(
5029 vterm_obtain_state(term->tl_vterm),
5030 &term->tl_default_color.fg,
5031 &term->tl_default_color.bg);
5032 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005033}
5034
5035/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005036 * Return the text to show for the buffer name and status.
5037 */
5038 char_u *
5039term_get_status_text(term_T *term)
5040{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005041 if (term->tl_status_text != NULL)
5042 return term->tl_status_text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005043
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005044 char_u *txt;
5045 size_t len;
5046 char_u *fname;
5047
5048 if (term->tl_normal_mode)
5049 {
5050 if (term_job_running(term))
5051 txt = (char_u *)_("Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005052 else
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005053 txt = (char_u *)_("Terminal-finished");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005054 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005055 else if (term->tl_title != NULL)
5056 txt = term->tl_title;
5057 else if (term_none_open(term))
5058 txt = (char_u *)_("active");
5059 else if (term_job_running(term))
5060 txt = (char_u *)_("running");
5061 else
5062 txt = (char_u *)_("finished");
5063 fname = buf_get_fname(term->tl_buffer);
5064 len = 9 + STRLEN(fname) + STRLEN(txt);
5065 term->tl_status_text = alloc(len);
5066 if (term->tl_status_text != NULL)
5067 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
5068 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005069 return term->tl_status_text;
5070}
5071
5072/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00005073 * Clear the cached value of the status text.
5074 */
5075 void
5076term_clear_status_text(term_T *term)
5077{
5078 VIM_CLEAR(term->tl_status_text);
5079}
5080
5081/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005082 * Mark references in jobs of terminals.
5083 */
5084 int
5085set_ref_in_term(int copyID)
5086{
5087 int abort = FALSE;
5088 term_T *term;
5089 typval_T tv;
5090
Bram Moolenaar75a1a942019-06-20 03:45:36 +02005091 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005092 if (term->tl_job != NULL)
5093 {
5094 tv.v_type = VAR_JOB;
5095 tv.vval.v_job = term->tl_job;
Yegappan Lakshmanan9cb865e2025-03-23 16:42:16 +01005096 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005097 }
5098 return abort;
5099}
5100
5101/*
5102 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005103 * Returns NULL when the buffer is not for a terminal window and logs a message
5104 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005105 */
5106 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005107term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005108{
5109 buf_T *buf;
5110
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005111 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01005112 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005113 --emsg_off;
5114 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005115 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01005116 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005117 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005118 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005119 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005120 return buf;
5121}
5122
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005123 static void
5124clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005125{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005126 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005127 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
5128 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005129}
5130
5131 static void
5132dump_term_color(FILE *fd, VTermColor *color)
5133{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005134 int index;
5135
5136 if (VTERM_COLOR_IS_INDEXED(color))
5137 index = color->index + 1;
5138 else if (color->type == 0)
5139 // use RGB values
5140 index = 255;
5141 else
5142 // default color
5143 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005144 fprintf(fd, "%02x%02x%02x%d",
5145 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005146 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005147}
5148
5149/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005150 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01005151 *
5152 * Each screen cell in full is:
5153 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5154 * {characters} is a space for an empty cell
5155 * For a double-width character "+" is changed to "*" and the next cell is
5156 * skipped.
5157 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5158 * when "&" use the same as the previous cell.
5159 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5160 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5161 * {color-idx} is a number from 0 to 255
5162 *
5163 * Screen cell with same width, attributes and color as the previous one:
5164 * |{characters}
5165 *
5166 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5167 *
5168 * Repeating the previous screen cell:
5169 * @{count}
5170 */
5171 void
5172f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5173{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005174 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005175 term_T *term;
5176 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005177 int max_height = 0;
5178 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005179 stat_T st;
5180 FILE *fd;
5181 VTermPos pos;
5182 VTermScreen *screen;
5183 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005184 VTermState *state;
5185 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005186
5187 if (check_restricted() || check_secure())
5188 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005189
5190 if (in_vim9script()
5191 && (check_for_buffer_arg(argvars, 0) == FAIL
5192 || check_for_string_arg(argvars, 1) == FAIL
5193 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5194 return;
5195
5196 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005197 if (buf == NULL)
5198 return;
5199 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005200 if (term->tl_vterm == NULL)
5201 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005202 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005203 return;
5204 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005205
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005206 if (argvars[2].v_type != VAR_UNKNOWN)
5207 {
5208 dict_T *d;
5209
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005210 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005211 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005212 d = argvars[2].vval.v_dict;
5213 if (d != NULL)
5214 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005215 max_height = dict_get_number(d, "rows");
5216 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005217 }
5218 }
5219
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005220 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005221 if (fname == NULL)
5222 return;
5223 if (mch_stat((char *)fname, &st) >= 0)
5224 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005225 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005226 return;
5227 }
5228
Bram Moolenaard96ff162018-02-18 22:13:29 +01005229 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5230 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005231 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005232 return;
5233 }
5234
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005235 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005236
5237 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005238 state = vterm_obtain_state(term->tl_vterm);
5239 vterm_state_get_cursorpos(state, &cursor_pos);
5240
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005241 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5242 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005243 {
5244 int repeat = 0;
5245
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005246 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5247 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005248 {
5249 VTermScreenCell cell;
5250 int same_attr;
5251 int same_chars = TRUE;
5252 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005253 int is_cursor_pos = (pos.col == cursor_pos.col
5254 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005255
5256 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005257 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005258
5259 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5260 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005261 int c = cell.chars[i];
5262 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005263 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005264
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005265 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005266 if (i == 0)
5267 {
5268 c = (c == NUL) ? ' ' : c;
5269 pc = (pc == NUL) ? ' ' : pc;
5270 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005271 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005272 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005273 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005274 break;
5275 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005276 same_attr = vtermAttr2hl(&cell.attrs)
5277 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005278 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5279 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005280 if (same_chars && cell.width == prev_cell.width && same_attr
5281 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005282 {
5283 ++repeat;
5284 }
5285 else
5286 {
5287 if (repeat > 0)
5288 {
5289 fprintf(fd, "@%d", repeat);
5290 repeat = 0;
5291 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005292 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005293
5294 if (cell.chars[0] == NUL)
5295 fputs(" ", fd);
5296 else
5297 {
5298 char_u charbuf[10];
5299 int len;
5300
5301 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5302 && cell.chars[i] != NUL; ++i)
5303 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005304 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005305 fwrite(charbuf, len, 1, fd);
5306 }
5307 }
5308
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005309 // When only the characters differ we don't write anything, the
5310 // following "|", "@" or NL will indicate using the same
5311 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005312 if (cell.width != prev_cell.width || !same_attr)
5313 {
5314 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005315 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005316 else
5317 fputs("+", fd);
5318
5319 if (same_attr)
5320 {
5321 fputs("&", fd);
5322 }
5323 else
5324 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005325 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005326 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005327 fputs("&", fd);
5328 else
5329 {
5330 fputs("#", fd);
5331 dump_term_color(fd, &cell.fg);
5332 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005333 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005334 fputs("&", fd);
5335 else
5336 {
5337 fputs("#", fd);
5338 dump_term_color(fd, &cell.bg);
5339 }
5340 }
5341 }
5342
5343 prev_cell = cell;
5344 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005345
5346 if (cell.width == 2)
5347 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005348 }
5349 if (repeat > 0)
5350 fprintf(fd, "@%d", repeat);
5351 fputs("\n", fd);
5352 }
5353
5354 fclose(fd);
5355}
5356
5357/*
5358 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5359 */
5360 static void
5361dump_is_corrupt(garray_T *gap)
5362{
5363 ga_concat(gap, (char_u *)"CORRUPT");
5364}
5365
5366 static void
5367append_cell(garray_T *gap, cellattr_T *cell)
5368{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005369 if (ga_grow(gap, 1) == FAIL)
5370 return;
5371
5372 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5373 ++gap->ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005374}
5375
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005376 static void
5377clear_cellattr(cellattr_T *cell)
5378{
5379 CLEAR_FIELD(*cell);
5380 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5381 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5382}
5383
Bram Moolenaard96ff162018-02-18 22:13:29 +01005384/*
5385 * Read the dump file from "fd" and append lines to the current buffer.
5386 * Return the cell width of the longest line.
5387 */
5388 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005389read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005390{
5391 int c;
5392 garray_T ga_text;
5393 garray_T ga_cell;
5394 char_u *prev_char = NULL;
5395 int attr = 0;
5396 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005397 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005398 term_T *term = curbuf->b_term;
5399 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005400 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005401
5402 ga_init2(&ga_text, 1, 90);
5403 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005404 clear_cellattr(&cell);
5405 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005406 cursor_pos->row = -1;
5407 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005408
5409 c = fgetc(fd);
5410 for (;;)
5411 {
5412 if (c == EOF)
5413 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005414 if (c == '\r')
5415 {
5416 // DOS line endings? Ignore.
5417 c = fgetc(fd);
5418 }
5419 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005420 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005421 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005422 if (ga_text.ga_data == NULL)
5423 dump_is_corrupt(&ga_text);
5424 if (ga_grow(&term->tl_scrollback, 1) == OK)
5425 {
5426 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5427 + term->tl_scrollback.ga_len;
5428
5429 if (max_cells < ga_cell.ga_len)
5430 max_cells = ga_cell.ga_len;
5431 line->sb_cols = ga_cell.ga_len;
5432 line->sb_cells = ga_cell.ga_data;
5433 line->sb_fill_attr = term->tl_default_color;
5434 ++term->tl_scrollback.ga_len;
5435 ga_init(&ga_cell);
5436
5437 ga_append(&ga_text, NUL);
5438 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5439 ga_text.ga_len, FALSE);
5440 }
5441 else
5442 ga_clear(&ga_cell);
5443 ga_text.ga_len = 0;
5444
5445 c = fgetc(fd);
5446 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005447 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005448 {
5449 int prev_len = ga_text.ga_len;
5450
Bram Moolenaar9271d052018-02-25 21:39:46 +01005451 if (c == '>')
5452 {
5453 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005454 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005455 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5456 cursor_pos->col = ga_cell.ga_len;
5457 }
5458
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005459 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005460 c = fgetc(fd);
5461 if (c != EOF)
5462 ga_append(&ga_text, c);
5463 for (;;)
5464 {
5465 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005466 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005467 || c == EOF || c == '\n')
5468 break;
5469 ga_append(&ga_text, c);
5470 }
5471
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005472 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005473 vim_free(prev_char);
5474 if (ga_text.ga_data != NULL)
5475 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5476 ga_text.ga_len - prev_len);
5477
Bram Moolenaar9271d052018-02-25 21:39:46 +01005478 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005479 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005480 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005481 }
5482 else if (c == '+' || c == '*')
5483 {
5484 int is_bg;
5485
5486 cell.width = c == '+' ? 1 : 2;
5487
5488 c = fgetc(fd);
5489 if (c == '&')
5490 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005491 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005492 c = fgetc(fd);
5493 }
Keith Thompson184f71c2024-01-04 21:19:04 +01005494 else if (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005495 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005496 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005497 attr = 0;
Keith Thompson184f71c2024-01-04 21:19:04 +01005498 while (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005499 {
5500 attr = attr * 10 + (c - '0');
5501 c = fgetc(fd);
5502 }
5503 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005504
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005505 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005506 for (is_bg = 0; is_bg <= 1; ++is_bg)
5507 {
5508 if (c == '&')
5509 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005510 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005511 c = fgetc(fd);
5512 }
5513 else if (c == '#')
5514 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005515 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005516
5517 c = fgetc(fd);
5518 red = hex2nr(c);
5519 c = fgetc(fd);
5520 red = (red << 4) + hex2nr(c);
5521 c = fgetc(fd);
5522 green = hex2nr(c);
5523 c = fgetc(fd);
5524 green = (green << 4) + hex2nr(c);
5525 c = fgetc(fd);
5526 blue = hex2nr(c);
5527 c = fgetc(fd);
5528 blue = (blue << 4) + hex2nr(c);
5529 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005530 if (!SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005531 dump_is_corrupt(&ga_text);
Keith Thompson184f71c2024-01-04 21:19:04 +01005532 while (SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005533 {
5534 index = index * 10 + (c - '0');
5535 c = fgetc(fd);
5536 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005537 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005538 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005539 type = VTERM_COLOR_RGB;
5540 if (index == 0)
5541 {
5542 if (is_bg)
5543 type |= VTERM_COLOR_DEFAULT_BG;
5544 else
5545 type |= VTERM_COLOR_DEFAULT_FG;
5546 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005547 }
5548 else
5549 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005550 type = VTERM_COLOR_INDEXED;
5551 index -= 1;
5552 }
5553 if (is_bg)
5554 {
5555 cell.bg.type = type;
5556 cell.bg.red = red;
5557 cell.bg.green = green;
5558 cell.bg.blue = blue;
5559 cell.bg.index = index;
5560 }
5561 else
5562 {
5563 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005564 cell.fg.red = red;
5565 cell.fg.green = green;
5566 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005567 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005568 }
5569 }
5570 else
5571 dump_is_corrupt(&ga_text);
5572 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005573 }
5574 else
5575 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005576 }
5577 else
5578 dump_is_corrupt(&ga_text);
5579
5580 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005581 if (cell.width == 2)
5582 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005583 }
5584 else if (c == '@')
5585 {
5586 if (prev_char == NULL)
5587 dump_is_corrupt(&ga_text);
5588 else
5589 {
5590 int count = 0;
5591
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005592 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005593 for (;;)
5594 {
5595 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005596 if (!SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005597 break;
5598 count = count * 10 + (c - '0');
5599 }
5600
5601 while (count-- > 0)
5602 {
5603 ga_concat(&ga_text, prev_char);
5604 append_cell(&ga_cell, &cell);
5605 }
5606 }
5607 }
5608 else
5609 {
5610 dump_is_corrupt(&ga_text);
5611 c = fgetc(fd);
5612 }
5613 }
5614
5615 if (ga_text.ga_len > 0)
5616 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005617 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005618 dump_is_corrupt(&ga_text);
5619 ga_append(&ga_text, NUL);
5620 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5621 ga_text.ga_len, FALSE);
5622 }
5623
5624 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005625 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005626 vim_free(prev_char);
5627
5628 return max_cells;
5629}
5630
5631/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005632 * Return an allocated string with at least "text_width" "=" characters and
5633 * "fname" inserted in the middle.
5634 */
5635 static char_u *
5636get_separator(int text_width, char_u *fname)
5637{
5638 int width = MAX(text_width, curwin->w_width);
5639 char_u *textline;
5640 int fname_size;
5641 char_u *p = fname;
5642 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005643 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005644
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005645 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005646 if (textline == NULL)
5647 return NULL;
5648
5649 fname_size = vim_strsize(fname);
5650 if (fname_size < width - 8)
5651 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005652 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005653 width = MAX(text_width, fname_size + 8);
5654 }
5655 else if (fname_size > width - 8)
5656 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005657 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005658 p = gettail(fname);
5659 fname_size = vim_strsize(p);
5660 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005661 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005662 while (fname_size > width - 8)
5663 {
5664 p += (*mb_ptr2len)(p);
5665 fname_size = vim_strsize(p);
5666 }
5667
5668 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5669 textline[i] = '=';
5670 textline[i++] = ' ';
5671
5672 STRCPY(textline + i, p);
5673 off = STRLEN(textline);
5674 textline[off] = ' ';
5675 for (i = 1; i < (width - fname_size) / 2; ++i)
5676 textline[off + i] = '=';
5677 textline[off + i] = NUL;
5678
5679 return textline;
5680}
5681
5682/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005683 * Common for "term_dumpdiff()" and "term_dumpload()".
5684 */
5685 static void
5686term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5687{
5688 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005689 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005690 char_u buf1[NUMBUFLEN];
5691 char_u buf2[NUMBUFLEN];
5692 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005693 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005694 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005695 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005696 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005697 char_u *textline = NULL;
5698
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005699 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005700 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005701 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005702 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005703 if (fname1 == NULL || (do_diff && fname2 == NULL))
5704 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005705 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005706 return;
5707 }
5708 fd1 = mch_fopen((char *)fname1, READBIN);
5709 if (fd1 == NULL)
5710 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005711 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005712 return;
5713 }
5714 if (do_diff)
5715 {
5716 fd2 = mch_fopen((char *)fname2, READBIN);
5717 if (fd2 == NULL)
5718 {
5719 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005720 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005721 return;
5722 }
5723 }
5724
5725 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005726 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5727 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5728 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5729 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5730 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005731
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005732 if (opt.jo_term_name == NULL)
5733 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005734 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005735
Bram Moolenaar51e14382019-05-25 20:21:28 +02005736 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005737 if (fname_tofree != NULL)
5738 {
5739 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5740 opt.jo_term_name = fname_tofree;
5741 }
5742 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005743
Bram Moolenaar87abab92019-06-03 21:14:59 +02005744 if (opt.jo_bufnr_buf != NULL)
5745 {
5746 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5747
5748 // With "bufnr" argument: enter the window with this buffer and make it
5749 // empty.
5750 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005751 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005752 else
5753 {
5754 buf = curbuf;
5755 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005756 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005757 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005758 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005759 }
5760 }
5761 else
5762 // Create a new terminal window.
5763 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5764
Bram Moolenaard96ff162018-02-18 22:13:29 +01005765 if (buf != NULL && buf->b_term != NULL)
5766 {
5767 int i;
5768 linenr_T bot_lnum;
5769 linenr_T lnum;
5770 term_T *term = buf->b_term;
5771 int width;
5772 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005773 VTermPos cursor_pos1;
5774 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005775
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005776 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005777
Bram Moolenaard96ff162018-02-18 22:13:29 +01005778 rettv->vval.v_number = buf->b_fnum;
5779
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005780 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005781 width = read_dump_file(fd1, &cursor_pos1);
5782
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005783 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005784 if (cursor_pos1.row >= 0)
5785 {
5786 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5787 coladvance(cursor_pos1.col);
5788 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005789
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005790 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005791 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005792
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005793 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005794 if (!do_diff)
5795 goto theend;
5796
5797 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5798
Bram Moolenaar4a696342018-04-05 18:45:26 +02005799 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005800 if (textline == NULL)
5801 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005802 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5803 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5804 vim_free(textline);
5805
5806 textline = get_separator(width, fname2);
5807 if (textline == NULL)
5808 goto theend;
5809 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5810 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005811 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005812
5813 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005814 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005815 if (width2 > width)
5816 {
5817 vim_free(textline);
5818 textline = alloc(width2 + 1);
5819 if (textline == NULL)
5820 goto theend;
5821 width = width2;
5822 textline[width] = NUL;
5823 }
5824 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5825
5826 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5827 {
5828 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5829 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005830 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005831 for (i = 0; i < width; ++i)
5832 textline[i] = '-';
5833 }
5834 else
5835 {
5836 char_u *line1;
5837 char_u *line2;
5838 char_u *p1;
5839 char_u *p2;
5840 int col;
5841 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5842 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5843 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5844 ->sb_cells;
5845
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005846 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005847 line1 = vim_strsave(ml_get(lnum));
5848 if (line1 == NULL)
5849 break;
5850 p1 = line1;
5851
5852 line2 = ml_get(lnum + bot_lnum);
5853 p2 = line2;
5854 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5855 {
5856 int len1 = utfc_ptr2len(p1);
5857 int len2 = utfc_ptr2len(p2);
5858
5859 textline[col] = ' ';
5860 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005861 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005862 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005863 else if (lnum == cursor_pos1.row + 1
5864 && col == cursor_pos1.col
5865 && (cursor_pos1.row != cursor_pos2.row
5866 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005867 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005868 textline[col] = '>';
5869 else if (lnum == cursor_pos2.row + 1
5870 && col == cursor_pos2.col
5871 && (cursor_pos1.row != cursor_pos2.row
5872 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005873 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005874 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005875 else if (cellattr1 != NULL && cellattr2 != NULL)
5876 {
5877 if ((cellattr1 + col)->width
5878 != (cellattr2 + col)->width)
5879 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005880 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005881 &(cellattr2 + col)->fg))
5882 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005883 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005884 &(cellattr2 + col)->bg))
5885 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005886 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5887 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005888 textline[col] = 'a';
5889 }
5890 p1 += len1;
5891 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005892 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005893 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005894
5895 while (col < width)
5896 {
5897 if (*p1 == NUL && *p2 == NUL)
5898 textline[col] = '?';
5899 else if (*p1 == NUL)
5900 {
5901 textline[col] = '+';
5902 p2 += utfc_ptr2len(p2);
5903 }
5904 else
5905 {
5906 textline[col] = '-';
5907 p1 += utfc_ptr2len(p1);
5908 }
5909 ++col;
5910 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005911
5912 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005913 }
5914 if (add_empty_scrollback(term, &term->tl_default_color,
5915 term->tl_top_diff_rows) == OK)
5916 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5917 ++bot_lnum;
5918 }
5919
5920 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5921 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005922 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005923 for (i = 0; i < width; ++i)
5924 textline[i] = '+';
5925 if (add_empty_scrollback(term, &term->tl_default_color,
5926 term->tl_top_diff_rows) == OK)
5927 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5928 ++lnum;
5929 ++bot_lnum;
5930 }
5931
5932 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005933
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005934 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005935 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005936 }
5937
5938theend:
5939 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005940 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005941 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005942 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005943 fclose(fd2);
5944}
5945
5946/*
5947 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5948 * bottom files.
5949 * Return FAIL when this is not possible.
5950 */
5951 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005952term_swap_diff(void)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005953{
5954 term_T *term = curbuf->b_term;
5955 linenr_T line_count;
5956 linenr_T top_rows;
5957 linenr_T bot_rows;
5958 linenr_T bot_start;
5959 linenr_T lnum;
5960 char_u *p;
5961 sb_line_T *sb_line;
5962
5963 if (term == NULL
5964 || !term_is_finished(curbuf)
5965 || term->tl_top_diff_rows == 0
5966 || term->tl_scrollback.ga_len == 0)
5967 return FAIL;
5968
5969 line_count = curbuf->b_ml.ml_line_count;
5970 top_rows = term->tl_top_diff_rows;
5971 bot_rows = term->tl_bot_diff_rows;
5972 bot_start = line_count - bot_rows;
5973 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5974
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005975 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005976 for (lnum = 1; lnum <= top_rows; ++lnum)
5977 {
5978 p = vim_strsave(ml_get(1));
5979 if (p == NULL)
5980 return OK;
5981 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005982 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005983 vim_free(p);
5984 }
5985
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005986 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005987 for (lnum = 1; lnum <= bot_rows; ++lnum)
5988 {
5989 p = vim_strsave(ml_get(bot_start + lnum));
5990 if (p == NULL)
5991 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005992 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005993 ml_append(lnum - 1, p, 0, FALSE);
5994 vim_free(p);
5995 }
5996
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005997 // move top title to bottom
5998 p = vim_strsave(ml_get(bot_rows + 1));
5999 if (p == NULL)
6000 return OK;
6001 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02006002 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01006003 vim_free(p);
6004
6005 // move bottom title to top
6006 p = vim_strsave(ml_get(line_count - top_rows));
6007 if (p == NULL)
6008 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02006009 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01006010 ml_append(bot_rows, p, 0, FALSE);
6011 vim_free(p);
6012
Bram Moolenaard96ff162018-02-18 22:13:29 +01006013 if (top_rows == bot_rows)
6014 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006015 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01006016 for (lnum = 0; lnum < top_rows; ++lnum)
6017 {
6018 sb_line_T temp;
6019
6020 temp = *(sb_line + lnum);
6021 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
6022 *(sb_line + bot_start + lnum) = temp;
6023 }
6024 }
6025 else
6026 {
6027 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006028 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006029
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006030 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01006031 if (temp != NULL)
6032 {
6033 mch_memmove(temp, term->tl_scrollback.ga_data, size);
6034 mch_memmove(term->tl_scrollback.ga_data,
6035 temp + bot_start,
6036 sizeof(sb_line_T) * bot_rows);
6037 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
6038 temp + top_rows,
6039 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
6040 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
6041 + line_count - top_rows,
6042 temp,
6043 sizeof(sb_line_T) * top_rows);
6044 vim_free(temp);
6045 }
6046 }
6047
6048 term->tl_top_diff_rows = bot_rows;
6049 term->tl_bot_diff_rows = top_rows;
6050
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006051 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006052 return OK;
6053}
6054
6055/*
6056 * "term_dumpdiff(filename, filename, options)" function
6057 */
6058 void
6059f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
6060{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02006061 if (in_vim9script()
6062 && (check_for_string_arg(argvars, 0) == FAIL
6063 || check_for_string_arg(argvars, 1) == FAIL
6064 || check_for_opt_dict_arg(argvars, 2) == FAIL))
6065 return;
6066
Bram Moolenaard96ff162018-02-18 22:13:29 +01006067 term_load_dump(argvars, rettv, TRUE);
6068}
6069
6070/*
6071 * "term_dumpload(filename, options)" function
6072 */
6073 void
6074f_term_dumpload(typval_T *argvars, typval_T *rettv)
6075{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006076 if (in_vim9script()
6077 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02006078 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006079 return;
6080
Bram Moolenaard96ff162018-02-18 22:13:29 +01006081 term_load_dump(argvars, rettv, FALSE);
6082}
6083
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006084/*
6085 * "term_getaltscreen(buf)" function
6086 */
6087 void
6088f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
6089{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006090 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006091
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006092 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6093 return;
6094
6095 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006096 if (buf == NULL)
6097 return;
6098 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
6099}
6100
6101/*
6102 * "term_getattr(attr, name)" function
6103 */
6104 void
6105f_term_getattr(typval_T *argvars, typval_T *rettv)
6106{
6107 int attr;
6108 size_t i;
6109 char_u *name;
6110
6111 static struct {
6112 char *name;
6113 int attr;
6114 } attrs[] = {
6115 {"bold", HL_BOLD},
6116 {"italic", HL_ITALIC},
6117 {"underline", HL_UNDERLINE},
6118 {"strike", HL_STRIKETHROUGH},
6119 {"reverse", HL_INVERSE},
6120 };
6121
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02006122 if (in_vim9script()
6123 && (check_for_number_arg(argvars, 0) == FAIL
6124 || check_for_string_arg(argvars, 1) == FAIL))
6125 return;
6126
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006127 attr = tv_get_number(&argvars[0]);
6128 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006129 if (name == NULL)
6130 return;
6131
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02006132 if (attr > HL_ALL)
6133 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02006134 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006135 if (STRCMP(name, attrs[i].name) == 0)
6136 {
6137 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
6138 break;
6139 }
6140}
6141
6142/*
6143 * "term_getcursor(buf)" function
6144 */
6145 void
6146f_term_getcursor(typval_T *argvars, typval_T *rettv)
6147{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006148 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006149 term_T *term;
6150 list_T *l;
6151 dict_T *d;
6152
6153 if (rettv_list_alloc(rettv) == FAIL)
6154 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006155
6156 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6157 return;
6158
6159 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006160 if (buf == NULL)
6161 return;
6162 term = buf->b_term;
6163
6164 l = rettv->vval.v_list;
6165 list_append_number(l, term->tl_cursor_pos.row + 1);
6166 list_append_number(l, term->tl_cursor_pos.col + 1);
6167
6168 d = dict_alloc();
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00006169 if (d == NULL)
6170 return;
6171
6172 dict_add_number(d, "visible", term->tl_cursor_visible);
6173 dict_add_number(d, "blink", blink_state_is_inverted()
6174 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6175 dict_add_number(d, "shape", term->tl_cursor_shape);
6176 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
6177 list_append_dict(l, d);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006178}
6179
6180/*
6181 * "term_getjob(buf)" function
6182 */
6183 void
6184f_term_getjob(typval_T *argvars, typval_T *rettv)
6185{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006186 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006187
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006188 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6189 return;
6190
6191 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006192 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006193 {
Ernie Raela78eb252024-06-13 17:24:54 +02006194 if (in_vim9script())
6195 {
6196 rettv->v_type = VAR_JOB;
6197 rettv->vval.v_job = NULL;
6198 }
6199 else
6200 {
6201 rettv->v_type = VAR_SPECIAL;
6202 rettv->vval.v_number = VVAL_NULL;
6203 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006204 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006205 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006206
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006207 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006208 rettv->vval.v_job = buf->b_term->tl_job;
6209 if (rettv->vval.v_job != NULL)
6210 ++rettv->vval.v_job->jv_refcount;
6211}
6212
6213 static int
6214get_row_number(typval_T *tv, term_T *term)
6215{
6216 if (tv->v_type == VAR_STRING
6217 && tv->vval.v_string != NULL
6218 && STRCMP(tv->vval.v_string, ".") == 0)
6219 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006220 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006221}
6222
6223/*
6224 * "term_getline(buf, row)" function
6225 */
6226 void
6227f_term_getline(typval_T *argvars, typval_T *rettv)
6228{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006229 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006230 term_T *term;
6231 int row;
6232
6233 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006234
6235 if (in_vim9script()
6236 && (check_for_buffer_arg(argvars, 0) == FAIL
6237 || check_for_lnum_arg(argvars, 1) == FAIL))
6238 return;
6239
6240 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006241 if (buf == NULL)
6242 return;
6243 term = buf->b_term;
6244 row = get_row_number(&argvars[1], term);
6245
6246 if (term->tl_vterm == NULL)
6247 {
6248 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6249
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006250 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006251 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6252 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6253 }
6254 else
6255 {
6256 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6257 VTermRect rect;
6258 int len;
6259 char_u *p;
6260
6261 if (row < 0 || row >= term->tl_rows)
6262 return;
6263 len = term->tl_cols * MB_MAXBYTES + 1;
6264 p = alloc(len);
6265 if (p == NULL)
6266 return;
6267 rettv->vval.v_string = p;
6268
6269 rect.start_col = 0;
6270 rect.end_col = term->tl_cols;
6271 rect.start_row = row;
6272 rect.end_row = row + 1;
6273 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6274 }
6275}
6276
6277/*
6278 * "term_getscrolled(buf)" function
6279 */
6280 void
6281f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6282{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006283 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006284
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006285 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6286 return;
6287
6288 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006289 if (buf == NULL)
6290 return;
6291 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6292}
6293
6294/*
6295 * "term_getsize(buf)" function
6296 */
6297 void
6298f_term_getsize(typval_T *argvars, typval_T *rettv)
6299{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006300 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006301 list_T *l;
6302
6303 if (rettv_list_alloc(rettv) == FAIL)
6304 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006305
6306 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6307 return;
6308
6309 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006310 if (buf == NULL)
6311 return;
6312
6313 l = rettv->vval.v_list;
6314 list_append_number(l, buf->b_term->tl_rows);
6315 list_append_number(l, buf->b_term->tl_cols);
6316}
6317
6318/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006319 * "term_setsize(buf, rows, cols)" function
6320 */
6321 void
Dominique Pellé0268ff32024-07-28 21:12:20 +02006322f_term_setsize(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006323{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006324 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006325 term_T *term;
6326 varnumber_T rows, cols;
6327
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006328 if (in_vim9script()
6329 && (check_for_buffer_arg(argvars, 0) == FAIL
6330 || check_for_number_arg(argvars, 1) == FAIL
6331 || check_for_number_arg(argvars, 2) == FAIL))
6332 return;
6333
6334 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006335 if (buf == NULL)
6336 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006337 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006338 return;
6339 }
6340 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006341 return;
6342 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006343 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006344 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006345 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006346 cols = cols <= 0 ? term->tl_cols : cols;
6347 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006348 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006349
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006350 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006351 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6352 term_report_winsize(term, term->tl_rows, term->tl_cols);
6353}
6354
6355/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006356 * "term_getstatus(buf)" function
6357 */
6358 void
6359f_term_getstatus(typval_T *argvars, typval_T *rettv)
6360{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006361 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006362 term_T *term;
6363 char_u val[100];
6364
6365 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006366
6367 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6368 return;
6369
6370 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006371 if (buf == NULL)
6372 return;
6373 term = buf->b_term;
6374
6375 if (term_job_running(term))
6376 STRCPY(val, "running");
6377 else
6378 STRCPY(val, "finished");
6379 if (term->tl_normal_mode)
6380 STRCAT(val, ",normal");
6381 rettv->vval.v_string = vim_strsave(val);
6382}
6383
6384/*
6385 * "term_gettitle(buf)" function
6386 */
6387 void
6388f_term_gettitle(typval_T *argvars, typval_T *rettv)
6389{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006390 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006391
6392 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006393
6394 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6395 return;
6396
6397 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006398 if (buf == NULL)
6399 return;
6400
6401 if (buf->b_term->tl_title != NULL)
6402 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6403}
6404
6405/*
6406 * "term_gettty(buf)" function
6407 */
6408 void
6409f_term_gettty(typval_T *argvars, typval_T *rettv)
6410{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006411 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006412 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006413 int num = 0;
6414
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006415 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006416 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006417 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6418 return;
6419
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006420 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006421 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006422 if (buf == NULL)
6423 return;
6424 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006425 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006426
6427 switch (num)
6428 {
6429 case 0:
6430 if (buf->b_term->tl_job != NULL)
6431 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006432 break;
6433 case 1:
6434 if (buf->b_term->tl_job != NULL)
6435 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006436 break;
6437 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006438 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006439 return;
6440 }
6441 if (p != NULL)
6442 rettv->vval.v_string = vim_strsave(p);
6443}
6444
6445/*
6446 * "term_list()" function
6447 */
6448 void
6449f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6450{
6451 term_T *tp;
6452 list_T *l;
6453
6454 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6455 return;
6456
6457 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006458 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006459 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006460 if (list_append_number(l,
6461 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6462 return;
6463}
6464
6465/*
6466 * "term_scrape(buf, row)" function
6467 */
6468 void
6469f_term_scrape(typval_T *argvars, typval_T *rettv)
6470{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006471 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006472 VTermScreen *screen = NULL;
6473 VTermPos pos;
6474 list_T *l;
6475 term_T *term;
6476 char_u *p;
6477 sb_line_T *line;
6478
6479 if (rettv_list_alloc(rettv) == FAIL)
6480 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006481
6482 if (in_vim9script()
6483 && (check_for_buffer_arg(argvars, 0) == FAIL
6484 || check_for_lnum_arg(argvars, 1) == FAIL))
6485 return;
6486
6487 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006488 if (buf == NULL)
6489 return;
6490 term = buf->b_term;
6491
6492 l = rettv->vval.v_list;
6493 pos.row = get_row_number(&argvars[1], term);
6494
6495 if (term->tl_vterm != NULL)
6496 {
6497 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006498 if (screen == NULL) // can't really happen
6499 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006500 p = NULL;
6501 line = NULL;
6502 }
6503 else
6504 {
6505 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6506
6507 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6508 return;
6509 p = ml_get_buf(buf, lnum + 1, FALSE);
6510 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6511 }
6512
6513 for (pos.col = 0; pos.col < term->tl_cols; )
6514 {
6515 dict_T *dcell;
6516 int width;
6517 VTermScreenCellAttrs attrs;
6518 VTermColor fg, bg;
6519 char_u rgb[8];
6520 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6521 int off = 0;
6522 int i;
6523
6524 if (screen == NULL)
6525 {
6526 cellattr_T *cellattr;
6527 int len;
6528
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006529 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006530 if (pos.col >= line->sb_cols)
6531 break;
6532 cellattr = line->sb_cells + pos.col;
6533 width = cellattr->width;
6534 attrs = cellattr->attrs;
6535 fg = cellattr->fg;
6536 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006537 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006538 mch_memmove(mbs, p, len);
6539 mbs[len] = NUL;
6540 p += len;
6541 }
6542 else
6543 {
6544 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006545
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006546 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6547 break;
6548 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6549 {
6550 if (cell.chars[i] == 0)
6551 break;
6552 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6553 }
6554 mbs[off] = NUL;
6555 width = cell.width;
6556 attrs = cell.attrs;
6557 fg = cell.fg;
6558 bg = cell.bg;
6559 }
6560 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006561 if (dcell == NULL)
6562 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006563 list_append_dict(l, dcell);
6564
Bram Moolenaare0be1672018-07-08 16:50:37 +02006565 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006566
6567 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6568 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006569 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006570 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6571 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006572 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006573
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006574 dict_add_number(dcell, "attr",
6575 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006576 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006577
6578 ++pos.col;
6579 if (width == 2)
6580 ++pos.col;
6581 }
6582}
6583
6584/*
6585 * "term_sendkeys(buf, keys)" function
6586 */
6587 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006588f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006589{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006590 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006591 char_u *msg;
6592 term_T *term;
6593
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006594 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006595 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006596 || check_for_string_arg(argvars, 1) == FAIL))
6597 return;
6598
6599 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006600 if (buf == NULL)
6601 return;
6602
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006603 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006604 if (msg == NULL)
6605 return;
6606 term = buf->b_term;
6607 if (term->tl_vterm == NULL)
6608 return;
6609
6610 while (*msg != NUL)
6611 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006612 int c;
6613
6614 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6615 {
6616 c = TO_SPECIAL(msg[1], msg[2]);
6617 msg += 3;
6618 }
6619 else
6620 {
6621 c = PTR2CHAR(msg);
6622 msg += MB_CPTR2LEN(msg);
6623 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006624 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006625 }
6626}
6627
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006628#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6629/*
6630 * "term_getansicolors(buf)" function
6631 */
6632 void
6633f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6634{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006635 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006636 term_T *term;
6637 VTermState *state;
6638 VTermColor color;
6639 char_u hexbuf[10];
6640 int index;
6641 list_T *list;
6642
6643 if (rettv_list_alloc(rettv) == FAIL)
6644 return;
6645
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006646 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6647 return;
6648
6649 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006650 if (buf == NULL)
6651 return;
6652 term = buf->b_term;
6653 if (term->tl_vterm == NULL)
6654 return;
6655
6656 list = rettv->vval.v_list;
6657 state = vterm_obtain_state(term->tl_vterm);
6658 for (index = 0; index < 16; index++)
6659 {
6660 vterm_state_get_palette_color(state, index, &color);
6661 sprintf((char *)hexbuf, "#%02x%02x%02x",
6662 color.red, color.green, color.blue);
6663 if (list_append_string(list, hexbuf, 7) == FAIL)
6664 return;
6665 }
6666}
6667
6668/*
6669 * "term_setansicolors(buf, list)" function
6670 */
6671 void
6672f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6673{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006674 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006675 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006676 listitem_T *li;
6677 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006678
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006679 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006680 && (check_for_buffer_arg(argvars, 0) == FAIL
6681 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006682 return;
6683
6684 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006685 if (buf == NULL)
6686 return;
6687 term = buf->b_term;
6688 if (term->tl_vterm == NULL)
6689 return;
6690
Bram Moolenaard83392a2022-09-01 12:22:46 +01006691 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006692 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006693
LemonBoyb2b3acb2022-05-20 10:10:34 +01006694 if (argvars[1].vval.v_list->lv_first == &range_list_item
6695 || argvars[1].vval.v_list->lv_len != 16)
6696 {
Bram Moolenaar23919542023-05-05 22:12:22 +01006697 semsg(_(e_invalid_value_for_argument_str), "\"colors\"");
LemonBoyb2b3acb2022-05-20 10:10:34 +01006698 return;
6699 }
6700
6701 if (term->tl_palette == NULL)
6702 term->tl_palette = ALLOC_MULT(long_u, 16);
6703 if (term->tl_palette == NULL)
6704 return;
6705
6706 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6707 {
6708 char_u *color_name;
6709 guicolor_T guicolor;
6710
6711 color_name = tv_get_string_chk(&li->li_tv);
6712 if (color_name == NULL)
6713 return;
6714
6715 guicolor = GUI_GET_COLOR(color_name);
6716 if (guicolor == INVALCOLOR)
6717 {
6718 semsg(_(e_cannot_allocate_color_str), color_name);
6719 return;
6720 }
6721
6722 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6723 }
6724
6725 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006726}
6727#endif
6728
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006729/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006730 * "term_setapi(buf, api)" function
6731 */
6732 void
6733f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6734{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006735 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006736 term_T *term;
6737 char_u *api;
6738
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006739 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006740 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006741 || check_for_string_arg(argvars, 1) == FAIL))
6742 return;
6743
6744 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006745 if (buf == NULL)
6746 return;
6747 term = buf->b_term;
6748 vim_free(term->tl_api);
6749 api = tv_get_string_chk(&argvars[1]);
6750 if (api != NULL)
6751 term->tl_api = vim_strsave(api);
6752 else
6753 term->tl_api = NULL;
6754}
6755
6756/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006757 * "term_setrestore(buf, command)" function
6758 */
6759 void
6760f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6761{
6762#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006763 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006764 term_T *term;
6765 char_u *cmd;
6766
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006767 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006768 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006769 || check_for_string_arg(argvars, 1) == FAIL))
6770 return;
6771
6772 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006773 if (buf == NULL)
6774 return;
6775 term = buf->b_term;
6776 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006777 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006778 if (cmd != NULL)
6779 term->tl_command = vim_strsave(cmd);
6780 else
6781 term->tl_command = NULL;
6782#endif
6783}
6784
6785/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006786 * "term_setkill(buf, how)" function
6787 */
6788 void
6789f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6790{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006791 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006792 term_T *term;
6793 char_u *how;
6794
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006795 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006796 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006797 || check_for_string_arg(argvars, 1) == FAIL))
6798 return;
6799
6800 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006801 if (buf == NULL)
6802 return;
6803 term = buf->b_term;
6804 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006805 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006806 if (how != NULL)
6807 term->tl_kill = vim_strsave(how);
6808 else
6809 term->tl_kill = NULL;
6810}
6811
6812/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006813 * "term_start(command, options)" function
6814 */
6815 void
6816f_term_start(typval_T *argvars, typval_T *rettv)
6817{
6818 jobopt_T opt;
6819 buf_T *buf;
6820
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006821 if (in_vim9script()
6822 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6823 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6824 return;
6825
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006826 init_job_options(&opt);
6827 if (argvars[1].v_type != VAR_UNKNOWN
6828 && get_job_options(&argvars[1], &opt,
6829 JO_TIMEOUT_ALL + JO_STOPONEXIT
6830 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6831 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6832 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6833 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006834 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006835 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006836 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006837 return;
6838
Bram Moolenaar13568252018-03-16 20:46:58 +01006839 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006840
6841 if (buf != NULL && buf->b_term != NULL)
6842 rettv->vval.v_number = buf->b_fnum;
6843}
6844
6845/*
6846 * "term_wait" function
6847 */
6848 void
6849f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6850{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006851 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006852
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006853 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006854 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006855 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006856 return;
6857
6858 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006859 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006860 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006861 if (buf->b_term->tl_job == NULL)
6862 {
6863 ch_log(NULL, "term_wait(): no job to wait for");
6864 return;
6865 }
6866 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006867 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006868 return;
6869
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006870 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006871 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006872 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6873 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006874 // The job is dead, keep reading channel I/O until the channel is
6875 // closed. buf->b_term may become NULL if the terminal was closed while
6876 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006877 ch_log(NULL, "term_wait(): waiting for channel to close");
6878 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6879 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006880 term_flush_messages();
6881
Bram Moolenaard45aa552018-05-21 22:50:29 +02006882 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006883 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006884 // If the terminal is closed when the channel is closed the
6885 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006886 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006887 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6888 // came here from a close callback, only wait one time
6889 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006890 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006891
6892 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006893 }
6894 else
6895 {
6896 long wait = 10L;
6897
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006898 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006899
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006900 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006901 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006902 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006903 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006904
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006905 // Flushing messages on channels is hopefully sufficient.
6906 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006907 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006908 }
6909}
6910
6911/*
6912 * Called when a channel has sent all the lines to a terminal.
6913 * Send a CTRL-D to mark the end of the text.
6914 */
6915 void
6916term_send_eof(channel_T *ch)
6917{
6918 term_T *term;
6919
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006920 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006921 if (term->tl_job == ch->ch_job)
6922 {
6923 if (term->tl_eof_chars != NULL)
6924 {
6925 channel_send(ch, PART_IN, term->tl_eof_chars,
6926 (int)STRLEN(term->tl_eof_chars), NULL);
6927 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6928 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006929# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006930 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006931 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006932 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6933# endif
6934 }
6935}
6936
Bram Moolenaar113e1072019-01-20 15:30:40 +01006937#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006938 job_T *
6939term_getjob(term_T *term)
6940{
6941 return term != NULL ? term->tl_job : NULL;
6942}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006943#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006944
Bram Moolenaar4f974752019-02-17 17:44:42 +01006945# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006946
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006947///////////////////////////////////////
6948// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006949#ifdef PROTO
6950typedef int COORD;
6951typedef int DWORD;
6952typedef int HANDLE;
6953typedef int *DWORD_PTR;
6954typedef int HPCON;
6955typedef int HRESULT;
6956typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006957typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006958typedef int PSIZE_T;
6959typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006960typedef int BOOL;
6961# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006962#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006963
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006964HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6965HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6966HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006967BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6968BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6969void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006970
6971 static int
6972dyn_conpty_init(int verbose)
6973{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006974 static HMODULE hKerneldll = NULL;
6975 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006976 static struct
6977 {
6978 char *name;
6979 FARPROC *ptr;
6980 } conpty_entry[] =
6981 {
6982 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6983 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6984 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6985 {"InitializeProcThreadAttributeList",
6986 (FARPROC*)&pInitializeProcThreadAttributeList},
6987 {"UpdateProcThreadAttribute",
6988 (FARPROC*)&pUpdateProcThreadAttribute},
6989 {"DeleteProcThreadAttributeList",
6990 (FARPROC*)&pDeleteProcThreadAttributeList},
6991 {NULL, NULL}
6992 };
6993
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006994 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006995 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006996 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006997 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006998 return FAIL;
6999 }
7000
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007001 // No need to initialize twice.
7002 if (hKerneldll)
7003 return OK;
7004
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007005 hKerneldll = vimLoadLib("kernel32.dll");
7006 for (i = 0; conpty_entry[i].name != NULL
7007 && conpty_entry[i].ptr != NULL; ++i)
7008 {
7009 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
7010 conpty_entry[i].name)) == NULL)
7011 {
7012 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007013 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007014 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007015 return FAIL;
7016 }
7017 }
7018
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007019 return OK;
7020}
7021
7022 static int
7023conpty_term_and_job_init(
7024 term_T *term,
7025 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007026 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007027 jobopt_T *opt,
7028 jobopt_T *orig_opt)
7029{
7030 WCHAR *cmd_wchar = NULL;
7031 WCHAR *cmd_wchar_copy = NULL;
7032 WCHAR *cwd_wchar = NULL;
7033 WCHAR *env_wchar = NULL;
7034 channel_T *channel = NULL;
7035 job_T *job = NULL;
7036 HANDLE jo = NULL;
7037 garray_T ga_cmd, ga_env;
7038 char_u *cmd = NULL;
7039 HRESULT hr;
7040 COORD consize;
7041 SIZE_T breq;
7042 PROCESS_INFORMATION proc_info;
7043 HANDLE i_theirs = NULL;
7044 HANDLE o_theirs = NULL;
7045 HANDLE i_ours = NULL;
7046 HANDLE o_ours = NULL;
7047
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007048 ga_init2(&ga_cmd, sizeof(char*), 20);
7049 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007050
7051 if (argvar->v_type == VAR_STRING)
7052 {
7053 cmd = argvar->vval.v_string;
7054 }
7055 else if (argvar->v_type == VAR_LIST)
7056 {
7057 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
7058 goto failed;
7059 cmd = ga_cmd.ga_data;
7060 }
7061 if (cmd == NULL || *cmd == NUL)
7062 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007063 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007064 goto failed;
7065 }
7066
7067 term->tl_arg0_cmd = vim_strsave(cmd);
7068
7069 cmd_wchar = enc_to_utf16(cmd, NULL);
7070
7071 if (cmd_wchar != NULL)
7072 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007073 // Request by CreateProcessW
7074 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007075 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007076 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
7077 }
7078
7079 ga_clear(&ga_cmd);
7080 if (cmd_wchar == NULL)
7081 goto failed;
7082 if (opt->jo_cwd != NULL)
John Marriott031f2272025-04-23 20:56:08 +02007083 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007084 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
John Marriott031f2272025-04-23 20:56:08 +02007085 if (cwd_wchar == NULL)
7086 goto failed;
7087 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007088
7089 win32_build_env(opt->jo_env, &ga_env, TRUE);
7090 env_wchar = ga_env.ga_data;
7091
7092 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
7093 goto failed;
7094 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
7095 goto failed;
7096
7097 consize.X = term->tl_cols;
7098 consize.Y = term->tl_rows;
7099 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
7100 &term->tl_conpty);
7101 if (FAILED(hr))
7102 goto failed;
7103
7104 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
7105
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007106 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007107 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007108 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007109 if (!term->tl_siex.lpAttributeList)
7110 goto failed;
7111 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
7112 0, &breq))
7113 goto failed;
7114 if (!pUpdateProcThreadAttribute(
7115 term->tl_siex.lpAttributeList, 0,
7116 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
7117 sizeof(HPCON), NULL, NULL))
7118 goto failed;
7119
7120 channel = add_channel();
7121 if (channel == NULL)
7122 goto failed;
7123
7124 job = job_alloc();
7125 if (job == NULL)
7126 goto failed;
7127 if (argvar->v_type == VAR_STRING)
7128 {
7129 int argc;
7130
7131 build_argv_from_string(cmd, &job->jv_argv, &argc);
7132 }
7133 else
7134 {
7135 int argc;
7136
7137 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7138 }
7139
7140 if (opt->jo_set & JO_IN_BUF)
7141 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7142
7143 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
7144 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02007145 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007146 env_wchar, cwd_wchar,
7147 &term->tl_siex.StartupInfo, &proc_info))
7148 goto failed;
7149
7150 CloseHandle(i_theirs);
7151 CloseHandle(o_theirs);
7152
7153 channel_set_pipes(channel,
7154 (sock_T)i_ours,
7155 (sock_T)o_ours,
7156 (sock_T)o_ours);
7157
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007158 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007159 channel->ch_write_text_mode = TRUE;
7160
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007161 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007162 channel->ch_anonymous_pipe = TRUE;
7163
7164 jo = CreateJobObject(NULL, NULL);
7165 if (jo == NULL)
7166 goto failed;
7167
7168 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7169 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007170 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007171 CloseHandle(jo);
7172 jo = NULL;
7173 }
7174
7175 ResumeThread(proc_info.hThread);
7176 CloseHandle(proc_info.hThread);
7177
7178 vim_free(cmd_wchar);
7179 vim_free(cmd_wchar_copy);
7180 vim_free(cwd_wchar);
7181 vim_free(env_wchar);
7182
7183 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7184 goto failed;
7185
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007186#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007187 if (term_use_palette())
7188 {
7189 if (term->tl_palette != NULL)
7190 set_vterm_palette(term->tl_vterm, term->tl_palette);
7191 else
7192 init_vterm_ansi_colors(term->tl_vterm);
7193 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007194#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007195
7196 channel_set_job(channel, job, opt);
7197 job_set_options(job, opt);
7198
7199 job->jv_channel = channel;
7200 job->jv_proc_info = proc_info;
7201 job->jv_job_object = jo;
7202 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007203 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007204 ++job->jv_refcount;
7205 term->tl_job = job;
7206
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007207 // Redirecting stdout and stderr doesn't work at the job level. Instead
7208 // open the file here and handle it in. opt->jo_io was changed in
7209 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007210 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7211 {
7212 char_u *fname = opt->jo_io_name[PART_OUT];
7213
7214 ch_log(channel, "Opening output file %s", fname);
7215 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7216 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007217 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007218 }
7219
7220 return OK;
7221
7222failed:
7223 ga_clear(&ga_cmd);
7224 ga_clear(&ga_env);
7225 vim_free(cmd_wchar);
7226 vim_free(cmd_wchar_copy);
7227 vim_free(cwd_wchar);
7228 if (channel != NULL)
7229 channel_clear(channel);
7230 if (job != NULL)
7231 {
7232 job->jv_channel = NULL;
7233 job_cleanup(job);
7234 }
7235 term->tl_job = NULL;
7236 if (jo != NULL)
7237 CloseHandle(jo);
7238
7239 if (term->tl_siex.lpAttributeList != NULL)
7240 {
7241 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7242 vim_free(term->tl_siex.lpAttributeList);
7243 }
7244 term->tl_siex.lpAttributeList = NULL;
7245 if (o_theirs != NULL)
7246 CloseHandle(o_theirs);
7247 if (o_ours != NULL)
7248 CloseHandle(o_ours);
7249 if (i_ours != NULL)
7250 CloseHandle(i_ours);
7251 if (i_theirs != NULL)
7252 CloseHandle(i_theirs);
7253 if (term->tl_conpty != NULL)
7254 pClosePseudoConsole(term->tl_conpty);
7255 term->tl_conpty = NULL;
7256 return FAIL;
7257}
7258
7259 static void
7260conpty_term_report_winsize(term_T *term, int rows, int cols)
7261{
7262 COORD consize;
7263
7264 consize.X = cols;
7265 consize.Y = rows;
7266 pResizePseudoConsole(term->tl_conpty, consize);
7267}
7268
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007269 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007270term_free_conpty(term_T *term)
7271{
7272 if (term->tl_siex.lpAttributeList != NULL)
7273 {
7274 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7275 vim_free(term->tl_siex.lpAttributeList);
7276 }
7277 term->tl_siex.lpAttributeList = NULL;
7278 if (term->tl_conpty != NULL)
7279 pClosePseudoConsole(term->tl_conpty);
7280 term->tl_conpty = NULL;
7281}
7282
7283 int
7284use_conpty(void)
7285{
7286 return has_conpty;
7287}
7288
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007289# ifndef PROTO
7290
7291#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7292#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007293#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007294
7295void* (*winpty_config_new)(UINT64, void*);
7296void* (*winpty_open)(void*, void*);
7297void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7298BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7299void (*winpty_config_set_mouse_mode)(void*, int);
7300void (*winpty_config_set_initial_size)(void*, int, int);
7301LPCWSTR (*winpty_conin_name)(void*);
7302LPCWSTR (*winpty_conout_name)(void*);
7303LPCWSTR (*winpty_conerr_name)(void*);
7304void (*winpty_free)(void*);
7305void (*winpty_config_free)(void*);
7306void (*winpty_spawn_config_free)(void*);
7307void (*winpty_error_free)(void*);
7308LPCWSTR (*winpty_error_msg)(void*);
7309BOOL (*winpty_set_size)(void*, int, int, void*);
7310HANDLE (*winpty_agent_process)(void*);
7311
7312#define WINPTY_DLL "winpty.dll"
7313
7314static HINSTANCE hWinPtyDLL = NULL;
7315# endif
7316
7317 static int
7318dyn_winpty_init(int verbose)
7319{
7320 int i;
7321 static struct
7322 {
7323 char *name;
7324 FARPROC *ptr;
7325 } winpty_entry[] =
7326 {
7327 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7328 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7329 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7330 {"winpty_config_set_mouse_mode",
7331 (FARPROC*)&winpty_config_set_mouse_mode},
7332 {"winpty_config_set_initial_size",
7333 (FARPROC*)&winpty_config_set_initial_size},
7334 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7335 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7336 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7337 {"winpty_free", (FARPROC*)&winpty_free},
7338 {"winpty_open", (FARPROC*)&winpty_open},
7339 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7340 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7341 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7342 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7343 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7344 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7345 {NULL, NULL}
7346 };
7347
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007348 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007349 if (hWinPtyDLL)
7350 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007351 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7352 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007353 if (*p_winptydll != NUL)
7354 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7355 if (!hWinPtyDLL)
7356 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7357 if (!hWinPtyDLL)
7358 {
7359 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007360 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007361 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7362 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007363 return FAIL;
7364 }
7365 for (i = 0; winpty_entry[i].name != NULL
7366 && winpty_entry[i].ptr != NULL; ++i)
7367 {
7368 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7369 winpty_entry[i].name)) == NULL)
7370 {
7371 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007372 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007373 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007374 return FAIL;
7375 }
7376 }
7377
7378 return OK;
7379}
7380
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007381 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007382winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007383 term_T *term,
7384 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007385 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007386 jobopt_T *opt,
7387 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007388{
7389 WCHAR *cmd_wchar = NULL;
7390 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007391 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007392 channel_T *channel = NULL;
7393 job_T *job = NULL;
7394 DWORD error;
7395 HANDLE jo = NULL;
7396 HANDLE child_process_handle;
7397 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007398 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007399 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007400 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007401 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007402
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007403 ga_init2(&ga_cmd, sizeof(char*), 20);
7404 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007405
7406 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007407 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007408 cmd = argvar->vval.v_string;
7409 }
7410 else if (argvar->v_type == VAR_LIST)
7411 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007412 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007413 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007414 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007415 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007416 if (cmd == NULL || *cmd == NUL)
7417 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007418 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007419 goto failed;
7420 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007421
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007422 term->tl_arg0_cmd = vim_strsave(cmd);
7423
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007424 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007425 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007426 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007427 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007428 if (opt->jo_cwd != NULL)
John Marriott031f2272025-04-23 20:56:08 +02007429 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007430 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
John Marriott031f2272025-04-23 20:56:08 +02007431 if (cwd_wchar == NULL)
7432 goto failed;
7433 }
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007434
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007435 win32_build_env(opt->jo_env, &ga_env, TRUE);
7436 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007437
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007438 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7439 if (term->tl_winpty_config == NULL)
7440 goto failed;
7441
7442 winpty_config_set_mouse_mode(term->tl_winpty_config,
7443 WINPTY_MOUSE_MODE_FORCE);
7444 winpty_config_set_initial_size(term->tl_winpty_config,
7445 term->tl_cols, term->tl_rows);
7446 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7447 if (term->tl_winpty == NULL)
7448 goto failed;
7449
7450 spawn_config = winpty_spawn_config_new(
7451 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7452 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7453 NULL,
7454 cmd_wchar,
7455 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007456 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007457 &winpty_err);
7458 if (spawn_config == NULL)
7459 goto failed;
7460
7461 channel = add_channel();
7462 if (channel == NULL)
7463 goto failed;
7464
7465 job = job_alloc();
7466 if (job == NULL)
7467 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007468 if (argvar->v_type == VAR_STRING)
7469 {
7470 int argc;
7471
7472 build_argv_from_string(cmd, &job->jv_argv, &argc);
7473 }
7474 else
7475 {
7476 int argc;
7477
7478 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7479 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007480
7481 if (opt->jo_set & JO_IN_BUF)
7482 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7483
7484 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7485 &child_thread_handle, &error, &winpty_err))
7486 goto failed;
7487
7488 channel_set_pipes(channel,
7489 (sock_T)CreateFileW(
7490 winpty_conin_name(term->tl_winpty),
7491 GENERIC_WRITE, 0, NULL,
7492 OPEN_EXISTING, 0, NULL),
7493 (sock_T)CreateFileW(
7494 winpty_conout_name(term->tl_winpty),
7495 GENERIC_READ, 0, NULL,
7496 OPEN_EXISTING, 0, NULL),
7497 (sock_T)CreateFileW(
7498 winpty_conerr_name(term->tl_winpty),
7499 GENERIC_READ, 0, NULL,
7500 OPEN_EXISTING, 0, NULL));
7501
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007502 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007503 channel->ch_write_text_mode = TRUE;
7504
7505 jo = CreateJobObject(NULL, NULL);
7506 if (jo == NULL)
7507 goto failed;
7508
7509 if (!AssignProcessToJobObject(jo, child_process_handle))
7510 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007511 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007512 CloseHandle(jo);
7513 jo = NULL;
7514 }
7515
7516 winpty_spawn_config_free(spawn_config);
7517 vim_free(cmd_wchar);
7518 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007519 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007520
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007521 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7522 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007523
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007524#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007525 if (term_use_palette())
7526 {
7527 if (term->tl_palette != NULL)
7528 set_vterm_palette(term->tl_vterm, term->tl_palette);
7529 else
7530 init_vterm_ansi_colors(term->tl_vterm);
7531 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007532#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007533
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007534 channel_set_job(channel, job, opt);
7535 job_set_options(job, opt);
7536
7537 job->jv_channel = channel;
7538 job->jv_proc_info.hProcess = child_process_handle;
7539 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7540 job->jv_job_object = jo;
7541 job->jv_status = JOB_STARTED;
7542 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007543 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007544 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007545 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007546 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007547 ++job->jv_refcount;
7548 term->tl_job = job;
7549
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007550 // Redirecting stdout and stderr doesn't work at the job level. Instead
7551 // open the file here and handle it in. opt->jo_io was changed in
7552 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007553 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7554 {
7555 char_u *fname = opt->jo_io_name[PART_OUT];
7556
7557 ch_log(channel, "Opening output file %s", fname);
7558 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7559 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007560 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007561 }
7562
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007563 return OK;
7564
7565failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007566 ga_clear(&ga_cmd);
7567 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007568 vim_free(cmd_wchar);
7569 vim_free(cwd_wchar);
7570 if (spawn_config != NULL)
7571 winpty_spawn_config_free(spawn_config);
7572 if (channel != NULL)
7573 channel_clear(channel);
7574 if (job != NULL)
7575 {
7576 job->jv_channel = NULL;
7577 job_cleanup(job);
7578 }
7579 term->tl_job = NULL;
7580 if (jo != NULL)
7581 CloseHandle(jo);
7582 if (term->tl_winpty != NULL)
7583 winpty_free(term->tl_winpty);
7584 term->tl_winpty = NULL;
7585 if (term->tl_winpty_config != NULL)
7586 winpty_config_free(term->tl_winpty_config);
7587 term->tl_winpty_config = NULL;
7588 if (winpty_err != NULL)
7589 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007590 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007591 (short_u *)winpty_error_msg(winpty_err), NULL);
7592
John Marriott031f2272025-04-23 20:56:08 +02007593 if (msg != NULL)
7594 {
7595 emsg(msg);
7596 vim_free(msg);
7597 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007598 winpty_error_free(winpty_err);
7599 }
7600 return FAIL;
7601}
7602
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007603/*
7604 * Create a new terminal of "rows" by "cols" cells.
7605 * Store a reference in "term".
7606 * Return OK or FAIL.
7607 */
7608 static int
7609term_and_job_init(
7610 term_T *term,
7611 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007612 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007613 jobopt_T *opt,
7614 jobopt_T *orig_opt)
7615{
7616 int use_winpty = FALSE;
7617 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007618 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007619
7620 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7621 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7622
7623 if (!has_winpty && !has_conpty)
7624 // If neither is available give the errors for winpty, since when
7625 // conpty is not available it can't be installed either.
7626 return dyn_winpty_init(TRUE);
7627
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007628 if (opt->jo_tty_type != NUL)
7629 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007630
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007631 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007632 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007633 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007634 use_conpty = TRUE;
7635 else if (has_winpty)
7636 use_winpty = TRUE;
7637 // else: error
7638 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007639 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007640 {
7641 if (has_winpty)
7642 use_winpty = TRUE;
7643 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007644 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007645 {
7646 if (has_conpty)
7647 use_conpty = TRUE;
7648 else
7649 return dyn_conpty_init(TRUE);
7650 }
7651
7652 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007653 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007654
7655 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007656 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007657
7658 // error
7659 return dyn_winpty_init(TRUE);
7660}
7661
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007662 static int
7663create_pty_only(term_T *term, jobopt_T *options)
7664{
7665 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7666 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7667 char in_name[80], out_name[80];
7668 channel_T *channel = NULL;
7669
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007670 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7671 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007672
7673 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7674 GetCurrentProcessId(),
7675 curbuf->b_fnum);
7676 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7677 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7678 PIPE_UNLIMITED_INSTANCES,
7679 0, 0, NMPWAIT_NOWAIT, NULL);
7680 if (hPipeIn == INVALID_HANDLE_VALUE)
7681 goto failed;
7682
7683 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7684 GetCurrentProcessId(),
7685 curbuf->b_fnum);
7686 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7687 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7688 PIPE_UNLIMITED_INSTANCES,
7689 0, 0, 0, NULL);
7690 if (hPipeOut == INVALID_HANDLE_VALUE)
7691 goto failed;
7692
7693 ConnectNamedPipe(hPipeIn, NULL);
7694 ConnectNamedPipe(hPipeOut, NULL);
7695
7696 term->tl_job = job_alloc();
7697 if (term->tl_job == NULL)
7698 goto failed;
7699 ++term->tl_job->jv_refcount;
7700
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007701 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007702 term->tl_job->jv_status = JOB_FINISHED;
7703
7704 channel = add_channel();
7705 if (channel == NULL)
7706 goto failed;
7707 term->tl_job->jv_channel = channel;
7708 channel->ch_keep_open = TRUE;
7709 channel->ch_named_pipe = TRUE;
7710
7711 channel_set_pipes(channel,
7712 (sock_T)hPipeIn,
7713 (sock_T)hPipeOut,
7714 (sock_T)hPipeOut);
7715 channel_set_job(channel, term->tl_job, options);
7716 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7717 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7718
7719 return OK;
7720
7721failed:
7722 if (hPipeIn != NULL)
7723 CloseHandle(hPipeIn);
7724 if (hPipeOut != NULL)
7725 CloseHandle(hPipeOut);
7726 return FAIL;
7727}
7728
7729/*
7730 * Free the terminal emulator part of "term".
7731 */
7732 static void
7733term_free_vterm(term_T *term)
7734{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007735 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007736 if (term->tl_winpty != NULL)
7737 winpty_free(term->tl_winpty);
7738 term->tl_winpty = NULL;
7739 if (term->tl_winpty_config != NULL)
7740 winpty_config_free(term->tl_winpty_config);
7741 term->tl_winpty_config = NULL;
7742 if (term->tl_vterm != NULL)
7743 vterm_free(term->tl_vterm);
7744 term->tl_vterm = NULL;
7745}
7746
7747/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007748 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007749 */
7750 static void
7751term_report_winsize(term_T *term, int rows, int cols)
7752{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007753 if (term->tl_conpty)
7754 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007755 if (term->tl_winpty)
7756 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7757}
7758
7759 int
7760terminal_enabled(void)
7761{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007762 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007763}
7764
7765# else
7766
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007767///////////////////////////////////////
7768// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007769
7770/*
7771 * Create a new terminal of "rows" by "cols" cells.
7772 * Start job for "cmd".
7773 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007774 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007775 * Return OK or FAIL.
7776 */
7777 static int
7778term_and_job_init(
7779 term_T *term,
7780 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007781 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007782 jobopt_T *opt,
7783 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007784{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007785 term->tl_arg0_cmd = NULL;
7786
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007787 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7788 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007789
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007790#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007791 if (term_use_palette())
7792 {
7793 if (term->tl_palette != NULL)
7794 set_vterm_palette(term->tl_vterm, term->tl_palette);
7795 else
7796 init_vterm_ansi_colors(term->tl_vterm);
7797 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007798#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007799
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007800 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007801 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007802 if (term->tl_job != NULL)
7803 ++term->tl_job->jv_refcount;
7804
7805 return term->tl_job != NULL
7806 && term->tl_job->jv_channel != NULL
7807 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7808}
7809
7810 static int
7811create_pty_only(term_T *term, jobopt_T *opt)
7812{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007813 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7814 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007815
7816 term->tl_job = job_alloc();
7817 if (term->tl_job == NULL)
7818 return FAIL;
7819 ++term->tl_job->jv_refcount;
7820
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007821 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007822 term->tl_job->jv_status = JOB_FINISHED;
7823
7824 return mch_create_pty_channel(term->tl_job, opt);
7825}
7826
7827/*
7828 * Free the terminal emulator part of "term".
7829 */
7830 static void
7831term_free_vterm(term_T *term)
7832{
7833 if (term->tl_vterm != NULL)
7834 vterm_free(term->tl_vterm);
7835 term->tl_vterm = NULL;
7836}
7837
7838/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007839 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007840 */
7841 static void
7842term_report_winsize(term_T *term, int rows, int cols)
7843{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007844 // Use an ioctl() to report the new window size to the job.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007845 if (term->tl_job == NULL || term->tl_job->jv_channel == NULL)
7846 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007847
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007848 int fd = -1;
7849 int part;
7850
7851 for (part = PART_OUT; part < PART_COUNT; ++part)
7852 {
7853 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
7854 if (mch_isatty(fd))
7855 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007856 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007857 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7858 mch_signal_job(term->tl_job, (char_u *)"winch");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007859}
7860
7861# endif
7862
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007863#endif // FEAT_TERMINAL