blob: a0758409eaa35c2475a41c21e02710c6a210327a [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,
Naruhiko Nishinobe5bd4d2025-05-14 21:20:28 +02001354 curwin->w_wincol + curwin->w_wcol + TPL_LCOL(NULL));
Bram Moolenaar58806c12023-04-29 14:26:02 +01001355 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001356 if (redraw)
1357 {
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001358 aco_save_T aco;
1359
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001360 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1361 cursor_on();
1362 out_flush();
1363#ifdef FEAT_GUI
1364 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001365 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001366 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001367 gui_mch_flush();
1368 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001369#endif
Bram Moolenaar24fe33a2022-11-24 00:09:02 +00001370 // Make sure an invoked autocmd doesn't delete the buffer (and the
1371 // terminal) under our fingers.
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001372 ++term->tl_buffer->b_locked;
1373
1374 // save and restore curwin and curbuf, in case the autocmd changes them
1375 aucmd_prepbuf(&aco, curbuf);
1376 apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, FALSE, term->tl_buffer);
1377 aucmd_restbuf(&aco);
1378
1379 --term->tl_buffer->b_locked;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001380 }
1381}
1382
1383/*
1384 * Invoked when "msg" output from a job was received. Write it to the terminal
1385 * of "buffer".
1386 */
1387 void
1388write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1389{
1390 size_t len = STRLEN(msg);
1391 term_T *term = buffer->b_term;
1392
Bram Moolenaar4f974752019-02-17 17:44:42 +01001393#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001394 // Win32: Cannot redirect output of the job, intercept it here and write to
1395 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001396 if (term->tl_out_fd != NULL)
1397 {
1398 ch_log(channel, "Writing %d bytes to output file", (int)len);
1399 fwrite(msg, len, 1, term->tl_out_fd);
1400 return;
1401 }
1402#endif
1403
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001404 if (term->tl_vterm == NULL)
1405 {
1406 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1407 return;
1408 }
1409 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001410 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001411 term_write_job_output(term, msg, len);
1412
Bram Moolenaar13568252018-03-16 20:46:58 +01001413#ifdef FEAT_GUI
1414 if (term->tl_system)
1415 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001416 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001417 update_system_term(term);
1418 update_cursor(term, TRUE);
1419 }
1420 else
1421#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001422 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1423 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001424 if (!term->tl_normal_mode)
1425 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001426 // Don't use update_screen() when editing the command line, it gets
1427 // cleared.
1428 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001429 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001430 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001431 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001432 update_screen(UPD_VALID_NO_UPDATE);
Naruhiko Nishinobe5bd4d2025-05-14 21:20:28 +02001433#if defined(FEAT_TABPANEL)
1434 if (redraw_tabpanel)
1435 draw_tabpanel();
1436#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001437 // update_screen() can be slow, check the terminal wasn't closed
1438 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001439 if (buffer == curbuf && curbuf->b_term != NULL)
1440 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001441 }
1442 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001443 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001444 }
1445}
1446
1447/*
1448 * Send a mouse position and click to the vterm
1449 */
1450 static int
1451term_send_mouse(VTerm *vterm, int button, int pressed)
1452{
1453 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001454 int row = mouse_row - W_WINROW(curwin);
1455 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001456
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001457#ifdef FEAT_PROP_POPUP
1458 if (popup_is_popup(curwin))
1459 {
1460 row -= popup_top_extra(curwin);
1461 col -= popup_left_extra(curwin);
1462 }
1463#endif
1464 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001465 if (button != 0)
1466 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001467 return TRUE;
1468}
1469
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001470static int enter_mouse_col = -1;
1471static int enter_mouse_row = -1;
1472
1473/*
1474 * Handle a mouse click, drag or release.
1475 * Return TRUE when a mouse event is sent to the terminal.
1476 */
1477 static int
1478term_mouse_click(VTerm *vterm, int key)
1479{
1480#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001481 // For modeless selection mouse drag and release events are ignored, unless
1482 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001483 static int ignore_drag_release = TRUE;
1484 VTermMouseState mouse_state;
1485
1486 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1487 if (mouse_state.flags == 0)
1488 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001489 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001490 switch (key)
1491 {
1492 case K_LEFTDRAG:
1493 case K_LEFTRELEASE:
1494 case K_RIGHTDRAG:
1495 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001496 // Ignore drag and release events when the button-down wasn't
1497 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001498 if (ignore_drag_release)
1499 {
1500 int save_mouse_col, save_mouse_row;
1501
1502 if (enter_mouse_col < 0)
1503 break;
1504
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001505 // mouse click in the window gave us focus, handle that
1506 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001507 save_mouse_col = mouse_col;
1508 save_mouse_row = mouse_row;
1509 mouse_col = enter_mouse_col;
1510 mouse_row = enter_mouse_row;
1511 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1512 mouse_col = save_mouse_col;
1513 mouse_row = save_mouse_row;
1514 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001515 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001516 case K_LEFTMOUSE:
1517 case K_RIGHTMOUSE:
1518 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1519 ignore_drag_release = TRUE;
1520 else
1521 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001522 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001523 if (clip_star.available)
1524 {
1525 int button, is_click, is_drag;
1526
1527 button = get_mouse_button(KEY2TERMCAP1(key),
1528 &is_click, &is_drag);
1529 if (mouse_model_popup() && button == MOUSE_LEFT
1530 && (mod_mask & MOD_MASK_SHIFT))
1531 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001532 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001533 button = MOUSE_RIGHT;
1534 mod_mask &= ~MOD_MASK_SHIFT;
1535 }
1536 clip_modeless(button, is_click, is_drag);
1537 }
1538 break;
1539
1540 case K_MIDDLEMOUSE:
1541 if (clip_star.available)
1542 insert_reg('*', TRUE);
1543 break;
1544 }
1545 enter_mouse_col = -1;
1546 return FALSE;
1547 }
1548#endif
1549 enter_mouse_col = -1;
1550
1551 switch (key)
1552 {
1553 case K_LEFTMOUSE:
1554 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1555 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1556 case K_LEFTRELEASE:
1557 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1558 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1559 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1560 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1561 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1562 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1563 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1564 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1565 }
1566 return TRUE;
1567}
1568
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001569/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001570 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1571 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001572 * Return the number of bytes in "buf".
1573 */
1574 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001575term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001576{
1577 VTerm *vterm = term->tl_vterm;
1578 VTermKey key = VTERM_KEY_NONE;
1579 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001580 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001581
1582 switch (c)
1583 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001584 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001585
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001586 // don't use VTERM_KEY_BACKSPACE, it always
1587 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001588 case K_BS: c = term_backspace_char; break;
1589
1590 case ESC: key = VTERM_KEY_ESCAPE; break;
1591 case K_DEL: key = VTERM_KEY_DEL; break;
1592 case K_DOWN: key = VTERM_KEY_DOWN; break;
1593 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1594 key = VTERM_KEY_DOWN; break;
1595 case K_END: key = VTERM_KEY_END; break;
1596 case K_S_END: mod = VTERM_MOD_SHIFT;
1597 key = VTERM_KEY_END; break;
1598 case K_C_END: mod = VTERM_MOD_CTRL;
1599 key = VTERM_KEY_END; break;
1600 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1601 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1602 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1603 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1604 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1605 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1606 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1607 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1608 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1609 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1610 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1611 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1612 case K_HOME: key = VTERM_KEY_HOME; break;
1613 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1614 key = VTERM_KEY_HOME; break;
1615 case K_C_HOME: mod = VTERM_MOD_CTRL;
1616 key = VTERM_KEY_HOME; break;
1617 case K_INS: key = VTERM_KEY_INS; break;
1618 case K_K0: key = VTERM_KEY_KP_0; break;
1619 case K_K1: key = VTERM_KEY_KP_1; break;
1620 case K_K2: key = VTERM_KEY_KP_2; break;
1621 case K_K3: key = VTERM_KEY_KP_3; break;
1622 case K_K4: key = VTERM_KEY_KP_4; break;
1623 case K_K5: key = VTERM_KEY_KP_5; break;
1624 case K_K6: key = VTERM_KEY_KP_6; break;
1625 case K_K7: key = VTERM_KEY_KP_7; break;
1626 case K_K8: key = VTERM_KEY_KP_8; break;
1627 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001628 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001629 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001630 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001631 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001632 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1633 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001634 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1635 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001636 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1637 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001638 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1639 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1640 case K_LEFT: key = VTERM_KEY_LEFT; break;
1641 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1642 key = VTERM_KEY_LEFT; break;
1643 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1644 key = VTERM_KEY_LEFT; break;
1645 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1646 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1647 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1648 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1649 key = VTERM_KEY_RIGHT; break;
1650 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1651 key = VTERM_KEY_RIGHT; break;
1652 case K_UP: key = VTERM_KEY_UP; break;
1653 case K_S_UP: mod = VTERM_MOD_SHIFT;
1654 key = VTERM_KEY_UP; break;
1655 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001656 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1657 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001658
Bram Moolenaara42ad572017-11-16 13:08:04 +01001659 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1660 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001661 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1662 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001663
1664 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001665 case K_LEFTMOUSE_NM:
1666 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001667 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001668 case K_LEFTRELEASE_NM:
1669 case K_MOUSEMOVE:
1670 case K_MIDDLEMOUSE:
1671 case K_MIDDLEDRAG:
1672 case K_MIDDLERELEASE:
1673 case K_RIGHTMOUSE:
1674 case K_RIGHTDRAG:
1675 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1676 return 0;
1677 other = TRUE;
1678 break;
1679
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001680 case K_X1MOUSE: /* TODO */ return 0;
1681 case K_X1DRAG: /* TODO */ return 0;
1682 case K_X1RELEASE: /* TODO */ return 0;
1683 case K_X2MOUSE: /* TODO */ return 0;
1684 case K_X2DRAG: /* TODO */ return 0;
1685 case K_X2RELEASE: /* TODO */ return 0;
1686
1687 case K_IGNORE: return 0;
1688 case K_NOP: return 0;
1689 case K_UNDO: return 0;
1690 case K_HELP: return 0;
1691 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1692 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1693 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1694 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1695 case K_SELECT: return 0;
1696#ifdef FEAT_GUI
1697 case K_VER_SCROLLBAR: return 0;
1698 case K_HOR_SCROLLBAR: return 0;
1699#endif
1700#ifdef FEAT_GUI_TABLINE
1701 case K_TABLINE: return 0;
1702 case K_TABMENU: return 0;
1703#endif
1704#ifdef FEAT_NETBEANS_INTG
1705 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1706#endif
1707#ifdef FEAT_DND
1708 case K_DROP: return 0;
1709#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001710 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001711 case K_PS: vterm_keyboard_start_paste(vterm);
1712 other = TRUE;
1713 break;
1714 case K_PE: vterm_keyboard_end_paste(vterm);
1715 other = TRUE;
1716 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001717 }
1718
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001719 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001720 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001721 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001722 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001723 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001724 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001725 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001726
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001727 // Ctrl-Shift-i may have the key "I" instead of "i", but for the kitty
1728 // keyboard protocol should use "i". Applies to all ascii letters.
1729 if (ASCII_ISUPPER(c)
Bram Moolenaarebed1b02022-11-24 14:05:19 +00001730 && vterm_is_kitty_keyboard(vterm)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001731 && mod == (VTERM_MOD_CTRL | VTERM_MOD_SHIFT))
1732 c = TOLOWER_ASC(c);
1733
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 /*
1735 * Convert special keys to vterm keys:
1736 * - Write keys to vterm: vterm_keyboard_key()
1737 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001738 */
1739 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001740 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001741 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001742 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001743 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001744 vterm_keyboard_unichar(vterm, c, mod);
1745
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001746 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001747 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1748}
1749
1750/*
1751 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001752 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001753 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001754 */
1755 static int
1756term_job_running_check(term_T *term, int check_job_status)
1757{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001758 // Also consider the job finished when the channel is closed, to avoid a
1759 // race condition when updating the title.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001760 if (term == NULL
1761 || term->tl_job == NULL
1762 || !channel_is_open(term->tl_job->jv_channel))
1763 return FALSE;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001764
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001765 job_T *job = term->tl_job;
1766
1767 // Careful: Checking the job status may invoke callbacks, which close
1768 // the buffer and terminate "term". However, "job" will not be freed
1769 // yet.
1770 if (check_job_status)
1771 job_status(job);
1772 return (job->jv_status == JOB_STARTED
1773 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001774}
1775
1776/*
1777 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001778 */
1779 int
1780term_job_running(term_T *term)
1781{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001782 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001783}
1784
1785/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001786 * Return TRUE if the job for "term" is still running, ignoring the job was
1787 * "NONE".
1788 */
1789 int
1790term_job_running_not_none(term_T *term)
1791{
1792 return term_job_running(term) && !term_none_open(term);
1793}
1794
1795/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001796 * Return TRUE if "term" has an active channel and used ":term NONE".
1797 */
1798 int
1799term_none_open(term_T *term)
1800{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001801 // Also consider the job finished when the channel is closed, to avoid a
1802 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001803 return term != NULL
1804 && term->tl_job != NULL
1805 && channel_is_open(term->tl_job->jv_channel)
1806 && term->tl_job->jv_channel->ch_keep_open;
1807}
1808
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001809//
1810// Used to confirm whether we would like to kill a terminal.
1811// Return OK when the user confirms to kill it.
1812// Return FAIL if the user selects otherwise.
1813//
1814 int
1815term_confirm_stop(buf_T *buf)
1816{
1817 char_u buff[DIALOG_MSG_SIZE];
1818 int ret;
1819
1820 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1821 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1822 if (ret == VIM_YES)
1823 return OK;
1824 else
1825 return FAIL;
1826}
1827
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001828/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001829 * Used when exiting: kill the job in "buf" if so desired.
1830 * Return OK when the job finished.
1831 * Return FAIL when the job is still running.
1832 */
1833 int
1834term_try_stop_job(buf_T *buf)
1835{
1836 int count;
1837 char *how = (char *)buf->b_term->tl_kill;
1838
1839#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001840 if ((how == NULL || *how == NUL)
1841 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001842 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001843 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001844 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001845 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001846 return FAIL;
1847 }
1848#endif
1849 if (how == NULL || *how == NUL)
1850 return FAIL;
1851
1852 job_stop(buf->b_term->tl_job, NULL, how);
1853
Bram Moolenaar9172d232019-01-29 23:06:54 +01001854 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001855 for (count = 0; count < 100; ++count)
1856 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001857 job_T *job;
1858
1859 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001860 if (!buf_valid(buf)
1861 || buf->b_term == NULL
1862 || buf->b_term->tl_job == NULL)
1863 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001864 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001865
Bram Moolenaar9172d232019-01-29 23:06:54 +01001866 // Call job_status() to update jv_status. It may cause the job to be
1867 // cleaned up but it won't be freed.
1868 job_status(job);
1869 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001870 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001871
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001872 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001873 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001874 }
1875 return FAIL;
1876}
1877
1878/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001879 * Add the last line of the scrollback buffer to the buffer in the window.
1880 */
1881 static void
1882add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1883{
1884 buf_T *buf = term->tl_buffer;
1885 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1886 linenr_T lnum = buf->b_ml.ml_line_count;
1887
Bram Moolenaar4f974752019-02-17 17:44:42 +01001888#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001889 if (!enc_utf8 && enc_codepage > 0)
1890 {
1891 WCHAR *ret = NULL;
1892 int length = 0;
1893
1894 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1895 &ret, &length);
1896 if (ret != NULL)
1897 {
1898 WideCharToMultiByte_alloc(enc_codepage, 0,
1899 ret, length, (char **)&text, &len, 0, 0);
1900 vim_free(ret);
1901 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1902 vim_free(text);
1903 }
1904 }
1905 else
1906#endif
1907 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1908 if (empty)
1909 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001910 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001911 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001912 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913 curbuf = curwin->w_buffer;
1914 }
1915}
1916
1917 static void
1918cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1919{
1920 attr->width = cell->width;
1921 attr->attrs = cell->attrs;
1922 attr->fg = cell->fg;
1923 attr->bg = cell->bg;
1924}
1925
1926 static int
1927equal_celattr(cellattr_T *a, cellattr_T *b)
1928{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001929 // We only compare the RGB colors, ignoring the ANSI index and type.
1930 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001931 return a->fg.red == b->fg.red
1932 && a->fg.green == b->fg.green
1933 && a->fg.blue == b->fg.blue
1934 && a->bg.red == b->bg.red
1935 && a->bg.green == b->bg.green
1936 && a->bg.blue == b->bg.blue;
1937}
1938
Bram Moolenaard96ff162018-02-18 22:13:29 +01001939/*
1940 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1941 * line at this position. Otherwise at the end.
1942 */
1943 static int
1944add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1945{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001946 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
1947 return FALSE;
1948
1949 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1950 + term->tl_scrollback.ga_len;
1951
1952 if (lnum > 0)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001953 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001954 int i;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001955
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001956 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001957 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001958 *line = *(line - 1);
1959 --line;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001960 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01001961 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001962 line->sb_cols = 0;
1963 line->sb_cells = NULL;
1964 line->sb_fill_attr = *fill_attr;
1965 ++term->tl_scrollback.ga_len;
1966 return OK;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001967}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001968
1969/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001970 * Remove the terminal contents from the scrollback and the buffer.
1971 * Used before adding a new scrollback line or updating the buffer for lines
1972 * displayed in the terminal.
1973 */
1974 static void
1975cleanup_scrollback(term_T *term)
1976{
1977 sb_line_T *line;
1978 garray_T *gap;
1979
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001980 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001981 gap = &term->tl_scrollback;
1982 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1983 && gap->ga_len > 0)
1984 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001985 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001986 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1987 vim_free(line->sb_cells);
1988 --gap->ga_len;
1989 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001990 curbuf = curwin->w_buffer;
1991 if (curbuf == term->tl_buffer)
1992 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001993}
1994
1995/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001996 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001997 */
1998 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001999update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002000{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002001 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002002 int len;
2003 int lines_skipped = 0;
2004 VTermPos pos;
2005 VTermScreenCell cell;
2006 cellattr_T fill_attr, new_fill_attr;
2007 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002008
2009 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
2010 "Adding terminal window snapshot to buffer");
2011
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002012 // First remove the lines that were appended before, they might be
2013 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002014 cleanup_scrollback(term);
2015
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016 screen = vterm_obtain_screen(term->tl_vterm);
2017 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002018 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
2019 {
2020 len = 0;
2021 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
2022 if (vterm_screen_get_cell(screen, pos, &cell) != 0
2023 && cell.chars[0] != NUL)
2024 {
2025 len = pos.col + 1;
2026 new_fill_attr = term->tl_default_color;
2027 }
2028 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002029 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002030 cell2cellattr(&cell, &new_fill_attr);
2031
2032 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
2033 ++lines_skipped;
2034 else
2035 {
2036 while (lines_skipped > 0)
2037 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002038 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002039 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002040 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002041 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002042 }
2043
2044 if (len == 0)
2045 p = NULL;
2046 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002047 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002048 if ((p != NULL || len == 0)
2049 && ga_grow(&term->tl_scrollback, 1) == OK)
2050 {
2051 garray_T ga;
2052 int width;
2053 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
2054 + term->tl_scrollback.ga_len;
2055
2056 ga_init2(&ga, 1, 100);
2057 for (pos.col = 0; pos.col < len; pos.col += width)
2058 {
2059 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2060 {
2061 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02002062 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002063 if (ga_grow(&ga, 1) == OK)
2064 ga.ga_len += utf_char2bytes(' ',
2065 (char_u *)ga.ga_data + ga.ga_len);
2066 }
2067 else
2068 {
2069 width = cell.width;
2070
2071 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01002072 if (width == 2)
2073 // second cell of double-width character has the
2074 // same attributes.
2075 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002076
Bram Moolenaara79fd562018-12-20 20:47:32 +01002077 // Each character can be up to 6 bytes.
2078 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002079 {
2080 int i;
2081 int c;
2082
2083 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
2084 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2085 (char_u *)ga.ga_data + ga.ga_len);
2086 }
2087 }
2088 }
2089 line->sb_cols = len;
2090 line->sb_cells = p;
2091 line->sb_fill_attr = new_fill_attr;
2092 fill_attr = new_fill_attr;
2093 ++term->tl_scrollback.ga_len;
2094
2095 if (ga_grow(&ga, 1) == FAIL)
2096 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2097 else
2098 {
2099 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2100 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2101 }
2102 ga_clear(&ga);
2103 }
2104 else
2105 vim_free(p);
2106 }
2107 }
2108
Bram Moolenaarf3aea592018-11-11 22:18:21 +01002109 // Add trailing empty lines.
2110 for (pos.row = term->tl_scrollback.ga_len;
2111 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
2112 ++pos.row)
2113 {
2114 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
2115 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2116 }
2117
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002118 term->tl_dirty_snapshot = FALSE;
2119#ifdef FEAT_TIMERS
2120 term->tl_timer_set = FALSE;
2121#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002122}
2123
2124/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002125 * Loop over all windows in the current tab, and also curwin, which is not
2126 * encountered when using a terminal in a popup window.
2127 * Return TRUE if "*wp" was set to the next window.
2128 */
2129 static int
2130for_all_windows_and_curwin(win_T **wp, int *did_curwin)
2131{
2132 if (*wp == NULL)
2133 *wp = firstwin;
2134 else if ((*wp)->w_next != NULL)
2135 *wp = (*wp)->w_next;
2136 else if (!*did_curwin)
2137 *wp = curwin;
2138 else
2139 return FALSE;
2140 if (*wp == curwin)
2141 *did_curwin = TRUE;
2142 return TRUE;
2143}
2144
2145/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002146 * If needed, add the current lines of the terminal to scrollback and to the
2147 * buffer. Called after the job has ended and when switching to
2148 * Terminal-Normal mode.
2149 * When "redraw" is TRUE redraw the windows that show the terminal.
2150 */
2151 static void
2152may_move_terminal_to_buffer(term_T *term, int redraw)
2153{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002154 if (term->tl_vterm == NULL)
2155 return;
2156
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002157 // Update the snapshot only if something changes or the buffer does not
2158 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002159 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2160 <= term->tl_scrollback_scrolled)
2161 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002162
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002163 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002164 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2165 &term->tl_default_color.fg, &term->tl_default_color.bg);
2166
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002167 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002168 {
2169 win_T *wp = NULL;
2170 int did_curwin = FALSE;
2171
2172 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002173 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002174 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002176 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2177 wp->w_cursor.col = 0;
2178 wp->w_valid = 0;
2179 if (wp->w_cursor.lnum >= wp->w_height)
2180 {
2181 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002182
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002183 if (wp->w_topline < min_topline)
2184 wp->w_topline = min_topline;
2185 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002186 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002187 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002188 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002189 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002190}
2191
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002192#if defined(FEAT_TIMERS) || defined(PROTO)
2193/*
2194 * Check if any terminal timer expired. If so, copy text from the terminal to
2195 * the buffer.
2196 * Return the time until the next timer will expire.
2197 */
2198 int
2199term_check_timers(int next_due_arg, proftime_T *now)
2200{
2201 term_T *term;
2202 int next_due = next_due_arg;
2203
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002204 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002205 {
2206 if (term->tl_timer_set && !term->tl_normal_mode)
2207 {
2208 long this_due = proftime_time_left(&term->tl_timer_due, now);
2209
2210 if (this_due <= 1)
2211 {
2212 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002213 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002214 }
2215 else if (next_due == -1 || next_due > this_due)
2216 next_due = this_due;
2217 }
2218 }
2219
2220 return next_due;
2221}
2222#endif
2223
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002224/*
2225 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2226 * otherwise end it.
2227 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002228 static void
2229set_terminal_mode(term_T *term, int normal_mode)
2230{
2231 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002232 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002233 if (!normal_mode)
2234 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002235 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 if (term->tl_buffer == curbuf)
2237 maketitle();
2238}
2239
2240/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002241 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002242 * Move the vterm contents into the scrollback buffer and free the vterm.
2243 */
2244 static void
2245cleanup_vterm(term_T *term)
2246{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002247 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002248 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002249 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002250 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002251}
2252
2253/*
2254 * Switch from Terminal-Job mode to Terminal-Normal mode.
2255 * Suspends updating the terminal window.
2256 */
2257 static void
2258term_enter_normal_mode(void)
2259{
2260 term_T *term = curbuf->b_term;
2261
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002262 set_terminal_mode(term, TRUE);
2263
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002264 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002265 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002266
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002267 // Move the window cursor to the position of the cursor in the
2268 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002269 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2270 + term->tl_cursor_pos.row + 1;
2271 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002272 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2273 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002274 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002275
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002276 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002277 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2278}
2279
2280/*
2281 * Returns TRUE if the current window contains a terminal and we are in
2282 * Terminal-Normal mode.
2283 */
2284 int
2285term_in_normal_mode(void)
2286{
2287 term_T *term = curbuf->b_term;
2288
2289 return term != NULL && term->tl_normal_mode;
2290}
2291
2292/*
2293 * Switch from Terminal-Normal mode to Terminal-Job mode.
2294 * Restores updating the terminal window.
2295 */
2296 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002297term_enter_job_mode(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002298{
2299 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002300
2301 set_terminal_mode(term, FALSE);
2302
2303 if (term->tl_channel_closed)
2304 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002305 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002306#ifdef FEAT_PROP_POPUP
2307 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002308 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002309#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002310}
2311
2312/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002313 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2314 * modifiers into a basic key. However, we may only find out after calling
2315 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2316 * "no_reduce_keys" before using it.
2317 */
2318typedef enum {
2319 NRKS_NONE, // initial value
2320 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2321 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2322 // check_no_reduce_keys(), must be decremented.
2323} reduce_key_state_T;
2324
2325static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2326
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002327/*
2328 * Return TRUE if the term is using modifyOtherKeys level 2 or the kitty
2329 * keyboard protocol.
2330 */
2331 static int
2332vterm_using_key_protocol(void)
2333{
2334 return curbuf->b_term != NULL
2335 && curbuf->b_term->tl_vterm != NULL
2336 && (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm)
2337 || vterm_is_kitty_keyboard(curbuf->b_term->tl_vterm));
2338}
2339
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002340 void
2341check_no_reduce_keys(void)
2342{
2343 if (no_reduce_key_state != NRKS_CHECK
2344 || no_reduce_keys >= 1
2345 || curbuf->b_term == NULL
2346 || curbuf->b_term->tl_vterm == NULL)
2347 return;
2348
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002349 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002350 {
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002351 // "modify_other_keys" or kitty keyboard protocol was enabled while
2352 // waiting.
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002353 no_reduce_key_state = NRKS_SET;
2354 ++no_reduce_keys;
2355 }
2356}
2357
2358/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002359 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002360 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002361 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002362 */
2363 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002364term_vgetc(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002365{
2366 int c;
2367 int save_State = State;
2368
Bram Moolenaar24959102022-05-07 20:01:16 +01002369 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002370 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002371#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002372 ctrl_break_was_pressed = FALSE;
2373#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002374
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002375 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002376 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002377 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002378 no_reduce_key_state = NRKS_SET;
2379 }
2380 else
2381 {
2382 no_reduce_key_state = NRKS_CHECK;
2383 }
2384
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002385 c = vgetc();
2386 got_int = FALSE;
2387 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002388
2389 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002390 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002391 no_reduce_key_state = NRKS_NONE;
2392
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002393 return c;
2394}
2395
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002396static int mouse_was_outside = FALSE;
2397
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002398/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002399 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002400 * Return FAIL when the key needs to be handled in Normal mode.
2401 * Return OK when the key was dropped or sent to the terminal.
2402 */
2403 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002404send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002405{
2406 char msg[KEY_BUF_LEN];
2407 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002408 int dragging_outside = FALSE;
2409
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002410 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002411 switch (c)
2412 {
2413 case NUL:
2414 case K_ZERO:
2415 if (typed)
2416 stuffcharReadbuff(c);
2417 return FAIL;
2418
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002419 case K_TABLINE:
2420 stuffcharReadbuff(c);
2421 return FAIL;
2422
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002423 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002424 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002425 return FAIL;
2426
2427 case K_LEFTDRAG:
2428 case K_MIDDLEDRAG:
2429 case K_RIGHTDRAG:
2430 case K_X1DRAG:
2431 case K_X2DRAG:
2432 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002433 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002434 case K_LEFTMOUSE:
2435 case K_LEFTMOUSE_NM:
2436 case K_LEFTRELEASE:
2437 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002438 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002439 case K_MIDDLEMOUSE:
2440 case K_MIDDLERELEASE:
2441 case K_RIGHTMOUSE:
2442 case K_RIGHTRELEASE:
2443 case K_X1MOUSE:
2444 case K_X1RELEASE:
2445 case K_X2MOUSE:
2446 case K_X2RELEASE:
2447
2448 case K_MOUSEUP:
2449 case K_MOUSEDOWN:
2450 case K_MOUSELEFT:
2451 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002452 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002453 int row = mouse_row;
2454 int col = mouse_col;
2455
2456#ifdef FEAT_PROP_POPUP
2457 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002458 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002459 row -= popup_top_extra(curwin);
2460 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002461 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002462#endif
2463 if (row < W_WINROW(curwin)
2464 || row >= (W_WINROW(curwin) + curwin->w_height)
2465 || col < curwin->w_wincol
2466 || col >= W_ENDCOL(curwin)
2467 || dragging_outside)
2468 {
2469 // click or scroll outside the current window or on status
2470 // line or vertical separator
2471 if (typed)
2472 {
2473 stuffcharReadbuff(c);
2474 mouse_was_outside = TRUE;
2475 }
2476 return FAIL;
2477 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002478 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002479 break;
2480
2481 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002482 case K_SCRIPT_COMMAND:
2483 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002484 }
2485 if (typed)
2486 mouse_was_outside = FALSE;
2487
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002488 // Convert the typed key to a sequence of bytes for the job.
2489 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002490 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002491 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002492 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2493 (char_u *)msg, (int)len, NULL);
2494
2495 return OK;
2496}
2497
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002498/*
2499 * Handle CTRL-W "": send register contents to the job.
2500 */
2501 static void
2502term_paste_register(int prev_c UNUSED)
2503{
2504 int c;
2505 list_T *l;
2506 listitem_T *item;
2507 long reglen = 0;
2508 int type;
2509
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002510 if (add_to_showcmd(prev_c))
2511 if (add_to_showcmd('"'))
2512 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002513
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002514 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002515 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002516
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002517 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002518 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002519 return;
2520
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002521 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002522 if (c == '=' && get_expr_register() != '=')
2523 return;
2524 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002525 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002526 return;
2527
2528 l = (list_T *)get_reg_contents(c, GREG_LIST);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002529 if (l == NULL)
2530 return;
2531
2532 type = get_reg_type(c, &reglen);
2533 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002534 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002535 char_u *s = tv_get_string(&item->li_tv);
2536#ifdef MSWIN
2537 char_u *tmp = s;
2538
2539 if (!enc_utf8 && enc_codepage > 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002540 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002541 WCHAR *ret = NULL;
2542 int length = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002543
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002544 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2545 (int)STRLEN(s), &ret, &length);
2546 if (ret != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002547 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002548 WideCharToMultiByte_alloc(CP_UTF8, 0,
2549 ret, length, (char **)&s, &length, 0, 0);
2550 vim_free(ret);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002551 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002552 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002553#endif
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002554 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2555 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002556#ifdef MSWIN
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002557 if (tmp != s)
2558 vim_free(s);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002559#endif
2560
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002561 if (item->li_next != NULL || type == MLINE)
2562 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2563 (char_u *)"\r", 1, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002564 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002565 list_free(l);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002566}
2567
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002568/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002569 * Return TRUE when waiting for a character in the terminal, the cursor of the
2570 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002571 */
2572 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002573terminal_is_active(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002574{
2575 return in_terminal_loop != NULL;
2576}
2577
Bram Moolenaar83d47902020-03-26 20:34:00 +01002578/*
dundargocc57b5bc2022-11-02 13:30:51 +00002579 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002580 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002581 static int
2582term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002583{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002584 char_u *name;
2585
2586 if (wp != NULL && *wp->w_p_wcr != NUL)
2587 name = wp->w_p_wcr;
2588 else if (term->tl_highlight_name != NULL)
2589 name = term->tl_highlight_name;
2590 else
2591 name = (char_u*)"Terminal";
2592
2593 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002594}
2595
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002596#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002597 cursorentry_T *
2598term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2599{
2600 term_T *term = in_terminal_loop;
2601 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002602 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002603 guicolor_T term_fg = INVALCOLOR;
2604 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002605
Bram Moolenaara80faa82020-04-12 19:37:17 +02002606 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002607 entry.shape = entry.mshape =
2608 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2609 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2610 SHAPE_BLOCK;
2611 entry.percentage = 20;
2612 if (term->tl_cursor_blink)
2613 {
2614 entry.blinkwait = 700;
2615 entry.blinkon = 400;
2616 entry.blinkoff = 250;
2617 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002618
Bram Moolenaar83d47902020-03-26 20:34:00 +01002619 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002620 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002621 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002622 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002623 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002624 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002625 else
2626 *fg = gui.back_pixel;
2627
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002628 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002629 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002630 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002631 *bg = term_fg;
2632 else
2633 *bg = gui.norm_pixel;
2634 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002635 else
2636 *bg = color_name2handle(term->tl_cursor_color);
2637 entry.name = "n";
2638 entry.used_for = SHAPE_CURSOR;
2639
2640 return &entry;
2641}
2642#endif
2643
Bram Moolenaard317b382018-02-08 22:33:31 +01002644 static void
2645may_output_cursor_props(void)
2646{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002647 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002648 || last_set_cursor_shape != desired_cursor_shape
2649 || last_set_cursor_blink != desired_cursor_blink)
2650 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002651 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002652 last_set_cursor_shape = desired_cursor_shape;
2653 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002654 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002655 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002656 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002657 ui_cursor_shape_forced(TRUE);
2658 else
2659 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2660 }
2661}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002662
Bram Moolenaard317b382018-02-08 22:33:31 +01002663/*
2664 * Set the cursor color and shape, if not last set to these.
2665 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002666 static void
2667may_set_cursor_props(term_T *term)
2668{
2669#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002670 // For the GUI the cursor properties are obtained with
2671 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002672 if (gui.in_use)
2673 return;
2674#endif
2675 if (in_terminal_loop == term)
2676 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002677 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002678 desired_cursor_shape = term->tl_cursor_shape;
2679 desired_cursor_blink = term->tl_cursor_blink;
2680 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002681 }
2682}
2683
Bram Moolenaard317b382018-02-08 22:33:31 +01002684/*
2685 * Reset the desired cursor properties and restore them when needed.
2686 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002687 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002688prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002689{
2690#ifdef FEAT_GUI
2691 if (gui.in_use)
2692 return;
2693#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002694 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002695 desired_cursor_shape = -1;
2696 desired_cursor_blink = -1;
2697 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002698}
2699
2700/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002701 * Returns TRUE if the current window contains a terminal and we are sending
2702 * keys to the job.
2703 * If "check_job_status" is TRUE update the job status.
2704 */
2705 static int
2706term_use_loop_check(int check_job_status)
2707{
2708 term_T *term = curbuf->b_term;
2709
2710 return term != NULL
2711 && !term->tl_normal_mode
2712 && term->tl_vterm != NULL
2713 && term_job_running_check(term, check_job_status);
2714}
2715
2716/*
2717 * Returns TRUE if the current window contains a terminal and we are sending
2718 * keys to the job.
2719 */
2720 int
2721term_use_loop(void)
2722{
2723 return term_use_loop_check(FALSE);
2724}
2725
2726/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002727 * Called when entering a window with the mouse. If this is a terminal window
2728 * we may want to change state.
2729 */
2730 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002731term_win_entered(void)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002732{
2733 term_T *term = curbuf->b_term;
2734
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002735 if (term == NULL)
2736 return;
2737
2738 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002739 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002740 reset_VIsual_and_resel();
2741 if (State & MODE_INSERT)
2742 stop_insert_mode = TRUE;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002743 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002744 mouse_was_outside = FALSE;
2745 enter_mouse_col = mouse_col;
2746 enter_mouse_row = mouse_row;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002747}
2748
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002749 void
2750term_focus_change(int in_focus)
2751{
2752 term_T *term = curbuf->b_term;
2753
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002754 if (term == NULL || term->tl_vterm == NULL)
2755 return;
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002756
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002757 VTermState *state = vterm_obtain_state(term->tl_vterm);
2758
2759 if (in_focus)
2760 vterm_state_focus_in(state);
2761 else
2762 vterm_state_focus_out(state);
2763 term_forward_output(term);
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002764}
2765
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002766/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002767 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2768 * Return the Ctrl-key value in that case.
2769 */
2770 static int
2771raw_c_to_ctrl(int c)
2772{
2773 if ((mod_mask & MOD_MASK_CTRL)
2774 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2775 return c & 0x1f;
2776 return c;
2777}
2778
2779/*
2780 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002781 * Also when the Kitty keyboard protocol is used.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002782 * May set "mod_mask".
2783 */
2784 static int
2785ctrl_to_raw_c(int c)
2786{
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002787 if (c < 0x20 && vterm_using_key_protocol())
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002788 {
2789 mod_mask |= MOD_MASK_CTRL;
2790 return c + '@';
2791 }
2792 return c;
2793}
2794
2795/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002796 * Wait for input and send it to the job.
2797 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2798 * when there is no more typahead.
2799 * Return when the start of a CTRL-W command is typed or anything else that
2800 * should be handled as a Normal mode command.
2801 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2802 * the terminal was closed.
2803 */
2804 int
2805terminal_loop(int blocking)
2806{
2807 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002808 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002809 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002810 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002811#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002812 int tty_fd = curbuf->b_term->tl_job->jv_channel
2813 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002814#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002815 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002816
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002817 // Remember the terminal we are sending keys to. However, the terminal
2818 // might be closed while waiting for a character, e.g. typing "exit" in a
2819 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2820 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002821 in_terminal_loop = curbuf->b_term;
2822
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002823 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002824 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002825 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002826 if (termwinkey == Ctrl_W)
2827 termwinkey = 0;
2828 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002829 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002830 may_set_cursor_props(curbuf->b_term);
2831
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002832 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002833 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002834#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002835 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002836#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002837 // TODO: skip screen update when handling a sequence of keys.
2838 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002839 while (must_redraw != 0)
2840 if (update_screen(0) == FAIL)
2841 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002842 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002843 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002844 break;
2845
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002846 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002847 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002848
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002849 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002850 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002851 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002852 // Job finished while waiting for a character. Push back the
2853 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002854 if (raw_c != K_IGNORE)
2855 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002856 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002857 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002858 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002859 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002860 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002861
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002862#ifdef UNIX
2863 /*
2864 * The shell or another program may change the tty settings. Getting
2865 * them for every typed character is a bit of overhead, but it's needed
2866 * for the first character typed, e.g. when Vim starts in a shell.
2867 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002868 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002869 {
2870 ttyinfo_T info;
2871
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002872 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002873 if (get_tty_info(tty_fd, &info) == OK)
2874 term_backspace_char = info.backspace;
2875 }
2876#endif
2877
Bram Moolenaar4f974752019-02-17 17:44:42 +01002878#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002879 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2880 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002881 if (ctrl_break_was_pressed)
2882 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2883#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002884 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2885 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002886 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002887#ifdef FEAT_GUI
2888 && !curbuf->b_term->tl_system
2889#endif
2890 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002891 {
2892 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002893 int prev_raw_c = raw_c;
2894 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002895
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002896 if (add_to_showcmd(c))
2897 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002898
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002899 raw_c = term_vgetc();
2900 c = raw_c_to_ctrl(raw_c);
2901
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002902 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002903
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002904 if (!term_use_loop_check(TRUE)
2905 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002906 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002907 break;
2908
2909 if (prev_c == Ctrl_BSL)
2910 {
2911 if (c == Ctrl_N)
2912 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002913 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002914 term_enter_normal_mode();
2915 ret = FAIL;
2916 goto theend;
2917 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002918 // Send both keys to the terminal, first one here, second one
2919 // below.
2920 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2921 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922 }
2923 else if (c == Ctrl_C)
2924 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002925 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002926 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2927 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002928 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002929 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002930 // "CTRL-W .": send CTRL-W to the job
2931 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002932 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002933 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002934 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002935 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002936 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002937 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002938 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002939 else if (c == 'N')
2940 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002941 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002942 term_enter_normal_mode();
2943 ret = FAIL;
2944 goto theend;
2945 }
2946 else if (c == '"')
2947 {
2948 term_paste_register(prev_c);
2949 continue;
2950 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002951 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002952 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002953 // space for CTRL-W, modifier, multi-byte char and NUL
2954 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002955
2956 // Put the command into the typeahead buffer, when using the
2957 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2958 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002959 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002960 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002961 ret = OK;
2962 goto theend;
2963 }
2964 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002965# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002966 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002967 {
2968 WCHAR wc;
2969 char_u mb[3];
2970
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002971 mb[0] = (unsigned)raw_c >> 8;
2972 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002973 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002974 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002975 }
2976# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002977 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002978 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002979 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002980 // We are sure to come back here, don't reset the cursor color
2981 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002982 restore_cursor = FALSE;
2983
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002984 ret = OK;
2985 goto theend;
2986 }
2987 }
2988 ret = FAIL;
2989
2990theend:
2991 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002992 if (restore_cursor)
2993 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002994
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002995 // Move a snapshot of the screen contents to the buffer, so that completion
2996 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002997 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2998 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002999
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003000 return ret;
3001}
3002
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003003 static void
3004may_toggle_cursor(term_T *term)
3005{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003006 if (in_terminal_loop != term)
3007 return;
3008
3009 if (term->tl_cursor_visible)
3010 cursor_on();
3011 else
3012 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003013}
3014
3015/*
3016 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01003017 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003018 */
3019 static int
3020color2index(VTermColor *color, int fg, int *boldp)
3021{
3022 int red = color->red;
3023 int blue = color->blue;
3024 int green = color->green;
3025
LemonBoyb2b3acb2022-05-20 10:10:34 +01003026 *boldp = FALSE;
3027
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003028 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003029 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01003030
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003031 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003032 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003033 // Use the color as-is if possible, give up otherwise.
3034 if (color->index < t_colors)
3035 return color->index + 1;
3036 // 8-color terminals can actually display twice as many colors by
3037 // setting the high-intensity/bold bit.
3038 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003039 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003040 *boldp = TRUE;
3041 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003042 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01003043 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003044 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01003045
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003046 if (t_colors >= 256)
3047 {
3048 if (red == blue && red == green)
3049 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003050 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003051 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003052 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
3053 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
3054 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003055 int i;
3056
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003057 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003058 return 17; // 00/00/00
3059 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003060 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003061 for (i = 0; i < 23; ++i)
3062 if (red < cutoff[i])
3063 return i + 233;
3064 return 256;
3065 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003066 {
3067 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
3068 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003069
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003070 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003071 for (ri = 0; ri < 5; ++ri)
3072 if (red < cutoff[ri])
3073 break;
3074 for (gi = 0; gi < 5; ++gi)
3075 if (green < cutoff[gi])
3076 break;
3077 for (bi = 0; bi < 5; ++bi)
3078 if (blue < cutoff[bi])
3079 break;
3080 return 17 + ri * 36 + gi * 6 + bi;
3081 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003082 }
3083 return 0;
3084}
3085
3086/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01003087 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003088 */
3089 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003090vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003091{
3092 int attr = 0;
3093
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003094 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003096 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003098 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003099 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003100 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003101 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003102 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003103 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003104 return attr;
3105}
3106
3107/*
3108 * Store Vterm attributes in "cell" from highlight flags.
3109 */
3110 static void
3111hl2vtermAttr(int attr, cellattr_T *cell)
3112{
Bram Moolenaara80faa82020-04-12 19:37:17 +02003113 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003114 if (attr & HL_BOLD)
3115 cell->attrs.bold = 1;
3116 if (attr & HL_UNDERLINE)
3117 cell->attrs.underline = 1;
3118 if (attr & HL_ITALIC)
3119 cell->attrs.italic = 1;
3120 if (attr & HL_STRIKETHROUGH)
3121 cell->attrs.strike = 1;
3122 if (attr & HL_INVERSE)
3123 cell->attrs.reverse = 1;
3124}
3125
3126/*
3127 * Convert the attributes of a vterm cell into an attribute index.
3128 */
3129 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003130cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003131 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003132 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003133 VTermScreenCellAttrs *cellattrs,
3134 VTermColor *cellfg,
3135 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003136{
3137 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003138 VTermColor *fg = cellfg;
3139 VTermColor *bg = cellbg;
3140 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3141 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3142
3143 if (is_default_fg || is_default_bg)
3144 {
3145 if (wp != NULL && *wp->w_p_wcr != NUL)
3146 {
3147 if (is_default_fg)
3148 fg = &wp->w_term_wincolor.fg;
3149 if (is_default_bg)
3150 bg = &wp->w_term_wincolor.bg;
3151 }
3152 else
3153 {
3154 if (is_default_fg)
3155 fg = &term->tl_default_color.fg;
3156 if (is_default_bg)
3157 bg = &term->tl_default_color.bg;
3158 }
3159 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003160
3161#ifdef FEAT_GUI
3162 if (gui.in_use)
3163 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003164 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3165 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3166 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003167 }
3168 else
3169#endif
3170#ifdef FEAT_TERMGUICOLORS
3171 if (p_tgc)
3172 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003173 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3174 ? INVALCOLOR
3175 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3176 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3177 ? INVALCOLOR
3178 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3179 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003180 }
3181 else
3182#endif
3183 {
3184 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003185 int ctermfg = color2index(fg, TRUE, &bold);
3186 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003187
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003188 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003189 if (bold == TRUE)
3190 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003191
3192 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003193 }
3194 return 0;
3195}
3196
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003197 static void
3198set_dirty_snapshot(term_T *term)
3199{
3200 term->tl_dirty_snapshot = TRUE;
3201#ifdef FEAT_TIMERS
3202 if (!term->tl_normal_mode)
3203 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003204 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003205 profile_setlimit(100L, &term->tl_timer_due);
3206 term->tl_timer_set = TRUE;
3207 }
3208#endif
3209}
3210
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003211 static int
3212handle_damage(VTermRect rect, void *user)
3213{
3214 term_T *term = (term_T *)user;
3215
3216 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3217 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003218 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003219 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003220 return 1;
3221}
3222
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003223 static void
3224term_scroll_up(term_T *term, int start_row, int count)
3225{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003226 win_T *wp = NULL;
3227 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003228 VTermColor fg, bg;
3229 VTermScreenCellAttrs attr;
3230 int clear_attr;
3231
Bram Moolenaara80faa82020-04-12 19:37:17 +02003232 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003233
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003234 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003235 {
3236 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003237 {
3238 // Set the color to clear lines with.
3239 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3240 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003241 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003242 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003243 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003244 }
3245}
3246
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003247 static int
3248handle_moverect(VTermRect dest, VTermRect src, void *user)
3249{
3250 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003251 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003252
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003253 // Scrolling up is done much more efficiently by deleting lines instead of
3254 // redrawing the text. But avoid doing this multiple times, postpone until
3255 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003256 if (dest.start_col == src.start_col
3257 && dest.end_col == src.end_col
3258 && dest.start_row < src.start_row)
3259 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003260 if (dest.start_row == 0)
3261 term->tl_postponed_scroll += count;
3262 else
3263 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003264 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003265
3266 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3267 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003268 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003269
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003270 // Note sure if the scrolling will work correctly, let's do a complete
3271 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003272 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003273 return 1;
3274}
3275
3276 static int
3277handle_movecursor(
3278 VTermPos pos,
3279 VTermPos oldpos UNUSED,
3280 int visible,
3281 void *user)
3282{
3283 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003284 win_T *wp = NULL;
3285 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003286
3287 term->tl_cursor_pos = pos;
3288 term->tl_cursor_visible = visible;
3289
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003290 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003291 {
3292 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003293 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003294 }
3295 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003296 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003297
3298 return 1;
3299}
3300
3301 static int
3302handle_settermprop(
3303 VTermProp prop,
3304 VTermValue *value,
3305 void *user)
3306{
3307 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003308 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003309
3310 switch (prop)
3311 {
3312 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003313 if (disable_vterm_title_for_testing)
3314 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003315 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003316 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003317 if (strval == NULL)
3318 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003319 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003320 // a blank title isn't useful, make it empty, so that "running" is
3321 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003322 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003323 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003324 // Same as blank
3325 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003326 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003327 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3328 term->tl_title = NULL;
3329 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003330 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003331 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003332#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003333 else if (!enc_utf8 && enc_codepage > 0)
3334 {
3335 WCHAR *ret = NULL;
3336 int length = 0;
3337
3338 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003339 (char*)value->string.str,
3340 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003341 if (ret != NULL)
3342 {
3343 WideCharToMultiByte_alloc(enc_codepage, 0,
3344 ret, length, (char**)&term->tl_title,
3345 &length, 0, 0);
3346 vim_free(ret);
3347 }
3348 }
3349#endif
3350 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003351 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003352 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003353 strval = NULL;
3354 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003355 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003356 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003357 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003358 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003359 curwin->w_redr_status = TRUE;
3360 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003361 break;
3362
3363 case VTERM_PROP_CURSORVISIBLE:
3364 term->tl_cursor_visible = value->boolean;
3365 may_toggle_cursor(term);
3366 out_flush();
3367 break;
3368
3369 case VTERM_PROP_CURSORBLINK:
3370 term->tl_cursor_blink = value->boolean;
3371 may_set_cursor_props(term);
3372 break;
3373
3374 case VTERM_PROP_CURSORSHAPE:
3375 term->tl_cursor_shape = value->number;
3376 may_set_cursor_props(term);
3377 break;
3378
3379 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003380 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003381 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003382 if (strval == NULL)
3383 break;
3384 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003385 may_set_cursor_props(term);
3386 break;
3387
3388 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003389 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003390 term->tl_using_altscreen = value->boolean;
3391 break;
3392
3393 default:
3394 break;
3395 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003396 vim_free(strval);
3397
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003398 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003399 return 1;
3400}
3401
3402/*
3403 * The job running in the terminal resized the terminal.
3404 */
3405 static int
3406handle_resize(int rows, int cols, void *user)
3407{
3408 term_T *term = (term_T *)user;
3409 win_T *wp;
3410
3411 term->tl_rows = rows;
3412 term->tl_cols = cols;
3413 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003414 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003415 term->tl_vterm_size_changed = FALSE;
3416 else
3417 {
3418 FOR_ALL_WINDOWS(wp)
3419 {
3420 if (wp->w_buffer == term->tl_buffer)
3421 {
3422 win_setheight_win(rows, wp);
3423 win_setwidth_win(cols, wp);
3424 }
3425 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003426 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003427 }
3428 return 1;
3429}
3430
3431/*
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003432 * If the number of lines that are stored goes over 'termwinscroll' then
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003433 * delete the first 10%.
3434 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3435 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003436 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003437 static void
3438limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003439{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003440 if (gap->ga_len < term->tl_buffer->b_p_twsl)
3441 return;
3442
Milly6d5f4a02024-10-22 23:17:45 +02003443 int todo = MAX(term->tl_buffer->b_p_twsl / 10,
3444 gap->ga_len - term->tl_buffer->b_p_twsl);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003445 int i;
3446
3447 curbuf = term->tl_buffer;
3448 for (i = 0; i < todo; ++i)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003449 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003450 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003451 if (update_buffer)
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003452 ml_delete(1);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003453 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003454 curbuf = curwin->w_buffer;
3455
3456 gap->ga_len -= todo;
3457 mch_memmove(gap->ga_data,
3458 (sb_line_T *)gap->ga_data + todo,
3459 sizeof(sb_line_T) * gap->ga_len);
3460 if (update_buffer)
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003461 {
Hirohito Higashifa9753a2025-04-27 15:36:43 +02003462 win_T *curwin_save = curwin;
3463 win_T *wp = NULL;
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003464
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003465 term->tl_scrollback_scrolled -= todo;
Christian Brabandt1254e6d2024-07-29 21:19:51 +02003466
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003467 FOR_ALL_WINDOWS(wp)
3468 {
3469 if (wp->w_buffer == term->tl_buffer)
3470 {
3471 curwin = wp;
3472 check_cursor();
Hirohito Higashifa9753a2025-04-27 15:36:43 +02003473 update_topline();
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003474 }
3475 }
3476 curwin = curwin_save;
3477 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003478}
3479
3480/*
3481 * Handle a line that is pushed off the top of the screen.
3482 */
3483 static int
3484handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3485{
3486 term_T *term = (term_T *)user;
3487 garray_T *gap;
3488 int update_buffer;
3489
3490 if (term->tl_normal_mode)
3491 {
3492 // In Terminal-Normal mode the user interacts with the buffer, thus we
3493 // must not change it. Postpone adding the scrollback lines.
3494 gap = &term->tl_scrollback_postponed;
3495 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003496 }
3497 else
3498 {
3499 // First remove the lines that were appended before, the pushed line
3500 // goes above it.
3501 cleanup_scrollback(term);
3502 gap = &term->tl_scrollback;
3503 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003504 }
3505
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003506 limit_scrollback(term, gap, update_buffer);
3507
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003508 if (ga_grow(gap, 1) == FAIL)
3509 return 0;
3510
3511 cellattr_T *p = NULL;
3512 int len = 0;
3513 int i;
3514 int c;
3515 int col;
3516 int text_len;
3517 char_u *text;
3518 sb_line_T *line;
3519 garray_T ga;
3520 cellattr_T fill_attr = term->tl_default_color;
3521
3522 // do not store empty cells at the end
3523 for (i = 0; i < cols; ++i)
3524 if (cells[i].chars[0] != 0)
3525 len = i + 1;
3526 else
3527 cell2cellattr(&cells[i], &fill_attr);
3528
3529 ga_init2(&ga, 1, 100);
3530 if (len > 0)
3531 p = ALLOC_MULT(cellattr_T, len);
3532 if (p != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003533 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003534 for (col = 0; col < len; col += cells[col].width)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003535 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003536 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003537 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003538 ga.ga_len = 0;
3539 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003540 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003541 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3542 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3543 (char_u *)ga.ga_data + ga.ga_len);
3544 cell2cellattr(&cells[col], &p[col]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003545 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003546 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003547 if (ga_grow(&ga, 1) == FAIL)
3548 {
3549 if (update_buffer)
3550 text = (char_u *)"";
3551 else
3552 text = vim_strsave((char_u *)"");
3553 text_len = 0;
3554 }
3555 else
3556 {
3557 text = ga.ga_data;
3558 text_len = ga.ga_len;
3559 *(text + text_len) = NUL;
3560 }
3561 if (update_buffer)
3562 add_scrollback_line_to_buffer(term, text, text_len);
3563
3564 line = (sb_line_T *)gap->ga_data + gap->ga_len;
3565 line->sb_cols = len;
3566 line->sb_cells = p;
3567 line->sb_fill_attr = fill_attr;
3568 if (update_buffer)
3569 {
3570 line->sb_text = NULL;
3571 ++term->tl_scrollback_scrolled;
3572 ga_clear(&ga); // free the text
3573 }
3574 else
3575 {
3576 line->sb_text = text;
3577 ga_init(&ga); // text is kept in tl_scrollback_postponed
3578 }
3579 ++gap->ga_len;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003580 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003581}
3582
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003583/*
3584 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3585 * received and stored in tl_scrollback_postponed.
3586 */
3587 static void
3588handle_postponed_scrollback(term_T *term)
3589{
3590 int i;
3591
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003592 if (term->tl_scrollback_postponed.ga_len == 0)
3593 return;
3594 ch_log(NULL, "Moving postponed scrollback to scrollback");
3595
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003596 // First remove the lines that were appended before, the pushed lines go
3597 // above it.
3598 cleanup_scrollback(term);
3599
3600 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3601 {
3602 char_u *text;
3603 sb_line_T *pp_line;
3604 sb_line_T *line;
3605
3606 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3607 break;
3608 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3609
3610 text = pp_line->sb_text;
3611 if (text == NULL)
3612 text = (char_u *)"";
3613 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3614 vim_free(pp_line->sb_text);
3615
3616 line = (sb_line_T *)term->tl_scrollback.ga_data
3617 + term->tl_scrollback.ga_len;
3618 line->sb_cols = pp_line->sb_cols;
3619 line->sb_cells = pp_line->sb_cells;
3620 line->sb_fill_attr = pp_line->sb_fill_attr;
3621 line->sb_text = NULL;
3622 ++term->tl_scrollback_scrolled;
3623 ++term->tl_scrollback.ga_len;
3624 }
3625
3626 ga_clear(&term->tl_scrollback_postponed);
3627 limit_scrollback(term, &term->tl_scrollback, TRUE);
3628}
3629
LemonBoy77771d32022-04-13 11:47:25 +01003630/*
3631 * Called when the terminal wants to ring the system bell.
3632 */
3633 static int
3634handle_bell(void *user UNUSED)
3635{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003636 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003637 return 0;
3638}
3639
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003640static VTermScreenCallbacks screen_callbacks = {
Yegappan Lakshmanan562610c2025-05-04 21:05:51 +02003641 handle_damage, // damage
3642 handle_moverect, // moverect
3643 handle_movecursor, // movecursor
3644 handle_settermprop, // settermprop
3645 handle_bell, // bell
3646 handle_resize, // resize
3647 handle_pushline, // sb_pushline
3648 NULL, // sb_popline
3649 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003650};
3651
3652/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003653 * Do the work after the channel of a terminal was closed.
3654 * Must be called only when updating_screen is FALSE.
3655 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3656 */
3657 static int
3658term_after_channel_closed(term_T *term)
3659{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003660 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003661 if (!term->tl_normal_mode)
3662 {
3663 int fnum = term->tl_buffer->b_fnum;
3664
3665 cleanup_vterm(term);
3666
3667 if (term->tl_finish == TL_FINISH_CLOSE)
3668 {
3669 aco_save_T aco;
zeertzjqbc11f6d2024-08-16 21:11:31 +02003670 int do_set_w_locked = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003671#ifdef FEAT_PROP_POPUP
3672 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003673
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003674 // If this was a terminal in a popup window, go back to the
3675 // previous window.
3676 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3677 {
3678 pwin = curwin;
3679 if (win_valid(prevwin))
3680 win_enter(prevwin, FALSE);
3681 }
3682 else
3683#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003684 // If this is the last normal window: exit Vim.
3685 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3686 {
3687 exarg_T ea;
3688
Bram Moolenaara80faa82020-04-12 19:37:17 +02003689 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003690 ex_quit(&ea);
3691 return TRUE;
3692 }
3693
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003694 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003695 ch_log(NULL, "terminal job finished, closing window");
3696 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaare76062c2022-11-28 18:51:43 +00003697 if (curbuf == term->tl_buffer)
3698 {
3699 // Avoid closing the window if we temporarily use it.
3700 if (is_aucmd_win(curwin))
zeertzjqbc11f6d2024-08-16 21:11:31 +02003701 do_set_w_locked = TRUE;
3702 if (do_set_w_locked)
Christian Brabandt0a6e57b2024-08-15 22:15:28 +02003703 curwin->w_locked = TRUE;
Bram Moolenaare76062c2022-11-28 18:51:43 +00003704 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
zeertzjqbc11f6d2024-08-16 21:11:31 +02003705 if (do_set_w_locked)
Christian Brabandt0a6e57b2024-08-15 22:15:28 +02003706 curwin->w_locked = FALSE;
Bram Moolenaare76062c2022-11-28 18:51:43 +00003707 aucmd_restbuf(&aco);
3708 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003709#ifdef FEAT_PROP_POPUP
3710 if (pwin != NULL)
3711 popup_close_with_retval(pwin, 0);
3712#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003713 return TRUE;
3714 }
3715 if (term->tl_finish == TL_FINISH_OPEN
3716 && term->tl_buffer->b_nwindows == 0)
3717 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003718 char *cmd = term->tl_opencmd == NULL
3719 ? "botright sbuf %d"
3720 : (char *)term->tl_opencmd;
3721 size_t len = strlen(cmd) + 50;
3722 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003723
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003724 if (buf != NULL)
3725 {
3726 ch_log(NULL, "terminal job finished, opening window");
3727 vim_snprintf(buf, len, cmd, fnum);
3728 do_cmdline_cmd((char_u *)buf);
3729 vim_free(buf);
3730 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003731 }
3732 else
3733 ch_log(NULL, "terminal job finished");
3734 }
3735
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003736 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003737 return FALSE;
3738}
3739
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003740#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3741/*
3742 * If the current window is a terminal in a popup window and the job has
3743 * finished, close the popup window and to back to the previous window.
3744 * Otherwise return FAIL.
3745 */
3746 int
3747may_close_term_popup(void)
3748{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003749 if (!popup_is_popup(curwin) || curbuf->b_term == NULL
3750 || term_job_running_not_none(curbuf->b_term))
3751 return FAIL;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003752
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003753 win_T *pwin = curwin;
3754
3755 if (win_valid(prevwin))
3756 win_enter(prevwin, FALSE);
3757 popup_close_with_retval(pwin, 0);
3758 return OK;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003759}
3760#endif
3761
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003762/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003763 * Called when a channel is going to be closed, before invoking the close
3764 * callback.
3765 */
3766 void
3767term_channel_closing(channel_T *ch)
3768{
3769 term_T *term;
3770
3771 for (term = first_term; term != NULL; term = term->tl_next)
3772 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3773 term->tl_channel_closing = TRUE;
3774}
3775
3776/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003777 * Called when a channel has been closed.
3778 * If this was a channel for a terminal window then finish it up.
3779 */
3780 void
3781term_channel_closed(channel_T *ch)
3782{
3783 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003784 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003785 int did_one = FALSE;
3786
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003787 for (term = first_term; term != NULL; term = next_term)
3788 {
3789 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003790 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003791 {
3792 term->tl_channel_closed = TRUE;
3793 did_one = TRUE;
3794
Bram Moolenaard23a8232018-02-10 18:45:26 +01003795 VIM_CLEAR(term->tl_title);
3796 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003797#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003798 if (term->tl_out_fd != NULL)
3799 {
3800 fclose(term->tl_out_fd);
3801 term->tl_out_fd = NULL;
3802 }
3803#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003804
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003805 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003806 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003807 // Cannot open or close windows now. Can happen when
3808 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003809 term->tl_channel_recently_closed = TRUE;
3810 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003811 }
3812
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003813 if (term_after_channel_closed(term))
3814 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003815 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003816 }
3817
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003818 if (did_one)
3819 {
3820 redraw_statuslines();
3821
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003822 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003823 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003824 typebuf_was_filled = TRUE;
3825
3826 term = curbuf->b_term;
3827 if (term != NULL)
3828 {
3829 if (term->tl_job == ch->ch_job)
3830 maketitle();
3831 update_cursor(term, term->tl_cursor_visible);
3832 }
3833 }
3834}
3835
3836/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003837 * To be called after resetting updating_screen: handle any terminal where the
3838 * channel was closed.
3839 */
3840 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003841term_check_channel_closed_recently(void)
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003842{
3843 term_T *term;
3844 term_T *next_term;
3845
3846 for (term = first_term; term != NULL; term = next_term)
3847 {
3848 next_term = term->tl_next;
3849 if (term->tl_channel_recently_closed)
3850 {
3851 term->tl_channel_recently_closed = FALSE;
3852 if (term_after_channel_closed(term))
3853 // start over, the list may have changed
3854 next_term = first_term;
3855 }
3856 }
3857}
3858
3859/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003860 * Fill one screen line from a line of the terminal.
3861 * Advances "pos" to past the last column.
3862 */
3863 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003864term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003865 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003866 win_T *wp,
3867 VTermScreen *screen,
3868 VTermPos *pos,
3869 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003870{
3871 int off = screen_get_current_line_off();
3872
3873 for (pos->col = 0; pos->col < max_col; )
3874 {
3875 VTermScreenCell cell;
3876 int c;
3877
3878 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003879 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003880
3881 c = cell.chars[0];
3882 if (c == NUL)
3883 {
3884 ScreenLines[off] = ' ';
3885 if (enc_utf8)
3886 ScreenLinesUC[off] = NUL;
3887 }
3888 else
3889 {
3890 if (enc_utf8)
3891 {
3892 int i;
3893
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003894 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003895 for (i = 0; i < Screen_mco
3896 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3897 {
3898 ScreenLinesC[i][off] = cell.chars[i + 1];
3899 if (cell.chars[i + 1] == 0)
3900 break;
3901 }
3902 if (c >= 0x80 || (Screen_mco > 0
3903 && ScreenLinesC[0][off] != 0))
3904 {
3905 ScreenLines[off] = ' ';
3906 ScreenLinesUC[off] = c;
3907 }
3908 else
3909 {
3910 ScreenLines[off] = c;
3911 ScreenLinesUC[off] = NUL;
3912 }
3913 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003914#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003915 else if (has_mbyte && c >= 0x80)
3916 {
3917 char_u mb[MB_MAXBYTES+1];
3918 WCHAR wc = c;
3919
3920 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3921 (char*)mb, 2, 0, 0) > 1)
3922 {
3923 ScreenLines[off] = mb[0];
3924 ScreenLines[off + 1] = mb[1];
3925 cell.width = mb_ptr2cells(mb);
3926 }
3927 else
3928 ScreenLines[off] = c;
3929 }
3930#endif
3931 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003932 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003933 ScreenLines[off] = c;
3934 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003935 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3936 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003937
3938 ++pos->col;
3939 ++off;
3940 if (cell.width == 2)
3941 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003942 // don't set the second byte to NUL for a DBCS encoding, it
3943 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003944 if (enc_utf8)
3945 {
3946 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003947 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003948 }
3949 else if (!has_mbyte)
3950 {
3951 // Can't show a double-width character with a single-byte
3952 // 'encoding', just use a space.
3953 ScreenLines[off] = ' ';
3954 ScreenAttrs[off] = ScreenAttrs[off - 1];
3955 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003956
3957 ++pos->col;
3958 ++off;
3959 }
3960 }
3961}
3962
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003963#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003964 static void
3965update_system_term(term_T *term)
3966{
3967 VTermPos pos;
3968 VTermScreen *screen;
3969
3970 if (term->tl_vterm == NULL)
3971 return;
3972 screen = vterm_obtain_screen(term->tl_vterm);
3973
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003974 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003975 while (term->tl_toprow > 0
3976 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3977 {
3978 int save_p_more = p_more;
3979
3980 p_more = FALSE;
3981 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003982 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003983 p_more = save_p_more;
3984 --term->tl_toprow;
3985 }
3986
3987 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3988 && pos.row < Rows; ++pos.row)
3989 {
3990 if (pos.row < term->tl_rows)
3991 {
3992 int max_col = MIN(Columns, term->tl_cols);
3993
Bram Moolenaar83d47902020-03-26 20:34:00 +01003994 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003995 }
3996 else
3997 pos.col = 0;
3998
zeertzjqd0c1b772024-03-16 15:03:33 +01003999 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, -1,
4000 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01004001 }
4002
4003 term->tl_dirty_row_start = MAX_ROW;
4004 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01004005}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01004006#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01004007
4008/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004009 * Return TRUE if window "wp" is to be redrawn with term_update_window().
4010 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004011 * Terminal-Normal mode.
4012 */
4013 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004014term_do_update_window(win_T *wp)
4015{
4016 term_T *term = wp->w_buffer->b_term;
4017
4018 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
4019}
4020
4021/*
4022 * Called to update a window that contains an active terminal.
4023 */
4024 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004025term_update_window(win_T *wp)
4026{
4027 term_T *term = wp->w_buffer->b_term;
4028 VTerm *vterm;
4029 VTermScreen *screen;
4030 VTermState *state;
4031 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004032 int rows, cols;
4033 int newrows, newcols;
4034 int minsize;
4035 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004036
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004037 vterm = term->tl_vterm;
4038 screen = vterm_obtain_screen(vterm);
4039 state = vterm_obtain_state(vterm);
4040
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004041 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
4042 // With UPD_SOME_VALID only redraw what was marked dirty.
4043 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004044 {
4045 term->tl_dirty_row_start = 0;
4046 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004047
4048 if (term->tl_postponed_scroll > 0
4049 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004050 // Scrolling is usually faster than redrawing, when there are only
4051 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004052 term_scroll_up(term, 0, term->tl_postponed_scroll);
4053 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004054 }
4055
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004056 /*
4057 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004058 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004059 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004060 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004061
Bram Moolenaar498c2562018-04-15 23:45:15 +02004062 newrows = 99999;
4063 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004064 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02004065 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004066 // Always use curwin, it may be a popup window.
4067 win_T *wwp = twp == NULL ? curwin : twp;
4068
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004069 // When more than one window shows the same terminal, use the
4070 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004071 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004072 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004073 newrows = MIN(newrows, wwp->w_height);
4074 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004075 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004076 if (twp == NULL)
4077 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004078 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02004079 if (newrows == 99999 || newcols == 99999)
4080 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02004081 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
4082 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
4083
Bram Moolenaareba13e42021-02-23 17:47:23 +01004084 // If no cell is visible there is no point in resizing. Also, vterm can't
4085 // handle a zero height.
4086 if (newrows == 0 || newcols == 0)
4087 return;
4088
Bram Moolenaar498c2562018-04-15 23:45:15 +02004089 if (term->tl_rows != newrows || term->tl_cols != newcols)
4090 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004091 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004092 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004093 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02004094 newrows);
4095 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02004096
4097 // Updating the terminal size will cause the snapshot to be cleared.
4098 // When not in terminal_loop() we need to restore it.
4099 if (term != in_terminal_loop)
4100 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004101 }
4102
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004103 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004104 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01004105 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004106
Bram Moolenaar3a497e12017-09-30 20:40:27 +02004107 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
4108 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004109 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004110 if (pos.row < term->tl_rows)
4111 {
Bram Moolenaar13568252018-03-16 20:46:58 +01004112 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004113
Bram Moolenaar83d47902020-03-26 20:34:00 +01004114 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004115 }
4116 else
4117 pos.col = 0;
4118
Bram Moolenaar510f0372022-07-04 17:46:22 +01004119 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01004120#ifdef FEAT_MENU
4121 + winbar_height(wp)
4122#endif
Naruhiko Nishinobe5bd4d2025-05-14 21:20:28 +02004123 , wp->w_wincol + TPL_LCOL(wp), pos.col,
4124 wp->w_width, -1,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004125#ifdef FEAT_PROP_POPUP
4126 popup_is_popup(wp) ? SLF_POPUP :
4127#endif
4128 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004129 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00004130}
4131
4132/*
4133 * Called after updating all windows: may reset dirty rows.
4134 */
4135 void
4136term_did_update_window(win_T *wp)
4137{
4138 term_T *term = wp->w_buffer->b_term;
4139
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004140 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode
4141 || wp->w_redr_type != 0)
4142 return;
4143
4144 term->tl_dirty_row_start = MAX_ROW;
4145 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004146}
4147
4148/*
4149 * Return TRUE if "wp" is a terminal window where the job has finished.
4150 */
4151 int
4152term_is_finished(buf_T *buf)
4153{
4154 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
4155}
4156
4157/*
4158 * Return TRUE if "wp" is a terminal window where the job has finished or we
4159 * are in Terminal-Normal mode, thus we show the buffer contents.
4160 */
4161 int
4162term_show_buffer(buf_T *buf)
4163{
4164 term_T *term = buf->b_term;
4165
4166 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4167}
4168
4169/*
4170 * The current buffer is going to be changed. If there is terminal
4171 * highlighting remove it now.
4172 */
4173 void
4174term_change_in_curbuf(void)
4175{
4176 term_T *term = curbuf->b_term;
4177
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004178 if (!term_is_finished(curbuf) || term->tl_scrollback.ga_len <= 0)
4179 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004180
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004181 free_scrollback(term);
4182 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
4183
4184 // The buffer is now like a normal buffer, it cannot be easily
4185 // abandoned when changed.
4186 set_string_option_direct((char_u *)"buftype", -1,
4187 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004188}
4189
4190/*
4191 * Get the screen attribute for a position in the buffer.
4192 * Use a negative "col" to get the filler background color.
4193 */
4194 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004195term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004196{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004197 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004198 term_T *term = buf->b_term;
4199 sb_line_T *line;
4200 cellattr_T *cellattr;
4201
4202 if (lnum > term->tl_scrollback.ga_len)
4203 cellattr = &term->tl_default_color;
4204 else
4205 {
4206 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4207 if (col < 0 || col >= line->sb_cols)
4208 cellattr = &line->sb_fill_attr;
4209 else
4210 cellattr = line->sb_cells + col;
4211 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004212 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004213}
4214
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004215/*
4216 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004217 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004218 */
4219 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004220cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004221{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004222 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4223 if (rgb->index == 0)
4224 rgb->type = VTERM_COLOR_RGB;
4225 else
4226 {
4227 rgb->type = VTERM_COLOR_INDEXED;
4228 --rgb->index;
4229 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004230}
4231
4232/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004233 * Initialize vterm color from the synID.
4234 * Returns TRUE if color is set to "fg" and "bg".
4235 * Otherwise returns FALSE.
4236 */
4237 static int
4238get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4239{
4240#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4241 // Use the actual color for the GUI and when 'termguicolors' is set.
4242 if (0
4243# ifdef FEAT_GUI
4244 || gui.in_use
4245# endif
4246# ifdef FEAT_TERMGUICOLORS
4247 || p_tgc
4248# ifdef FEAT_VTP
4249 // Finally get INVALCOLOR on this execution path
4250 || (!p_tgc && t_colors >= 256)
4251# endif
4252# endif
4253 )
4254 {
4255 guicolor_T fg_rgb = INVALCOLOR;
4256 guicolor_T bg_rgb = INVALCOLOR;
4257
4258 if (id > 0)
4259 syn_id2colors(id, &fg_rgb, &bg_rgb);
4260
4261 if (fg_rgb != INVALCOLOR)
4262 {
4263 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4264 fg->red = (unsigned)(rgb >> 16);
4265 fg->green = (unsigned)(rgb >> 8) & 255;
4266 fg->blue = (unsigned)rgb & 255;
4267 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4268 }
4269 else
4270 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4271
4272 if (bg_rgb != INVALCOLOR)
4273 {
4274 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4275 bg->red = (unsigned)(rgb >> 16);
4276 bg->green = (unsigned)(rgb >> 8) & 255;
4277 bg->blue = (unsigned)rgb & 255;
4278 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4279 }
4280 else
4281 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4282
4283 return TRUE;
4284 }
4285 else
4286#endif
4287 if (t_colors >= 16)
4288 {
4289 int cterm_fg = -1;
4290 int cterm_bg = -1;
4291
4292 if (id > 0)
4293 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4294
4295 if (cterm_fg >= 0)
4296 {
4297 cterm_color2vterm(cterm_fg, fg);
4298 fg->type |= VTERM_COLOR_DEFAULT_FG;
4299 }
4300 else
4301 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4302
4303 if (cterm_bg >= 0)
4304 {
4305 cterm_color2vterm(cterm_bg, bg);
4306 bg->type |= VTERM_COLOR_DEFAULT_BG;
4307 }
4308 else
4309 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4310
4311 return TRUE;
4312 }
4313
4314 return FALSE;
4315}
4316
4317 void
4318term_reset_wincolor(win_T *wp)
4319{
4320 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4321 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4322}
4323
4324/*
4325 * Cache the color of 'wincolor'.
4326 */
4327 void
4328term_update_wincolor(win_T *wp)
4329{
4330 int id = 0;
4331
4332 if (*wp->w_p_wcr != NUL)
4333 id = syn_name2id(wp->w_p_wcr);
4334 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4335 &wp->w_term_wincolor.bg))
4336 term_reset_wincolor(wp);
4337}
4338
4339/*
4340 * Called when option 'termguicolors' was set,
4341 * or when any highlight is changed.
4342 */
4343 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004344term_update_wincolor_all(void)
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004345{
4346 win_T *wp = NULL;
4347 int did_curwin = FALSE;
4348
4349 while (for_all_windows_and_curwin(&wp, &did_curwin))
4350 term_update_wincolor(wp);
4351}
4352
4353/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004354 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004355 */
4356 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004357init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004358{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004359 VTermColor *fg, *bg;
4360 int fgval, bgval;
4361 int id;
4362
Bram Moolenaara80faa82020-04-12 19:37:17 +02004363 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004364 term->tl_default_color.width = 1;
4365 fg = &term->tl_default_color.fg;
4366 bg = &term->tl_default_color.bg;
4367
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004368 // Vterm uses a default black background. Set it to white when
4369 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004370 if (*p_bg == 'l')
4371 {
4372 fgval = 0;
4373 bgval = 255;
4374 }
4375 else
4376 {
4377 fgval = 255;
4378 bgval = 0;
4379 }
4380 fg->red = fg->green = fg->blue = fgval;
4381 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004382 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4383 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004384
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004385 // The highlight group overrules the defaults.
4386 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004387
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004388 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004389 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004390#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004391 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004392#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004393
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004394 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004395 if (cterm_normal_fg_color > 0)
4396 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004397 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004398# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4399# ifdef VIMDLL
4400 if (!gui.in_use)
4401# endif
4402 {
4403 tmp = fg->red;
4404 fg->red = fg->blue;
4405 fg->blue = tmp;
4406 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004407# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004408 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004409# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004410 else
4411 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004412# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004413
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004414 if (cterm_normal_bg_color > 0)
4415 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004416 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004417# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4418# ifdef VIMDLL
4419 if (!gui.in_use)
4420# endif
4421 {
4422 tmp = fg->red;
4423 fg->red = fg->blue;
4424 fg->blue = tmp;
4425 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004426# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004427 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004428# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004429 else
4430 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004431# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004432 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004433}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004434
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004435#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4436/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004437 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4438 * "ansi_colors" argument in term_start()) shall be applied.
4439 */
4440 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004441term_use_palette(void)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004442{
4443 if (0
4444#ifdef FEAT_GUI
4445 || gui.in_use
4446#endif
4447#ifdef FEAT_TERMGUICOLORS
4448 || p_tgc
4449#endif
4450 )
4451 return TRUE;
4452 return FALSE;
4453}
4454
4455/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004456 * Set the 16 ANSI colors from array of RGB values
4457 */
4458 static void
4459set_vterm_palette(VTerm *vterm, long_u *rgb)
4460{
4461 int index = 0;
4462 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004463
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004464 for (; index < 16; index++)
4465 {
4466 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004467
Millyb771b6b2021-11-23 12:07:25 +00004468 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004469 color.red = (unsigned)(rgb[index] >> 16);
4470 color.green = (unsigned)(rgb[index] >> 8) & 255;
4471 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004472 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004473 vterm_state_set_palette_color(state, index, &color);
4474 }
4475}
4476
4477/*
4478 * Set the ANSI color palette from a list of colors
4479 */
4480 static int
4481set_ansi_colors_list(VTerm *vterm, list_T *list)
4482{
4483 int n = 0;
4484 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004485 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004486
Bram Moolenaarb0992022020-01-30 14:55:42 +01004487 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004488 {
4489 char_u *color_name;
4490 guicolor_T guicolor;
4491
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004492 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004493 if (color_name == NULL)
4494 return FAIL;
4495
4496 guicolor = GUI_GET_COLOR(color_name);
4497 if (guicolor == INVALCOLOR)
4498 return FAIL;
4499
4500 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4501 }
4502
4503 if (n != 16 || li != NULL)
4504 return FAIL;
4505
4506 set_vterm_palette(vterm, rgb);
4507
4508 return OK;
4509}
4510
4511/*
4512 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4513 */
4514 static void
4515init_vterm_ansi_colors(VTerm *vterm)
4516{
4517 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4518
LemonBoyb2b3acb2022-05-20 10:10:34 +01004519 if (var == NULL)
4520 return;
4521
4522 if (var->di_tv.v_type != VAR_LIST
4523 || var->di_tv.vval.v_list == NULL
4524 || var->di_tv.vval.v_list->lv_first == &range_list_item
4525 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004526 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004527}
4528#endif
4529
Bram Moolenaar52acb112018-03-18 19:20:22 +01004530/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004531 * Handles a "drop" command from the job in the terminal.
4532 * "item" is the file name, "item->li_next" may have options.
4533 */
4534 static void
4535handle_drop_command(listitem_T *item)
4536{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004537 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004538 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004539 int bufnr;
4540 win_T *wp;
4541 tabpage_T *tp;
4542 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004543 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004544
4545 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4546 FOR_ALL_TAB_WINDOWS(tp, wp)
4547 {
4548 if (wp->w_buffer->b_fnum == bufnr)
4549 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004550 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004551 goto_tabpage_win(tp, wp);
4552 return;
4553 }
4554 }
4555
Bram Moolenaara80faa82020-04-12 19:37:17 +02004556 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004557
4558 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4559 && opt_item->li_tv.vval.v_dict != NULL)
4560 {
4561 dict_T *dict = opt_item->li_tv.vval.v_dict;
4562 char_u *p;
4563
Bram Moolenaard61efa52022-07-23 09:52:04 +01004564 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004565 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004566 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004567 if (p != NULL)
4568 {
4569 if (check_ff_value(p) == FAIL)
4570 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4571 else
4572 ea.force_ff = *p;
4573 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004574 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004575 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004576 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004577 if (p != NULL)
4578 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004579 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004580 if (ea.cmd != NULL)
4581 {
4582 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4583 ea.force_enc = 11;
4584 tofree = ea.cmd;
4585 }
4586 }
4587
Bram Moolenaard61efa52022-07-23 09:52:04 +01004588 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004589 if (p != NULL)
4590 get_bad_opt(p, &ea);
4591
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004592 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004593 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004594 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004595 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004596 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004597 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004598 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004599 ea.force_bin = FORCE_NOBIN;
4600 }
4601
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004602 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004603 if (ea.cmd == NULL)
4604 ea.cmd = (char_u *)"split";
4605 ea.arg = fname;
4606 ea.cmdidx = CMD_split;
4607 ex_splitview(&ea);
4608
4609 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004610}
4611
4612/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004613 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4614 */
4615 static int
4616is_permitted_term_api(char_u *func, char_u *pat)
4617{
4618 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4619}
4620
4621/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004622 * Handles a function call from the job running in a terminal.
4623 * "item" is the function name, "item->li_next" has the arguments.
4624 */
4625 static void
4626handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4627{
4628 char_u *func;
4629 typval_T argvars[2];
4630 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004631 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004632
4633 if (item->li_next == NULL)
4634 {
4635 ch_log(channel, "Missing function arguments for call");
4636 return;
4637 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004638 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004639
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004640 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004641 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004642 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004643 return;
4644 }
4645
4646 argvars[0].v_type = VAR_NUMBER;
4647 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4648 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004649 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004650 funcexe.fe_firstline = 1L;
4651 funcexe.fe_lastline = 1L;
4652 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004653 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004654 {
4655 clear_tv(&rettv);
4656 ch_log(channel, "Function %s called", func);
4657 }
4658 else
4659 ch_log(channel, "Calling function %s failed", func);
4660}
4661
4662/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004663 * URL decoding (also know as Percent-encoding).
4664 *
4665 * Note this function currently is only used for decoding shell's
4666 * OSC 7 escape sequence which we can assume all bytes are valid
4667 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4668 * encoding bytes like 0xfe, 0xff.
4669 */
4670 static size_t
4671url_decode(const char *src, const size_t len, char_u *dst)
4672{
4673 size_t i = 0, j = 0;
4674
4675 while (i < len)
4676 {
4677 if (src[i] == '%' && i + 2 < len)
4678 {
4679 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4680 j++;
4681 i += 3;
4682 }
4683 else
4684 {
4685 dst[j] = src[i];
4686 i++;
4687 j++;
4688 }
4689 }
4690 dst[j] = '\0';
4691 return j;
4692}
4693
4694/*
4695 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4696 *
4697 * The OSC 7 sequence has the format of
4698 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4699 * and what VTerm provides via VTermStringFragment is
4700 * "file://HOSTNAME/CURRENT/DIR"
4701 */
4702 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004703sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004704{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004705 int offset = 7; // len of "file://" is 7
4706 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004707 char_u *new_dir;
4708
4709 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004710 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004711 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004712 ++offset;
4713 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004714 }
4715
Bram Moolenaar474ad392022-08-21 11:37:17 +01004716 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004717 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004718 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004719 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004720 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004721 }
4722
Bram Moolenaar474ad392022-08-21 11:37:17 +01004723 new_dir = alloc(gap->ga_len - offset + 1);
4724 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004725 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4726 vim_free(new_dir);
4727}
4728
4729/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004730 * Called by libvterm when it cannot recognize an OSC sequence.
4731 * We recognize a terminal API command.
4732 */
4733 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004734parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004735{
4736 term_T *term = (term_T *)user;
4737 js_read_T reader;
4738 typval_T tv;
4739 channel_T *channel = term->tl_job == NULL ? NULL
4740 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004741 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004742
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004743 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004744 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004745 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004746
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004747 // Concatenate what was received until the final piece is found.
4748 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4749 {
4750 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004751 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004752 }
4753 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004754 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004755 if (!frag.final)
4756 return 1;
4757
4758 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004759
4760 if (command == 7)
4761 {
4762 sync_shell_dir(gap);
4763 ga_clear(gap);
4764 return 1;
4765 }
4766
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004767 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004768 reader.js_fill = NULL;
4769 reader.js_used = 0;
4770 if (json_decode(&reader, &tv, 0) == OK
4771 && tv.v_type == VAR_LIST
4772 && tv.vval.v_list != NULL)
4773 {
4774 listitem_T *item = tv.vval.v_list->lv_first;
4775
4776 if (item == NULL)
4777 ch_log(channel, "Missing command");
4778 else
4779 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004780 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004781
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004782 // Make sure an invoked command doesn't delete the buffer (and the
4783 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004784 ++term->tl_buffer->b_locked;
4785
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004786 item = item->li_next;
4787 if (item == NULL)
4788 ch_log(channel, "Missing argument for %s", cmd);
4789 else if (STRCMP(cmd, "drop") == 0)
4790 handle_drop_command(item);
4791 else if (STRCMP(cmd, "call") == 0)
4792 handle_call_command(term, channel, item);
4793 else
4794 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004795 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004796 }
4797 }
4798 else
4799 ch_log(channel, "Invalid JSON received");
4800
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004801 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004802 clear_tv(&tv);
4803 return 1;
4804}
4805
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004806/*
4807 * Called by libvterm when it cannot recognize a CSI sequence.
4808 * We recognize the window position report.
4809 */
4810 static int
4811parse_csi(
4812 const char *leader UNUSED,
4813 const long args[],
4814 int argcount,
4815 const char *intermed UNUSED,
4816 char command,
4817 void *user)
4818{
4819 term_T *term = (term_T *)user;
4820 char buf[100];
4821 int len;
4822 int x = 0;
4823 int y = 0;
4824 win_T *wp;
4825
4826 // We recognize only CSI 13 t
4827 if (command != 't' || argcount != 1 || args[0] != 13)
4828 return 0; // not handled
4829
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004830 // When getting the window position is not possible or it fails it results
4831 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004832#if defined(FEAT_GUI) \
4833 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4834 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004835 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004836#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004837
4838 FOR_ALL_WINDOWS(wp)
4839 if (wp->w_buffer == term->tl_buffer)
4840 break;
4841 if (wp != NULL)
4842 {
4843#ifdef FEAT_GUI
4844 if (gui.in_use)
4845 {
4846 x += wp->w_wincol * gui.char_width;
4847 y += W_WINROW(wp) * gui.char_height;
4848 }
4849 else
4850#endif
4851 {
4852 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004853 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004854 x += wp->w_wincol * 7;
4855 y += W_WINROW(wp) * 10;
4856 }
4857 }
4858
4859 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4860 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4861 (char_u *)buf, len, NULL);
4862 return 1;
4863}
4864
Bram Moolenaard8637282020-05-20 18:41:41 +02004865static VTermStateFallbacks state_fallbacks = {
Yegappan Lakshmanan562610c2025-05-04 21:05:51 +02004866 NULL, // control
4867 parse_csi, // csi
4868 parse_osc, // osc
4869 NULL, // dcs
4870 NULL, // apc
4871 NULL, // pm
4872 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004873};
4874
4875/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004876 * Use Vim's allocation functions for vterm so profiling works.
4877 */
4878 static void *
4879vterm_malloc(size_t size, void *data UNUSED)
4880{
Bram Moolenaar88137392021-11-12 16:01:15 +00004881 // make sure that the length is not zero
4882 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004883}
4884
4885 static void
4886vterm_memfree(void *ptr, void *data UNUSED)
4887{
4888 vim_free(ptr);
4889}
4890
4891static VTermAllocatorFunctions vterm_allocator = {
4892 &vterm_malloc,
4893 &vterm_memfree
4894};
4895
4896/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004897 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004898 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004899 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004900 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004901create_vterm(term_T *term, int rows, int cols)
4902{
4903 VTerm *vterm;
4904 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004905 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004906 VTermValue value;
4907
Bram Moolenaar756ef112018-04-10 12:04:27 +02004908 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004909 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004910 if (vterm == NULL)
4911 return FAIL;
4912
4913 // Allocate screen and state here, so we can bail out if that fails.
4914 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004915 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004916 if (state == NULL || screen == NULL)
4917 {
4918 vterm_free(vterm);
4919 return FAIL;
4920 }
4921
Bram Moolenaar52acb112018-03-18 19:20:22 +01004922 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004923 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004924 vterm_set_utf8(vterm, 1);
4925
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004926 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004927
4928 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004929 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004930 &term->tl_default_color.fg,
4931 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004932
Bram Moolenaar9e587872019-05-13 20:27:23 +02004933 if (t_colors < 16)
4934 // Less than 16 colors: assume that bold means using a bright color for
4935 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004936 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4937
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004938 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004939 vterm_screen_reset(screen, 1 /* hard */);
4940
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004941 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004942 vterm_screen_enable_altscreen(screen, 1);
4943
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004944 // For unix do not use a blinking cursor. In an xterm this causes the
4945 // cursor to blink if it's blinking in the xterm.
4946 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004947#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004948 if (GetCaretBlinkTime() == INFINITE)
4949 value.boolean = 0;
4950 else
4951 value.boolean = 1;
4952#else
4953 value.boolean = 0;
4954#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004955 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004956 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004957
4958 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004959}
4960
4961/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004962 * Reset the terminal palette to its default value.
4963 */
4964 static void
4965term_reset_palette(VTerm *vterm)
4966{
4967 VTermState *state = vterm_obtain_state(vterm);
4968 int index;
4969
4970 for (index = 0; index < 16; index++)
4971 {
4972 VTermColor color;
4973
4974 color.type = VTERM_COLOR_INDEXED;
4975 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4976 &color.index);
4977 // The first valid index starts at 1.
4978 color.index -= 1;
4979
4980 vterm_state_set_palette_color(state, index, &color);
4981 }
4982}
4983
4984 static void
4985term_update_palette(term_T *term)
4986{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004987#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004988 if (term_use_palette()
4989 && (term->tl_palette != NULL
4990 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004991 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004992 {
4993 if (term->tl_palette != NULL)
4994 set_vterm_palette(term->tl_vterm, term->tl_palette);
4995 else
4996 init_vterm_ansi_colors(term->tl_vterm);
4997 }
4998 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004999#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01005000 term_reset_palette(term->tl_vterm);
5001}
5002
5003/*
5004 * Called when option 'termguicolors' is changed.
5005 */
5006 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005007term_update_palette_all(void)
LemonBoyb2b3acb2022-05-20 10:10:34 +01005008{
5009 term_T *term;
5010
5011 FOR_ALL_TERMS(term)
5012 {
5013 if (term->tl_vterm == NULL)
5014 continue;
5015 term_update_palette(term);
5016 }
5017}
5018
5019/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005020 * Called when option 'background' or 'termguicolors' was set,
5021 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02005022 */
5023 void
5024term_update_colors_all(void)
5025{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005026 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02005027
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005028 FOR_ALL_TERMS(term)
5029 {
5030 if (term->tl_vterm == NULL)
5031 continue;
5032 init_default_colors(term);
5033 vterm_state_set_default_colors(
5034 vterm_obtain_state(term->tl_vterm),
5035 &term->tl_default_color.fg,
5036 &term->tl_default_color.bg);
5037 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005038}
5039
5040/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005041 * Return the text to show for the buffer name and status.
5042 */
5043 char_u *
5044term_get_status_text(term_T *term)
5045{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005046 if (term->tl_status_text != NULL)
5047 return term->tl_status_text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005048
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005049 char_u *txt;
5050 size_t len;
5051 char_u *fname;
5052
5053 if (term->tl_normal_mode)
5054 {
5055 if (term_job_running(term))
5056 txt = (char_u *)_("Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005057 else
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005058 txt = (char_u *)_("Terminal-finished");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005059 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005060 else if (term->tl_title != NULL)
5061 txt = term->tl_title;
5062 else if (term_none_open(term))
5063 txt = (char_u *)_("active");
5064 else if (term_job_running(term))
5065 txt = (char_u *)_("running");
5066 else
5067 txt = (char_u *)_("finished");
5068 fname = buf_get_fname(term->tl_buffer);
5069 len = 9 + STRLEN(fname) + STRLEN(txt);
5070 term->tl_status_text = alloc(len);
5071 if (term->tl_status_text != NULL)
5072 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
5073 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005074 return term->tl_status_text;
5075}
5076
5077/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00005078 * Clear the cached value of the status text.
5079 */
5080 void
5081term_clear_status_text(term_T *term)
5082{
5083 VIM_CLEAR(term->tl_status_text);
5084}
5085
5086/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005087 * Mark references in jobs of terminals.
5088 */
5089 int
5090set_ref_in_term(int copyID)
5091{
5092 int abort = FALSE;
5093 term_T *term;
5094 typval_T tv;
5095
Bram Moolenaar75a1a942019-06-20 03:45:36 +02005096 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005097 if (term->tl_job != NULL)
5098 {
5099 tv.v_type = VAR_JOB;
5100 tv.vval.v_job = term->tl_job;
Yegappan Lakshmanan9cb865e2025-03-23 16:42:16 +01005101 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005102 }
5103 return abort;
5104}
5105
5106/*
5107 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005108 * Returns NULL when the buffer is not for a terminal window and logs a message
5109 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005110 */
5111 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005112term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005113{
5114 buf_T *buf;
5115
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005116 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01005117 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005118 --emsg_off;
5119 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005120 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01005121 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005122 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005123 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005124 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005125 return buf;
5126}
5127
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005128 static void
5129clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005130{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005131 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005132 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
5133 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005134}
5135
5136 static void
5137dump_term_color(FILE *fd, VTermColor *color)
5138{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005139 int index;
5140
5141 if (VTERM_COLOR_IS_INDEXED(color))
5142 index = color->index + 1;
5143 else if (color->type == 0)
5144 // use RGB values
5145 index = 255;
5146 else
5147 // default color
5148 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005149 fprintf(fd, "%02x%02x%02x%d",
5150 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005151 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005152}
5153
5154/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005155 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01005156 *
5157 * Each screen cell in full is:
5158 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5159 * {characters} is a space for an empty cell
5160 * For a double-width character "+" is changed to "*" and the next cell is
5161 * skipped.
5162 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5163 * when "&" use the same as the previous cell.
5164 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5165 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5166 * {color-idx} is a number from 0 to 255
5167 *
5168 * Screen cell with same width, attributes and color as the previous one:
5169 * |{characters}
5170 *
5171 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5172 *
5173 * Repeating the previous screen cell:
5174 * @{count}
5175 */
5176 void
5177f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5178{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005179 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005180 term_T *term;
5181 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005182 int max_height = 0;
5183 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005184 stat_T st;
5185 FILE *fd;
5186 VTermPos pos;
5187 VTermScreen *screen;
5188 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005189 VTermState *state;
5190 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005191
5192 if (check_restricted() || check_secure())
5193 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005194
5195 if (in_vim9script()
5196 && (check_for_buffer_arg(argvars, 0) == FAIL
5197 || check_for_string_arg(argvars, 1) == FAIL
5198 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5199 return;
5200
5201 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005202 if (buf == NULL)
5203 return;
5204 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005205 if (term->tl_vterm == NULL)
5206 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005207 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005208 return;
5209 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005210
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005211 if (argvars[2].v_type != VAR_UNKNOWN)
5212 {
5213 dict_T *d;
5214
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005215 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005216 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005217 d = argvars[2].vval.v_dict;
5218 if (d != NULL)
5219 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005220 max_height = dict_get_number(d, "rows");
5221 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005222 }
5223 }
5224
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005225 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005226 if (fname == NULL)
5227 return;
5228 if (mch_stat((char *)fname, &st) >= 0)
5229 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005230 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005231 return;
5232 }
5233
Bram Moolenaard96ff162018-02-18 22:13:29 +01005234 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5235 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005236 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005237 return;
5238 }
5239
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005240 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005241
5242 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005243 state = vterm_obtain_state(term->tl_vterm);
5244 vterm_state_get_cursorpos(state, &cursor_pos);
5245
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005246 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5247 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005248 {
5249 int repeat = 0;
5250
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005251 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5252 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005253 {
5254 VTermScreenCell cell;
5255 int same_attr;
5256 int same_chars = TRUE;
5257 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005258 int is_cursor_pos = (pos.col == cursor_pos.col
5259 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005260
5261 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005262 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005263
5264 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5265 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005266 int c = cell.chars[i];
5267 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005268 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005269
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005270 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005271 if (i == 0)
5272 {
5273 c = (c == NUL) ? ' ' : c;
5274 pc = (pc == NUL) ? ' ' : pc;
5275 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005276 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005277 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005278 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005279 break;
5280 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005281 same_attr = vtermAttr2hl(&cell.attrs)
5282 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005283 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5284 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005285 if (same_chars && cell.width == prev_cell.width && same_attr
5286 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005287 {
5288 ++repeat;
5289 }
5290 else
5291 {
5292 if (repeat > 0)
5293 {
5294 fprintf(fd, "@%d", repeat);
5295 repeat = 0;
5296 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005297 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005298
5299 if (cell.chars[0] == NUL)
5300 fputs(" ", fd);
5301 else
5302 {
5303 char_u charbuf[10];
5304 int len;
5305
5306 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5307 && cell.chars[i] != NUL; ++i)
5308 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005309 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005310 fwrite(charbuf, len, 1, fd);
5311 }
5312 }
5313
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005314 // When only the characters differ we don't write anything, the
5315 // following "|", "@" or NL will indicate using the same
5316 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005317 if (cell.width != prev_cell.width || !same_attr)
5318 {
5319 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005320 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005321 else
5322 fputs("+", fd);
5323
5324 if (same_attr)
5325 {
5326 fputs("&", fd);
5327 }
5328 else
5329 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005330 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005331 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005332 fputs("&", fd);
5333 else
5334 {
5335 fputs("#", fd);
5336 dump_term_color(fd, &cell.fg);
5337 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005338 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005339 fputs("&", fd);
5340 else
5341 {
5342 fputs("#", fd);
5343 dump_term_color(fd, &cell.bg);
5344 }
5345 }
5346 }
5347
5348 prev_cell = cell;
5349 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005350
5351 if (cell.width == 2)
5352 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005353 }
5354 if (repeat > 0)
5355 fprintf(fd, "@%d", repeat);
5356 fputs("\n", fd);
5357 }
5358
5359 fclose(fd);
5360}
5361
5362/*
5363 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5364 */
5365 static void
5366dump_is_corrupt(garray_T *gap)
5367{
5368 ga_concat(gap, (char_u *)"CORRUPT");
5369}
5370
5371 static void
5372append_cell(garray_T *gap, cellattr_T *cell)
5373{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005374 if (ga_grow(gap, 1) == FAIL)
5375 return;
5376
5377 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5378 ++gap->ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005379}
5380
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005381 static void
5382clear_cellattr(cellattr_T *cell)
5383{
5384 CLEAR_FIELD(*cell);
5385 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5386 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5387}
5388
Bram Moolenaard96ff162018-02-18 22:13:29 +01005389/*
5390 * Read the dump file from "fd" and append lines to the current buffer.
5391 * Return the cell width of the longest line.
5392 */
5393 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005394read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005395{
5396 int c;
5397 garray_T ga_text;
5398 garray_T ga_cell;
5399 char_u *prev_char = NULL;
5400 int attr = 0;
5401 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005402 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005403 term_T *term = curbuf->b_term;
5404 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005405 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005406
5407 ga_init2(&ga_text, 1, 90);
5408 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005409 clear_cellattr(&cell);
5410 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005411 cursor_pos->row = -1;
5412 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005413
5414 c = fgetc(fd);
5415 for (;;)
5416 {
5417 if (c == EOF)
5418 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005419 if (c == '\r')
5420 {
5421 // DOS line endings? Ignore.
5422 c = fgetc(fd);
5423 }
5424 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005425 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005426 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005427 if (ga_text.ga_data == NULL)
5428 dump_is_corrupt(&ga_text);
5429 if (ga_grow(&term->tl_scrollback, 1) == OK)
5430 {
5431 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5432 + term->tl_scrollback.ga_len;
5433
5434 if (max_cells < ga_cell.ga_len)
5435 max_cells = ga_cell.ga_len;
5436 line->sb_cols = ga_cell.ga_len;
5437 line->sb_cells = ga_cell.ga_data;
5438 line->sb_fill_attr = term->tl_default_color;
5439 ++term->tl_scrollback.ga_len;
5440 ga_init(&ga_cell);
5441
5442 ga_append(&ga_text, NUL);
5443 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5444 ga_text.ga_len, FALSE);
5445 }
5446 else
5447 ga_clear(&ga_cell);
5448 ga_text.ga_len = 0;
5449
5450 c = fgetc(fd);
5451 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005452 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005453 {
5454 int prev_len = ga_text.ga_len;
5455
Bram Moolenaar9271d052018-02-25 21:39:46 +01005456 if (c == '>')
5457 {
5458 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005459 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005460 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5461 cursor_pos->col = ga_cell.ga_len;
5462 }
5463
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005464 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005465 c = fgetc(fd);
5466 if (c != EOF)
5467 ga_append(&ga_text, c);
5468 for (;;)
5469 {
5470 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005471 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005472 || c == EOF || c == '\n')
5473 break;
5474 ga_append(&ga_text, c);
5475 }
5476
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005477 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005478 vim_free(prev_char);
5479 if (ga_text.ga_data != NULL)
5480 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5481 ga_text.ga_len - prev_len);
5482
Bram Moolenaar9271d052018-02-25 21:39:46 +01005483 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005484 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005485 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005486 }
5487 else if (c == '+' || c == '*')
5488 {
5489 int is_bg;
5490
5491 cell.width = c == '+' ? 1 : 2;
5492
5493 c = fgetc(fd);
5494 if (c == '&')
5495 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005496 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005497 c = fgetc(fd);
5498 }
Keith Thompson184f71c2024-01-04 21:19:04 +01005499 else if (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005500 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005501 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005502 attr = 0;
Keith Thompson184f71c2024-01-04 21:19:04 +01005503 while (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005504 {
5505 attr = attr * 10 + (c - '0');
5506 c = fgetc(fd);
5507 }
5508 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005509
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005510 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005511 for (is_bg = 0; is_bg <= 1; ++is_bg)
5512 {
5513 if (c == '&')
5514 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005515 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005516 c = fgetc(fd);
5517 }
5518 else if (c == '#')
5519 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005520 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005521
5522 c = fgetc(fd);
5523 red = hex2nr(c);
5524 c = fgetc(fd);
5525 red = (red << 4) + hex2nr(c);
5526 c = fgetc(fd);
5527 green = hex2nr(c);
5528 c = fgetc(fd);
5529 green = (green << 4) + hex2nr(c);
5530 c = fgetc(fd);
5531 blue = hex2nr(c);
5532 c = fgetc(fd);
5533 blue = (blue << 4) + hex2nr(c);
5534 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005535 if (!SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005536 dump_is_corrupt(&ga_text);
Keith Thompson184f71c2024-01-04 21:19:04 +01005537 while (SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005538 {
5539 index = index * 10 + (c - '0');
5540 c = fgetc(fd);
5541 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005542 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005543 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005544 type = VTERM_COLOR_RGB;
5545 if (index == 0)
5546 {
5547 if (is_bg)
5548 type |= VTERM_COLOR_DEFAULT_BG;
5549 else
5550 type |= VTERM_COLOR_DEFAULT_FG;
5551 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005552 }
5553 else
5554 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005555 type = VTERM_COLOR_INDEXED;
5556 index -= 1;
5557 }
5558 if (is_bg)
5559 {
5560 cell.bg.type = type;
5561 cell.bg.red = red;
5562 cell.bg.green = green;
5563 cell.bg.blue = blue;
5564 cell.bg.index = index;
5565 }
5566 else
5567 {
5568 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005569 cell.fg.red = red;
5570 cell.fg.green = green;
5571 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005572 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005573 }
5574 }
5575 else
5576 dump_is_corrupt(&ga_text);
5577 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005578 }
5579 else
5580 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005581 }
5582 else
5583 dump_is_corrupt(&ga_text);
5584
5585 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005586 if (cell.width == 2)
5587 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005588 }
5589 else if (c == '@')
5590 {
5591 if (prev_char == NULL)
5592 dump_is_corrupt(&ga_text);
5593 else
5594 {
5595 int count = 0;
5596
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005597 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005598 for (;;)
5599 {
5600 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005601 if (!SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005602 break;
5603 count = count * 10 + (c - '0');
5604 }
5605
5606 while (count-- > 0)
5607 {
5608 ga_concat(&ga_text, prev_char);
5609 append_cell(&ga_cell, &cell);
5610 }
5611 }
5612 }
5613 else
5614 {
5615 dump_is_corrupt(&ga_text);
5616 c = fgetc(fd);
5617 }
5618 }
5619
5620 if (ga_text.ga_len > 0)
5621 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005622 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005623 dump_is_corrupt(&ga_text);
5624 ga_append(&ga_text, NUL);
5625 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5626 ga_text.ga_len, FALSE);
5627 }
5628
5629 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005630 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005631 vim_free(prev_char);
5632
5633 return max_cells;
5634}
5635
5636/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005637 * Return an allocated string with at least "text_width" "=" characters and
5638 * "fname" inserted in the middle.
5639 */
5640 static char_u *
5641get_separator(int text_width, char_u *fname)
5642{
5643 int width = MAX(text_width, curwin->w_width);
5644 char_u *textline;
5645 int fname_size;
5646 char_u *p = fname;
5647 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005648 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005649
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005650 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005651 if (textline == NULL)
5652 return NULL;
5653
5654 fname_size = vim_strsize(fname);
5655 if (fname_size < width - 8)
5656 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005657 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005658 width = MAX(text_width, fname_size + 8);
5659 }
5660 else if (fname_size > width - 8)
5661 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005662 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005663 p = gettail(fname);
5664 fname_size = vim_strsize(p);
5665 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005666 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005667 while (fname_size > width - 8)
5668 {
5669 p += (*mb_ptr2len)(p);
5670 fname_size = vim_strsize(p);
5671 }
5672
5673 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5674 textline[i] = '=';
5675 textline[i++] = ' ';
5676
5677 STRCPY(textline + i, p);
5678 off = STRLEN(textline);
5679 textline[off] = ' ';
5680 for (i = 1; i < (width - fname_size) / 2; ++i)
5681 textline[off + i] = '=';
5682 textline[off + i] = NUL;
5683
5684 return textline;
5685}
5686
5687/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005688 * Common for "term_dumpdiff()" and "term_dumpload()".
5689 */
5690 static void
5691term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5692{
5693 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005694 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005695 char_u buf1[NUMBUFLEN];
5696 char_u buf2[NUMBUFLEN];
5697 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005698 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005699 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005700 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005701 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005702 char_u *textline = NULL;
5703
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005704 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005705 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005706 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005707 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005708 if (fname1 == NULL || (do_diff && fname2 == NULL))
5709 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005710 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005711 return;
5712 }
5713 fd1 = mch_fopen((char *)fname1, READBIN);
5714 if (fd1 == NULL)
5715 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005716 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005717 return;
5718 }
5719 if (do_diff)
5720 {
5721 fd2 = mch_fopen((char *)fname2, READBIN);
5722 if (fd2 == NULL)
5723 {
5724 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005725 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005726 return;
5727 }
5728 }
5729
5730 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005731 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5732 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5733 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5734 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5735 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005736
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005737 if (opt.jo_term_name == NULL)
5738 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005739 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005740
Bram Moolenaar51e14382019-05-25 20:21:28 +02005741 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005742 if (fname_tofree != NULL)
5743 {
5744 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5745 opt.jo_term_name = fname_tofree;
5746 }
5747 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005748
Bram Moolenaar87abab92019-06-03 21:14:59 +02005749 if (opt.jo_bufnr_buf != NULL)
5750 {
5751 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5752
5753 // With "bufnr" argument: enter the window with this buffer and make it
5754 // empty.
5755 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005756 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005757 else
5758 {
5759 buf = curbuf;
5760 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005761 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005762 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005763 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005764 }
5765 }
5766 else
5767 // Create a new terminal window.
5768 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5769
Bram Moolenaard96ff162018-02-18 22:13:29 +01005770 if (buf != NULL && buf->b_term != NULL)
5771 {
5772 int i;
5773 linenr_T bot_lnum;
5774 linenr_T lnum;
5775 term_T *term = buf->b_term;
5776 int width;
5777 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005778 VTermPos cursor_pos1;
5779 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005780
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005781 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005782
Bram Moolenaard96ff162018-02-18 22:13:29 +01005783 rettv->vval.v_number = buf->b_fnum;
5784
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005785 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005786 width = read_dump_file(fd1, &cursor_pos1);
5787
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005788 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005789 if (cursor_pos1.row >= 0)
5790 {
5791 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5792 coladvance(cursor_pos1.col);
5793 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005794
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005795 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005796 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005797
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005798 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005799 if (!do_diff)
5800 goto theend;
5801
5802 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5803
Bram Moolenaar4a696342018-04-05 18:45:26 +02005804 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005805 if (textline == NULL)
5806 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005807 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5808 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5809 vim_free(textline);
5810
5811 textline = get_separator(width, fname2);
5812 if (textline == NULL)
5813 goto theend;
5814 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5815 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005816 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005817
5818 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005819 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005820 if (width2 > width)
5821 {
5822 vim_free(textline);
5823 textline = alloc(width2 + 1);
5824 if (textline == NULL)
5825 goto theend;
5826 width = width2;
5827 textline[width] = NUL;
5828 }
5829 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5830
5831 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5832 {
5833 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5834 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005835 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005836 for (i = 0; i < width; ++i)
5837 textline[i] = '-';
5838 }
5839 else
5840 {
5841 char_u *line1;
5842 char_u *line2;
5843 char_u *p1;
5844 char_u *p2;
5845 int col;
5846 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5847 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5848 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5849 ->sb_cells;
5850
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005851 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005852 line1 = vim_strsave(ml_get(lnum));
5853 if (line1 == NULL)
5854 break;
5855 p1 = line1;
5856
5857 line2 = ml_get(lnum + bot_lnum);
5858 p2 = line2;
5859 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5860 {
5861 int len1 = utfc_ptr2len(p1);
5862 int len2 = utfc_ptr2len(p2);
5863
5864 textline[col] = ' ';
5865 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005866 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005867 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005868 else if (lnum == cursor_pos1.row + 1
5869 && col == cursor_pos1.col
5870 && (cursor_pos1.row != cursor_pos2.row
5871 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005872 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005873 textline[col] = '>';
5874 else if (lnum == cursor_pos2.row + 1
5875 && col == cursor_pos2.col
5876 && (cursor_pos1.row != cursor_pos2.row
5877 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005878 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005879 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005880 else if (cellattr1 != NULL && cellattr2 != NULL)
5881 {
5882 if ((cellattr1 + col)->width
5883 != (cellattr2 + col)->width)
5884 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005885 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005886 &(cellattr2 + col)->fg))
5887 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005888 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005889 &(cellattr2 + col)->bg))
5890 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005891 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5892 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005893 textline[col] = 'a';
5894 }
5895 p1 += len1;
5896 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005897 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005898 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005899
5900 while (col < width)
5901 {
5902 if (*p1 == NUL && *p2 == NUL)
5903 textline[col] = '?';
5904 else if (*p1 == NUL)
5905 {
5906 textline[col] = '+';
5907 p2 += utfc_ptr2len(p2);
5908 }
5909 else
5910 {
5911 textline[col] = '-';
5912 p1 += utfc_ptr2len(p1);
5913 }
5914 ++col;
5915 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005916
5917 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005918 }
5919 if (add_empty_scrollback(term, &term->tl_default_color,
5920 term->tl_top_diff_rows) == OK)
5921 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5922 ++bot_lnum;
5923 }
5924
5925 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5926 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005927 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005928 for (i = 0; i < width; ++i)
5929 textline[i] = '+';
5930 if (add_empty_scrollback(term, &term->tl_default_color,
5931 term->tl_top_diff_rows) == OK)
5932 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5933 ++lnum;
5934 ++bot_lnum;
5935 }
5936
5937 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005938
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005939 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005940 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005941 }
5942
5943theend:
5944 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005945 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005946 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005947 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005948 fclose(fd2);
5949}
5950
5951/*
5952 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5953 * bottom files.
5954 * Return FAIL when this is not possible.
5955 */
5956 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005957term_swap_diff(void)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005958{
5959 term_T *term = curbuf->b_term;
5960 linenr_T line_count;
5961 linenr_T top_rows;
5962 linenr_T bot_rows;
5963 linenr_T bot_start;
5964 linenr_T lnum;
5965 char_u *p;
5966 sb_line_T *sb_line;
5967
5968 if (term == NULL
5969 || !term_is_finished(curbuf)
5970 || term->tl_top_diff_rows == 0
5971 || term->tl_scrollback.ga_len == 0)
5972 return FAIL;
5973
5974 line_count = curbuf->b_ml.ml_line_count;
5975 top_rows = term->tl_top_diff_rows;
5976 bot_rows = term->tl_bot_diff_rows;
5977 bot_start = line_count - bot_rows;
5978 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5979
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005980 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005981 for (lnum = 1; lnum <= top_rows; ++lnum)
5982 {
5983 p = vim_strsave(ml_get(1));
5984 if (p == NULL)
5985 return OK;
5986 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005987 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005988 vim_free(p);
5989 }
5990
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005991 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005992 for (lnum = 1; lnum <= bot_rows; ++lnum)
5993 {
5994 p = vim_strsave(ml_get(bot_start + lnum));
5995 if (p == NULL)
5996 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005997 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005998 ml_append(lnum - 1, p, 0, FALSE);
5999 vim_free(p);
6000 }
6001
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01006002 // move top title to bottom
6003 p = vim_strsave(ml_get(bot_rows + 1));
6004 if (p == NULL)
6005 return OK;
6006 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02006007 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01006008 vim_free(p);
6009
6010 // move bottom title to top
6011 p = vim_strsave(ml_get(line_count - top_rows));
6012 if (p == NULL)
6013 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02006014 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01006015 ml_append(bot_rows, p, 0, FALSE);
6016 vim_free(p);
6017
Bram Moolenaard96ff162018-02-18 22:13:29 +01006018 if (top_rows == bot_rows)
6019 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006020 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01006021 for (lnum = 0; lnum < top_rows; ++lnum)
6022 {
6023 sb_line_T temp;
6024
6025 temp = *(sb_line + lnum);
6026 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
6027 *(sb_line + bot_start + lnum) = temp;
6028 }
6029 }
6030 else
6031 {
6032 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006033 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006034
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006035 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01006036 if (temp != NULL)
6037 {
6038 mch_memmove(temp, term->tl_scrollback.ga_data, size);
6039 mch_memmove(term->tl_scrollback.ga_data,
6040 temp + bot_start,
6041 sizeof(sb_line_T) * bot_rows);
6042 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
6043 temp + top_rows,
6044 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
6045 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
6046 + line_count - top_rows,
6047 temp,
6048 sizeof(sb_line_T) * top_rows);
6049 vim_free(temp);
6050 }
6051 }
6052
6053 term->tl_top_diff_rows = bot_rows;
6054 term->tl_bot_diff_rows = top_rows;
6055
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006056 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006057 return OK;
6058}
6059
6060/*
6061 * "term_dumpdiff(filename, filename, options)" function
6062 */
6063 void
6064f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
6065{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02006066 if (in_vim9script()
6067 && (check_for_string_arg(argvars, 0) == FAIL
6068 || check_for_string_arg(argvars, 1) == FAIL
6069 || check_for_opt_dict_arg(argvars, 2) == FAIL))
6070 return;
6071
Bram Moolenaard96ff162018-02-18 22:13:29 +01006072 term_load_dump(argvars, rettv, TRUE);
6073}
6074
6075/*
6076 * "term_dumpload(filename, options)" function
6077 */
6078 void
6079f_term_dumpload(typval_T *argvars, typval_T *rettv)
6080{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006081 if (in_vim9script()
6082 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02006083 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006084 return;
6085
Bram Moolenaard96ff162018-02-18 22:13:29 +01006086 term_load_dump(argvars, rettv, FALSE);
6087}
6088
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006089/*
6090 * "term_getaltscreen(buf)" function
6091 */
6092 void
6093f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
6094{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006095 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006096
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006097 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6098 return;
6099
6100 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006101 if (buf == NULL)
6102 return;
6103 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
6104}
6105
6106/*
6107 * "term_getattr(attr, name)" function
6108 */
6109 void
6110f_term_getattr(typval_T *argvars, typval_T *rettv)
6111{
6112 int attr;
6113 size_t i;
6114 char_u *name;
6115
6116 static struct {
6117 char *name;
6118 int attr;
6119 } attrs[] = {
6120 {"bold", HL_BOLD},
6121 {"italic", HL_ITALIC},
6122 {"underline", HL_UNDERLINE},
6123 {"strike", HL_STRIKETHROUGH},
6124 {"reverse", HL_INVERSE},
6125 };
6126
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02006127 if (in_vim9script()
6128 && (check_for_number_arg(argvars, 0) == FAIL
6129 || check_for_string_arg(argvars, 1) == FAIL))
6130 return;
6131
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006132 attr = tv_get_number(&argvars[0]);
6133 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006134 if (name == NULL)
6135 return;
6136
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02006137 if (attr > HL_ALL)
6138 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02006139 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006140 if (STRCMP(name, attrs[i].name) == 0)
6141 {
6142 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
6143 break;
6144 }
6145}
6146
6147/*
6148 * "term_getcursor(buf)" function
6149 */
6150 void
6151f_term_getcursor(typval_T *argvars, typval_T *rettv)
6152{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006153 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006154 term_T *term;
6155 list_T *l;
6156 dict_T *d;
6157
6158 if (rettv_list_alloc(rettv) == FAIL)
6159 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006160
6161 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6162 return;
6163
6164 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006165 if (buf == NULL)
6166 return;
6167 term = buf->b_term;
6168
6169 l = rettv->vval.v_list;
6170 list_append_number(l, term->tl_cursor_pos.row + 1);
6171 list_append_number(l, term->tl_cursor_pos.col + 1);
6172
6173 d = dict_alloc();
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00006174 if (d == NULL)
6175 return;
6176
6177 dict_add_number(d, "visible", term->tl_cursor_visible);
6178 dict_add_number(d, "blink", blink_state_is_inverted()
6179 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6180 dict_add_number(d, "shape", term->tl_cursor_shape);
6181 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
6182 list_append_dict(l, d);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006183}
6184
6185/*
6186 * "term_getjob(buf)" function
6187 */
6188 void
6189f_term_getjob(typval_T *argvars, typval_T *rettv)
6190{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006191 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006192
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006193 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6194 return;
6195
6196 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006197 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006198 {
Ernie Raela78eb252024-06-13 17:24:54 +02006199 if (in_vim9script())
6200 {
6201 rettv->v_type = VAR_JOB;
6202 rettv->vval.v_job = NULL;
6203 }
6204 else
6205 {
6206 rettv->v_type = VAR_SPECIAL;
6207 rettv->vval.v_number = VVAL_NULL;
6208 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006209 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006210 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006211
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006212 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006213 rettv->vval.v_job = buf->b_term->tl_job;
6214 if (rettv->vval.v_job != NULL)
6215 ++rettv->vval.v_job->jv_refcount;
6216}
6217
6218 static int
6219get_row_number(typval_T *tv, term_T *term)
6220{
6221 if (tv->v_type == VAR_STRING
6222 && tv->vval.v_string != NULL
6223 && STRCMP(tv->vval.v_string, ".") == 0)
6224 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006225 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006226}
6227
6228/*
6229 * "term_getline(buf, row)" function
6230 */
6231 void
6232f_term_getline(typval_T *argvars, typval_T *rettv)
6233{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006234 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006235 term_T *term;
6236 int row;
6237
6238 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006239
6240 if (in_vim9script()
6241 && (check_for_buffer_arg(argvars, 0) == FAIL
6242 || check_for_lnum_arg(argvars, 1) == FAIL))
6243 return;
6244
6245 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006246 if (buf == NULL)
6247 return;
6248 term = buf->b_term;
6249 row = get_row_number(&argvars[1], term);
6250
6251 if (term->tl_vterm == NULL)
6252 {
6253 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6254
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006255 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006256 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6257 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6258 }
6259 else
6260 {
6261 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6262 VTermRect rect;
6263 int len;
6264 char_u *p;
6265
6266 if (row < 0 || row >= term->tl_rows)
6267 return;
6268 len = term->tl_cols * MB_MAXBYTES + 1;
6269 p = alloc(len);
6270 if (p == NULL)
6271 return;
6272 rettv->vval.v_string = p;
6273
6274 rect.start_col = 0;
6275 rect.end_col = term->tl_cols;
6276 rect.start_row = row;
6277 rect.end_row = row + 1;
6278 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6279 }
6280}
6281
6282/*
6283 * "term_getscrolled(buf)" function
6284 */
6285 void
6286f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6287{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006288 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006289
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006290 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6291 return;
6292
6293 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006294 if (buf == NULL)
6295 return;
6296 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6297}
6298
6299/*
6300 * "term_getsize(buf)" function
6301 */
6302 void
6303f_term_getsize(typval_T *argvars, typval_T *rettv)
6304{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006305 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006306 list_T *l;
6307
6308 if (rettv_list_alloc(rettv) == FAIL)
6309 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006310
6311 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6312 return;
6313
6314 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006315 if (buf == NULL)
6316 return;
6317
6318 l = rettv->vval.v_list;
6319 list_append_number(l, buf->b_term->tl_rows);
6320 list_append_number(l, buf->b_term->tl_cols);
6321}
6322
6323/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006324 * "term_setsize(buf, rows, cols)" function
6325 */
6326 void
Dominique Pellé0268ff32024-07-28 21:12:20 +02006327f_term_setsize(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006328{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006329 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006330 term_T *term;
6331 varnumber_T rows, cols;
6332
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006333 if (in_vim9script()
6334 && (check_for_buffer_arg(argvars, 0) == FAIL
6335 || check_for_number_arg(argvars, 1) == FAIL
6336 || check_for_number_arg(argvars, 2) == FAIL))
6337 return;
6338
6339 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006340 if (buf == NULL)
6341 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006342 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006343 return;
6344 }
6345 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006346 return;
6347 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006348 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006349 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006350 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006351 cols = cols <= 0 ? term->tl_cols : cols;
6352 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006353 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006354
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006355 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006356 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6357 term_report_winsize(term, term->tl_rows, term->tl_cols);
6358}
6359
6360/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006361 * "term_getstatus(buf)" function
6362 */
6363 void
6364f_term_getstatus(typval_T *argvars, typval_T *rettv)
6365{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006366 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006367 term_T *term;
6368 char_u val[100];
6369
6370 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006371
6372 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6373 return;
6374
6375 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006376 if (buf == NULL)
6377 return;
6378 term = buf->b_term;
6379
6380 if (term_job_running(term))
6381 STRCPY(val, "running");
6382 else
6383 STRCPY(val, "finished");
6384 if (term->tl_normal_mode)
6385 STRCAT(val, ",normal");
6386 rettv->vval.v_string = vim_strsave(val);
6387}
6388
6389/*
6390 * "term_gettitle(buf)" function
6391 */
6392 void
6393f_term_gettitle(typval_T *argvars, typval_T *rettv)
6394{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006395 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006396
6397 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006398
6399 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6400 return;
6401
6402 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006403 if (buf == NULL)
6404 return;
6405
6406 if (buf->b_term->tl_title != NULL)
6407 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6408}
6409
6410/*
6411 * "term_gettty(buf)" function
6412 */
6413 void
6414f_term_gettty(typval_T *argvars, typval_T *rettv)
6415{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006416 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006417 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006418 int num = 0;
6419
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006420 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006421 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006422 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6423 return;
6424
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006425 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006426 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006427 if (buf == NULL)
6428 return;
6429 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006430 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006431
6432 switch (num)
6433 {
6434 case 0:
6435 if (buf->b_term->tl_job != NULL)
6436 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006437 break;
6438 case 1:
6439 if (buf->b_term->tl_job != NULL)
6440 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006441 break;
6442 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006443 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006444 return;
6445 }
6446 if (p != NULL)
6447 rettv->vval.v_string = vim_strsave(p);
6448}
6449
6450/*
6451 * "term_list()" function
6452 */
6453 void
6454f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6455{
6456 term_T *tp;
6457 list_T *l;
6458
6459 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6460 return;
6461
6462 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006463 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006464 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006465 if (list_append_number(l,
6466 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6467 return;
6468}
6469
6470/*
6471 * "term_scrape(buf, row)" function
6472 */
6473 void
6474f_term_scrape(typval_T *argvars, typval_T *rettv)
6475{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006476 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006477 VTermScreen *screen = NULL;
6478 VTermPos pos;
6479 list_T *l;
6480 term_T *term;
6481 char_u *p;
6482 sb_line_T *line;
6483
6484 if (rettv_list_alloc(rettv) == FAIL)
6485 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006486
6487 if (in_vim9script()
6488 && (check_for_buffer_arg(argvars, 0) == FAIL
6489 || check_for_lnum_arg(argvars, 1) == FAIL))
6490 return;
6491
6492 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006493 if (buf == NULL)
6494 return;
6495 term = buf->b_term;
6496
6497 l = rettv->vval.v_list;
6498 pos.row = get_row_number(&argvars[1], term);
6499
6500 if (term->tl_vterm != NULL)
6501 {
6502 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006503 if (screen == NULL) // can't really happen
6504 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006505 p = NULL;
6506 line = NULL;
6507 }
6508 else
6509 {
6510 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6511
6512 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6513 return;
6514 p = ml_get_buf(buf, lnum + 1, FALSE);
6515 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6516 }
6517
6518 for (pos.col = 0; pos.col < term->tl_cols; )
6519 {
6520 dict_T *dcell;
6521 int width;
6522 VTermScreenCellAttrs attrs;
6523 VTermColor fg, bg;
6524 char_u rgb[8];
6525 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6526 int off = 0;
6527 int i;
6528
6529 if (screen == NULL)
6530 {
6531 cellattr_T *cellattr;
6532 int len;
6533
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006534 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006535 if (pos.col >= line->sb_cols)
6536 break;
6537 cellattr = line->sb_cells + pos.col;
6538 width = cellattr->width;
6539 attrs = cellattr->attrs;
6540 fg = cellattr->fg;
6541 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006542 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006543 mch_memmove(mbs, p, len);
6544 mbs[len] = NUL;
6545 p += len;
6546 }
6547 else
6548 {
6549 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006550
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006551 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6552 break;
6553 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6554 {
6555 if (cell.chars[i] == 0)
6556 break;
6557 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6558 }
6559 mbs[off] = NUL;
6560 width = cell.width;
6561 attrs = cell.attrs;
6562 fg = cell.fg;
6563 bg = cell.bg;
6564 }
6565 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006566 if (dcell == NULL)
6567 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006568 list_append_dict(l, dcell);
6569
Bram Moolenaare0be1672018-07-08 16:50:37 +02006570 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006571
6572 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6573 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006574 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006575 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6576 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006577 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006578
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006579 dict_add_number(dcell, "attr",
6580 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006581 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006582
6583 ++pos.col;
6584 if (width == 2)
6585 ++pos.col;
6586 }
6587}
6588
6589/*
6590 * "term_sendkeys(buf, keys)" function
6591 */
6592 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006593f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006594{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006595 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006596 char_u *msg;
6597 term_T *term;
6598
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006599 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006600 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006601 || check_for_string_arg(argvars, 1) == FAIL))
6602 return;
6603
6604 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006605 if (buf == NULL)
6606 return;
6607
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006608 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006609 if (msg == NULL)
6610 return;
6611 term = buf->b_term;
6612 if (term->tl_vterm == NULL)
6613 return;
6614
6615 while (*msg != NUL)
6616 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006617 int c;
6618
6619 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6620 {
6621 c = TO_SPECIAL(msg[1], msg[2]);
6622 msg += 3;
6623 }
6624 else
6625 {
6626 c = PTR2CHAR(msg);
6627 msg += MB_CPTR2LEN(msg);
6628 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006629 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006630 }
6631}
6632
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006633#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6634/*
6635 * "term_getansicolors(buf)" function
6636 */
6637 void
6638f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6639{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006640 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006641 term_T *term;
6642 VTermState *state;
6643 VTermColor color;
6644 char_u hexbuf[10];
6645 int index;
6646 list_T *list;
6647
6648 if (rettv_list_alloc(rettv) == FAIL)
6649 return;
6650
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006651 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6652 return;
6653
6654 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006655 if (buf == NULL)
6656 return;
6657 term = buf->b_term;
6658 if (term->tl_vterm == NULL)
6659 return;
6660
6661 list = rettv->vval.v_list;
6662 state = vterm_obtain_state(term->tl_vterm);
6663 for (index = 0; index < 16; index++)
6664 {
6665 vterm_state_get_palette_color(state, index, &color);
6666 sprintf((char *)hexbuf, "#%02x%02x%02x",
6667 color.red, color.green, color.blue);
6668 if (list_append_string(list, hexbuf, 7) == FAIL)
6669 return;
6670 }
6671}
6672
6673/*
6674 * "term_setansicolors(buf, list)" function
6675 */
6676 void
6677f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6678{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006679 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006680 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006681 listitem_T *li;
6682 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006683
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006684 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006685 && (check_for_buffer_arg(argvars, 0) == FAIL
6686 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006687 return;
6688
6689 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006690 if (buf == NULL)
6691 return;
6692 term = buf->b_term;
6693 if (term->tl_vterm == NULL)
6694 return;
6695
Bram Moolenaard83392a2022-09-01 12:22:46 +01006696 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006697 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006698
LemonBoyb2b3acb2022-05-20 10:10:34 +01006699 if (argvars[1].vval.v_list->lv_first == &range_list_item
6700 || argvars[1].vval.v_list->lv_len != 16)
6701 {
Bram Moolenaar23919542023-05-05 22:12:22 +01006702 semsg(_(e_invalid_value_for_argument_str), "\"colors\"");
LemonBoyb2b3acb2022-05-20 10:10:34 +01006703 return;
6704 }
6705
6706 if (term->tl_palette == NULL)
6707 term->tl_palette = ALLOC_MULT(long_u, 16);
6708 if (term->tl_palette == NULL)
6709 return;
6710
6711 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6712 {
6713 char_u *color_name;
6714 guicolor_T guicolor;
6715
6716 color_name = tv_get_string_chk(&li->li_tv);
6717 if (color_name == NULL)
6718 return;
6719
6720 guicolor = GUI_GET_COLOR(color_name);
6721 if (guicolor == INVALCOLOR)
6722 {
6723 semsg(_(e_cannot_allocate_color_str), color_name);
6724 return;
6725 }
6726
6727 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6728 }
6729
6730 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006731}
6732#endif
6733
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006734/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006735 * "term_setapi(buf, api)" function
6736 */
6737 void
6738f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6739{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006740 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006741 term_T *term;
6742 char_u *api;
6743
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006744 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006745 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006746 || check_for_string_arg(argvars, 1) == FAIL))
6747 return;
6748
6749 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006750 if (buf == NULL)
6751 return;
6752 term = buf->b_term;
6753 vim_free(term->tl_api);
6754 api = tv_get_string_chk(&argvars[1]);
6755 if (api != NULL)
6756 term->tl_api = vim_strsave(api);
6757 else
6758 term->tl_api = NULL;
6759}
6760
6761/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006762 * "term_setrestore(buf, command)" function
6763 */
6764 void
6765f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6766{
6767#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006768 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006769 term_T *term;
6770 char_u *cmd;
6771
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006772 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006773 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006774 || check_for_string_arg(argvars, 1) == FAIL))
6775 return;
6776
6777 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006778 if (buf == NULL)
6779 return;
6780 term = buf->b_term;
6781 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006782 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006783 if (cmd != NULL)
6784 term->tl_command = vim_strsave(cmd);
6785 else
6786 term->tl_command = NULL;
6787#endif
6788}
6789
6790/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006791 * "term_setkill(buf, how)" function
6792 */
6793 void
6794f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6795{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006796 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006797 term_T *term;
6798 char_u *how;
6799
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006800 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006801 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006802 || check_for_string_arg(argvars, 1) == FAIL))
6803 return;
6804
6805 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006806 if (buf == NULL)
6807 return;
6808 term = buf->b_term;
6809 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006810 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006811 if (how != NULL)
6812 term->tl_kill = vim_strsave(how);
6813 else
6814 term->tl_kill = NULL;
6815}
6816
6817/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006818 * "term_start(command, options)" function
6819 */
6820 void
6821f_term_start(typval_T *argvars, typval_T *rettv)
6822{
6823 jobopt_T opt;
6824 buf_T *buf;
6825
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006826 if (in_vim9script()
6827 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6828 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6829 return;
6830
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006831 init_job_options(&opt);
6832 if (argvars[1].v_type != VAR_UNKNOWN
6833 && get_job_options(&argvars[1], &opt,
6834 JO_TIMEOUT_ALL + JO_STOPONEXIT
6835 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6836 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6837 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6838 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006839 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006840 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006841 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006842 return;
6843
Bram Moolenaar13568252018-03-16 20:46:58 +01006844 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006845
6846 if (buf != NULL && buf->b_term != NULL)
6847 rettv->vval.v_number = buf->b_fnum;
6848}
6849
6850/*
6851 * "term_wait" function
6852 */
6853 void
6854f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6855{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006856 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006857
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006858 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006859 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006860 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006861 return;
6862
6863 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006864 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006865 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006866 if (buf->b_term->tl_job == NULL)
6867 {
6868 ch_log(NULL, "term_wait(): no job to wait for");
6869 return;
6870 }
6871 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006872 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006873 return;
6874
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006875 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006876 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006877 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6878 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006879 // The job is dead, keep reading channel I/O until the channel is
6880 // closed. buf->b_term may become NULL if the terminal was closed while
6881 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006882 ch_log(NULL, "term_wait(): waiting for channel to close");
6883 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6884 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006885 term_flush_messages();
6886
Bram Moolenaard45aa552018-05-21 22:50:29 +02006887 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006888 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006889 // If the terminal is closed when the channel is closed the
6890 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006891 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006892 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6893 // came here from a close callback, only wait one time
6894 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006895 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006896
6897 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006898 }
6899 else
6900 {
6901 long wait = 10L;
6902
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006903 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006904
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006905 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006906 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006907 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006908 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006909
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006910 // Flushing messages on channels is hopefully sufficient.
6911 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006912 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006913 }
6914}
6915
6916/*
6917 * Called when a channel has sent all the lines to a terminal.
6918 * Send a CTRL-D to mark the end of the text.
6919 */
6920 void
6921term_send_eof(channel_T *ch)
6922{
6923 term_T *term;
6924
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006925 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006926 if (term->tl_job == ch->ch_job)
6927 {
6928 if (term->tl_eof_chars != NULL)
6929 {
6930 channel_send(ch, PART_IN, term->tl_eof_chars,
6931 (int)STRLEN(term->tl_eof_chars), NULL);
6932 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6933 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006934# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006935 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006936 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006937 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6938# endif
6939 }
6940}
6941
Bram Moolenaar113e1072019-01-20 15:30:40 +01006942#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006943 job_T *
6944term_getjob(term_T *term)
6945{
6946 return term != NULL ? term->tl_job : NULL;
6947}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006948#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006949
Bram Moolenaar4f974752019-02-17 17:44:42 +01006950# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006951
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006952///////////////////////////////////////
6953// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006954#ifdef PROTO
6955typedef int COORD;
6956typedef int DWORD;
6957typedef int HANDLE;
6958typedef int *DWORD_PTR;
6959typedef int HPCON;
6960typedef int HRESULT;
6961typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006962typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006963typedef int PSIZE_T;
6964typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006965typedef int BOOL;
6966# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006967#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006968
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006969HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6970HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6971HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006972BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6973BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6974void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006975
6976 static int
6977dyn_conpty_init(int verbose)
6978{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006979 static HMODULE hKerneldll = NULL;
6980 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006981 static struct
6982 {
6983 char *name;
6984 FARPROC *ptr;
6985 } conpty_entry[] =
6986 {
6987 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6988 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6989 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6990 {"InitializeProcThreadAttributeList",
6991 (FARPROC*)&pInitializeProcThreadAttributeList},
6992 {"UpdateProcThreadAttribute",
6993 (FARPROC*)&pUpdateProcThreadAttribute},
6994 {"DeleteProcThreadAttributeList",
6995 (FARPROC*)&pDeleteProcThreadAttributeList},
6996 {NULL, NULL}
6997 };
6998
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006999 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007000 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007001 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00007002 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007003 return FAIL;
7004 }
7005
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007006 // No need to initialize twice.
7007 if (hKerneldll)
7008 return OK;
7009
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007010 hKerneldll = vimLoadLib("kernel32.dll");
7011 for (i = 0; conpty_entry[i].name != NULL
7012 && conpty_entry[i].ptr != NULL; ++i)
7013 {
7014 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
7015 conpty_entry[i].name)) == NULL)
7016 {
7017 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007018 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007019 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007020 return FAIL;
7021 }
7022 }
7023
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007024 return OK;
7025}
7026
7027 static int
7028conpty_term_and_job_init(
7029 term_T *term,
7030 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007031 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007032 jobopt_T *opt,
7033 jobopt_T *orig_opt)
7034{
7035 WCHAR *cmd_wchar = NULL;
7036 WCHAR *cmd_wchar_copy = NULL;
7037 WCHAR *cwd_wchar = NULL;
7038 WCHAR *env_wchar = NULL;
7039 channel_T *channel = NULL;
7040 job_T *job = NULL;
7041 HANDLE jo = NULL;
7042 garray_T ga_cmd, ga_env;
7043 char_u *cmd = NULL;
7044 HRESULT hr;
7045 COORD consize;
7046 SIZE_T breq;
7047 PROCESS_INFORMATION proc_info;
7048 HANDLE i_theirs = NULL;
7049 HANDLE o_theirs = NULL;
7050 HANDLE i_ours = NULL;
7051 HANDLE o_ours = NULL;
7052
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007053 ga_init2(&ga_cmd, sizeof(char*), 20);
7054 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007055
7056 if (argvar->v_type == VAR_STRING)
7057 {
7058 cmd = argvar->vval.v_string;
7059 }
7060 else if (argvar->v_type == VAR_LIST)
7061 {
7062 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
7063 goto failed;
7064 cmd = ga_cmd.ga_data;
7065 }
7066 if (cmd == NULL || *cmd == NUL)
7067 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007068 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007069 goto failed;
7070 }
7071
7072 term->tl_arg0_cmd = vim_strsave(cmd);
7073
7074 cmd_wchar = enc_to_utf16(cmd, NULL);
7075
7076 if (cmd_wchar != NULL)
7077 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007078 // Request by CreateProcessW
7079 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007080 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007081 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
7082 }
7083
7084 ga_clear(&ga_cmd);
7085 if (cmd_wchar == NULL)
7086 goto failed;
7087 if (opt->jo_cwd != NULL)
John Marriott031f2272025-04-23 20:56:08 +02007088 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007089 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
John Marriott031f2272025-04-23 20:56:08 +02007090 if (cwd_wchar == NULL)
7091 goto failed;
7092 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007093
7094 win32_build_env(opt->jo_env, &ga_env, TRUE);
7095 env_wchar = ga_env.ga_data;
7096
7097 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
7098 goto failed;
7099 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
7100 goto failed;
7101
7102 consize.X = term->tl_cols;
7103 consize.Y = term->tl_rows;
7104 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
7105 &term->tl_conpty);
7106 if (FAILED(hr))
7107 goto failed;
7108
7109 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
7110
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007111 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007112 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007113 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007114 if (!term->tl_siex.lpAttributeList)
7115 goto failed;
7116 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
7117 0, &breq))
7118 goto failed;
7119 if (!pUpdateProcThreadAttribute(
7120 term->tl_siex.lpAttributeList, 0,
7121 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
7122 sizeof(HPCON), NULL, NULL))
7123 goto failed;
7124
7125 channel = add_channel();
7126 if (channel == NULL)
7127 goto failed;
7128
7129 job = job_alloc();
7130 if (job == NULL)
7131 goto failed;
7132 if (argvar->v_type == VAR_STRING)
7133 {
7134 int argc;
7135
7136 build_argv_from_string(cmd, &job->jv_argv, &argc);
7137 }
7138 else
7139 {
7140 int argc;
7141
7142 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7143 }
7144
7145 if (opt->jo_set & JO_IN_BUF)
7146 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7147
7148 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
7149 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02007150 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007151 env_wchar, cwd_wchar,
7152 &term->tl_siex.StartupInfo, &proc_info))
7153 goto failed;
7154
7155 CloseHandle(i_theirs);
7156 CloseHandle(o_theirs);
7157
7158 channel_set_pipes(channel,
7159 (sock_T)i_ours,
7160 (sock_T)o_ours,
7161 (sock_T)o_ours);
7162
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007163 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007164 channel->ch_write_text_mode = TRUE;
7165
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007166 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007167 channel->ch_anonymous_pipe = TRUE;
7168
7169 jo = CreateJobObject(NULL, NULL);
7170 if (jo == NULL)
7171 goto failed;
7172
7173 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7174 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007175 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007176 CloseHandle(jo);
7177 jo = NULL;
7178 }
7179
7180 ResumeThread(proc_info.hThread);
7181 CloseHandle(proc_info.hThread);
7182
7183 vim_free(cmd_wchar);
7184 vim_free(cmd_wchar_copy);
7185 vim_free(cwd_wchar);
7186 vim_free(env_wchar);
7187
7188 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7189 goto failed;
7190
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007191#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007192 if (term_use_palette())
7193 {
7194 if (term->tl_palette != NULL)
7195 set_vterm_palette(term->tl_vterm, term->tl_palette);
7196 else
7197 init_vterm_ansi_colors(term->tl_vterm);
7198 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007199#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007200
7201 channel_set_job(channel, job, opt);
7202 job_set_options(job, opt);
7203
7204 job->jv_channel = channel;
7205 job->jv_proc_info = proc_info;
7206 job->jv_job_object = jo;
7207 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007208 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007209 ++job->jv_refcount;
7210 term->tl_job = job;
7211
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007212 // Redirecting stdout and stderr doesn't work at the job level. Instead
7213 // open the file here and handle it in. opt->jo_io was changed in
7214 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007215 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7216 {
7217 char_u *fname = opt->jo_io_name[PART_OUT];
7218
7219 ch_log(channel, "Opening output file %s", fname);
7220 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7221 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007222 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007223 }
7224
7225 return OK;
7226
7227failed:
7228 ga_clear(&ga_cmd);
7229 ga_clear(&ga_env);
7230 vim_free(cmd_wchar);
7231 vim_free(cmd_wchar_copy);
7232 vim_free(cwd_wchar);
7233 if (channel != NULL)
7234 channel_clear(channel);
7235 if (job != NULL)
7236 {
7237 job->jv_channel = NULL;
7238 job_cleanup(job);
7239 }
7240 term->tl_job = NULL;
7241 if (jo != NULL)
7242 CloseHandle(jo);
7243
7244 if (term->tl_siex.lpAttributeList != NULL)
7245 {
7246 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7247 vim_free(term->tl_siex.lpAttributeList);
7248 }
7249 term->tl_siex.lpAttributeList = NULL;
7250 if (o_theirs != NULL)
7251 CloseHandle(o_theirs);
7252 if (o_ours != NULL)
7253 CloseHandle(o_ours);
7254 if (i_ours != NULL)
7255 CloseHandle(i_ours);
7256 if (i_theirs != NULL)
7257 CloseHandle(i_theirs);
7258 if (term->tl_conpty != NULL)
7259 pClosePseudoConsole(term->tl_conpty);
7260 term->tl_conpty = NULL;
7261 return FAIL;
7262}
7263
7264 static void
7265conpty_term_report_winsize(term_T *term, int rows, int cols)
7266{
7267 COORD consize;
7268
7269 consize.X = cols;
7270 consize.Y = rows;
7271 pResizePseudoConsole(term->tl_conpty, consize);
7272}
7273
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007274 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007275term_free_conpty(term_T *term)
7276{
7277 if (term->tl_siex.lpAttributeList != NULL)
7278 {
7279 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7280 vim_free(term->tl_siex.lpAttributeList);
7281 }
7282 term->tl_siex.lpAttributeList = NULL;
7283 if (term->tl_conpty != NULL)
7284 pClosePseudoConsole(term->tl_conpty);
7285 term->tl_conpty = NULL;
7286}
7287
7288 int
7289use_conpty(void)
7290{
7291 return has_conpty;
7292}
7293
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007294# ifndef PROTO
7295
7296#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7297#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007298#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007299
7300void* (*winpty_config_new)(UINT64, void*);
7301void* (*winpty_open)(void*, void*);
7302void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7303BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7304void (*winpty_config_set_mouse_mode)(void*, int);
7305void (*winpty_config_set_initial_size)(void*, int, int);
7306LPCWSTR (*winpty_conin_name)(void*);
7307LPCWSTR (*winpty_conout_name)(void*);
7308LPCWSTR (*winpty_conerr_name)(void*);
7309void (*winpty_free)(void*);
7310void (*winpty_config_free)(void*);
7311void (*winpty_spawn_config_free)(void*);
7312void (*winpty_error_free)(void*);
7313LPCWSTR (*winpty_error_msg)(void*);
7314BOOL (*winpty_set_size)(void*, int, int, void*);
7315HANDLE (*winpty_agent_process)(void*);
7316
7317#define WINPTY_DLL "winpty.dll"
7318
7319static HINSTANCE hWinPtyDLL = NULL;
7320# endif
7321
7322 static int
7323dyn_winpty_init(int verbose)
7324{
7325 int i;
7326 static struct
7327 {
7328 char *name;
7329 FARPROC *ptr;
7330 } winpty_entry[] =
7331 {
7332 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7333 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7334 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7335 {"winpty_config_set_mouse_mode",
7336 (FARPROC*)&winpty_config_set_mouse_mode},
7337 {"winpty_config_set_initial_size",
7338 (FARPROC*)&winpty_config_set_initial_size},
7339 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7340 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7341 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7342 {"winpty_free", (FARPROC*)&winpty_free},
7343 {"winpty_open", (FARPROC*)&winpty_open},
7344 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7345 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7346 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7347 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7348 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7349 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7350 {NULL, NULL}
7351 };
7352
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007353 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007354 if (hWinPtyDLL)
7355 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007356 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7357 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007358 if (*p_winptydll != NUL)
7359 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7360 if (!hWinPtyDLL)
7361 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7362 if (!hWinPtyDLL)
7363 {
7364 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007365 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007366 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7367 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007368 return FAIL;
7369 }
7370 for (i = 0; winpty_entry[i].name != NULL
7371 && winpty_entry[i].ptr != NULL; ++i)
7372 {
7373 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7374 winpty_entry[i].name)) == NULL)
7375 {
7376 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007377 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007378 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007379 return FAIL;
7380 }
7381 }
7382
7383 return OK;
7384}
7385
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007386 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007387winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007388 term_T *term,
7389 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007390 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007391 jobopt_T *opt,
7392 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007393{
7394 WCHAR *cmd_wchar = NULL;
7395 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007396 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007397 channel_T *channel = NULL;
7398 job_T *job = NULL;
7399 DWORD error;
7400 HANDLE jo = NULL;
7401 HANDLE child_process_handle;
7402 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007403 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007404 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007405 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007406 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007407
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007408 ga_init2(&ga_cmd, sizeof(char*), 20);
7409 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007410
7411 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007412 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007413 cmd = argvar->vval.v_string;
7414 }
7415 else if (argvar->v_type == VAR_LIST)
7416 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007417 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007418 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007419 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007420 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007421 if (cmd == NULL || *cmd == NUL)
7422 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007423 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007424 goto failed;
7425 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007426
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007427 term->tl_arg0_cmd = vim_strsave(cmd);
7428
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007429 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007430 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007431 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007432 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007433 if (opt->jo_cwd != NULL)
John Marriott031f2272025-04-23 20:56:08 +02007434 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007435 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
John Marriott031f2272025-04-23 20:56:08 +02007436 if (cwd_wchar == NULL)
7437 goto failed;
7438 }
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007439
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007440 win32_build_env(opt->jo_env, &ga_env, TRUE);
7441 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007442
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007443 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7444 if (term->tl_winpty_config == NULL)
7445 goto failed;
7446
7447 winpty_config_set_mouse_mode(term->tl_winpty_config,
7448 WINPTY_MOUSE_MODE_FORCE);
7449 winpty_config_set_initial_size(term->tl_winpty_config,
7450 term->tl_cols, term->tl_rows);
7451 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7452 if (term->tl_winpty == NULL)
7453 goto failed;
7454
7455 spawn_config = winpty_spawn_config_new(
7456 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7457 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7458 NULL,
7459 cmd_wchar,
7460 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007461 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007462 &winpty_err);
7463 if (spawn_config == NULL)
7464 goto failed;
7465
7466 channel = add_channel();
7467 if (channel == NULL)
7468 goto failed;
7469
7470 job = job_alloc();
7471 if (job == NULL)
7472 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007473 if (argvar->v_type == VAR_STRING)
7474 {
7475 int argc;
7476
7477 build_argv_from_string(cmd, &job->jv_argv, &argc);
7478 }
7479 else
7480 {
7481 int argc;
7482
7483 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7484 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007485
7486 if (opt->jo_set & JO_IN_BUF)
7487 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7488
7489 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7490 &child_thread_handle, &error, &winpty_err))
7491 goto failed;
7492
7493 channel_set_pipes(channel,
7494 (sock_T)CreateFileW(
7495 winpty_conin_name(term->tl_winpty),
7496 GENERIC_WRITE, 0, NULL,
7497 OPEN_EXISTING, 0, NULL),
7498 (sock_T)CreateFileW(
7499 winpty_conout_name(term->tl_winpty),
7500 GENERIC_READ, 0, NULL,
7501 OPEN_EXISTING, 0, NULL),
7502 (sock_T)CreateFileW(
7503 winpty_conerr_name(term->tl_winpty),
7504 GENERIC_READ, 0, NULL,
7505 OPEN_EXISTING, 0, NULL));
7506
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007507 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007508 channel->ch_write_text_mode = TRUE;
7509
7510 jo = CreateJobObject(NULL, NULL);
7511 if (jo == NULL)
7512 goto failed;
7513
7514 if (!AssignProcessToJobObject(jo, child_process_handle))
7515 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007516 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007517 CloseHandle(jo);
7518 jo = NULL;
7519 }
7520
7521 winpty_spawn_config_free(spawn_config);
7522 vim_free(cmd_wchar);
7523 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007524 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007525
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007526 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7527 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007528
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007529#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007530 if (term_use_palette())
7531 {
7532 if (term->tl_palette != NULL)
7533 set_vterm_palette(term->tl_vterm, term->tl_palette);
7534 else
7535 init_vterm_ansi_colors(term->tl_vterm);
7536 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007537#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007538
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007539 channel_set_job(channel, job, opt);
7540 job_set_options(job, opt);
7541
7542 job->jv_channel = channel;
7543 job->jv_proc_info.hProcess = child_process_handle;
7544 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7545 job->jv_job_object = jo;
7546 job->jv_status = JOB_STARTED;
7547 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007548 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007549 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007550 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007551 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007552 ++job->jv_refcount;
7553 term->tl_job = job;
7554
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007555 // Redirecting stdout and stderr doesn't work at the job level. Instead
7556 // open the file here and handle it in. opt->jo_io was changed in
7557 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007558 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7559 {
7560 char_u *fname = opt->jo_io_name[PART_OUT];
7561
7562 ch_log(channel, "Opening output file %s", fname);
7563 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7564 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007565 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007566 }
7567
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007568 return OK;
7569
7570failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007571 ga_clear(&ga_cmd);
7572 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007573 vim_free(cmd_wchar);
7574 vim_free(cwd_wchar);
7575 if (spawn_config != NULL)
7576 winpty_spawn_config_free(spawn_config);
7577 if (channel != NULL)
7578 channel_clear(channel);
7579 if (job != NULL)
7580 {
7581 job->jv_channel = NULL;
7582 job_cleanup(job);
7583 }
7584 term->tl_job = NULL;
7585 if (jo != NULL)
7586 CloseHandle(jo);
7587 if (term->tl_winpty != NULL)
7588 winpty_free(term->tl_winpty);
7589 term->tl_winpty = NULL;
7590 if (term->tl_winpty_config != NULL)
7591 winpty_config_free(term->tl_winpty_config);
7592 term->tl_winpty_config = NULL;
7593 if (winpty_err != NULL)
7594 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007595 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007596 (short_u *)winpty_error_msg(winpty_err), NULL);
7597
John Marriott031f2272025-04-23 20:56:08 +02007598 if (msg != NULL)
7599 {
7600 emsg(msg);
7601 vim_free(msg);
7602 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007603 winpty_error_free(winpty_err);
7604 }
7605 return FAIL;
7606}
7607
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007608/*
7609 * Create a new terminal of "rows" by "cols" cells.
7610 * Store a reference in "term".
7611 * Return OK or FAIL.
7612 */
7613 static int
7614term_and_job_init(
7615 term_T *term,
7616 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007617 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007618 jobopt_T *opt,
7619 jobopt_T *orig_opt)
7620{
7621 int use_winpty = FALSE;
7622 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007623 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007624
7625 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7626 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7627
7628 if (!has_winpty && !has_conpty)
7629 // If neither is available give the errors for winpty, since when
7630 // conpty is not available it can't be installed either.
7631 return dyn_winpty_init(TRUE);
7632
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007633 if (opt->jo_tty_type != NUL)
7634 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007635
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007636 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007637 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007638 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007639 use_conpty = TRUE;
7640 else if (has_winpty)
7641 use_winpty = TRUE;
7642 // else: error
7643 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007644 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007645 {
7646 if (has_winpty)
7647 use_winpty = TRUE;
7648 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007649 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007650 {
7651 if (has_conpty)
7652 use_conpty = TRUE;
7653 else
7654 return dyn_conpty_init(TRUE);
7655 }
7656
7657 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007658 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007659
7660 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007661 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007662
7663 // error
7664 return dyn_winpty_init(TRUE);
7665}
7666
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007667 static int
7668create_pty_only(term_T *term, jobopt_T *options)
7669{
7670 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7671 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7672 char in_name[80], out_name[80];
7673 channel_T *channel = NULL;
7674
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007675 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7676 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007677
7678 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7679 GetCurrentProcessId(),
7680 curbuf->b_fnum);
7681 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7682 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7683 PIPE_UNLIMITED_INSTANCES,
7684 0, 0, NMPWAIT_NOWAIT, NULL);
7685 if (hPipeIn == INVALID_HANDLE_VALUE)
7686 goto failed;
7687
7688 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7689 GetCurrentProcessId(),
7690 curbuf->b_fnum);
7691 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7692 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7693 PIPE_UNLIMITED_INSTANCES,
7694 0, 0, 0, NULL);
7695 if (hPipeOut == INVALID_HANDLE_VALUE)
7696 goto failed;
7697
7698 ConnectNamedPipe(hPipeIn, NULL);
7699 ConnectNamedPipe(hPipeOut, NULL);
7700
7701 term->tl_job = job_alloc();
7702 if (term->tl_job == NULL)
7703 goto failed;
7704 ++term->tl_job->jv_refcount;
7705
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007706 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007707 term->tl_job->jv_status = JOB_FINISHED;
7708
7709 channel = add_channel();
7710 if (channel == NULL)
7711 goto failed;
7712 term->tl_job->jv_channel = channel;
7713 channel->ch_keep_open = TRUE;
7714 channel->ch_named_pipe = TRUE;
7715
7716 channel_set_pipes(channel,
7717 (sock_T)hPipeIn,
7718 (sock_T)hPipeOut,
7719 (sock_T)hPipeOut);
7720 channel_set_job(channel, term->tl_job, options);
7721 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7722 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7723
7724 return OK;
7725
7726failed:
7727 if (hPipeIn != NULL)
7728 CloseHandle(hPipeIn);
7729 if (hPipeOut != NULL)
7730 CloseHandle(hPipeOut);
7731 return FAIL;
7732}
7733
7734/*
7735 * Free the terminal emulator part of "term".
7736 */
7737 static void
7738term_free_vterm(term_T *term)
7739{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007740 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007741 if (term->tl_winpty != NULL)
7742 winpty_free(term->tl_winpty);
7743 term->tl_winpty = NULL;
7744 if (term->tl_winpty_config != NULL)
7745 winpty_config_free(term->tl_winpty_config);
7746 term->tl_winpty_config = NULL;
7747 if (term->tl_vterm != NULL)
7748 vterm_free(term->tl_vterm);
7749 term->tl_vterm = NULL;
7750}
7751
7752/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007753 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007754 */
7755 static void
7756term_report_winsize(term_T *term, int rows, int cols)
7757{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007758 if (term->tl_conpty)
7759 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007760 if (term->tl_winpty)
7761 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7762}
7763
7764 int
7765terminal_enabled(void)
7766{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007767 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007768}
7769
7770# else
7771
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007772///////////////////////////////////////
7773// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007774
7775/*
7776 * Create a new terminal of "rows" by "cols" cells.
7777 * Start job for "cmd".
7778 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007779 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007780 * Return OK or FAIL.
7781 */
7782 static int
7783term_and_job_init(
7784 term_T *term,
7785 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007786 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007787 jobopt_T *opt,
7788 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007789{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007790 term->tl_arg0_cmd = NULL;
7791
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007792 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7793 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007794
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007795#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007796 if (term_use_palette())
7797 {
7798 if (term->tl_palette != NULL)
7799 set_vterm_palette(term->tl_vterm, term->tl_palette);
7800 else
7801 init_vterm_ansi_colors(term->tl_vterm);
7802 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007803#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007804
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007805 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007806 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007807 if (term->tl_job != NULL)
7808 ++term->tl_job->jv_refcount;
7809
7810 return term->tl_job != NULL
7811 && term->tl_job->jv_channel != NULL
7812 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7813}
7814
7815 static int
7816create_pty_only(term_T *term, jobopt_T *opt)
7817{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007818 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7819 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007820
7821 term->tl_job = job_alloc();
7822 if (term->tl_job == NULL)
7823 return FAIL;
7824 ++term->tl_job->jv_refcount;
7825
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007826 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007827 term->tl_job->jv_status = JOB_FINISHED;
7828
7829 return mch_create_pty_channel(term->tl_job, opt);
7830}
7831
7832/*
7833 * Free the terminal emulator part of "term".
7834 */
7835 static void
7836term_free_vterm(term_T *term)
7837{
7838 if (term->tl_vterm != NULL)
7839 vterm_free(term->tl_vterm);
7840 term->tl_vterm = NULL;
7841}
7842
7843/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007844 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007845 */
7846 static void
7847term_report_winsize(term_T *term, int rows, int cols)
7848{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007849 // Use an ioctl() to report the new window size to the job.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007850 if (term->tl_job == NULL || term->tl_job->jv_channel == NULL)
7851 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007852
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007853 int fd = -1;
7854 int part;
7855
7856 for (part = PART_OUT; part < PART_COUNT; ++part)
7857 {
7858 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
7859 if (mch_isatty(fd))
7860 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007861 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007862 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7863 mch_signal_job(term->tl_job, (char_u *)"winch");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007864}
7865
7866# endif
7867
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007868#endif // FEAT_TERMINAL