blob: 88791b865bfe41ab114ab65f317befa62b566b72 [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020039 */
40
41#include "vim.h"
42
43#if defined(FEAT_TERMINAL) || defined(PROTO)
44
45#ifndef MIN
46# define MIN(x,y) ((x) < (y) ? (x) : (y))
47#endif
48#ifndef MAX
49# define MAX(x,y) ((x) > (y) ? (x) : (y))
50#endif
51
52#include "libvterm/include/vterm.h"
53
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010054// This is VTermScreenCell without the characters, thus much smaller.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055typedef struct {
56 VTermScreenCellAttrs attrs;
57 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010058 VTermColor fg;
59 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060} cellattr_T;
61
62typedef struct sb_line_S {
Bram Moolenaar29ae2232019-02-14 21:22:01 +010063 int sb_cols; // can differ per line
64 cellattr_T *sb_cells; // allocated
65 cellattr_T sb_fill_attr; // for short line
66 char_u *sb_text; // for tl_scrollback_postponed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067} sb_line_T;
68
Bram Moolenaar4f974752019-02-17 17:44:42 +010069#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010070# ifndef HPCON
71# define HPCON VOID*
72# endif
73# ifndef EXTENDED_STARTUPINFO_PRESENT
74# define EXTENDED_STARTUPINFO_PRESENT 0x00080000
75# endif
76# ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
77# define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE 0x00020016
78# endif
79typedef struct _DYN_STARTUPINFOEXW
80{
81 STARTUPINFOW StartupInfo;
82 LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
83} DYN_STARTUPINFOEXW, *PDYN_STARTUPINFOEXW;
84#endif
85
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010086// typedef term_T in structs.h
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020087struct terminal_S {
88 term_T *tl_next;
89
90 VTerm *tl_vterm;
91 job_T *tl_job;
92 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010093#if defined(FEAT_GUI)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010094 int tl_system; // when non-zero used for :!cmd output
95 int tl_toprow; // row with first line of system terminal
Bram Moolenaar13568252018-03-16 20:46:58 +010096#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010098 // Set when setting the size of a vterm, reset after redrawing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020099 int tl_vterm_size_changed;
100
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100101 int tl_normal_mode; // TRUE: Terminal-Normal mode
Bram Moolenaareea32af2021-11-21 14:51:13 +0000102 int tl_channel_closing;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200103 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200104 int tl_channel_recently_closed; // still need to handle tl_finish
105
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100106 int tl_finish;
107#define TL_FINISH_UNSET NUL
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100108#define TL_FINISH_CLOSE 'c' // ++close or :terminal without argument
109#define TL_FINISH_NOCLOSE 'n' // ++noclose
110#define TL_FINISH_OPEN 'o' // ++open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200111 char_u *tl_opencmd;
112 char_u *tl_eof_chars;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200113 char_u *tl_api; // prefix for terminal API function
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200114
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100115 char_u *tl_arg0_cmd; // To format the status bar
116
Bram Moolenaar4f974752019-02-17 17:44:42 +0100117#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200118 void *tl_winpty_config;
119 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200120
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100121 HPCON tl_conpty;
122 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
123
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200124 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200125#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100126#if defined(FEAT_SESSION)
127 char_u *tl_command;
128#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100129 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100131 // last known vterm size
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200132 int tl_rows;
133 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200134
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100135 char_u *tl_title; // NULL or allocated
136 char_u *tl_status_text; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200137
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100138 // Range of screen rows to update. Zero based.
139 int tl_dirty_row_start; // MAX_ROW if nothing dirty
140 int tl_dirty_row_end; // row below last one to update
141 int tl_dirty_snapshot; // text updated after making snapshot
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200142#ifdef FEAT_TIMERS
143 int tl_timer_set;
144 proftime_T tl_timer_due;
145#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100146 int tl_postponed_scroll; // to be scrolled up
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200148 garray_T tl_scrollback;
149 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100150 garray_T tl_scrollback_postponed;
151
Bram Moolenaar83d47902020-03-26 20:34:00 +0100152 char_u *tl_highlight_name; // replaces "Terminal"; allocated
153
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200154 cellattr_T tl_default_color;
155
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100156 linenr_T tl_top_diff_rows; // rows of top diff file or zero
157 linenr_T tl_bot_diff_rows; // rows of bottom diff file
Bram Moolenaard96ff162018-02-18 22:13:29 +0100158
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200159 VTermPos tl_cursor_pos;
160 int tl_cursor_visible;
161 int tl_cursor_blink;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100162 int tl_cursor_shape; // 1: block, 2: underline, 3: bar
163 char_u *tl_cursor_color; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200164
LemonBoyb2b3acb2022-05-20 10:10:34 +0100165 long_u *tl_palette; // array of 16 colors specified by term_start, can
166 // be NULL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167 int tl_using_altscreen;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200168 garray_T tl_osc_buf; // incomplete OSC string
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200169};
170
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100171#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
172#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200173
174/*
175 * List of all active terminals.
176 */
177static term_T *first_term = NULL;
178
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100179// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200180static term_T *in_terminal_loop = NULL;
181
Bram Moolenaar4f974752019-02-17 17:44:42 +0100182#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100183static BOOL has_winpty = FALSE;
184static BOOL has_conpty = FALSE;
185#endif
186
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100187#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188#define KEY_BUF_LEN 200
189
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200190#define FOR_ALL_TERMS(term) \
191 for ((term) = first_term; (term) != NULL; (term) = (term)->tl_next)
192
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193/*
194 * Functions with separate implementation for MS-Windows and Unix-like systems.
195 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200196static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200197static int create_pty_only(term_T *term, jobopt_T *opt);
198static void term_report_winsize(term_T *term, int rows, int cols);
199static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100200#ifdef FEAT_GUI
201static void update_system_term(term_T *term);
202#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200203
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100204static void handle_postponed_scrollback(term_T *term);
205
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100206// The character that we know (or assume) that the terminal expects for the
207// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200208static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200209
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100210// Store the last set and the desired cursor properties, so that we only update
211// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200212static char_u *last_set_cursor_color = NULL;
213static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100214static int last_set_cursor_shape = -1;
215static int desired_cursor_shape = -1;
216static int last_set_cursor_blink = -1;
217static int desired_cursor_blink = -1;
218
219
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100220///////////////////////////////////////
221// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200222
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200223 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200224cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
225{
226 if (lhs_color != NULL && rhs_color != NULL)
227 return STRCMP(lhs_color, rhs_color) == 0;
228 return lhs_color == NULL && rhs_color == NULL;
229}
230
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200231 static void
232cursor_color_copy(char_u **to_color, char_u *from_color)
233{
234 // Avoid a free & alloc if the value is already right.
235 if (cursor_color_equal(*to_color, from_color))
236 return;
237 vim_free(*to_color);
238 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
239}
240
241 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200242cursor_color_get(char_u *color)
243{
244 return (color == NULL) ? (char_u *)"" : color;
245}
246
247
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200248/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200249 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200250 * current window.
251 * Sets "rows" and/or "cols" to zero when it should follow the window size.
252 * Return TRUE if the size is the minimum size: "24*80".
253 */
254 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200255parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200256{
257 int minsize = FALSE;
258
259 *rows = 0;
260 *cols = 0;
261
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000262 if (*wp->w_p_tws == NUL)
263 return FALSE;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200264
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000265 char_u *p = vim_strchr(wp->w_p_tws, 'x');
266
267 // Syntax of value was already checked when it's set.
268 if (p == NULL)
269 {
270 minsize = TRUE;
271 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200272 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000273 *rows = atoi((char *)wp->w_p_tws);
274 *cols = atoi((char *)p + 1);
Christian Brabandtceee7a82023-09-21 16:55:06 +0200275 if (*rows > VTERM_MAX_ROWS)
276 *rows = VTERM_MAX_ROWS;
277 if (*cols > VTERM_MAX_COLS)
278 *cols = VTERM_MAX_COLS;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200279 return minsize;
280}
281
282/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200283 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200284 */
285 static void
Bram Moolenaarb936b792020-09-04 18:34:09 +0200286set_term_and_win_size(term_T *term, jobopt_T *opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200287{
Bram Moolenaarb936b792020-09-04 18:34:09 +0200288 int rows, cols;
289 int minsize;
290
Bram Moolenaar13568252018-03-16 20:46:58 +0100291#ifdef FEAT_GUI
292 if (term->tl_system)
293 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100294 // Use the whole screen for the system command. However, it will start
295 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100296 term->tl_rows = Rows;
297 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200298 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100299 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100300#endif
Bram Moolenaarb936b792020-09-04 18:34:09 +0200301 term->tl_rows = curwin->w_height;
302 term->tl_cols = curwin->w_width;
303
304 minsize = parse_termwinsize(curwin, &rows, &cols);
305 if (minsize)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200306 {
Bram Moolenaarb936b792020-09-04 18:34:09 +0200307 if (term->tl_rows < rows)
308 term->tl_rows = rows;
309 if (term->tl_cols < cols)
310 term->tl_cols = cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200312 if ((opt->jo_set2 & JO2_TERM_ROWS))
313 term->tl_rows = opt->jo_term_rows;
314 else if (rows != 0)
315 term->tl_rows = rows;
316 if ((opt->jo_set2 & JO2_TERM_COLS))
317 term->tl_cols = opt->jo_term_cols;
318 else if (cols != 0)
319 term->tl_cols = cols;
320
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200321 if (!opt->jo_hidden)
Bram Moolenaarb936b792020-09-04 18:34:09 +0200322 {
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200323 if (term->tl_rows != curwin->w_height)
324 win_setheight_win(term->tl_rows, curwin);
325 if (term->tl_cols != curwin->w_width)
326 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaarb936b792020-09-04 18:34:09 +0200327
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200328 // Set 'winsize' now to avoid a resize at the next redraw.
329 if (!minsize && *curwin->w_p_tws != NUL)
330 {
331 char_u buf[100];
332
333 vim_snprintf((char *)buf, 100, "%dx%d",
334 term->tl_rows, term->tl_cols);
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100335 set_option_value_give_err((char_u *)"termwinsize",
336 0L, buf, OPT_LOCAL);
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200337 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200338 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200339}
340
341/*
342 * Initialize job options for a terminal job.
343 * Caller may overrule some of them.
344 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100345 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346init_job_options(jobopt_T *opt)
347{
348 clear_job_options(opt);
349
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100350 opt->jo_mode = CH_MODE_RAW;
351 opt->jo_out_mode = CH_MODE_RAW;
352 opt->jo_err_mode = CH_MODE_RAW;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200353 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
354}
355
356/*
357 * Set job options mandatory for a terminal job.
358 */
359 static void
360setup_job_options(jobopt_T *opt, int rows, int cols)
361{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100362#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100363 // Win32: Redirecting the job output won't work, thus always connect stdout
364 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200365 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200366#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200367 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100368 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200369 opt->jo_io[PART_OUT] = JIO_BUFFER;
370 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
371 opt->jo_modifiable[PART_OUT] = 0;
372 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
373 }
374
Bram Moolenaar4f974752019-02-17 17:44:42 +0100375#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100376 // Win32: Redirecting the job output won't work, thus always connect stderr
377 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200378 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200379#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200380 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100381 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200382 opt->jo_io[PART_ERR] = JIO_BUFFER;
383 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
384 opt->jo_modifiable[PART_ERR] = 0;
385 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
386 }
387
388 opt->jo_pty = TRUE;
389 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
390 opt->jo_term_rows = rows;
391 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
392 opt->jo_term_cols = cols;
393}
394
395/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200396 * Flush messages on channels.
397 */
398 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +0000399term_flush_messages(void)
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200400{
401 mch_check_messages();
402 parse_queued_messages();
403}
404
405/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100406 * Close a terminal buffer (and its window). Used when creating the terminal
407 * fails.
408 */
409 static void
410term_close_buffer(buf_T *buf, buf_T *old_curbuf)
411{
412 free_terminal(buf);
413 if (old_curbuf != NULL)
414 {
415 --curbuf->b_nwindows;
416 curbuf = old_curbuf;
417 curwin->w_buffer = curbuf;
418 ++curbuf->b_nwindows;
419 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100420 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100421
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100422 // Wiping out the buffer will also close the window and call
423 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100424 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
425}
426
427/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100429 * Use either "argvar" or "argv", the other must be NULL.
430 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
431 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200432 * Returns NULL when failed.
433 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100434 buf_T *
435term_start(
436 typval_T *argvar,
437 char **argv,
438 jobopt_T *opt,
439 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200440{
441 exarg_T split_ea;
442 win_T *old_curwin = curwin;
443 term_T *term;
444 buf_T *old_curbuf = NULL;
445 int res;
446 buf_T *newbuf;
Bram Moolenaare1004402020-10-24 20:49:43 +0200447 int vertical = opt->jo_vertical || (cmdmod.cmod_split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200448 jobopt_T orig_opt; // only partly filled
Christian Brabandt991657e2024-10-15 20:31:14 +0200449 pos_T save_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200450
451 if (check_restricted() || check_secure())
452 return NULL;
Bram Moolenaare5b44862021-05-30 13:54:03 +0200453 if (cmdwin_type != 0)
454 {
455 emsg(_(e_cannot_open_terminal_from_command_line_window));
456 return NULL;
457 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200458
459 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
460 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
461 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100462 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
463 || (argvar != NULL
464 && argvar->v_type == VAR_LIST
465 && argvar->vval.v_list != NULL
466 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200467 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000468 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200469 return NULL;
470 }
471
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200472 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200473 if (term == NULL)
474 return NULL;
475 term->tl_dirty_row_end = MAX_ROW;
476 term->tl_cursor_visible = TRUE;
477 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
478 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100479#ifdef FEAT_GUI
480 term->tl_system = (flags & TERM_START_SYSTEM);
481#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200482 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100483 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200484 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200485
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200486 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200487 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200488 if (opt->jo_curwin)
489 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100490 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100491 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200492 {
493 no_write_message();
494 vim_free(term);
495 return NULL;
496 }
497 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200498 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
499 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
500 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200501 {
502 vim_free(term);
503 return NULL;
504 }
505 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100506 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200507 {
508 buf_T *buf;
509
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100510 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100511 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200512 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
513 BLN_NEW | BLN_LISTED);
514 if (buf == NULL || ml_open(buf) == FAIL)
515 {
516 vim_free(term);
517 return NULL;
518 }
519 old_curbuf = curbuf;
520 --curbuf->b_nwindows;
521 curbuf = buf;
Christian Brabandt991657e2024-10-15 20:31:14 +0200522 save_cursor = curwin->w_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200523 curwin->w_buffer = buf;
524 ++curbuf->b_nwindows;
525 }
526 else
527 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100528 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200529 split_ea.cmdidx = CMD_new;
530 split_ea.cmd = (char_u *)"new";
531 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100532 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200533 {
534 split_ea.line2 = opt->jo_term_rows;
535 split_ea.addr_count = 1;
536 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100537 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200538 {
539 split_ea.line2 = opt->jo_term_cols;
540 split_ea.addr_count = 1;
541 }
542
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200543 int cmod_split_modified = FALSE;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100544 if (vertical)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200545 {
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200546 if (!(cmdmod.cmod_split & WSP_VERT))
547 cmod_split_modified = TRUE;
Bram Moolenaare1004402020-10-24 20:49:43 +0200548 cmdmod.cmod_split |= WSP_VERT;
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200549 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200550 ex_splitview(&split_ea);
Yegappan Lakshmanan4877cb42024-06-11 19:18:12 +0200551 if (cmod_split_modified)
Yegappan Lakshmanand603e952024-06-10 18:16:34 +0200552 cmdmod.cmod_split &= ~WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200553 if (curwin == old_curwin)
554 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100555 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200556 vim_free(term);
557 return NULL;
558 }
559 }
560 term->tl_buffer = curbuf;
561 curbuf->b_term = term;
562
563 if (!opt->jo_hidden)
564 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100565 // Only one size was taken care of with :new, do the other one. With
566 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100567 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100569 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200570 win_setwidth(opt->jo_term_cols);
571 }
572
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100573 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200574 term->tl_next = first_term;
575 first_term = term;
576
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100577 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
578
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200579 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100580 {
581 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200582 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100583 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100584 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100585 {
586 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100587 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100588 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200589 else
590 {
591 int i;
592 size_t len;
593 char_u *cmd, *p;
594
595 if (argvar->v_type == VAR_STRING)
596 {
597 cmd = argvar->vval.v_string;
598 if (cmd == NULL)
599 cmd = (char_u *)"";
600 else if (STRCMP(cmd, "NONE") == 0)
601 cmd = (char_u *)"pty";
602 }
603 else if (argvar->v_type != VAR_LIST
604 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100605 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100606 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200607 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
608 cmd = (char_u*)"";
609
610 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200611 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200612
613 for (i = 0; p != NULL; ++i)
614 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100615 // Prepend a ! to the command name to avoid the buffer name equals
616 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200617 if (i == 0)
618 vim_snprintf((char *)p, len, "!%s", cmd);
619 else
620 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
621 if (buflist_findname(p) == NULL)
622 {
623 vim_free(curbuf->b_ffname);
624 curbuf->b_ffname = p;
625 break;
626 }
627 }
628 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100629 vim_free(curbuf->b_sfname);
630 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200631 curbuf->b_fname = curbuf->b_ffname;
632
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100633 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
634
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200635 if (opt->jo_term_opencmd != NULL)
636 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
637
638 if (opt->jo_eof_chars != NULL)
639 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
640
641 set_string_option_direct((char_u *)"buftype", -1,
642 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200643 // Avoid that 'buftype' is reset when this buffer is entered.
644 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200645
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100646 // Mark the buffer as not modifiable. It can only be made modifiable after
647 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200648 curbuf->b_p_ma = FALSE;
649
Bram Moolenaarb936b792020-09-04 18:34:09 +0200650 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100651#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200652 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
653#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200654 setup_job_options(opt, term->tl_rows, term->tl_cols);
655
Bram Moolenaar13568252018-03-16 20:46:58 +0100656 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100657 return curbuf;
658
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100659#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100660 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100661 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100662 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100663 else if (argvar->v_type == VAR_STRING)
664 {
665 char_u *cmd = argvar->vval.v_string;
666
667 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
668 term->tl_command = vim_strsave(cmd);
669 }
670 else if (argvar->v_type == VAR_LIST
671 && argvar->vval.v_list != NULL
672 && argvar->vval.v_list->lv_len > 0)
673 {
674 garray_T ga;
675 listitem_T *item;
676
677 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200678 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100679 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100680 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100681 char_u *p;
682
683 if (s == NULL)
684 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100685 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100686 if (p == NULL)
687 break;
688 ga_concat(&ga, p);
689 vim_free(p);
690 ga_append(&ga, ' ');
691 }
692 if (item == NULL)
693 {
694 ga_append(&ga, NUL);
695 term->tl_command = ga.ga_data;
696 }
697 else
698 ga_clear(&ga);
699 }
700#endif
701
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100702 if (opt->jo_term_kill != NULL)
703 {
704 char_u *p = skiptowhite(opt->jo_term_kill);
705
706 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
707 }
708
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200709 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100710 {
711 char_u *p = skiptowhite(opt->jo_term_api);
712
713 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
714 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200715 else
716 term->tl_api = vim_strsave((char_u *)"Tapi_");
717
Bram Moolenaar83d47902020-03-26 20:34:00 +0100718 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
719 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
720
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100721#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100722 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
723 if (opt->jo_set2 & JO2_ANSI_COLORS)
724 {
725 term->tl_palette = ALLOC_MULT(long_u, 16);
726 if (term->tl_palette == NULL)
727 {
728 vim_free(term);
729 return NULL;
730 }
731 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
732 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100733#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100734
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100735 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100736 if (argv == NULL
737 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200738 && argvar->vval.v_string != NULL
739 && STRCMP(argvar->vval.v_string, "NONE") == 0)
740 res = create_pty_only(term, opt);
741 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200742 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200743
744 newbuf = curbuf;
745 if (res == OK)
746 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100747 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200748 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
749 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100750#ifdef FEAT_GUI
751 if (term->tl_system)
752 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100753 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100754 term->tl_toprow = msg_row + 1;
755 term->tl_dirty_row_end = 0;
756 }
757#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200758
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100759 // Make sure we don't get stuck on sending keys to the job, it leads to
760 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200761 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
762
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200763 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200764 {
765 --curbuf->b_nwindows;
766 curbuf = old_curbuf;
767 curwin->w_buffer = curbuf;
Christian Brabandt991657e2024-10-15 20:31:14 +0200768 curwin->w_cursor = save_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200769 ++curbuf->b_nwindows;
770 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000771 else if (vgetc_busy
772#ifdef FEAT_TIMERS
773 || timer_busy
774#endif
775 || input_busy)
776 {
777 char_u ignore[4];
778
779 // When waiting for input need to return and possibly end up in
780 // terminal_loop() instead.
781 ignore[0] = K_SPECIAL;
782 ignore[1] = KS_EXTRA;
783 ignore[2] = KE_IGNORE;
784 ignore[3] = NUL;
785 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
786 typebuf_was_filled = TRUE;
787 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788 }
789 else
790 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100791 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200792 return NULL;
793 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100794
Bram Moolenaar13568252018-03-16 20:46:58 +0100795 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200796 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
797 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200798 return newbuf;
799}
800
801/*
802 * ":terminal": open a terminal window and execute a job in it.
803 */
804 void
805ex_terminal(exarg_T *eap)
806{
807 typval_T argvar[2];
808 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100809 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200810 char_u *cmd;
811 char_u *tofree = NULL;
812
813 init_job_options(&opt);
814
815 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100816 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200817 {
818 char_u *p, *ep;
819
820 cmd += 2;
821 p = skiptowhite(cmd);
822 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200823 if (ep != NULL)
824 {
825 if (ep < p)
826 p = ep;
827 else
828 ep = NULL;
829 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200830
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200831 // Note: Keep this in sync with get_terminalopt_name.
832
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200833# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
834 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
835 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200836 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200837 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100838 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200839 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200840 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200841 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200842 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200843 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200844 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200845 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100846 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100847 else if (OPTARG_HAS("shell"))
848 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200849 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100850 {
851 opt.jo_set2 |= JO2_TERM_KILL;
852 opt.jo_term_kill = ep + 1;
853 p = skiptowhite(cmd);
854 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200855 else if (OPTARG_HAS("api"))
856 {
857 opt.jo_set2 |= JO2_TERM_API;
858 if (ep != NULL)
859 {
860 opt.jo_term_api = ep + 1;
861 p = skiptowhite(cmd);
862 }
863 else
864 opt.jo_term_api = NULL;
865 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100866 else if (OPTARG_HAS("rows") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200867 {
868 opt.jo_set2 |= JO2_TERM_ROWS;
869 opt.jo_term_rows = atoi((char *)ep + 1);
870 p = skiptowhite(cmd);
871 }
Keith Thompson184f71c2024-01-04 21:19:04 +0100872 else if (OPTARG_HAS("cols") && ep != NULL && SAFE_isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200873 {
874 opt.jo_set2 |= JO2_TERM_COLS;
875 opt.jo_term_cols = atoi((char *)ep + 1);
876 p = skiptowhite(cmd);
877 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200878 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200879 {
880 char_u *buf = NULL;
881 char_u *keys;
882
Bram Moolenaar21109272020-01-30 16:27:20 +0100883 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200884 p = skiptowhite(cmd);
885 *p = NUL;
zeertzjq7e0bae02023-08-11 23:15:38 +0200886 keys = replace_termcodes(ep + 1, &buf, 0,
Bram Moolenaar459fd782019-10-13 16:43:39 +0200887 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200888 opt.jo_set2 |= JO2_EOF_CHARS;
889 opt.jo_eof_chars = vim_strsave(keys);
890 vim_free(buf);
891 *p = ' ';
892 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100893#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100894 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
895 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100896 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100897 int tty_type = NUL;
898
899 p = skiptowhite(cmd);
900 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
901 tty_type = 'w';
902 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
903 tty_type = 'c';
904 else
905 {
Bram Moolenaar50809a42023-05-20 16:39:07 +0100906 semsg(_(e_invalid_value_for_argument_str), "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100907 goto theend;
908 }
909 opt.jo_set2 |= JO2_TTY_TYPE;
910 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100911 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100912#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200913 else
914 {
915 if (*p)
916 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000917 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100918 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200919 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200920# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200921 cmd = skipwhite(p);
922 }
923 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100924 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100925 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200926 tofree = cmd = vim_strsave(p_sh);
927
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100928 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100929 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200930 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100931 }
932
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200933 if (eap->addr_count > 0)
934 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100935 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200936 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
937 opt.jo_io[PART_IN] = JIO_BUFFER;
938 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
939 opt.jo_in_top = eap->line1;
940 opt.jo_in_bot = eap->line2;
941 }
942
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100943 if (opt_shell && tofree == NULL)
944 {
945#ifdef UNIX
946 char **argv = NULL;
947 char_u *tofree1 = NULL;
948 char_u *tofree2 = NULL;
949
950 // :term ++shell command
951 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
952 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100953 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100954 vim_free(tofree1);
955 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100956 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100957#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100958# ifdef MSWIN
959 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
960 char_u *newcmd;
961
962 newcmd = alloc(cmdlen);
963 if (newcmd == NULL)
964 goto theend;
965 tofree = newcmd;
966 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
967 cmd = newcmd;
968# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000969 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100970 goto theend;
971# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100972#endif
973 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100974 argvar[0].v_type = VAR_STRING;
975 argvar[0].vval.v_string = cmd;
976 argvar[1].v_type = VAR_UNKNOWN;
977 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100978
979theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100980 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200981 vim_free(opt.jo_eof_chars);
982}
983
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200984 static char_u *
985get_terminalopt_name(expand_T *xp UNUSED, int idx)
986{
987 // Note: Keep this in sync with ex_terminal.
988 static char *(p_termopt_values[]) =
989 {
990 "close",
991 "noclose",
992 "open",
993 "curwin",
994 "hidden",
995 "norestore",
996 "shell",
997 "kill=",
998 "rows=",
999 "cols=",
1000 "eof=",
1001 "type=",
1002 "api=",
1003 };
1004
1005 if (idx < (int)ARRAY_LENGTH(p_termopt_values))
1006 return (char_u*)p_termopt_values[idx];
1007 return NULL;
1008}
1009
1010 static char_u *
1011get_termkill_name(expand_T *xp UNUSED, int idx)
1012{
1013 // These are platform-specific values used for job_stop(). They are defined
1014 // in each platform's mch_signal_job(). Just use a unified auto-complete
1015 // list for simplicity.
1016 static char *(p_termkill_values[]) =
1017 {
1018 "term",
1019 "hup",
1020 "quit",
1021 "int",
1022 "kill",
1023 "winch",
1024 };
1025
1026 if (idx < (int)ARRAY_LENGTH(p_termkill_values))
1027 return (char_u*)p_termkill_values[idx];
1028 return NULL;
1029}
1030
1031/*
1032 * Command-line expansion for :terminal [options]
1033 */
1034 int
1035expand_terminal_opt(
1036 char_u *pat,
1037 expand_T *xp,
1038 regmatch_T *rmp,
1039 char_u ***matches,
1040 int *numMatches)
1041{
1042 if (xp->xp_pattern > xp->xp_line && *(xp->xp_pattern-1) == '=')
1043 {
1044 char_u *(*cb)(expand_T *, int) = NULL;
1045
1046 char_u *name_end = xp->xp_pattern - 1;
1047 if (name_end - xp->xp_line >= 4
1048 && STRNCMP(name_end - 4, "kill", 4) == 0)
1049 cb = get_termkill_name;
1050
1051 if (cb != NULL)
1052 {
1053 return ExpandGeneric(
1054 pat,
1055 xp,
1056 rmp,
1057 matches,
1058 numMatches,
1059 cb,
1060 FALSE);
1061 }
1062 return FAIL;
1063 }
1064 return ExpandGeneric(
1065 pat,
1066 xp,
1067 rmp,
1068 matches,
1069 numMatches,
1070 get_terminalopt_name,
1071 FALSE);
1072}
1073
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001074#if defined(FEAT_SESSION) || defined(PROTO)
1075/*
1076 * Write a :terminal command to the session file to restore the terminal in
1077 * window "wp".
1078 * Return FAIL if writing fails.
1079 */
1080 int
Bram Moolenaar0e655112020-09-11 20:36:36 +02001081term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001082{
Bram Moolenaar0e655112020-09-11 20:36:36 +02001083 const int bufnr = wp->w_buffer->b_fnum;
1084 term_T *term = wp->w_buffer->b_term;
1085
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001086 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001087 {
1088 // There are multiple views into this terminal buffer. We don't want to
1089 // create the terminal multiple times. If it's the first time, create,
1090 // otherwise link to the first buffer.
1091 char id_as_str[NUMBUFLEN];
1092 hashitem_T *entry;
1093
1094 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
1095
1096 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
1097 if (!HASHITEM_EMPTY(entry))
1098 {
1099 // we've already opened this terminal buffer
1100 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
1101 return FAIL;
1102 return put_eol(fd);
1103 }
1104 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001105
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001106 // Create the terminal and run the command. This is not without
1107 // risk, but let's assume the user only creates a session when this
1108 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001109 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1110 term->tl_cols, term->tl_rows) < 0)
1111 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001112#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001113 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1114 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001115#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001116 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1117 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001118 if (put_eol(fd) != OK)
1119 return FAIL;
1120
1121 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1122 return FAIL;
1123
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001124 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001125 {
1126 char *hash_key = alloc(NUMBUFLEN);
1127
1128 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00001129 hash_add(terminal_bufs, (char_u *)hash_key, "terminal session");
Bram Moolenaar0e655112020-09-11 20:36:36 +02001130 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001131
1132 return put_eol(fd);
1133}
1134
1135/*
1136 * Return TRUE if "buf" has a terminal that should be restored.
1137 */
1138 int
1139term_should_restore(buf_T *buf)
1140{
1141 term_T *term = buf->b_term;
1142
1143 return term != NULL && (term->tl_command == NULL
1144 || STRCMP(term->tl_command, "NONE") != 0);
1145}
1146#endif
1147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001148/*
1149 * Free the scrollback buffer for "term".
1150 */
1151 static void
1152free_scrollback(term_T *term)
1153{
1154 int i;
1155
1156 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1157 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1158 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001159 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1160 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1161 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001162}
1163
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001164
1165// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001166static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001167
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001168/*
1169 * Free a terminal and everything it refers to.
1170 * Kills the job if there is one.
1171 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001172 * The actual terminal structure is freed later in free_unused_terminals(),
1173 * because callbacks may wipe out a buffer while the terminal is still
1174 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001175 */
1176 void
1177free_terminal(buf_T *buf)
1178{
1179 term_T *term = buf->b_term;
1180 term_T *tp;
1181
1182 if (term == NULL)
1183 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001184
1185 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001186 if (first_term == term)
1187 first_term = term->tl_next;
1188 else
1189 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1190 if (tp->tl_next == term)
1191 {
1192 tp->tl_next = term->tl_next;
1193 break;
1194 }
1195
1196 if (term->tl_job != NULL)
1197 {
1198 if (term->tl_job->jv_status != JOB_ENDED
1199 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001200 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001201 job_stop(term->tl_job, NULL, "kill");
1202 job_unref(term->tl_job);
1203 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001204 term->tl_next = terminals_to_free;
1205 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001206
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001207 buf->b_term = NULL;
1208 if (in_terminal_loop == term)
1209 in_terminal_loop = NULL;
1210}
1211
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001212 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00001213free_unused_terminals(void)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001214{
1215 while (terminals_to_free != NULL)
1216 {
1217 term_T *term = terminals_to_free;
1218
1219 terminals_to_free = term->tl_next;
1220
1221 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001222 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001223
1224 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001225 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001226 vim_free(term->tl_title);
1227#ifdef FEAT_SESSION
1228 vim_free(term->tl_command);
1229#endif
1230 vim_free(term->tl_kill);
1231 vim_free(term->tl_status_text);
1232 vim_free(term->tl_opencmd);
1233 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001234 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001235#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001236 if (term->tl_out_fd != NULL)
1237 fclose(term->tl_out_fd);
1238#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001239 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001240 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001241 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001242 vim_free(term);
1243 }
1244}
1245
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001246/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001247 * Get the part that is connected to the tty. Normally this is PART_IN, but
1248 * when writing buffer lines to the job it can be another. This makes it
1249 * possible to do "1,5term vim -".
1250 */
1251 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001252get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001253{
1254#ifdef UNIX
1255 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1256 int i;
1257
1258 for (i = 0; i < 3; ++i)
1259 {
1260 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1261
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001262 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001263 return parts[i];
1264 }
1265#endif
1266 return PART_IN;
1267}
1268
1269/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001270 * Read any vterm output and send it on the channel.
1271 */
1272 static void
1273term_forward_output(term_T *term)
1274{
1275 VTerm *vterm = term->tl_vterm;
1276 char buf[KEY_BUF_LEN];
1277 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1278
1279 if (curlen > 0)
1280 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1281 (char_u *)buf, (int)curlen, NULL);
1282}
1283
1284/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001285 * Write job output "msg[len]" to the vterm.
1286 */
1287 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001288term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001289{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001290 char_u *msg = msg_arg;
1291 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001292 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001293 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001294 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1295
1296 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1297 // the end.
1298 if (len > limit)
1299 {
1300 char_u *p = msg + len - limit;
1301
1302 p -= (*mb_head_off)(msg, p);
1303 len -= p - msg;
1304 msg = p;
1305 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001306
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001307 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001308
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001309 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001310 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001311 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001312
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001313 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001314 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1315}
1316
1317 static void
Bram Moolenaar58806c12023-04-29 14:26:02 +01001318position_cursor(win_T *wp, VTermPos *pos)
1319{
1320 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1321 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1322#ifdef FEAT_PROP_POPUP
1323 if (popup_is_popup(wp))
1324 {
1325 wp->w_wrow += popup_top_extra(wp);
1326 wp->w_wcol += popup_left_extra(wp);
1327 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
1328 }
1329 else
1330 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
1331#endif
1332 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1333}
1334
1335 static void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001336update_cursor(term_T *term, int redraw)
1337{
1338 if (term->tl_normal_mode)
1339 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001340#ifdef FEAT_GUI
1341 if (term->tl_system)
1342 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1343 term->tl_cursor_pos.col);
1344 else
1345#endif
Bram Moolenaar58806c12023-04-29 14:26:02 +01001346 if (!term_job_running(term))
1347 // avoid the cursor positioned below the last used line
Bram Moolenaar13568252018-03-16 20:46:58 +01001348 setcursor();
Bram Moolenaar58806c12023-04-29 14:26:02 +01001349 else
1350 {
1351 // do not use the window cursor position
1352 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1353 windgoto(W_WINROW(curwin) + curwin->w_wrow,
1354 curwin->w_wincol + curwin->w_wcol);
1355 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001356 if (redraw)
1357 {
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001358 aco_save_T aco;
1359
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001360 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1361 cursor_on();
1362 out_flush();
1363#ifdef FEAT_GUI
1364 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001365 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001366 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001367 gui_mch_flush();
1368 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001369#endif
Bram Moolenaar24fe33a2022-11-24 00:09:02 +00001370 // Make sure an invoked autocmd doesn't delete the buffer (and the
1371 // terminal) under our fingers.
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001372 ++term->tl_buffer->b_locked;
1373
1374 // save and restore curwin and curbuf, in case the autocmd changes them
1375 aucmd_prepbuf(&aco, curbuf);
1376 apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, FALSE, term->tl_buffer);
1377 aucmd_restbuf(&aco);
1378
1379 --term->tl_buffer->b_locked;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001380 }
1381}
1382
1383/*
1384 * Invoked when "msg" output from a job was received. Write it to the terminal
1385 * of "buffer".
1386 */
1387 void
1388write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1389{
1390 size_t len = STRLEN(msg);
1391 term_T *term = buffer->b_term;
1392
Bram Moolenaar4f974752019-02-17 17:44:42 +01001393#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001394 // Win32: Cannot redirect output of the job, intercept it here and write to
1395 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001396 if (term->tl_out_fd != NULL)
1397 {
1398 ch_log(channel, "Writing %d bytes to output file", (int)len);
1399 fwrite(msg, len, 1, term->tl_out_fd);
1400 return;
1401 }
1402#endif
1403
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001404 if (term->tl_vterm == NULL)
1405 {
1406 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1407 return;
1408 }
1409 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001410 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001411 term_write_job_output(term, msg, len);
1412
Bram Moolenaar13568252018-03-16 20:46:58 +01001413#ifdef FEAT_GUI
1414 if (term->tl_system)
1415 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001416 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001417 update_system_term(term);
1418 update_cursor(term, TRUE);
1419 }
1420 else
1421#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001422 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1423 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001424 if (!term->tl_normal_mode)
1425 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001426 // Don't use update_screen() when editing the command line, it gets
1427 // cleared.
1428 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001429 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001430 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001431 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001432 update_screen(UPD_VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001433 // update_screen() can be slow, check the terminal wasn't closed
1434 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001435 if (buffer == curbuf && curbuf->b_term != NULL)
1436 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001437 }
1438 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001439 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001440 }
1441}
1442
1443/*
1444 * Send a mouse position and click to the vterm
1445 */
1446 static int
1447term_send_mouse(VTerm *vterm, int button, int pressed)
1448{
1449 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001450 int row = mouse_row - W_WINROW(curwin);
1451 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001452
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001453#ifdef FEAT_PROP_POPUP
1454 if (popup_is_popup(curwin))
1455 {
1456 row -= popup_top_extra(curwin);
1457 col -= popup_left_extra(curwin);
1458 }
1459#endif
1460 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001461 if (button != 0)
1462 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001463 return TRUE;
1464}
1465
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001466static int enter_mouse_col = -1;
1467static int enter_mouse_row = -1;
1468
1469/*
1470 * Handle a mouse click, drag or release.
1471 * Return TRUE when a mouse event is sent to the terminal.
1472 */
1473 static int
1474term_mouse_click(VTerm *vterm, int key)
1475{
1476#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001477 // For modeless selection mouse drag and release events are ignored, unless
1478 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001479 static int ignore_drag_release = TRUE;
1480 VTermMouseState mouse_state;
1481
1482 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1483 if (mouse_state.flags == 0)
1484 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001485 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001486 switch (key)
1487 {
1488 case K_LEFTDRAG:
1489 case K_LEFTRELEASE:
1490 case K_RIGHTDRAG:
1491 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001492 // Ignore drag and release events when the button-down wasn't
1493 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001494 if (ignore_drag_release)
1495 {
1496 int save_mouse_col, save_mouse_row;
1497
1498 if (enter_mouse_col < 0)
1499 break;
1500
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001501 // mouse click in the window gave us focus, handle that
1502 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001503 save_mouse_col = mouse_col;
1504 save_mouse_row = mouse_row;
1505 mouse_col = enter_mouse_col;
1506 mouse_row = enter_mouse_row;
1507 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1508 mouse_col = save_mouse_col;
1509 mouse_row = save_mouse_row;
1510 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001511 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001512 case K_LEFTMOUSE:
1513 case K_RIGHTMOUSE:
1514 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1515 ignore_drag_release = TRUE;
1516 else
1517 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001518 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001519 if (clip_star.available)
1520 {
1521 int button, is_click, is_drag;
1522
1523 button = get_mouse_button(KEY2TERMCAP1(key),
1524 &is_click, &is_drag);
1525 if (mouse_model_popup() && button == MOUSE_LEFT
1526 && (mod_mask & MOD_MASK_SHIFT))
1527 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001528 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001529 button = MOUSE_RIGHT;
1530 mod_mask &= ~MOD_MASK_SHIFT;
1531 }
1532 clip_modeless(button, is_click, is_drag);
1533 }
1534 break;
1535
1536 case K_MIDDLEMOUSE:
1537 if (clip_star.available)
1538 insert_reg('*', TRUE);
1539 break;
1540 }
1541 enter_mouse_col = -1;
1542 return FALSE;
1543 }
1544#endif
1545 enter_mouse_col = -1;
1546
1547 switch (key)
1548 {
1549 case K_LEFTMOUSE:
1550 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1551 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1552 case K_LEFTRELEASE:
1553 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1554 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1555 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1556 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1557 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1558 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1559 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1560 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1561 }
1562 return TRUE;
1563}
1564
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001565/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001566 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1567 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001568 * Return the number of bytes in "buf".
1569 */
1570 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001571term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001572{
1573 VTerm *vterm = term->tl_vterm;
1574 VTermKey key = VTERM_KEY_NONE;
1575 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001576 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001577
1578 switch (c)
1579 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001580 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001581
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001582 // don't use VTERM_KEY_BACKSPACE, it always
1583 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001584 case K_BS: c = term_backspace_char; break;
1585
1586 case ESC: key = VTERM_KEY_ESCAPE; break;
1587 case K_DEL: key = VTERM_KEY_DEL; break;
1588 case K_DOWN: key = VTERM_KEY_DOWN; break;
1589 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1590 key = VTERM_KEY_DOWN; break;
1591 case K_END: key = VTERM_KEY_END; break;
1592 case K_S_END: mod = VTERM_MOD_SHIFT;
1593 key = VTERM_KEY_END; break;
1594 case K_C_END: mod = VTERM_MOD_CTRL;
1595 key = VTERM_KEY_END; break;
1596 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1597 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1598 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1599 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1600 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1601 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1602 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1603 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1604 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1605 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1606 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1607 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1608 case K_HOME: key = VTERM_KEY_HOME; break;
1609 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1610 key = VTERM_KEY_HOME; break;
1611 case K_C_HOME: mod = VTERM_MOD_CTRL;
1612 key = VTERM_KEY_HOME; break;
1613 case K_INS: key = VTERM_KEY_INS; break;
1614 case K_K0: key = VTERM_KEY_KP_0; break;
1615 case K_K1: key = VTERM_KEY_KP_1; break;
1616 case K_K2: key = VTERM_KEY_KP_2; break;
1617 case K_K3: key = VTERM_KEY_KP_3; break;
1618 case K_K4: key = VTERM_KEY_KP_4; break;
1619 case K_K5: key = VTERM_KEY_KP_5; break;
1620 case K_K6: key = VTERM_KEY_KP_6; break;
1621 case K_K7: key = VTERM_KEY_KP_7; break;
1622 case K_K8: key = VTERM_KEY_KP_8; break;
1623 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001624 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001625 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001626 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001628 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1629 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001630 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1631 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001632 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1633 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001634 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1635 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1636 case K_LEFT: key = VTERM_KEY_LEFT; break;
1637 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1638 key = VTERM_KEY_LEFT; break;
1639 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1640 key = VTERM_KEY_LEFT; break;
1641 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1642 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1643 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1644 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1645 key = VTERM_KEY_RIGHT; break;
1646 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1647 key = VTERM_KEY_RIGHT; break;
1648 case K_UP: key = VTERM_KEY_UP; break;
1649 case K_S_UP: mod = VTERM_MOD_SHIFT;
1650 key = VTERM_KEY_UP; break;
1651 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001652 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1653 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001654
Bram Moolenaara42ad572017-11-16 13:08:04 +01001655 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1656 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001657 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1658 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001659
1660 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001661 case K_LEFTMOUSE_NM:
1662 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001663 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001664 case K_LEFTRELEASE_NM:
1665 case K_MOUSEMOVE:
1666 case K_MIDDLEMOUSE:
1667 case K_MIDDLEDRAG:
1668 case K_MIDDLERELEASE:
1669 case K_RIGHTMOUSE:
1670 case K_RIGHTDRAG:
1671 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1672 return 0;
1673 other = TRUE;
1674 break;
1675
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001676 case K_X1MOUSE: /* TODO */ return 0;
1677 case K_X1DRAG: /* TODO */ return 0;
1678 case K_X1RELEASE: /* TODO */ return 0;
1679 case K_X2MOUSE: /* TODO */ return 0;
1680 case K_X2DRAG: /* TODO */ return 0;
1681 case K_X2RELEASE: /* TODO */ return 0;
1682
1683 case K_IGNORE: return 0;
1684 case K_NOP: return 0;
1685 case K_UNDO: return 0;
1686 case K_HELP: return 0;
1687 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1688 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1689 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1690 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1691 case K_SELECT: return 0;
1692#ifdef FEAT_GUI
1693 case K_VER_SCROLLBAR: return 0;
1694 case K_HOR_SCROLLBAR: return 0;
1695#endif
1696#ifdef FEAT_GUI_TABLINE
1697 case K_TABLINE: return 0;
1698 case K_TABMENU: return 0;
1699#endif
1700#ifdef FEAT_NETBEANS_INTG
1701 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1702#endif
1703#ifdef FEAT_DND
1704 case K_DROP: return 0;
1705#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001706 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001707 case K_PS: vterm_keyboard_start_paste(vterm);
1708 other = TRUE;
1709 break;
1710 case K_PE: vterm_keyboard_end_paste(vterm);
1711 other = TRUE;
1712 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001713 }
1714
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001715 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001716 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001717 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001718 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001719 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001720 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001721 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001722
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001723 // Ctrl-Shift-i may have the key "I" instead of "i", but for the kitty
1724 // keyboard protocol should use "i". Applies to all ascii letters.
1725 if (ASCII_ISUPPER(c)
Bram Moolenaarebed1b02022-11-24 14:05:19 +00001726 && vterm_is_kitty_keyboard(vterm)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001727 && mod == (VTERM_MOD_CTRL | VTERM_MOD_SHIFT))
1728 c = TOLOWER_ASC(c);
1729
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001730 /*
1731 * Convert special keys to vterm keys:
1732 * - Write keys to vterm: vterm_keyboard_key()
1733 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 */
1735 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001736 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001737 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001738 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001739 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001740 vterm_keyboard_unichar(vterm, c, mod);
1741
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001742 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001743 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1744}
1745
1746/*
1747 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001748 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001749 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001750 */
1751 static int
1752term_job_running_check(term_T *term, int check_job_status)
1753{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001754 // Also consider the job finished when the channel is closed, to avoid a
1755 // race condition when updating the title.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001756 if (term == NULL
1757 || term->tl_job == NULL
1758 || !channel_is_open(term->tl_job->jv_channel))
1759 return FALSE;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001760
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001761 job_T *job = term->tl_job;
1762
1763 // Careful: Checking the job status may invoke callbacks, which close
1764 // the buffer and terminate "term". However, "job" will not be freed
1765 // yet.
1766 if (check_job_status)
1767 job_status(job);
1768 return (job->jv_status == JOB_STARTED
1769 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001770}
1771
1772/*
1773 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001774 */
1775 int
1776term_job_running(term_T *term)
1777{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001778 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001779}
1780
1781/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001782 * Return TRUE if the job for "term" is still running, ignoring the job was
1783 * "NONE".
1784 */
1785 int
1786term_job_running_not_none(term_T *term)
1787{
1788 return term_job_running(term) && !term_none_open(term);
1789}
1790
1791/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001792 * Return TRUE if "term" has an active channel and used ":term NONE".
1793 */
1794 int
1795term_none_open(term_T *term)
1796{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001797 // Also consider the job finished when the channel is closed, to avoid a
1798 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001799 return term != NULL
1800 && term->tl_job != NULL
1801 && channel_is_open(term->tl_job->jv_channel)
1802 && term->tl_job->jv_channel->ch_keep_open;
1803}
1804
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001805//
1806// Used to confirm whether we would like to kill a terminal.
1807// Return OK when the user confirms to kill it.
1808// Return FAIL if the user selects otherwise.
1809//
1810 int
1811term_confirm_stop(buf_T *buf)
1812{
1813 char_u buff[DIALOG_MSG_SIZE];
1814 int ret;
1815
1816 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1817 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1818 if (ret == VIM_YES)
1819 return OK;
1820 else
1821 return FAIL;
1822}
1823
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001825 * Used when exiting: kill the job in "buf" if so desired.
1826 * Return OK when the job finished.
1827 * Return FAIL when the job is still running.
1828 */
1829 int
1830term_try_stop_job(buf_T *buf)
1831{
1832 int count;
1833 char *how = (char *)buf->b_term->tl_kill;
1834
1835#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001836 if ((how == NULL || *how == NUL)
1837 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001838 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001839 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001840 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001841 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001842 return FAIL;
1843 }
1844#endif
1845 if (how == NULL || *how == NUL)
1846 return FAIL;
1847
1848 job_stop(buf->b_term->tl_job, NULL, how);
1849
Bram Moolenaar9172d232019-01-29 23:06:54 +01001850 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001851 for (count = 0; count < 100; ++count)
1852 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001853 job_T *job;
1854
1855 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001856 if (!buf_valid(buf)
1857 || buf->b_term == NULL
1858 || buf->b_term->tl_job == NULL)
1859 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001860 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001861
Bram Moolenaar9172d232019-01-29 23:06:54 +01001862 // Call job_status() to update jv_status. It may cause the job to be
1863 // cleaned up but it won't be freed.
1864 job_status(job);
1865 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001866 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001867
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001868 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001869 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001870 }
1871 return FAIL;
1872}
1873
1874/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875 * Add the last line of the scrollback buffer to the buffer in the window.
1876 */
1877 static void
1878add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1879{
1880 buf_T *buf = term->tl_buffer;
1881 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1882 linenr_T lnum = buf->b_ml.ml_line_count;
1883
Bram Moolenaar4f974752019-02-17 17:44:42 +01001884#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001885 if (!enc_utf8 && enc_codepage > 0)
1886 {
1887 WCHAR *ret = NULL;
1888 int length = 0;
1889
1890 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1891 &ret, &length);
1892 if (ret != NULL)
1893 {
1894 WideCharToMultiByte_alloc(enc_codepage, 0,
1895 ret, length, (char **)&text, &len, 0, 0);
1896 vim_free(ret);
1897 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1898 vim_free(text);
1899 }
1900 }
1901 else
1902#endif
1903 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1904 if (empty)
1905 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001906 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001907 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001908 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001909 curbuf = curwin->w_buffer;
1910 }
1911}
1912
1913 static void
1914cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1915{
1916 attr->width = cell->width;
1917 attr->attrs = cell->attrs;
1918 attr->fg = cell->fg;
1919 attr->bg = cell->bg;
1920}
1921
1922 static int
1923equal_celattr(cellattr_T *a, cellattr_T *b)
1924{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001925 // We only compare the RGB colors, ignoring the ANSI index and type.
1926 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001927 return a->fg.red == b->fg.red
1928 && a->fg.green == b->fg.green
1929 && a->fg.blue == b->fg.blue
1930 && a->bg.red == b->bg.red
1931 && a->bg.green == b->bg.green
1932 && a->bg.blue == b->bg.blue;
1933}
1934
Bram Moolenaard96ff162018-02-18 22:13:29 +01001935/*
1936 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1937 * line at this position. Otherwise at the end.
1938 */
1939 static int
1940add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1941{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001942 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
1943 return FALSE;
1944
1945 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1946 + term->tl_scrollback.ga_len;
1947
1948 if (lnum > 0)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001949 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001950 int i;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001951
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001952 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001953 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001954 *line = *(line - 1);
1955 --line;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001956 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01001957 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001958 line->sb_cols = 0;
1959 line->sb_cells = NULL;
1960 line->sb_fill_attr = *fill_attr;
1961 ++term->tl_scrollback.ga_len;
1962 return OK;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001963}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001964
1965/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001966 * Remove the terminal contents from the scrollback and the buffer.
1967 * Used before adding a new scrollback line or updating the buffer for lines
1968 * displayed in the terminal.
1969 */
1970 static void
1971cleanup_scrollback(term_T *term)
1972{
1973 sb_line_T *line;
1974 garray_T *gap;
1975
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001976 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001977 gap = &term->tl_scrollback;
1978 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1979 && gap->ga_len > 0)
1980 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001981 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001982 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1983 vim_free(line->sb_cells);
1984 --gap->ga_len;
1985 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001986 curbuf = curwin->w_buffer;
1987 if (curbuf == term->tl_buffer)
1988 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001989}
1990
1991/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001992 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993 */
1994 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001995update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001996{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001997 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001998 int len;
1999 int lines_skipped = 0;
2000 VTermPos pos;
2001 VTermScreenCell cell;
2002 cellattr_T fill_attr, new_fill_attr;
2003 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002004
2005 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
2006 "Adding terminal window snapshot to buffer");
2007
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002008 // First remove the lines that were appended before, they might be
2009 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002010 cleanup_scrollback(term);
2011
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002012 screen = vterm_obtain_screen(term->tl_vterm);
2013 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002014 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
2015 {
2016 len = 0;
2017 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
2018 if (vterm_screen_get_cell(screen, pos, &cell) != 0
2019 && cell.chars[0] != NUL)
2020 {
2021 len = pos.col + 1;
2022 new_fill_attr = term->tl_default_color;
2023 }
2024 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002025 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002026 cell2cellattr(&cell, &new_fill_attr);
2027
2028 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
2029 ++lines_skipped;
2030 else
2031 {
2032 while (lines_skipped > 0)
2033 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002034 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002035 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002036 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002037 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002038 }
2039
2040 if (len == 0)
2041 p = NULL;
2042 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002043 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002044 if ((p != NULL || len == 0)
2045 && ga_grow(&term->tl_scrollback, 1) == OK)
2046 {
2047 garray_T ga;
2048 int width;
2049 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
2050 + term->tl_scrollback.ga_len;
2051
2052 ga_init2(&ga, 1, 100);
2053 for (pos.col = 0; pos.col < len; pos.col += width)
2054 {
2055 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2056 {
2057 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02002058 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002059 if (ga_grow(&ga, 1) == OK)
2060 ga.ga_len += utf_char2bytes(' ',
2061 (char_u *)ga.ga_data + ga.ga_len);
2062 }
2063 else
2064 {
2065 width = cell.width;
2066
2067 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01002068 if (width == 2)
2069 // second cell of double-width character has the
2070 // same attributes.
2071 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002072
Bram Moolenaara79fd562018-12-20 20:47:32 +01002073 // Each character can be up to 6 bytes.
2074 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002075 {
2076 int i;
2077 int c;
2078
2079 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
2080 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2081 (char_u *)ga.ga_data + ga.ga_len);
2082 }
2083 }
2084 }
2085 line->sb_cols = len;
2086 line->sb_cells = p;
2087 line->sb_fill_attr = new_fill_attr;
2088 fill_attr = new_fill_attr;
2089 ++term->tl_scrollback.ga_len;
2090
2091 if (ga_grow(&ga, 1) == FAIL)
2092 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2093 else
2094 {
2095 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2096 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2097 }
2098 ga_clear(&ga);
2099 }
2100 else
2101 vim_free(p);
2102 }
2103 }
2104
Bram Moolenaarf3aea592018-11-11 22:18:21 +01002105 // Add trailing empty lines.
2106 for (pos.row = term->tl_scrollback.ga_len;
2107 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
2108 ++pos.row)
2109 {
2110 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
2111 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2112 }
2113
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002114 term->tl_dirty_snapshot = FALSE;
2115#ifdef FEAT_TIMERS
2116 term->tl_timer_set = FALSE;
2117#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002118}
2119
2120/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002121 * Loop over all windows in the current tab, and also curwin, which is not
2122 * encountered when using a terminal in a popup window.
2123 * Return TRUE if "*wp" was set to the next window.
2124 */
2125 static int
2126for_all_windows_and_curwin(win_T **wp, int *did_curwin)
2127{
2128 if (*wp == NULL)
2129 *wp = firstwin;
2130 else if ((*wp)->w_next != NULL)
2131 *wp = (*wp)->w_next;
2132 else if (!*did_curwin)
2133 *wp = curwin;
2134 else
2135 return FALSE;
2136 if (*wp == curwin)
2137 *did_curwin = TRUE;
2138 return TRUE;
2139}
2140
2141/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002142 * If needed, add the current lines of the terminal to scrollback and to the
2143 * buffer. Called after the job has ended and when switching to
2144 * Terminal-Normal mode.
2145 * When "redraw" is TRUE redraw the windows that show the terminal.
2146 */
2147 static void
2148may_move_terminal_to_buffer(term_T *term, int redraw)
2149{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002150 if (term->tl_vterm == NULL)
2151 return;
2152
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002153 // Update the snapshot only if something changes or the buffer does not
2154 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002155 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2156 <= term->tl_scrollback_scrolled)
2157 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002158
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002159 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002160 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2161 &term->tl_default_color.fg, &term->tl_default_color.bg);
2162
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002163 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002164 {
2165 win_T *wp = NULL;
2166 int did_curwin = FALSE;
2167
2168 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002169 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002170 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002171 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002172 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2173 wp->w_cursor.col = 0;
2174 wp->w_valid = 0;
2175 if (wp->w_cursor.lnum >= wp->w_height)
2176 {
2177 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002178
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002179 if (wp->w_topline < min_topline)
2180 wp->w_topline = min_topline;
2181 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002182 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002183 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002184 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002185 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002186}
2187
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002188#if defined(FEAT_TIMERS) || defined(PROTO)
2189/*
2190 * Check if any terminal timer expired. If so, copy text from the terminal to
2191 * the buffer.
2192 * Return the time until the next timer will expire.
2193 */
2194 int
2195term_check_timers(int next_due_arg, proftime_T *now)
2196{
2197 term_T *term;
2198 int next_due = next_due_arg;
2199
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002200 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002201 {
2202 if (term->tl_timer_set && !term->tl_normal_mode)
2203 {
2204 long this_due = proftime_time_left(&term->tl_timer_due, now);
2205
2206 if (this_due <= 1)
2207 {
2208 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002209 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002210 }
2211 else if (next_due == -1 || next_due > this_due)
2212 next_due = this_due;
2213 }
2214 }
2215
2216 return next_due;
2217}
2218#endif
2219
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002220/*
2221 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2222 * otherwise end it.
2223 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002224 static void
2225set_terminal_mode(term_T *term, int normal_mode)
2226{
2227 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002228 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002229 if (!normal_mode)
2230 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002231 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002232 if (term->tl_buffer == curbuf)
2233 maketitle();
2234}
2235
2236/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002237 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002238 * Move the vterm contents into the scrollback buffer and free the vterm.
2239 */
2240 static void
2241cleanup_vterm(term_T *term)
2242{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002243 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002244 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002245 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002246 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002247}
2248
2249/*
2250 * Switch from Terminal-Job mode to Terminal-Normal mode.
2251 * Suspends updating the terminal window.
2252 */
2253 static void
2254term_enter_normal_mode(void)
2255{
2256 term_T *term = curbuf->b_term;
2257
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002258 set_terminal_mode(term, TRUE);
2259
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002260 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002261 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002263 // Move the window cursor to the position of the cursor in the
2264 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002265 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2266 + term->tl_cursor_pos.row + 1;
2267 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002268 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2269 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002270 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002271
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002272 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002273 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2274}
2275
2276/*
2277 * Returns TRUE if the current window contains a terminal and we are in
2278 * Terminal-Normal mode.
2279 */
2280 int
2281term_in_normal_mode(void)
2282{
2283 term_T *term = curbuf->b_term;
2284
2285 return term != NULL && term->tl_normal_mode;
2286}
2287
2288/*
2289 * Switch from Terminal-Normal mode to Terminal-Job mode.
2290 * Restores updating the terminal window.
2291 */
2292 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002293term_enter_job_mode(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002294{
2295 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002296
2297 set_terminal_mode(term, FALSE);
2298
2299 if (term->tl_channel_closed)
2300 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002301 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002302#ifdef FEAT_PROP_POPUP
2303 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002304 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002305#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002306}
2307
2308/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002309 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2310 * modifiers into a basic key. However, we may only find out after calling
2311 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2312 * "no_reduce_keys" before using it.
2313 */
2314typedef enum {
2315 NRKS_NONE, // initial value
2316 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2317 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2318 // check_no_reduce_keys(), must be decremented.
2319} reduce_key_state_T;
2320
2321static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2322
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002323/*
2324 * Return TRUE if the term is using modifyOtherKeys level 2 or the kitty
2325 * keyboard protocol.
2326 */
2327 static int
2328vterm_using_key_protocol(void)
2329{
2330 return curbuf->b_term != NULL
2331 && curbuf->b_term->tl_vterm != NULL
2332 && (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm)
2333 || vterm_is_kitty_keyboard(curbuf->b_term->tl_vterm));
2334}
2335
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002336 void
2337check_no_reduce_keys(void)
2338{
2339 if (no_reduce_key_state != NRKS_CHECK
2340 || no_reduce_keys >= 1
2341 || curbuf->b_term == NULL
2342 || curbuf->b_term->tl_vterm == NULL)
2343 return;
2344
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002345 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002346 {
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002347 // "modify_other_keys" or kitty keyboard protocol was enabled while
2348 // waiting.
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002349 no_reduce_key_state = NRKS_SET;
2350 ++no_reduce_keys;
2351 }
2352}
2353
2354/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002355 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002356 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002357 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358 */
2359 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002360term_vgetc(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002361{
2362 int c;
2363 int save_State = State;
2364
Bram Moolenaar24959102022-05-07 20:01:16 +01002365 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002366 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002367#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002368 ctrl_break_was_pressed = FALSE;
2369#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002370
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002371 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002372 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002373 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002374 no_reduce_key_state = NRKS_SET;
2375 }
2376 else
2377 {
2378 no_reduce_key_state = NRKS_CHECK;
2379 }
2380
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002381 c = vgetc();
2382 got_int = FALSE;
2383 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002384
2385 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002386 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002387 no_reduce_key_state = NRKS_NONE;
2388
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002389 return c;
2390}
2391
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002392static int mouse_was_outside = FALSE;
2393
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002394/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002395 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002396 * Return FAIL when the key needs to be handled in Normal mode.
2397 * Return OK when the key was dropped or sent to the terminal.
2398 */
2399 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002400send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002401{
2402 char msg[KEY_BUF_LEN];
2403 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002404 int dragging_outside = FALSE;
2405
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002406 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002407 switch (c)
2408 {
2409 case NUL:
2410 case K_ZERO:
2411 if (typed)
2412 stuffcharReadbuff(c);
2413 return FAIL;
2414
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002415 case K_TABLINE:
2416 stuffcharReadbuff(c);
2417 return FAIL;
2418
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002419 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002420 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002421 return FAIL;
2422
2423 case K_LEFTDRAG:
2424 case K_MIDDLEDRAG:
2425 case K_RIGHTDRAG:
2426 case K_X1DRAG:
2427 case K_X2DRAG:
2428 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002429 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002430 case K_LEFTMOUSE:
2431 case K_LEFTMOUSE_NM:
2432 case K_LEFTRELEASE:
2433 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002434 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002435 case K_MIDDLEMOUSE:
2436 case K_MIDDLERELEASE:
2437 case K_RIGHTMOUSE:
2438 case K_RIGHTRELEASE:
2439 case K_X1MOUSE:
2440 case K_X1RELEASE:
2441 case K_X2MOUSE:
2442 case K_X2RELEASE:
2443
2444 case K_MOUSEUP:
2445 case K_MOUSEDOWN:
2446 case K_MOUSELEFT:
2447 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002448 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002449 int row = mouse_row;
2450 int col = mouse_col;
2451
2452#ifdef FEAT_PROP_POPUP
2453 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002454 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002455 row -= popup_top_extra(curwin);
2456 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002457 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002458#endif
2459 if (row < W_WINROW(curwin)
2460 || row >= (W_WINROW(curwin) + curwin->w_height)
2461 || col < curwin->w_wincol
2462 || col >= W_ENDCOL(curwin)
2463 || dragging_outside)
2464 {
2465 // click or scroll outside the current window or on status
2466 // line or vertical separator
2467 if (typed)
2468 {
2469 stuffcharReadbuff(c);
2470 mouse_was_outside = TRUE;
2471 }
2472 return FAIL;
2473 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002474 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002475 break;
2476
2477 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002478 case K_SCRIPT_COMMAND:
2479 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002480 }
2481 if (typed)
2482 mouse_was_outside = FALSE;
2483
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002484 // Convert the typed key to a sequence of bytes for the job.
2485 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002486 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002487 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002488 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2489 (char_u *)msg, (int)len, NULL);
2490
2491 return OK;
2492}
2493
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002494/*
2495 * Handle CTRL-W "": send register contents to the job.
2496 */
2497 static void
2498term_paste_register(int prev_c UNUSED)
2499{
2500 int c;
2501 list_T *l;
2502 listitem_T *item;
2503 long reglen = 0;
2504 int type;
2505
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002506 if (add_to_showcmd(prev_c))
2507 if (add_to_showcmd('"'))
2508 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002509
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002510 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002511 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002512
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002513 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002514 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002515 return;
2516
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002517 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002518 if (c == '=' && get_expr_register() != '=')
2519 return;
2520 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002521 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002522 return;
2523
2524 l = (list_T *)get_reg_contents(c, GREG_LIST);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002525 if (l == NULL)
2526 return;
2527
2528 type = get_reg_type(c, &reglen);
2529 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002530 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002531 char_u *s = tv_get_string(&item->li_tv);
2532#ifdef MSWIN
2533 char_u *tmp = s;
2534
2535 if (!enc_utf8 && enc_codepage > 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002536 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002537 WCHAR *ret = NULL;
2538 int length = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002540 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2541 (int)STRLEN(s), &ret, &length);
2542 if (ret != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002543 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002544 WideCharToMultiByte_alloc(CP_UTF8, 0,
2545 ret, length, (char **)&s, &length, 0, 0);
2546 vim_free(ret);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002547 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002548 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002549#endif
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002550 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2551 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002552#ifdef MSWIN
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002553 if (tmp != s)
2554 vim_free(s);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002555#endif
2556
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002557 if (item->li_next != NULL || type == MLINE)
2558 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2559 (char_u *)"\r", 1, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002560 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002561 list_free(l);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002562}
2563
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002564/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002565 * Return TRUE when waiting for a character in the terminal, the cursor of the
2566 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002567 */
2568 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002569terminal_is_active(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002570{
2571 return in_terminal_loop != NULL;
2572}
2573
Bram Moolenaar83d47902020-03-26 20:34:00 +01002574/*
dundargocc57b5bc2022-11-02 13:30:51 +00002575 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002576 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002577 static int
2578term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002579{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002580 char_u *name;
2581
2582 if (wp != NULL && *wp->w_p_wcr != NUL)
2583 name = wp->w_p_wcr;
2584 else if (term->tl_highlight_name != NULL)
2585 name = term->tl_highlight_name;
2586 else
2587 name = (char_u*)"Terminal";
2588
2589 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002590}
2591
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002592#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 cursorentry_T *
2594term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2595{
2596 term_T *term = in_terminal_loop;
2597 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002598 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002599 guicolor_T term_fg = INVALCOLOR;
2600 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002601
Bram Moolenaara80faa82020-04-12 19:37:17 +02002602 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002603 entry.shape = entry.mshape =
2604 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2605 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2606 SHAPE_BLOCK;
2607 entry.percentage = 20;
2608 if (term->tl_cursor_blink)
2609 {
2610 entry.blinkwait = 700;
2611 entry.blinkon = 400;
2612 entry.blinkoff = 250;
2613 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002614
Bram Moolenaar83d47902020-03-26 20:34:00 +01002615 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002616 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002617 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002618 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002619 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002620 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002621 else
2622 *fg = gui.back_pixel;
2623
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002624 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002625 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002626 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002627 *bg = term_fg;
2628 else
2629 *bg = gui.norm_pixel;
2630 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002631 else
2632 *bg = color_name2handle(term->tl_cursor_color);
2633 entry.name = "n";
2634 entry.used_for = SHAPE_CURSOR;
2635
2636 return &entry;
2637}
2638#endif
2639
Bram Moolenaard317b382018-02-08 22:33:31 +01002640 static void
2641may_output_cursor_props(void)
2642{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002643 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002644 || last_set_cursor_shape != desired_cursor_shape
2645 || last_set_cursor_blink != desired_cursor_blink)
2646 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002647 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002648 last_set_cursor_shape = desired_cursor_shape;
2649 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002650 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002651 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002652 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002653 ui_cursor_shape_forced(TRUE);
2654 else
2655 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2656 }
2657}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002658
Bram Moolenaard317b382018-02-08 22:33:31 +01002659/*
2660 * Set the cursor color and shape, if not last set to these.
2661 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002662 static void
2663may_set_cursor_props(term_T *term)
2664{
2665#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002666 // For the GUI the cursor properties are obtained with
2667 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002668 if (gui.in_use)
2669 return;
2670#endif
2671 if (in_terminal_loop == term)
2672 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002673 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002674 desired_cursor_shape = term->tl_cursor_shape;
2675 desired_cursor_blink = term->tl_cursor_blink;
2676 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002677 }
2678}
2679
Bram Moolenaard317b382018-02-08 22:33:31 +01002680/*
2681 * Reset the desired cursor properties and restore them when needed.
2682 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002683 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002684prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002685{
2686#ifdef FEAT_GUI
2687 if (gui.in_use)
2688 return;
2689#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002690 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002691 desired_cursor_shape = -1;
2692 desired_cursor_blink = -1;
2693 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002694}
2695
2696/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002697 * Returns TRUE if the current window contains a terminal and we are sending
2698 * keys to the job.
2699 * If "check_job_status" is TRUE update the job status.
2700 */
2701 static int
2702term_use_loop_check(int check_job_status)
2703{
2704 term_T *term = curbuf->b_term;
2705
2706 return term != NULL
2707 && !term->tl_normal_mode
2708 && term->tl_vterm != NULL
2709 && term_job_running_check(term, check_job_status);
2710}
2711
2712/*
2713 * Returns TRUE if the current window contains a terminal and we are sending
2714 * keys to the job.
2715 */
2716 int
2717term_use_loop(void)
2718{
2719 return term_use_loop_check(FALSE);
2720}
2721
2722/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002723 * Called when entering a window with the mouse. If this is a terminal window
2724 * we may want to change state.
2725 */
2726 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002727term_win_entered(void)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002728{
2729 term_T *term = curbuf->b_term;
2730
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002731 if (term == NULL)
2732 return;
2733
2734 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002735 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002736 reset_VIsual_and_resel();
2737 if (State & MODE_INSERT)
2738 stop_insert_mode = TRUE;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002739 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002740 mouse_was_outside = FALSE;
2741 enter_mouse_col = mouse_col;
2742 enter_mouse_row = mouse_row;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002743}
2744
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002745 void
2746term_focus_change(int in_focus)
2747{
2748 term_T *term = curbuf->b_term;
2749
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002750 if (term == NULL || term->tl_vterm == NULL)
2751 return;
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002752
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002753 VTermState *state = vterm_obtain_state(term->tl_vterm);
2754
2755 if (in_focus)
2756 vterm_state_focus_in(state);
2757 else
2758 vterm_state_focus_out(state);
2759 term_forward_output(term);
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002760}
2761
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002762/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002763 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2764 * Return the Ctrl-key value in that case.
2765 */
2766 static int
2767raw_c_to_ctrl(int c)
2768{
2769 if ((mod_mask & MOD_MASK_CTRL)
2770 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2771 return c & 0x1f;
2772 return c;
2773}
2774
2775/*
2776 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002777 * Also when the Kitty keyboard protocol is used.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002778 * May set "mod_mask".
2779 */
2780 static int
2781ctrl_to_raw_c(int c)
2782{
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002783 if (c < 0x20 && vterm_using_key_protocol())
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002784 {
2785 mod_mask |= MOD_MASK_CTRL;
2786 return c + '@';
2787 }
2788 return c;
2789}
2790
2791/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002792 * Wait for input and send it to the job.
2793 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2794 * when there is no more typahead.
2795 * Return when the start of a CTRL-W command is typed or anything else that
2796 * should be handled as a Normal mode command.
2797 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2798 * the terminal was closed.
2799 */
2800 int
2801terminal_loop(int blocking)
2802{
2803 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002804 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002805 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002806 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002807#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002808 int tty_fd = curbuf->b_term->tl_job->jv_channel
2809 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002810#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002811 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002812
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002813 // Remember the terminal we are sending keys to. However, the terminal
2814 // might be closed while waiting for a character, e.g. typing "exit" in a
2815 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2816 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002817 in_terminal_loop = curbuf->b_term;
2818
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002819 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002820 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002821 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002822 if (termwinkey == Ctrl_W)
2823 termwinkey = 0;
2824 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002825 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002826 may_set_cursor_props(curbuf->b_term);
2827
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002828 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002829 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002830#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002831 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002832#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002833 // TODO: skip screen update when handling a sequence of keys.
2834 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002835 while (must_redraw != 0)
2836 if (update_screen(0) == FAIL)
2837 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002838 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002839 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002840 break;
2841
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002842 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002843 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002844
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002845 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002846 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002847 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002848 // Job finished while waiting for a character. Push back the
2849 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002850 if (raw_c != K_IGNORE)
2851 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002852 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002853 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002854 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002855 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002856 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002857
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002858#ifdef UNIX
2859 /*
2860 * The shell or another program may change the tty settings. Getting
2861 * them for every typed character is a bit of overhead, but it's needed
2862 * for the first character typed, e.g. when Vim starts in a shell.
2863 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002864 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002865 {
2866 ttyinfo_T info;
2867
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002868 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002869 if (get_tty_info(tty_fd, &info) == OK)
2870 term_backspace_char = info.backspace;
2871 }
2872#endif
2873
Bram Moolenaar4f974752019-02-17 17:44:42 +01002874#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002875 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2876 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002877 if (ctrl_break_was_pressed)
2878 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2879#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002880 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2881 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002882 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002883#ifdef FEAT_GUI
2884 && !curbuf->b_term->tl_system
2885#endif
2886 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002887 {
2888 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002889 int prev_raw_c = raw_c;
2890 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002891
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002892 if (add_to_showcmd(c))
2893 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002894
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002895 raw_c = term_vgetc();
2896 c = raw_c_to_ctrl(raw_c);
2897
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002898 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002899
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002900 if (!term_use_loop_check(TRUE)
2901 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002902 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002903 break;
2904
2905 if (prev_c == Ctrl_BSL)
2906 {
2907 if (c == Ctrl_N)
2908 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002909 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002910 term_enter_normal_mode();
2911 ret = FAIL;
2912 goto theend;
2913 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002914 // Send both keys to the terminal, first one here, second one
2915 // below.
2916 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2917 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002918 }
2919 else if (c == Ctrl_C)
2920 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002921 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2923 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002924 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002926 // "CTRL-W .": send CTRL-W to the job
2927 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002928 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002929 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002930 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002931 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002932 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002933 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002934 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002935 else if (c == 'N')
2936 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002937 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002938 term_enter_normal_mode();
2939 ret = FAIL;
2940 goto theend;
2941 }
2942 else if (c == '"')
2943 {
2944 term_paste_register(prev_c);
2945 continue;
2946 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002947 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002948 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002949 // space for CTRL-W, modifier, multi-byte char and NUL
2950 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002951
2952 // Put the command into the typeahead buffer, when using the
2953 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2954 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002955 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002956 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002957 ret = OK;
2958 goto theend;
2959 }
2960 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002961# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002962 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002963 {
2964 WCHAR wc;
2965 char_u mb[3];
2966
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002967 mb[0] = (unsigned)raw_c >> 8;
2968 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002969 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002970 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002971 }
2972# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002973 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002974 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002975 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002976 // We are sure to come back here, don't reset the cursor color
2977 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002978 restore_cursor = FALSE;
2979
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002980 ret = OK;
2981 goto theend;
2982 }
2983 }
2984 ret = FAIL;
2985
2986theend:
2987 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002988 if (restore_cursor)
2989 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002990
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002991 // Move a snapshot of the screen contents to the buffer, so that completion
2992 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002993 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2994 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002995
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002996 return ret;
2997}
2998
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002999 static void
3000may_toggle_cursor(term_T *term)
3001{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003002 if (in_terminal_loop != term)
3003 return;
3004
3005 if (term->tl_cursor_visible)
3006 cursor_on();
3007 else
3008 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003009}
3010
3011/*
3012 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01003013 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003014 */
3015 static int
3016color2index(VTermColor *color, int fg, int *boldp)
3017{
3018 int red = color->red;
3019 int blue = color->blue;
3020 int green = color->green;
3021
LemonBoyb2b3acb2022-05-20 10:10:34 +01003022 *boldp = FALSE;
3023
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003024 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003025 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01003026
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003027 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003028 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003029 // Use the color as-is if possible, give up otherwise.
3030 if (color->index < t_colors)
3031 return color->index + 1;
3032 // 8-color terminals can actually display twice as many colors by
3033 // setting the high-intensity/bold bit.
3034 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003035 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003036 *boldp = TRUE;
3037 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003038 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01003039 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003040 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01003041
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003042 if (t_colors >= 256)
3043 {
3044 if (red == blue && red == green)
3045 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003046 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003047 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003048 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
3049 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
3050 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003051 int i;
3052
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003053 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003054 return 17; // 00/00/00
3055 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003056 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003057 for (i = 0; i < 23; ++i)
3058 if (red < cutoff[i])
3059 return i + 233;
3060 return 256;
3061 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003062 {
3063 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
3064 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003065
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003066 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003067 for (ri = 0; ri < 5; ++ri)
3068 if (red < cutoff[ri])
3069 break;
3070 for (gi = 0; gi < 5; ++gi)
3071 if (green < cutoff[gi])
3072 break;
3073 for (bi = 0; bi < 5; ++bi)
3074 if (blue < cutoff[bi])
3075 break;
3076 return 17 + ri * 36 + gi * 6 + bi;
3077 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003078 }
3079 return 0;
3080}
3081
3082/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01003083 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003084 */
3085 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003086vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003087{
3088 int attr = 0;
3089
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003090 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003091 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003092 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003093 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003094 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003096 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003098 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003099 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003100 return attr;
3101}
3102
3103/*
3104 * Store Vterm attributes in "cell" from highlight flags.
3105 */
3106 static void
3107hl2vtermAttr(int attr, cellattr_T *cell)
3108{
Bram Moolenaara80faa82020-04-12 19:37:17 +02003109 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003110 if (attr & HL_BOLD)
3111 cell->attrs.bold = 1;
3112 if (attr & HL_UNDERLINE)
3113 cell->attrs.underline = 1;
3114 if (attr & HL_ITALIC)
3115 cell->attrs.italic = 1;
3116 if (attr & HL_STRIKETHROUGH)
3117 cell->attrs.strike = 1;
3118 if (attr & HL_INVERSE)
3119 cell->attrs.reverse = 1;
3120}
3121
3122/*
3123 * Convert the attributes of a vterm cell into an attribute index.
3124 */
3125 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003126cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003127 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003128 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003129 VTermScreenCellAttrs *cellattrs,
3130 VTermColor *cellfg,
3131 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003132{
3133 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003134 VTermColor *fg = cellfg;
3135 VTermColor *bg = cellbg;
3136 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3137 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3138
3139 if (is_default_fg || is_default_bg)
3140 {
3141 if (wp != NULL && *wp->w_p_wcr != NUL)
3142 {
3143 if (is_default_fg)
3144 fg = &wp->w_term_wincolor.fg;
3145 if (is_default_bg)
3146 bg = &wp->w_term_wincolor.bg;
3147 }
3148 else
3149 {
3150 if (is_default_fg)
3151 fg = &term->tl_default_color.fg;
3152 if (is_default_bg)
3153 bg = &term->tl_default_color.bg;
3154 }
3155 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156
3157#ifdef FEAT_GUI
3158 if (gui.in_use)
3159 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003160 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3161 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3162 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003163 }
3164 else
3165#endif
3166#ifdef FEAT_TERMGUICOLORS
3167 if (p_tgc)
3168 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003169 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3170 ? INVALCOLOR
3171 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3172 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3173 ? INVALCOLOR
3174 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3175 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003176 }
3177 else
3178#endif
3179 {
3180 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003181 int ctermfg = color2index(fg, TRUE, &bold);
3182 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003183
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003184 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003185 if (bold == TRUE)
3186 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003187
3188 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003189 }
3190 return 0;
3191}
3192
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003193 static void
3194set_dirty_snapshot(term_T *term)
3195{
3196 term->tl_dirty_snapshot = TRUE;
3197#ifdef FEAT_TIMERS
3198 if (!term->tl_normal_mode)
3199 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003200 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003201 profile_setlimit(100L, &term->tl_timer_due);
3202 term->tl_timer_set = TRUE;
3203 }
3204#endif
3205}
3206
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003207 static int
3208handle_damage(VTermRect rect, void *user)
3209{
3210 term_T *term = (term_T *)user;
3211
3212 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3213 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003214 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003215 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003216 return 1;
3217}
3218
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003219 static void
3220term_scroll_up(term_T *term, int start_row, int count)
3221{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003222 win_T *wp = NULL;
3223 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003224 VTermColor fg, bg;
3225 VTermScreenCellAttrs attr;
3226 int clear_attr;
3227
Bram Moolenaara80faa82020-04-12 19:37:17 +02003228 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003229
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003230 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003231 {
3232 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003233 {
3234 // Set the color to clear lines with.
3235 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3236 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003237 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003238 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003239 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003240 }
3241}
3242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003243 static int
3244handle_moverect(VTermRect dest, VTermRect src, void *user)
3245{
3246 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003247 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003248
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003249 // Scrolling up is done much more efficiently by deleting lines instead of
3250 // redrawing the text. But avoid doing this multiple times, postpone until
3251 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003252 if (dest.start_col == src.start_col
3253 && dest.end_col == src.end_col
3254 && dest.start_row < src.start_row)
3255 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003256 if (dest.start_row == 0)
3257 term->tl_postponed_scroll += count;
3258 else
3259 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003260 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003261
3262 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3263 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003264 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003265
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003266 // Note sure if the scrolling will work correctly, let's do a complete
3267 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003268 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003269 return 1;
3270}
3271
3272 static int
3273handle_movecursor(
3274 VTermPos pos,
3275 VTermPos oldpos UNUSED,
3276 int visible,
3277 void *user)
3278{
3279 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003280 win_T *wp = NULL;
3281 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003282
3283 term->tl_cursor_pos = pos;
3284 term->tl_cursor_visible = visible;
3285
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003286 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003287 {
3288 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003289 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003290 }
3291 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003292 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003293
3294 return 1;
3295}
3296
3297 static int
3298handle_settermprop(
3299 VTermProp prop,
3300 VTermValue *value,
3301 void *user)
3302{
3303 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003304 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003305
3306 switch (prop)
3307 {
3308 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003309 if (disable_vterm_title_for_testing)
3310 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003311 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003312 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003313 if (strval == NULL)
3314 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003315 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003316 // a blank title isn't useful, make it empty, so that "running" is
3317 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003318 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003319 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003320 // Same as blank
3321 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003322 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003323 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3324 term->tl_title = NULL;
3325 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003326 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003327 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003328#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003329 else if (!enc_utf8 && enc_codepage > 0)
3330 {
3331 WCHAR *ret = NULL;
3332 int length = 0;
3333
3334 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003335 (char*)value->string.str,
3336 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003337 if (ret != NULL)
3338 {
3339 WideCharToMultiByte_alloc(enc_codepage, 0,
3340 ret, length, (char**)&term->tl_title,
3341 &length, 0, 0);
3342 vim_free(ret);
3343 }
3344 }
3345#endif
3346 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003347 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003348 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003349 strval = NULL;
3350 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003351 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003352 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003353 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003354 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003355 curwin->w_redr_status = TRUE;
3356 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357 break;
3358
3359 case VTERM_PROP_CURSORVISIBLE:
3360 term->tl_cursor_visible = value->boolean;
3361 may_toggle_cursor(term);
3362 out_flush();
3363 break;
3364
3365 case VTERM_PROP_CURSORBLINK:
3366 term->tl_cursor_blink = value->boolean;
3367 may_set_cursor_props(term);
3368 break;
3369
3370 case VTERM_PROP_CURSORSHAPE:
3371 term->tl_cursor_shape = value->number;
3372 may_set_cursor_props(term);
3373 break;
3374
3375 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003376 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003377 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003378 if (strval == NULL)
3379 break;
3380 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003381 may_set_cursor_props(term);
3382 break;
3383
3384 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003385 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003386 term->tl_using_altscreen = value->boolean;
3387 break;
3388
3389 default:
3390 break;
3391 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003392 vim_free(strval);
3393
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003394 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003395 return 1;
3396}
3397
3398/*
3399 * The job running in the terminal resized the terminal.
3400 */
3401 static int
3402handle_resize(int rows, int cols, void *user)
3403{
3404 term_T *term = (term_T *)user;
3405 win_T *wp;
3406
3407 term->tl_rows = rows;
3408 term->tl_cols = cols;
3409 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003410 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003411 term->tl_vterm_size_changed = FALSE;
3412 else
3413 {
3414 FOR_ALL_WINDOWS(wp)
3415 {
3416 if (wp->w_buffer == term->tl_buffer)
3417 {
3418 win_setheight_win(rows, wp);
3419 win_setwidth_win(cols, wp);
3420 }
3421 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003422 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003423 }
3424 return 1;
3425}
3426
3427/*
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003428 * If the number of lines that are stored goes over 'termwinscroll' then
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003429 * delete the first 10%.
3430 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3431 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003432 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003433 static void
3434limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003435{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003436 if (gap->ga_len < term->tl_buffer->b_p_twsl)
3437 return;
3438
Milly6d5f4a02024-10-22 23:17:45 +02003439 int todo = MAX(term->tl_buffer->b_p_twsl / 10,
3440 gap->ga_len - term->tl_buffer->b_p_twsl);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003441 int i;
3442
3443 curbuf = term->tl_buffer;
3444 for (i = 0; i < todo; ++i)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003445 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003446 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003447 if (update_buffer)
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003448 ml_delete(1);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003449 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003450 curbuf = curwin->w_buffer;
3451
3452 gap->ga_len -= todo;
3453 mch_memmove(gap->ga_data,
3454 (sb_line_T *)gap->ga_data + todo,
3455 sizeof(sb_line_T) * gap->ga_len);
3456 if (update_buffer)
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003457 {
3458 win_T *curwin_save = curwin;
3459 win_T *wp = NULL;
3460
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003461 term->tl_scrollback_scrolled -= todo;
Christian Brabandt1254e6d2024-07-29 21:19:51 +02003462
Hirohito Higashi926e2af2025-04-21 11:23:12 +02003463 FOR_ALL_WINDOWS(wp)
3464 {
3465 if (wp->w_buffer == term->tl_buffer)
3466 {
3467 curwin = wp;
3468 check_cursor();
3469 }
3470 }
3471 curwin = curwin_save;
3472 }
3473
Christian Brabandt1254e6d2024-07-29 21:19:51 +02003474 // make sure cursor is on a valid line
3475 if (curbuf == term->tl_buffer)
3476 check_cursor();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003477}
3478
3479/*
3480 * Handle a line that is pushed off the top of the screen.
3481 */
3482 static int
3483handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3484{
3485 term_T *term = (term_T *)user;
3486 garray_T *gap;
3487 int update_buffer;
3488
3489 if (term->tl_normal_mode)
3490 {
3491 // In Terminal-Normal mode the user interacts with the buffer, thus we
3492 // must not change it. Postpone adding the scrollback lines.
3493 gap = &term->tl_scrollback_postponed;
3494 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003495 }
3496 else
3497 {
3498 // First remove the lines that were appended before, the pushed line
3499 // goes above it.
3500 cleanup_scrollback(term);
3501 gap = &term->tl_scrollback;
3502 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003503 }
3504
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003505 limit_scrollback(term, gap, update_buffer);
3506
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003507 if (ga_grow(gap, 1) == FAIL)
3508 return 0;
3509
3510 cellattr_T *p = NULL;
3511 int len = 0;
3512 int i;
3513 int c;
3514 int col;
3515 int text_len;
3516 char_u *text;
3517 sb_line_T *line;
3518 garray_T ga;
3519 cellattr_T fill_attr = term->tl_default_color;
3520
3521 // do not store empty cells at the end
3522 for (i = 0; i < cols; ++i)
3523 if (cells[i].chars[0] != 0)
3524 len = i + 1;
3525 else
3526 cell2cellattr(&cells[i], &fill_attr);
3527
3528 ga_init2(&ga, 1, 100);
3529 if (len > 0)
3530 p = ALLOC_MULT(cellattr_T, len);
3531 if (p != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003532 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003533 for (col = 0; col < len; col += cells[col].width)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003534 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003535 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003536 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003537 ga.ga_len = 0;
3538 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003539 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003540 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3541 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3542 (char_u *)ga.ga_data + ga.ga_len);
3543 cell2cellattr(&cells[col], &p[col]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003544 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003545 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003546 if (ga_grow(&ga, 1) == FAIL)
3547 {
3548 if (update_buffer)
3549 text = (char_u *)"";
3550 else
3551 text = vim_strsave((char_u *)"");
3552 text_len = 0;
3553 }
3554 else
3555 {
3556 text = ga.ga_data;
3557 text_len = ga.ga_len;
3558 *(text + text_len) = NUL;
3559 }
3560 if (update_buffer)
3561 add_scrollback_line_to_buffer(term, text, text_len);
3562
3563 line = (sb_line_T *)gap->ga_data + gap->ga_len;
3564 line->sb_cols = len;
3565 line->sb_cells = p;
3566 line->sb_fill_attr = fill_attr;
3567 if (update_buffer)
3568 {
3569 line->sb_text = NULL;
3570 ++term->tl_scrollback_scrolled;
3571 ga_clear(&ga); // free the text
3572 }
3573 else
3574 {
3575 line->sb_text = text;
3576 ga_init(&ga); // text is kept in tl_scrollback_postponed
3577 }
3578 ++gap->ga_len;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003579 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003580}
3581
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003582/*
3583 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3584 * received and stored in tl_scrollback_postponed.
3585 */
3586 static void
3587handle_postponed_scrollback(term_T *term)
3588{
3589 int i;
3590
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003591 if (term->tl_scrollback_postponed.ga_len == 0)
3592 return;
3593 ch_log(NULL, "Moving postponed scrollback to scrollback");
3594
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003595 // First remove the lines that were appended before, the pushed lines go
3596 // above it.
3597 cleanup_scrollback(term);
3598
3599 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3600 {
3601 char_u *text;
3602 sb_line_T *pp_line;
3603 sb_line_T *line;
3604
3605 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3606 break;
3607 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3608
3609 text = pp_line->sb_text;
3610 if (text == NULL)
3611 text = (char_u *)"";
3612 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3613 vim_free(pp_line->sb_text);
3614
3615 line = (sb_line_T *)term->tl_scrollback.ga_data
3616 + term->tl_scrollback.ga_len;
3617 line->sb_cols = pp_line->sb_cols;
3618 line->sb_cells = pp_line->sb_cells;
3619 line->sb_fill_attr = pp_line->sb_fill_attr;
3620 line->sb_text = NULL;
3621 ++term->tl_scrollback_scrolled;
3622 ++term->tl_scrollback.ga_len;
3623 }
3624
3625 ga_clear(&term->tl_scrollback_postponed);
3626 limit_scrollback(term, &term->tl_scrollback, TRUE);
3627}
3628
LemonBoy77771d32022-04-13 11:47:25 +01003629/*
3630 * Called when the terminal wants to ring the system bell.
3631 */
3632 static int
3633handle_bell(void *user UNUSED)
3634{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003635 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003636 return 0;
3637}
3638
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003639static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003640 handle_damage, // damage
3641 handle_moverect, // moverect
3642 handle_movecursor, // movecursor
3643 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003644 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003645 handle_resize, // resize
3646 handle_pushline, // sb_pushline
Bram Moolenaar6a12d262022-10-16 19:26:52 +01003647 NULL, // sb_popline
3648 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003649};
3650
3651/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003652 * Do the work after the channel of a terminal was closed.
3653 * Must be called only when updating_screen is FALSE.
3654 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3655 */
3656 static int
3657term_after_channel_closed(term_T *term)
3658{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003659 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003660 if (!term->tl_normal_mode)
3661 {
3662 int fnum = term->tl_buffer->b_fnum;
3663
3664 cleanup_vterm(term);
3665
3666 if (term->tl_finish == TL_FINISH_CLOSE)
3667 {
3668 aco_save_T aco;
zeertzjqbc11f6d2024-08-16 21:11:31 +02003669 int do_set_w_locked = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003670#ifdef FEAT_PROP_POPUP
3671 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003672
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003673 // If this was a terminal in a popup window, go back to the
3674 // previous window.
3675 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3676 {
3677 pwin = curwin;
3678 if (win_valid(prevwin))
3679 win_enter(prevwin, FALSE);
3680 }
3681 else
3682#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003683 // If this is the last normal window: exit Vim.
3684 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3685 {
3686 exarg_T ea;
3687
Bram Moolenaara80faa82020-04-12 19:37:17 +02003688 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003689 ex_quit(&ea);
3690 return TRUE;
3691 }
3692
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003693 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003694 ch_log(NULL, "terminal job finished, closing window");
3695 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaare76062c2022-11-28 18:51:43 +00003696 if (curbuf == term->tl_buffer)
3697 {
3698 // Avoid closing the window if we temporarily use it.
3699 if (is_aucmd_win(curwin))
zeertzjqbc11f6d2024-08-16 21:11:31 +02003700 do_set_w_locked = TRUE;
3701 if (do_set_w_locked)
Christian Brabandt0a6e57b2024-08-15 22:15:28 +02003702 curwin->w_locked = TRUE;
Bram Moolenaare76062c2022-11-28 18:51:43 +00003703 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
zeertzjqbc11f6d2024-08-16 21:11:31 +02003704 if (do_set_w_locked)
Christian Brabandt0a6e57b2024-08-15 22:15:28 +02003705 curwin->w_locked = FALSE;
Bram Moolenaare76062c2022-11-28 18:51:43 +00003706 aucmd_restbuf(&aco);
3707 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003708#ifdef FEAT_PROP_POPUP
3709 if (pwin != NULL)
3710 popup_close_with_retval(pwin, 0);
3711#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003712 return TRUE;
3713 }
3714 if (term->tl_finish == TL_FINISH_OPEN
3715 && term->tl_buffer->b_nwindows == 0)
3716 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003717 char *cmd = term->tl_opencmd == NULL
3718 ? "botright sbuf %d"
3719 : (char *)term->tl_opencmd;
3720 size_t len = strlen(cmd) + 50;
3721 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003722
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003723 if (buf != NULL)
3724 {
3725 ch_log(NULL, "terminal job finished, opening window");
3726 vim_snprintf(buf, len, cmd, fnum);
3727 do_cmdline_cmd((char_u *)buf);
3728 vim_free(buf);
3729 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003730 }
3731 else
3732 ch_log(NULL, "terminal job finished");
3733 }
3734
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003735 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003736 return FALSE;
3737}
3738
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003739#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3740/*
3741 * If the current window is a terminal in a popup window and the job has
3742 * finished, close the popup window and to back to the previous window.
3743 * Otherwise return FAIL.
3744 */
3745 int
3746may_close_term_popup(void)
3747{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003748 if (!popup_is_popup(curwin) || curbuf->b_term == NULL
3749 || term_job_running_not_none(curbuf->b_term))
3750 return FAIL;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003751
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003752 win_T *pwin = curwin;
3753
3754 if (win_valid(prevwin))
3755 win_enter(prevwin, FALSE);
3756 popup_close_with_retval(pwin, 0);
3757 return OK;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003758}
3759#endif
3760
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003761/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003762 * Called when a channel is going to be closed, before invoking the close
3763 * callback.
3764 */
3765 void
3766term_channel_closing(channel_T *ch)
3767{
3768 term_T *term;
3769
3770 for (term = first_term; term != NULL; term = term->tl_next)
3771 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3772 term->tl_channel_closing = TRUE;
3773}
3774
3775/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003776 * Called when a channel has been closed.
3777 * If this was a channel for a terminal window then finish it up.
3778 */
3779 void
3780term_channel_closed(channel_T *ch)
3781{
3782 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003783 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003784 int did_one = FALSE;
3785
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003786 for (term = first_term; term != NULL; term = next_term)
3787 {
3788 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003789 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003790 {
3791 term->tl_channel_closed = TRUE;
3792 did_one = TRUE;
3793
Bram Moolenaard23a8232018-02-10 18:45:26 +01003794 VIM_CLEAR(term->tl_title);
3795 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003796#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003797 if (term->tl_out_fd != NULL)
3798 {
3799 fclose(term->tl_out_fd);
3800 term->tl_out_fd = NULL;
3801 }
3802#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003803
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003804 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003805 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003806 // Cannot open or close windows now. Can happen when
3807 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003808 term->tl_channel_recently_closed = TRUE;
3809 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003810 }
3811
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003812 if (term_after_channel_closed(term))
3813 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003814 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003815 }
3816
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003817 if (did_one)
3818 {
3819 redraw_statuslines();
3820
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003821 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003822 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003823 typebuf_was_filled = TRUE;
3824
3825 term = curbuf->b_term;
3826 if (term != NULL)
3827 {
3828 if (term->tl_job == ch->ch_job)
3829 maketitle();
3830 update_cursor(term, term->tl_cursor_visible);
3831 }
3832 }
3833}
3834
3835/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003836 * To be called after resetting updating_screen: handle any terminal where the
3837 * channel was closed.
3838 */
3839 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003840term_check_channel_closed_recently(void)
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003841{
3842 term_T *term;
3843 term_T *next_term;
3844
3845 for (term = first_term; term != NULL; term = next_term)
3846 {
3847 next_term = term->tl_next;
3848 if (term->tl_channel_recently_closed)
3849 {
3850 term->tl_channel_recently_closed = FALSE;
3851 if (term_after_channel_closed(term))
3852 // start over, the list may have changed
3853 next_term = first_term;
3854 }
3855 }
3856}
3857
3858/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003859 * Fill one screen line from a line of the terminal.
3860 * Advances "pos" to past the last column.
3861 */
3862 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003863term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003864 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003865 win_T *wp,
3866 VTermScreen *screen,
3867 VTermPos *pos,
3868 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003869{
3870 int off = screen_get_current_line_off();
3871
3872 for (pos->col = 0; pos->col < max_col; )
3873 {
3874 VTermScreenCell cell;
3875 int c;
3876
3877 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003878 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003879
3880 c = cell.chars[0];
3881 if (c == NUL)
3882 {
3883 ScreenLines[off] = ' ';
3884 if (enc_utf8)
3885 ScreenLinesUC[off] = NUL;
3886 }
3887 else
3888 {
3889 if (enc_utf8)
3890 {
3891 int i;
3892
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003893 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003894 for (i = 0; i < Screen_mco
3895 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3896 {
3897 ScreenLinesC[i][off] = cell.chars[i + 1];
3898 if (cell.chars[i + 1] == 0)
3899 break;
3900 }
3901 if (c >= 0x80 || (Screen_mco > 0
3902 && ScreenLinesC[0][off] != 0))
3903 {
3904 ScreenLines[off] = ' ';
3905 ScreenLinesUC[off] = c;
3906 }
3907 else
3908 {
3909 ScreenLines[off] = c;
3910 ScreenLinesUC[off] = NUL;
3911 }
3912 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003913#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003914 else if (has_mbyte && c >= 0x80)
3915 {
3916 char_u mb[MB_MAXBYTES+1];
3917 WCHAR wc = c;
3918
3919 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3920 (char*)mb, 2, 0, 0) > 1)
3921 {
3922 ScreenLines[off] = mb[0];
3923 ScreenLines[off + 1] = mb[1];
3924 cell.width = mb_ptr2cells(mb);
3925 }
3926 else
3927 ScreenLines[off] = c;
3928 }
3929#endif
3930 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003931 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003932 ScreenLines[off] = c;
3933 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003934 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3935 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003936
3937 ++pos->col;
3938 ++off;
3939 if (cell.width == 2)
3940 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003941 // don't set the second byte to NUL for a DBCS encoding, it
3942 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003943 if (enc_utf8)
3944 {
3945 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003946 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003947 }
3948 else if (!has_mbyte)
3949 {
3950 // Can't show a double-width character with a single-byte
3951 // 'encoding', just use a space.
3952 ScreenLines[off] = ' ';
3953 ScreenAttrs[off] = ScreenAttrs[off - 1];
3954 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003955
3956 ++pos->col;
3957 ++off;
3958 }
3959 }
3960}
3961
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003962#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003963 static void
3964update_system_term(term_T *term)
3965{
3966 VTermPos pos;
3967 VTermScreen *screen;
3968
3969 if (term->tl_vterm == NULL)
3970 return;
3971 screen = vterm_obtain_screen(term->tl_vterm);
3972
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003973 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003974 while (term->tl_toprow > 0
3975 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3976 {
3977 int save_p_more = p_more;
3978
3979 p_more = FALSE;
3980 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003981 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003982 p_more = save_p_more;
3983 --term->tl_toprow;
3984 }
3985
3986 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3987 && pos.row < Rows; ++pos.row)
3988 {
3989 if (pos.row < term->tl_rows)
3990 {
3991 int max_col = MIN(Columns, term->tl_cols);
3992
Bram Moolenaar83d47902020-03-26 20:34:00 +01003993 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003994 }
3995 else
3996 pos.col = 0;
3997
zeertzjqd0c1b772024-03-16 15:03:33 +01003998 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, -1,
3999 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01004000 }
4001
4002 term->tl_dirty_row_start = MAX_ROW;
4003 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01004004}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01004005#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01004006
4007/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004008 * Return TRUE if window "wp" is to be redrawn with term_update_window().
4009 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004010 * Terminal-Normal mode.
4011 */
4012 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004013term_do_update_window(win_T *wp)
4014{
4015 term_T *term = wp->w_buffer->b_term;
4016
4017 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
4018}
4019
4020/*
4021 * Called to update a window that contains an active terminal.
4022 */
4023 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004024term_update_window(win_T *wp)
4025{
4026 term_T *term = wp->w_buffer->b_term;
4027 VTerm *vterm;
4028 VTermScreen *screen;
4029 VTermState *state;
4030 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004031 int rows, cols;
4032 int newrows, newcols;
4033 int minsize;
4034 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004035
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004036 vterm = term->tl_vterm;
4037 screen = vterm_obtain_screen(vterm);
4038 state = vterm_obtain_state(vterm);
4039
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004040 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
4041 // With UPD_SOME_VALID only redraw what was marked dirty.
4042 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004043 {
4044 term->tl_dirty_row_start = 0;
4045 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004046
4047 if (term->tl_postponed_scroll > 0
4048 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004049 // Scrolling is usually faster than redrawing, when there are only
4050 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004051 term_scroll_up(term, 0, term->tl_postponed_scroll);
4052 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004053 }
4054
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004055 /*
4056 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004057 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004058 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004059 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004060
Bram Moolenaar498c2562018-04-15 23:45:15 +02004061 newrows = 99999;
4062 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004063 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02004064 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004065 // Always use curwin, it may be a popup window.
4066 win_T *wwp = twp == NULL ? curwin : twp;
4067
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004068 // When more than one window shows the same terminal, use the
4069 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004070 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004071 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004072 newrows = MIN(newrows, wwp->w_height);
4073 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004074 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004075 if (twp == NULL)
4076 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004077 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02004078 if (newrows == 99999 || newcols == 99999)
4079 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02004080 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
4081 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
4082
Bram Moolenaareba13e42021-02-23 17:47:23 +01004083 // If no cell is visible there is no point in resizing. Also, vterm can't
4084 // handle a zero height.
4085 if (newrows == 0 || newcols == 0)
4086 return;
4087
Bram Moolenaar498c2562018-04-15 23:45:15 +02004088 if (term->tl_rows != newrows || term->tl_cols != newcols)
4089 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004090 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004091 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004092 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02004093 newrows);
4094 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02004095
4096 // Updating the terminal size will cause the snapshot to be cleared.
4097 // When not in terminal_loop() we need to restore it.
4098 if (term != in_terminal_loop)
4099 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004100 }
4101
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004102 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004103 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01004104 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004105
Bram Moolenaar3a497e12017-09-30 20:40:27 +02004106 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
4107 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004108 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004109 if (pos.row < term->tl_rows)
4110 {
Bram Moolenaar13568252018-03-16 20:46:58 +01004111 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004112
Bram Moolenaar83d47902020-03-26 20:34:00 +01004113 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004114 }
4115 else
4116 pos.col = 0;
4117
Bram Moolenaar510f0372022-07-04 17:46:22 +01004118 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01004119#ifdef FEAT_MENU
4120 + winbar_height(wp)
4121#endif
zeertzjqd0c1b772024-03-16 15:03:33 +01004122 , wp->w_wincol, pos.col, wp->w_width, -1,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004123#ifdef FEAT_PROP_POPUP
4124 popup_is_popup(wp) ? SLF_POPUP :
4125#endif
4126 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004127 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00004128}
4129
4130/*
4131 * Called after updating all windows: may reset dirty rows.
4132 */
4133 void
4134term_did_update_window(win_T *wp)
4135{
4136 term_T *term = wp->w_buffer->b_term;
4137
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004138 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode
4139 || wp->w_redr_type != 0)
4140 return;
4141
4142 term->tl_dirty_row_start = MAX_ROW;
4143 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004144}
4145
4146/*
4147 * Return TRUE if "wp" is a terminal window where the job has finished.
4148 */
4149 int
4150term_is_finished(buf_T *buf)
4151{
4152 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
4153}
4154
4155/*
4156 * Return TRUE if "wp" is a terminal window where the job has finished or we
4157 * are in Terminal-Normal mode, thus we show the buffer contents.
4158 */
4159 int
4160term_show_buffer(buf_T *buf)
4161{
4162 term_T *term = buf->b_term;
4163
4164 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4165}
4166
4167/*
4168 * The current buffer is going to be changed. If there is terminal
4169 * highlighting remove it now.
4170 */
4171 void
4172term_change_in_curbuf(void)
4173{
4174 term_T *term = curbuf->b_term;
4175
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004176 if (!term_is_finished(curbuf) || term->tl_scrollback.ga_len <= 0)
4177 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004178
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004179 free_scrollback(term);
4180 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
4181
4182 // The buffer is now like a normal buffer, it cannot be easily
4183 // abandoned when changed.
4184 set_string_option_direct((char_u *)"buftype", -1,
4185 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004186}
4187
4188/*
4189 * Get the screen attribute for a position in the buffer.
4190 * Use a negative "col" to get the filler background color.
4191 */
4192 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004193term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004194{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004195 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004196 term_T *term = buf->b_term;
4197 sb_line_T *line;
4198 cellattr_T *cellattr;
4199
4200 if (lnum > term->tl_scrollback.ga_len)
4201 cellattr = &term->tl_default_color;
4202 else
4203 {
4204 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4205 if (col < 0 || col >= line->sb_cols)
4206 cellattr = &line->sb_fill_attr;
4207 else
4208 cellattr = line->sb_cells + col;
4209 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004210 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004211}
4212
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004213/*
4214 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004215 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004216 */
4217 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004218cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004219{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004220 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4221 if (rgb->index == 0)
4222 rgb->type = VTERM_COLOR_RGB;
4223 else
4224 {
4225 rgb->type = VTERM_COLOR_INDEXED;
4226 --rgb->index;
4227 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004228}
4229
4230/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004231 * Initialize vterm color from the synID.
4232 * Returns TRUE if color is set to "fg" and "bg".
4233 * Otherwise returns FALSE.
4234 */
4235 static int
4236get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4237{
4238#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4239 // Use the actual color for the GUI and when 'termguicolors' is set.
4240 if (0
4241# ifdef FEAT_GUI
4242 || gui.in_use
4243# endif
4244# ifdef FEAT_TERMGUICOLORS
4245 || p_tgc
4246# ifdef FEAT_VTP
4247 // Finally get INVALCOLOR on this execution path
4248 || (!p_tgc && t_colors >= 256)
4249# endif
4250# endif
4251 )
4252 {
4253 guicolor_T fg_rgb = INVALCOLOR;
4254 guicolor_T bg_rgb = INVALCOLOR;
4255
4256 if (id > 0)
4257 syn_id2colors(id, &fg_rgb, &bg_rgb);
4258
4259 if (fg_rgb != INVALCOLOR)
4260 {
4261 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4262 fg->red = (unsigned)(rgb >> 16);
4263 fg->green = (unsigned)(rgb >> 8) & 255;
4264 fg->blue = (unsigned)rgb & 255;
4265 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4266 }
4267 else
4268 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4269
4270 if (bg_rgb != INVALCOLOR)
4271 {
4272 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4273 bg->red = (unsigned)(rgb >> 16);
4274 bg->green = (unsigned)(rgb >> 8) & 255;
4275 bg->blue = (unsigned)rgb & 255;
4276 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4277 }
4278 else
4279 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4280
4281 return TRUE;
4282 }
4283 else
4284#endif
4285 if (t_colors >= 16)
4286 {
4287 int cterm_fg = -1;
4288 int cterm_bg = -1;
4289
4290 if (id > 0)
4291 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4292
4293 if (cterm_fg >= 0)
4294 {
4295 cterm_color2vterm(cterm_fg, fg);
4296 fg->type |= VTERM_COLOR_DEFAULT_FG;
4297 }
4298 else
4299 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4300
4301 if (cterm_bg >= 0)
4302 {
4303 cterm_color2vterm(cterm_bg, bg);
4304 bg->type |= VTERM_COLOR_DEFAULT_BG;
4305 }
4306 else
4307 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4308
4309 return TRUE;
4310 }
4311
4312 return FALSE;
4313}
4314
4315 void
4316term_reset_wincolor(win_T *wp)
4317{
4318 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4319 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4320}
4321
4322/*
4323 * Cache the color of 'wincolor'.
4324 */
4325 void
4326term_update_wincolor(win_T *wp)
4327{
4328 int id = 0;
4329
4330 if (*wp->w_p_wcr != NUL)
4331 id = syn_name2id(wp->w_p_wcr);
4332 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4333 &wp->w_term_wincolor.bg))
4334 term_reset_wincolor(wp);
4335}
4336
4337/*
4338 * Called when option 'termguicolors' was set,
4339 * or when any highlight is changed.
4340 */
4341 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004342term_update_wincolor_all(void)
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004343{
4344 win_T *wp = NULL;
4345 int did_curwin = FALSE;
4346
4347 while (for_all_windows_and_curwin(&wp, &did_curwin))
4348 term_update_wincolor(wp);
4349}
4350
4351/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004352 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004353 */
4354 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004355init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004356{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004357 VTermColor *fg, *bg;
4358 int fgval, bgval;
4359 int id;
4360
Bram Moolenaara80faa82020-04-12 19:37:17 +02004361 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004362 term->tl_default_color.width = 1;
4363 fg = &term->tl_default_color.fg;
4364 bg = &term->tl_default_color.bg;
4365
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004366 // Vterm uses a default black background. Set it to white when
4367 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004368 if (*p_bg == 'l')
4369 {
4370 fgval = 0;
4371 bgval = 255;
4372 }
4373 else
4374 {
4375 fgval = 255;
4376 bgval = 0;
4377 }
4378 fg->red = fg->green = fg->blue = fgval;
4379 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004380 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4381 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004382
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004383 // The highlight group overrules the defaults.
4384 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004385
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004386 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004387 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004388#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004389 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004390#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004391
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004392 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004393 if (cterm_normal_fg_color > 0)
4394 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004395 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004396# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4397# ifdef VIMDLL
4398 if (!gui.in_use)
4399# endif
4400 {
4401 tmp = fg->red;
4402 fg->red = fg->blue;
4403 fg->blue = tmp;
4404 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004405# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004406 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004407# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004408 else
4409 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004410# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004411
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004412 if (cterm_normal_bg_color > 0)
4413 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004414 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004415# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4416# ifdef VIMDLL
4417 if (!gui.in_use)
4418# endif
4419 {
4420 tmp = fg->red;
4421 fg->red = fg->blue;
4422 fg->blue = tmp;
4423 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004424# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004425 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004426# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004427 else
4428 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004429# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004430 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004431}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004432
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004433#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4434/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004435 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4436 * "ansi_colors" argument in term_start()) shall be applied.
4437 */
4438 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004439term_use_palette(void)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004440{
4441 if (0
4442#ifdef FEAT_GUI
4443 || gui.in_use
4444#endif
4445#ifdef FEAT_TERMGUICOLORS
4446 || p_tgc
4447#endif
4448 )
4449 return TRUE;
4450 return FALSE;
4451}
4452
4453/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004454 * Set the 16 ANSI colors from array of RGB values
4455 */
4456 static void
4457set_vterm_palette(VTerm *vterm, long_u *rgb)
4458{
4459 int index = 0;
4460 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004461
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004462 for (; index < 16; index++)
4463 {
4464 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004465
Millyb771b6b2021-11-23 12:07:25 +00004466 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004467 color.red = (unsigned)(rgb[index] >> 16);
4468 color.green = (unsigned)(rgb[index] >> 8) & 255;
4469 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004470 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004471 vterm_state_set_palette_color(state, index, &color);
4472 }
4473}
4474
4475/*
4476 * Set the ANSI color palette from a list of colors
4477 */
4478 static int
4479set_ansi_colors_list(VTerm *vterm, list_T *list)
4480{
4481 int n = 0;
4482 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004483 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004484
Bram Moolenaarb0992022020-01-30 14:55:42 +01004485 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004486 {
4487 char_u *color_name;
4488 guicolor_T guicolor;
4489
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004490 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004491 if (color_name == NULL)
4492 return FAIL;
4493
4494 guicolor = GUI_GET_COLOR(color_name);
4495 if (guicolor == INVALCOLOR)
4496 return FAIL;
4497
4498 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4499 }
4500
4501 if (n != 16 || li != NULL)
4502 return FAIL;
4503
4504 set_vterm_palette(vterm, rgb);
4505
4506 return OK;
4507}
4508
4509/*
4510 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4511 */
4512 static void
4513init_vterm_ansi_colors(VTerm *vterm)
4514{
4515 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4516
LemonBoyb2b3acb2022-05-20 10:10:34 +01004517 if (var == NULL)
4518 return;
4519
4520 if (var->di_tv.v_type != VAR_LIST
4521 || var->di_tv.vval.v_list == NULL
4522 || var->di_tv.vval.v_list->lv_first == &range_list_item
4523 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004524 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004525}
4526#endif
4527
Bram Moolenaar52acb112018-03-18 19:20:22 +01004528/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004529 * Handles a "drop" command from the job in the terminal.
4530 * "item" is the file name, "item->li_next" may have options.
4531 */
4532 static void
4533handle_drop_command(listitem_T *item)
4534{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004535 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004536 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004537 int bufnr;
4538 win_T *wp;
4539 tabpage_T *tp;
4540 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004541 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004542
4543 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4544 FOR_ALL_TAB_WINDOWS(tp, wp)
4545 {
4546 if (wp->w_buffer->b_fnum == bufnr)
4547 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004548 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004549 goto_tabpage_win(tp, wp);
4550 return;
4551 }
4552 }
4553
Bram Moolenaara80faa82020-04-12 19:37:17 +02004554 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004555
4556 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4557 && opt_item->li_tv.vval.v_dict != NULL)
4558 {
4559 dict_T *dict = opt_item->li_tv.vval.v_dict;
4560 char_u *p;
4561
Bram Moolenaard61efa52022-07-23 09:52:04 +01004562 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004563 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004564 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004565 if (p != NULL)
4566 {
4567 if (check_ff_value(p) == FAIL)
4568 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4569 else
4570 ea.force_ff = *p;
4571 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004572 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004573 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004574 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004575 if (p != NULL)
4576 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004577 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004578 if (ea.cmd != NULL)
4579 {
4580 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4581 ea.force_enc = 11;
4582 tofree = ea.cmd;
4583 }
4584 }
4585
Bram Moolenaard61efa52022-07-23 09:52:04 +01004586 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004587 if (p != NULL)
4588 get_bad_opt(p, &ea);
4589
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004590 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004591 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004592 if (dict_has_key(dict, "binary"))
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, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004595 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004596 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004597 ea.force_bin = FORCE_NOBIN;
4598 }
4599
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004600 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004601 if (ea.cmd == NULL)
4602 ea.cmd = (char_u *)"split";
4603 ea.arg = fname;
4604 ea.cmdidx = CMD_split;
4605 ex_splitview(&ea);
4606
4607 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004608}
4609
4610/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004611 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4612 */
4613 static int
4614is_permitted_term_api(char_u *func, char_u *pat)
4615{
4616 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4617}
4618
4619/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004620 * Handles a function call from the job running in a terminal.
4621 * "item" is the function name, "item->li_next" has the arguments.
4622 */
4623 static void
4624handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4625{
4626 char_u *func;
4627 typval_T argvars[2];
4628 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004629 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004630
4631 if (item->li_next == NULL)
4632 {
4633 ch_log(channel, "Missing function arguments for call");
4634 return;
4635 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004636 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004637
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004638 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004639 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004640 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004641 return;
4642 }
4643
4644 argvars[0].v_type = VAR_NUMBER;
4645 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4646 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004647 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004648 funcexe.fe_firstline = 1L;
4649 funcexe.fe_lastline = 1L;
4650 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004651 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004652 {
4653 clear_tv(&rettv);
4654 ch_log(channel, "Function %s called", func);
4655 }
4656 else
4657 ch_log(channel, "Calling function %s failed", func);
4658}
4659
4660/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004661 * URL decoding (also know as Percent-encoding).
4662 *
4663 * Note this function currently is only used for decoding shell's
4664 * OSC 7 escape sequence which we can assume all bytes are valid
4665 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4666 * encoding bytes like 0xfe, 0xff.
4667 */
4668 static size_t
4669url_decode(const char *src, const size_t len, char_u *dst)
4670{
4671 size_t i = 0, j = 0;
4672
4673 while (i < len)
4674 {
4675 if (src[i] == '%' && i + 2 < len)
4676 {
4677 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4678 j++;
4679 i += 3;
4680 }
4681 else
4682 {
4683 dst[j] = src[i];
4684 i++;
4685 j++;
4686 }
4687 }
4688 dst[j] = '\0';
4689 return j;
4690}
4691
4692/*
4693 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4694 *
4695 * The OSC 7 sequence has the format of
4696 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4697 * and what VTerm provides via VTermStringFragment is
4698 * "file://HOSTNAME/CURRENT/DIR"
4699 */
4700 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004701sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004702{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004703 int offset = 7; // len of "file://" is 7
4704 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004705 char_u *new_dir;
4706
4707 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004708 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004709 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004710 ++offset;
4711 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004712 }
4713
Bram Moolenaar474ad392022-08-21 11:37:17 +01004714 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004715 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004716 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004717 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004718 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004719 }
4720
Bram Moolenaar474ad392022-08-21 11:37:17 +01004721 new_dir = alloc(gap->ga_len - offset + 1);
4722 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004723 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4724 vim_free(new_dir);
4725}
4726
4727/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004728 * Called by libvterm when it cannot recognize an OSC sequence.
4729 * We recognize a terminal API command.
4730 */
4731 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004732parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004733{
4734 term_T *term = (term_T *)user;
4735 js_read_T reader;
4736 typval_T tv;
4737 channel_T *channel = term->tl_job == NULL ? NULL
4738 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004739 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004740
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004741 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004742 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004743 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004744
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004745 // Concatenate what was received until the final piece is found.
4746 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4747 {
4748 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004749 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004750 }
4751 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004752 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004753 if (!frag.final)
4754 return 1;
4755
4756 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004757
4758 if (command == 7)
4759 {
4760 sync_shell_dir(gap);
4761 ga_clear(gap);
4762 return 1;
4763 }
4764
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004765 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004766 reader.js_fill = NULL;
4767 reader.js_used = 0;
4768 if (json_decode(&reader, &tv, 0) == OK
4769 && tv.v_type == VAR_LIST
4770 && tv.vval.v_list != NULL)
4771 {
4772 listitem_T *item = tv.vval.v_list->lv_first;
4773
4774 if (item == NULL)
4775 ch_log(channel, "Missing command");
4776 else
4777 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004778 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004779
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004780 // Make sure an invoked command doesn't delete the buffer (and the
4781 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004782 ++term->tl_buffer->b_locked;
4783
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004784 item = item->li_next;
4785 if (item == NULL)
4786 ch_log(channel, "Missing argument for %s", cmd);
4787 else if (STRCMP(cmd, "drop") == 0)
4788 handle_drop_command(item);
4789 else if (STRCMP(cmd, "call") == 0)
4790 handle_call_command(term, channel, item);
4791 else
4792 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004793 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004794 }
4795 }
4796 else
4797 ch_log(channel, "Invalid JSON received");
4798
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004799 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004800 clear_tv(&tv);
4801 return 1;
4802}
4803
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004804/*
4805 * Called by libvterm when it cannot recognize a CSI sequence.
4806 * We recognize the window position report.
4807 */
4808 static int
4809parse_csi(
4810 const char *leader UNUSED,
4811 const long args[],
4812 int argcount,
4813 const char *intermed UNUSED,
4814 char command,
4815 void *user)
4816{
4817 term_T *term = (term_T *)user;
4818 char buf[100];
4819 int len;
4820 int x = 0;
4821 int y = 0;
4822 win_T *wp;
4823
4824 // We recognize only CSI 13 t
4825 if (command != 't' || argcount != 1 || args[0] != 13)
4826 return 0; // not handled
4827
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004828 // When getting the window position is not possible or it fails it results
4829 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004830#if defined(FEAT_GUI) \
4831 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4832 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004833 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004834#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004835
4836 FOR_ALL_WINDOWS(wp)
4837 if (wp->w_buffer == term->tl_buffer)
4838 break;
4839 if (wp != NULL)
4840 {
4841#ifdef FEAT_GUI
4842 if (gui.in_use)
4843 {
4844 x += wp->w_wincol * gui.char_width;
4845 y += W_WINROW(wp) * gui.char_height;
4846 }
4847 else
4848#endif
4849 {
4850 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004851 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004852 x += wp->w_wincol * 7;
4853 y += W_WINROW(wp) * 10;
4854 }
4855 }
4856
4857 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4858 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4859 (char_u *)buf, len, NULL);
4860 return 1;
4861}
4862
Bram Moolenaard8637282020-05-20 18:41:41 +02004863static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004864 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004865 parse_csi, // csi
4866 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004867 NULL, // dcs
4868 NULL, // apc
4869 NULL, // pm
4870 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004871};
4872
4873/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004874 * Use Vim's allocation functions for vterm so profiling works.
4875 */
4876 static void *
4877vterm_malloc(size_t size, void *data UNUSED)
4878{
Bram Moolenaar88137392021-11-12 16:01:15 +00004879 // make sure that the length is not zero
4880 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004881}
4882
4883 static void
4884vterm_memfree(void *ptr, void *data UNUSED)
4885{
4886 vim_free(ptr);
4887}
4888
4889static VTermAllocatorFunctions vterm_allocator = {
4890 &vterm_malloc,
4891 &vterm_memfree
4892};
4893
4894/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004895 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004896 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004897 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004898 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004899create_vterm(term_T *term, int rows, int cols)
4900{
4901 VTerm *vterm;
4902 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004903 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004904 VTermValue value;
4905
Bram Moolenaar756ef112018-04-10 12:04:27 +02004906 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004907 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004908 if (vterm == NULL)
4909 return FAIL;
4910
4911 // Allocate screen and state here, so we can bail out if that fails.
4912 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004913 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004914 if (state == NULL || screen == NULL)
4915 {
4916 vterm_free(vterm);
4917 return FAIL;
4918 }
4919
Bram Moolenaar52acb112018-03-18 19:20:22 +01004920 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004921 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004922 vterm_set_utf8(vterm, 1);
4923
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004924 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004925
4926 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004927 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004928 &term->tl_default_color.fg,
4929 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004930
Bram Moolenaar9e587872019-05-13 20:27:23 +02004931 if (t_colors < 16)
4932 // Less than 16 colors: assume that bold means using a bright color for
4933 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004934 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4935
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004936 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004937 vterm_screen_reset(screen, 1 /* hard */);
4938
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004939 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004940 vterm_screen_enable_altscreen(screen, 1);
4941
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004942 // For unix do not use a blinking cursor. In an xterm this causes the
4943 // cursor to blink if it's blinking in the xterm.
4944 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004945#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004946 if (GetCaretBlinkTime() == INFINITE)
4947 value.boolean = 0;
4948 else
4949 value.boolean = 1;
4950#else
4951 value.boolean = 0;
4952#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004953 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004954 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004955
4956 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004957}
4958
4959/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004960 * Reset the terminal palette to its default value.
4961 */
4962 static void
4963term_reset_palette(VTerm *vterm)
4964{
4965 VTermState *state = vterm_obtain_state(vterm);
4966 int index;
4967
4968 for (index = 0; index < 16; index++)
4969 {
4970 VTermColor color;
4971
4972 color.type = VTERM_COLOR_INDEXED;
4973 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4974 &color.index);
4975 // The first valid index starts at 1.
4976 color.index -= 1;
4977
4978 vterm_state_set_palette_color(state, index, &color);
4979 }
4980}
4981
4982 static void
4983term_update_palette(term_T *term)
4984{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004985#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004986 if (term_use_palette()
4987 && (term->tl_palette != NULL
4988 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004989 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004990 {
4991 if (term->tl_palette != NULL)
4992 set_vterm_palette(term->tl_vterm, term->tl_palette);
4993 else
4994 init_vterm_ansi_colors(term->tl_vterm);
4995 }
4996 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004997#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004998 term_reset_palette(term->tl_vterm);
4999}
5000
5001/*
5002 * Called when option 'termguicolors' is changed.
5003 */
5004 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005005term_update_palette_all(void)
LemonBoyb2b3acb2022-05-20 10:10:34 +01005006{
5007 term_T *term;
5008
5009 FOR_ALL_TERMS(term)
5010 {
5011 if (term->tl_vterm == NULL)
5012 continue;
5013 term_update_palette(term);
5014 }
5015}
5016
5017/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005018 * Called when option 'background' or 'termguicolors' was set,
5019 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02005020 */
5021 void
5022term_update_colors_all(void)
5023{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005024 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02005025
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005026 FOR_ALL_TERMS(term)
5027 {
5028 if (term->tl_vterm == NULL)
5029 continue;
5030 init_default_colors(term);
5031 vterm_state_set_default_colors(
5032 vterm_obtain_state(term->tl_vterm),
5033 &term->tl_default_color.fg,
5034 &term->tl_default_color.bg);
5035 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005036}
5037
5038/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005039 * Return the text to show for the buffer name and status.
5040 */
5041 char_u *
5042term_get_status_text(term_T *term)
5043{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005044 if (term->tl_status_text != NULL)
5045 return term->tl_status_text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005046
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005047 char_u *txt;
5048 size_t len;
5049 char_u *fname;
5050
5051 if (term->tl_normal_mode)
5052 {
5053 if (term_job_running(term))
5054 txt = (char_u *)_("Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005055 else
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005056 txt = (char_u *)_("Terminal-finished");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005057 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005058 else if (term->tl_title != NULL)
5059 txt = term->tl_title;
5060 else if (term_none_open(term))
5061 txt = (char_u *)_("active");
5062 else if (term_job_running(term))
5063 txt = (char_u *)_("running");
5064 else
5065 txt = (char_u *)_("finished");
5066 fname = buf_get_fname(term->tl_buffer);
5067 len = 9 + STRLEN(fname) + STRLEN(txt);
5068 term->tl_status_text = alloc(len);
5069 if (term->tl_status_text != NULL)
5070 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
5071 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005072 return term->tl_status_text;
5073}
5074
5075/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00005076 * Clear the cached value of the status text.
5077 */
5078 void
5079term_clear_status_text(term_T *term)
5080{
5081 VIM_CLEAR(term->tl_status_text);
5082}
5083
5084/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005085 * Mark references in jobs of terminals.
5086 */
5087 int
5088set_ref_in_term(int copyID)
5089{
5090 int abort = FALSE;
5091 term_T *term;
5092 typval_T tv;
5093
Bram Moolenaar75a1a942019-06-20 03:45:36 +02005094 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005095 if (term->tl_job != NULL)
5096 {
5097 tv.v_type = VAR_JOB;
5098 tv.vval.v_job = term->tl_job;
Yegappan Lakshmanan9cb865e2025-03-23 16:42:16 +01005099 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005100 }
5101 return abort;
5102}
5103
5104/*
5105 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005106 * Returns NULL when the buffer is not for a terminal window and logs a message
5107 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005108 */
5109 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005110term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005111{
5112 buf_T *buf;
5113
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005114 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01005115 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005116 --emsg_off;
5117 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005118 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01005119 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005120 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005121 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005122 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005123 return buf;
5124}
5125
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005126 static void
5127clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005128{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005129 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005130 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
5131 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005132}
5133
5134 static void
5135dump_term_color(FILE *fd, VTermColor *color)
5136{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005137 int index;
5138
5139 if (VTERM_COLOR_IS_INDEXED(color))
5140 index = color->index + 1;
5141 else if (color->type == 0)
5142 // use RGB values
5143 index = 255;
5144 else
5145 // default color
5146 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005147 fprintf(fd, "%02x%02x%02x%d",
5148 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005149 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005150}
5151
5152/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005153 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01005154 *
5155 * Each screen cell in full is:
5156 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5157 * {characters} is a space for an empty cell
5158 * For a double-width character "+" is changed to "*" and the next cell is
5159 * skipped.
5160 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5161 * when "&" use the same as the previous cell.
5162 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5163 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5164 * {color-idx} is a number from 0 to 255
5165 *
5166 * Screen cell with same width, attributes and color as the previous one:
5167 * |{characters}
5168 *
5169 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5170 *
5171 * Repeating the previous screen cell:
5172 * @{count}
5173 */
5174 void
5175f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5176{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005177 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005178 term_T *term;
5179 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005180 int max_height = 0;
5181 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005182 stat_T st;
5183 FILE *fd;
5184 VTermPos pos;
5185 VTermScreen *screen;
5186 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005187 VTermState *state;
5188 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005189
5190 if (check_restricted() || check_secure())
5191 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005192
5193 if (in_vim9script()
5194 && (check_for_buffer_arg(argvars, 0) == FAIL
5195 || check_for_string_arg(argvars, 1) == FAIL
5196 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5197 return;
5198
5199 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005200 if (buf == NULL)
5201 return;
5202 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005203 if (term->tl_vterm == NULL)
5204 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005205 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005206 return;
5207 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005208
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005209 if (argvars[2].v_type != VAR_UNKNOWN)
5210 {
5211 dict_T *d;
5212
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005213 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005214 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005215 d = argvars[2].vval.v_dict;
5216 if (d != NULL)
5217 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005218 max_height = dict_get_number(d, "rows");
5219 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005220 }
5221 }
5222
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005223 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005224 if (fname == NULL)
5225 return;
5226 if (mch_stat((char *)fname, &st) >= 0)
5227 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005228 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005229 return;
5230 }
5231
Bram Moolenaard96ff162018-02-18 22:13:29 +01005232 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5233 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005234 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005235 return;
5236 }
5237
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005238 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005239
5240 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005241 state = vterm_obtain_state(term->tl_vterm);
5242 vterm_state_get_cursorpos(state, &cursor_pos);
5243
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005244 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5245 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005246 {
5247 int repeat = 0;
5248
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005249 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5250 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005251 {
5252 VTermScreenCell cell;
5253 int same_attr;
5254 int same_chars = TRUE;
5255 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005256 int is_cursor_pos = (pos.col == cursor_pos.col
5257 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005258
5259 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005260 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005261
5262 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5263 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005264 int c = cell.chars[i];
5265 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005266 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005267
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005268 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005269 if (i == 0)
5270 {
5271 c = (c == NUL) ? ' ' : c;
5272 pc = (pc == NUL) ? ' ' : pc;
5273 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005274 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005275 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005276 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005277 break;
5278 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005279 same_attr = vtermAttr2hl(&cell.attrs)
5280 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005281 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5282 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005283 if (same_chars && cell.width == prev_cell.width && same_attr
5284 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005285 {
5286 ++repeat;
5287 }
5288 else
5289 {
5290 if (repeat > 0)
5291 {
5292 fprintf(fd, "@%d", repeat);
5293 repeat = 0;
5294 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005295 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005296
5297 if (cell.chars[0] == NUL)
5298 fputs(" ", fd);
5299 else
5300 {
5301 char_u charbuf[10];
5302 int len;
5303
5304 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5305 && cell.chars[i] != NUL; ++i)
5306 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005307 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005308 fwrite(charbuf, len, 1, fd);
5309 }
5310 }
5311
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005312 // When only the characters differ we don't write anything, the
5313 // following "|", "@" or NL will indicate using the same
5314 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005315 if (cell.width != prev_cell.width || !same_attr)
5316 {
5317 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005318 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005319 else
5320 fputs("+", fd);
5321
5322 if (same_attr)
5323 {
5324 fputs("&", fd);
5325 }
5326 else
5327 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005328 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005329 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005330 fputs("&", fd);
5331 else
5332 {
5333 fputs("#", fd);
5334 dump_term_color(fd, &cell.fg);
5335 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005336 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005337 fputs("&", fd);
5338 else
5339 {
5340 fputs("#", fd);
5341 dump_term_color(fd, &cell.bg);
5342 }
5343 }
5344 }
5345
5346 prev_cell = cell;
5347 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005348
5349 if (cell.width == 2)
5350 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005351 }
5352 if (repeat > 0)
5353 fprintf(fd, "@%d", repeat);
5354 fputs("\n", fd);
5355 }
5356
5357 fclose(fd);
5358}
5359
5360/*
5361 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5362 */
5363 static void
5364dump_is_corrupt(garray_T *gap)
5365{
5366 ga_concat(gap, (char_u *)"CORRUPT");
5367}
5368
5369 static void
5370append_cell(garray_T *gap, cellattr_T *cell)
5371{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005372 if (ga_grow(gap, 1) == FAIL)
5373 return;
5374
5375 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5376 ++gap->ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005377}
5378
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005379 static void
5380clear_cellattr(cellattr_T *cell)
5381{
5382 CLEAR_FIELD(*cell);
5383 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5384 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5385}
5386
Bram Moolenaard96ff162018-02-18 22:13:29 +01005387/*
5388 * Read the dump file from "fd" and append lines to the current buffer.
5389 * Return the cell width of the longest line.
5390 */
5391 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005392read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005393{
5394 int c;
5395 garray_T ga_text;
5396 garray_T ga_cell;
5397 char_u *prev_char = NULL;
5398 int attr = 0;
5399 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005400 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005401 term_T *term = curbuf->b_term;
5402 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005403 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005404
5405 ga_init2(&ga_text, 1, 90);
5406 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005407 clear_cellattr(&cell);
5408 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005409 cursor_pos->row = -1;
5410 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005411
5412 c = fgetc(fd);
5413 for (;;)
5414 {
5415 if (c == EOF)
5416 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005417 if (c == '\r')
5418 {
5419 // DOS line endings? Ignore.
5420 c = fgetc(fd);
5421 }
5422 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005423 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005424 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005425 if (ga_text.ga_data == NULL)
5426 dump_is_corrupt(&ga_text);
5427 if (ga_grow(&term->tl_scrollback, 1) == OK)
5428 {
5429 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5430 + term->tl_scrollback.ga_len;
5431
5432 if (max_cells < ga_cell.ga_len)
5433 max_cells = ga_cell.ga_len;
5434 line->sb_cols = ga_cell.ga_len;
5435 line->sb_cells = ga_cell.ga_data;
5436 line->sb_fill_attr = term->tl_default_color;
5437 ++term->tl_scrollback.ga_len;
5438 ga_init(&ga_cell);
5439
5440 ga_append(&ga_text, NUL);
5441 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5442 ga_text.ga_len, FALSE);
5443 }
5444 else
5445 ga_clear(&ga_cell);
5446 ga_text.ga_len = 0;
5447
5448 c = fgetc(fd);
5449 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005450 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005451 {
5452 int prev_len = ga_text.ga_len;
5453
Bram Moolenaar9271d052018-02-25 21:39:46 +01005454 if (c == '>')
5455 {
5456 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005457 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005458 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5459 cursor_pos->col = ga_cell.ga_len;
5460 }
5461
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005462 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005463 c = fgetc(fd);
5464 if (c != EOF)
5465 ga_append(&ga_text, c);
5466 for (;;)
5467 {
5468 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005469 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005470 || c == EOF || c == '\n')
5471 break;
5472 ga_append(&ga_text, c);
5473 }
5474
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005475 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005476 vim_free(prev_char);
5477 if (ga_text.ga_data != NULL)
5478 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5479 ga_text.ga_len - prev_len);
5480
Bram Moolenaar9271d052018-02-25 21:39:46 +01005481 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005482 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005483 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005484 }
5485 else if (c == '+' || c == '*')
5486 {
5487 int is_bg;
5488
5489 cell.width = c == '+' ? 1 : 2;
5490
5491 c = fgetc(fd);
5492 if (c == '&')
5493 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005494 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005495 c = fgetc(fd);
5496 }
Keith Thompson184f71c2024-01-04 21:19:04 +01005497 else if (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005498 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005499 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005500 attr = 0;
Keith Thompson184f71c2024-01-04 21:19:04 +01005501 while (SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005502 {
5503 attr = attr * 10 + (c - '0');
5504 c = fgetc(fd);
5505 }
5506 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005507
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005508 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005509 for (is_bg = 0; is_bg <= 1; ++is_bg)
5510 {
5511 if (c == '&')
5512 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005513 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005514 c = fgetc(fd);
5515 }
5516 else if (c == '#')
5517 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005518 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005519
5520 c = fgetc(fd);
5521 red = hex2nr(c);
5522 c = fgetc(fd);
5523 red = (red << 4) + hex2nr(c);
5524 c = fgetc(fd);
5525 green = hex2nr(c);
5526 c = fgetc(fd);
5527 green = (green << 4) + hex2nr(c);
5528 c = fgetc(fd);
5529 blue = hex2nr(c);
5530 c = fgetc(fd);
5531 blue = (blue << 4) + hex2nr(c);
5532 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005533 if (!SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005534 dump_is_corrupt(&ga_text);
Keith Thompson184f71c2024-01-04 21:19:04 +01005535 while (SAFE_isdigit(c))
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005536 {
5537 index = index * 10 + (c - '0');
5538 c = fgetc(fd);
5539 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005540 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005541 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005542 type = VTERM_COLOR_RGB;
5543 if (index == 0)
5544 {
5545 if (is_bg)
5546 type |= VTERM_COLOR_DEFAULT_BG;
5547 else
5548 type |= VTERM_COLOR_DEFAULT_FG;
5549 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005550 }
5551 else
5552 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005553 type = VTERM_COLOR_INDEXED;
5554 index -= 1;
5555 }
5556 if (is_bg)
5557 {
5558 cell.bg.type = type;
5559 cell.bg.red = red;
5560 cell.bg.green = green;
5561 cell.bg.blue = blue;
5562 cell.bg.index = index;
5563 }
5564 else
5565 {
5566 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005567 cell.fg.red = red;
5568 cell.fg.green = green;
5569 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005570 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005571 }
5572 }
5573 else
5574 dump_is_corrupt(&ga_text);
5575 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005576 }
5577 else
5578 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005579 }
5580 else
5581 dump_is_corrupt(&ga_text);
5582
5583 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005584 if (cell.width == 2)
5585 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005586 }
5587 else if (c == '@')
5588 {
5589 if (prev_char == NULL)
5590 dump_is_corrupt(&ga_text);
5591 else
5592 {
5593 int count = 0;
5594
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005595 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005596 for (;;)
5597 {
5598 c = fgetc(fd);
Keith Thompson184f71c2024-01-04 21:19:04 +01005599 if (!SAFE_isdigit(c))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005600 break;
5601 count = count * 10 + (c - '0');
5602 }
5603
5604 while (count-- > 0)
5605 {
5606 ga_concat(&ga_text, prev_char);
5607 append_cell(&ga_cell, &cell);
5608 }
5609 }
5610 }
5611 else
5612 {
5613 dump_is_corrupt(&ga_text);
5614 c = fgetc(fd);
5615 }
5616 }
5617
5618 if (ga_text.ga_len > 0)
5619 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005620 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005621 dump_is_corrupt(&ga_text);
5622 ga_append(&ga_text, NUL);
5623 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5624 ga_text.ga_len, FALSE);
5625 }
5626
5627 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005628 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005629 vim_free(prev_char);
5630
5631 return max_cells;
5632}
5633
5634/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005635 * Return an allocated string with at least "text_width" "=" characters and
5636 * "fname" inserted in the middle.
5637 */
5638 static char_u *
5639get_separator(int text_width, char_u *fname)
5640{
5641 int width = MAX(text_width, curwin->w_width);
5642 char_u *textline;
5643 int fname_size;
5644 char_u *p = fname;
5645 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005646 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005647
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005648 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005649 if (textline == NULL)
5650 return NULL;
5651
5652 fname_size = vim_strsize(fname);
5653 if (fname_size < width - 8)
5654 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005655 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005656 width = MAX(text_width, fname_size + 8);
5657 }
5658 else if (fname_size > width - 8)
5659 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005660 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005661 p = gettail(fname);
5662 fname_size = vim_strsize(p);
5663 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005664 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005665 while (fname_size > width - 8)
5666 {
5667 p += (*mb_ptr2len)(p);
5668 fname_size = vim_strsize(p);
5669 }
5670
5671 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5672 textline[i] = '=';
5673 textline[i++] = ' ';
5674
5675 STRCPY(textline + i, p);
5676 off = STRLEN(textline);
5677 textline[off] = ' ';
5678 for (i = 1; i < (width - fname_size) / 2; ++i)
5679 textline[off + i] = '=';
5680 textline[off + i] = NUL;
5681
5682 return textline;
5683}
5684
5685/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005686 * Common for "term_dumpdiff()" and "term_dumpload()".
5687 */
5688 static void
5689term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5690{
5691 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005692 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005693 char_u buf1[NUMBUFLEN];
5694 char_u buf2[NUMBUFLEN];
5695 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005696 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005697 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005698 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005699 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005700 char_u *textline = NULL;
5701
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005702 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005703 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005704 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005705 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005706 if (fname1 == NULL || (do_diff && fname2 == NULL))
5707 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005708 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005709 return;
5710 }
5711 fd1 = mch_fopen((char *)fname1, READBIN);
5712 if (fd1 == NULL)
5713 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005714 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005715 return;
5716 }
5717 if (do_diff)
5718 {
5719 fd2 = mch_fopen((char *)fname2, READBIN);
5720 if (fd2 == NULL)
5721 {
5722 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005723 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005724 return;
5725 }
5726 }
5727
5728 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005729 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5730 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5731 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5732 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5733 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005734
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005735 if (opt.jo_term_name == NULL)
5736 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005737 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005738
Bram Moolenaar51e14382019-05-25 20:21:28 +02005739 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005740 if (fname_tofree != NULL)
5741 {
5742 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5743 opt.jo_term_name = fname_tofree;
5744 }
5745 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005746
Bram Moolenaar87abab92019-06-03 21:14:59 +02005747 if (opt.jo_bufnr_buf != NULL)
5748 {
5749 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5750
5751 // With "bufnr" argument: enter the window with this buffer and make it
5752 // empty.
5753 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005754 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005755 else
5756 {
5757 buf = curbuf;
5758 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005759 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005760 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005761 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005762 }
5763 }
5764 else
5765 // Create a new terminal window.
5766 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5767
Bram Moolenaard96ff162018-02-18 22:13:29 +01005768 if (buf != NULL && buf->b_term != NULL)
5769 {
5770 int i;
5771 linenr_T bot_lnum;
5772 linenr_T lnum;
5773 term_T *term = buf->b_term;
5774 int width;
5775 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005776 VTermPos cursor_pos1;
5777 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005778
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005779 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005780
Bram Moolenaard96ff162018-02-18 22:13:29 +01005781 rettv->vval.v_number = buf->b_fnum;
5782
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005783 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005784 width = read_dump_file(fd1, &cursor_pos1);
5785
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005786 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005787 if (cursor_pos1.row >= 0)
5788 {
5789 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5790 coladvance(cursor_pos1.col);
5791 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005792
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005793 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005794 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005795
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005796 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005797 if (!do_diff)
5798 goto theend;
5799
5800 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5801
Bram Moolenaar4a696342018-04-05 18:45:26 +02005802 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005803 if (textline == NULL)
5804 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005805 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5806 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5807 vim_free(textline);
5808
5809 textline = get_separator(width, fname2);
5810 if (textline == NULL)
5811 goto theend;
5812 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5813 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005814 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005815
5816 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005817 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005818 if (width2 > width)
5819 {
5820 vim_free(textline);
5821 textline = alloc(width2 + 1);
5822 if (textline == NULL)
5823 goto theend;
5824 width = width2;
5825 textline[width] = NUL;
5826 }
5827 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5828
5829 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5830 {
5831 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5832 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005833 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005834 for (i = 0; i < width; ++i)
5835 textline[i] = '-';
5836 }
5837 else
5838 {
5839 char_u *line1;
5840 char_u *line2;
5841 char_u *p1;
5842 char_u *p2;
5843 int col;
5844 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5845 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5846 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5847 ->sb_cells;
5848
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005849 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005850 line1 = vim_strsave(ml_get(lnum));
5851 if (line1 == NULL)
5852 break;
5853 p1 = line1;
5854
5855 line2 = ml_get(lnum + bot_lnum);
5856 p2 = line2;
5857 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5858 {
5859 int len1 = utfc_ptr2len(p1);
5860 int len2 = utfc_ptr2len(p2);
5861
5862 textline[col] = ' ';
5863 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005864 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005865 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005866 else if (lnum == cursor_pos1.row + 1
5867 && col == cursor_pos1.col
5868 && (cursor_pos1.row != cursor_pos2.row
5869 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005870 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005871 textline[col] = '>';
5872 else if (lnum == cursor_pos2.row + 1
5873 && col == cursor_pos2.col
5874 && (cursor_pos1.row != cursor_pos2.row
5875 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005876 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005877 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005878 else if (cellattr1 != NULL && cellattr2 != NULL)
5879 {
5880 if ((cellattr1 + col)->width
5881 != (cellattr2 + col)->width)
5882 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005883 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005884 &(cellattr2 + col)->fg))
5885 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005886 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005887 &(cellattr2 + col)->bg))
5888 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005889 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5890 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005891 textline[col] = 'a';
5892 }
5893 p1 += len1;
5894 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005895 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005896 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005897
5898 while (col < width)
5899 {
5900 if (*p1 == NUL && *p2 == NUL)
5901 textline[col] = '?';
5902 else if (*p1 == NUL)
5903 {
5904 textline[col] = '+';
5905 p2 += utfc_ptr2len(p2);
5906 }
5907 else
5908 {
5909 textline[col] = '-';
5910 p1 += utfc_ptr2len(p1);
5911 }
5912 ++col;
5913 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005914
5915 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005916 }
5917 if (add_empty_scrollback(term, &term->tl_default_color,
5918 term->tl_top_diff_rows) == OK)
5919 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5920 ++bot_lnum;
5921 }
5922
5923 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5924 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005925 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005926 for (i = 0; i < width; ++i)
5927 textline[i] = '+';
5928 if (add_empty_scrollback(term, &term->tl_default_color,
5929 term->tl_top_diff_rows) == OK)
5930 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5931 ++lnum;
5932 ++bot_lnum;
5933 }
5934
5935 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005936
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005937 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005938 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005939 }
5940
5941theend:
5942 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005943 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005944 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005945 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005946 fclose(fd2);
5947}
5948
5949/*
5950 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5951 * bottom files.
5952 * Return FAIL when this is not possible.
5953 */
5954 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005955term_swap_diff(void)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005956{
5957 term_T *term = curbuf->b_term;
5958 linenr_T line_count;
5959 linenr_T top_rows;
5960 linenr_T bot_rows;
5961 linenr_T bot_start;
5962 linenr_T lnum;
5963 char_u *p;
5964 sb_line_T *sb_line;
5965
5966 if (term == NULL
5967 || !term_is_finished(curbuf)
5968 || term->tl_top_diff_rows == 0
5969 || term->tl_scrollback.ga_len == 0)
5970 return FAIL;
5971
5972 line_count = curbuf->b_ml.ml_line_count;
5973 top_rows = term->tl_top_diff_rows;
5974 bot_rows = term->tl_bot_diff_rows;
5975 bot_start = line_count - bot_rows;
5976 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5977
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005978 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005979 for (lnum = 1; lnum <= top_rows; ++lnum)
5980 {
5981 p = vim_strsave(ml_get(1));
5982 if (p == NULL)
5983 return OK;
5984 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005985 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005986 vim_free(p);
5987 }
5988
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005989 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005990 for (lnum = 1; lnum <= bot_rows; ++lnum)
5991 {
5992 p = vim_strsave(ml_get(bot_start + lnum));
5993 if (p == NULL)
5994 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005995 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005996 ml_append(lnum - 1, p, 0, FALSE);
5997 vim_free(p);
5998 }
5999
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01006000 // move top title to bottom
6001 p = vim_strsave(ml_get(bot_rows + 1));
6002 if (p == NULL)
6003 return OK;
6004 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02006005 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01006006 vim_free(p);
6007
6008 // move bottom title to top
6009 p = vim_strsave(ml_get(line_count - top_rows));
6010 if (p == NULL)
6011 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02006012 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01006013 ml_append(bot_rows, p, 0, FALSE);
6014 vim_free(p);
6015
Bram Moolenaard96ff162018-02-18 22:13:29 +01006016 if (top_rows == bot_rows)
6017 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006018 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01006019 for (lnum = 0; lnum < top_rows; ++lnum)
6020 {
6021 sb_line_T temp;
6022
6023 temp = *(sb_line + lnum);
6024 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
6025 *(sb_line + bot_start + lnum) = temp;
6026 }
6027 }
6028 else
6029 {
6030 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006031 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006032
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006033 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01006034 if (temp != NULL)
6035 {
6036 mch_memmove(temp, term->tl_scrollback.ga_data, size);
6037 mch_memmove(term->tl_scrollback.ga_data,
6038 temp + bot_start,
6039 sizeof(sb_line_T) * bot_rows);
6040 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
6041 temp + top_rows,
6042 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
6043 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
6044 + line_count - top_rows,
6045 temp,
6046 sizeof(sb_line_T) * top_rows);
6047 vim_free(temp);
6048 }
6049 }
6050
6051 term->tl_top_diff_rows = bot_rows;
6052 term->tl_bot_diff_rows = top_rows;
6053
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006054 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006055 return OK;
6056}
6057
6058/*
6059 * "term_dumpdiff(filename, filename, options)" function
6060 */
6061 void
6062f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
6063{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02006064 if (in_vim9script()
6065 && (check_for_string_arg(argvars, 0) == FAIL
6066 || check_for_string_arg(argvars, 1) == FAIL
6067 || check_for_opt_dict_arg(argvars, 2) == FAIL))
6068 return;
6069
Bram Moolenaard96ff162018-02-18 22:13:29 +01006070 term_load_dump(argvars, rettv, TRUE);
6071}
6072
6073/*
6074 * "term_dumpload(filename, options)" function
6075 */
6076 void
6077f_term_dumpload(typval_T *argvars, typval_T *rettv)
6078{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006079 if (in_vim9script()
6080 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02006081 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006082 return;
6083
Bram Moolenaard96ff162018-02-18 22:13:29 +01006084 term_load_dump(argvars, rettv, FALSE);
6085}
6086
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006087/*
6088 * "term_getaltscreen(buf)" function
6089 */
6090 void
6091f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
6092{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006093 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006094
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006095 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6096 return;
6097
6098 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006099 if (buf == NULL)
6100 return;
6101 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
6102}
6103
6104/*
6105 * "term_getattr(attr, name)" function
6106 */
6107 void
6108f_term_getattr(typval_T *argvars, typval_T *rettv)
6109{
6110 int attr;
6111 size_t i;
6112 char_u *name;
6113
6114 static struct {
6115 char *name;
6116 int attr;
6117 } attrs[] = {
6118 {"bold", HL_BOLD},
6119 {"italic", HL_ITALIC},
6120 {"underline", HL_UNDERLINE},
6121 {"strike", HL_STRIKETHROUGH},
6122 {"reverse", HL_INVERSE},
6123 };
6124
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02006125 if (in_vim9script()
6126 && (check_for_number_arg(argvars, 0) == FAIL
6127 || check_for_string_arg(argvars, 1) == FAIL))
6128 return;
6129
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006130 attr = tv_get_number(&argvars[0]);
6131 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006132 if (name == NULL)
6133 return;
6134
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02006135 if (attr > HL_ALL)
6136 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02006137 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006138 if (STRCMP(name, attrs[i].name) == 0)
6139 {
6140 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
6141 break;
6142 }
6143}
6144
6145/*
6146 * "term_getcursor(buf)" function
6147 */
6148 void
6149f_term_getcursor(typval_T *argvars, typval_T *rettv)
6150{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006151 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006152 term_T *term;
6153 list_T *l;
6154 dict_T *d;
6155
6156 if (rettv_list_alloc(rettv) == FAIL)
6157 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006158
6159 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6160 return;
6161
6162 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006163 if (buf == NULL)
6164 return;
6165 term = buf->b_term;
6166
6167 l = rettv->vval.v_list;
6168 list_append_number(l, term->tl_cursor_pos.row + 1);
6169 list_append_number(l, term->tl_cursor_pos.col + 1);
6170
6171 d = dict_alloc();
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00006172 if (d == NULL)
6173 return;
6174
6175 dict_add_number(d, "visible", term->tl_cursor_visible);
6176 dict_add_number(d, "blink", blink_state_is_inverted()
6177 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6178 dict_add_number(d, "shape", term->tl_cursor_shape);
6179 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
6180 list_append_dict(l, d);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006181}
6182
6183/*
6184 * "term_getjob(buf)" function
6185 */
6186 void
6187f_term_getjob(typval_T *argvars, typval_T *rettv)
6188{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006189 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006190
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006191 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6192 return;
6193
6194 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006195 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006196 {
Ernie Raela78eb252024-06-13 17:24:54 +02006197 if (in_vim9script())
6198 {
6199 rettv->v_type = VAR_JOB;
6200 rettv->vval.v_job = NULL;
6201 }
6202 else
6203 {
6204 rettv->v_type = VAR_SPECIAL;
6205 rettv->vval.v_number = VVAL_NULL;
6206 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006207 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006208 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006209
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006210 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006211 rettv->vval.v_job = buf->b_term->tl_job;
6212 if (rettv->vval.v_job != NULL)
6213 ++rettv->vval.v_job->jv_refcount;
6214}
6215
6216 static int
6217get_row_number(typval_T *tv, term_T *term)
6218{
6219 if (tv->v_type == VAR_STRING
6220 && tv->vval.v_string != NULL
6221 && STRCMP(tv->vval.v_string, ".") == 0)
6222 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006223 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006224}
6225
6226/*
6227 * "term_getline(buf, row)" function
6228 */
6229 void
6230f_term_getline(typval_T *argvars, typval_T *rettv)
6231{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006232 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006233 term_T *term;
6234 int row;
6235
6236 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006237
6238 if (in_vim9script()
6239 && (check_for_buffer_arg(argvars, 0) == FAIL
6240 || check_for_lnum_arg(argvars, 1) == FAIL))
6241 return;
6242
6243 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006244 if (buf == NULL)
6245 return;
6246 term = buf->b_term;
6247 row = get_row_number(&argvars[1], term);
6248
6249 if (term->tl_vterm == NULL)
6250 {
6251 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6252
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006253 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006254 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6255 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6256 }
6257 else
6258 {
6259 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6260 VTermRect rect;
6261 int len;
6262 char_u *p;
6263
6264 if (row < 0 || row >= term->tl_rows)
6265 return;
6266 len = term->tl_cols * MB_MAXBYTES + 1;
6267 p = alloc(len);
6268 if (p == NULL)
6269 return;
6270 rettv->vval.v_string = p;
6271
6272 rect.start_col = 0;
6273 rect.end_col = term->tl_cols;
6274 rect.start_row = row;
6275 rect.end_row = row + 1;
6276 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6277 }
6278}
6279
6280/*
6281 * "term_getscrolled(buf)" function
6282 */
6283 void
6284f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6285{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006286 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006287
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006288 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6289 return;
6290
6291 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006292 if (buf == NULL)
6293 return;
6294 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6295}
6296
6297/*
6298 * "term_getsize(buf)" function
6299 */
6300 void
6301f_term_getsize(typval_T *argvars, typval_T *rettv)
6302{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006303 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006304 list_T *l;
6305
6306 if (rettv_list_alloc(rettv) == FAIL)
6307 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006308
6309 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6310 return;
6311
6312 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006313 if (buf == NULL)
6314 return;
6315
6316 l = rettv->vval.v_list;
6317 list_append_number(l, buf->b_term->tl_rows);
6318 list_append_number(l, buf->b_term->tl_cols);
6319}
6320
6321/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006322 * "term_setsize(buf, rows, cols)" function
6323 */
6324 void
Dominique Pellé0268ff32024-07-28 21:12:20 +02006325f_term_setsize(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006326{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006327 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006328 term_T *term;
6329 varnumber_T rows, cols;
6330
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006331 if (in_vim9script()
6332 && (check_for_buffer_arg(argvars, 0) == FAIL
6333 || check_for_number_arg(argvars, 1) == FAIL
6334 || check_for_number_arg(argvars, 2) == FAIL))
6335 return;
6336
6337 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006338 if (buf == NULL)
6339 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006340 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006341 return;
6342 }
6343 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006344 return;
6345 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006346 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006347 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006348 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006349 cols = cols <= 0 ? term->tl_cols : cols;
6350 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006351 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006352
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006353 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006354 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6355 term_report_winsize(term, term->tl_rows, term->tl_cols);
6356}
6357
6358/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006359 * "term_getstatus(buf)" function
6360 */
6361 void
6362f_term_getstatus(typval_T *argvars, typval_T *rettv)
6363{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006364 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006365 term_T *term;
6366 char_u val[100];
6367
6368 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006369
6370 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6371 return;
6372
6373 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006374 if (buf == NULL)
6375 return;
6376 term = buf->b_term;
6377
6378 if (term_job_running(term))
6379 STRCPY(val, "running");
6380 else
6381 STRCPY(val, "finished");
6382 if (term->tl_normal_mode)
6383 STRCAT(val, ",normal");
6384 rettv->vval.v_string = vim_strsave(val);
6385}
6386
6387/*
6388 * "term_gettitle(buf)" function
6389 */
6390 void
6391f_term_gettitle(typval_T *argvars, typval_T *rettv)
6392{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006393 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006394
6395 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006396
6397 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6398 return;
6399
6400 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006401 if (buf == NULL)
6402 return;
6403
6404 if (buf->b_term->tl_title != NULL)
6405 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6406}
6407
6408/*
6409 * "term_gettty(buf)" function
6410 */
6411 void
6412f_term_gettty(typval_T *argvars, typval_T *rettv)
6413{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006414 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006415 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006416 int num = 0;
6417
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006418 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006419 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006420 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6421 return;
6422
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006423 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006424 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006425 if (buf == NULL)
6426 return;
6427 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006428 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006429
6430 switch (num)
6431 {
6432 case 0:
6433 if (buf->b_term->tl_job != NULL)
6434 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006435 break;
6436 case 1:
6437 if (buf->b_term->tl_job != NULL)
6438 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006439 break;
6440 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006441 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006442 return;
6443 }
6444 if (p != NULL)
6445 rettv->vval.v_string = vim_strsave(p);
6446}
6447
6448/*
6449 * "term_list()" function
6450 */
6451 void
6452f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6453{
6454 term_T *tp;
6455 list_T *l;
6456
6457 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6458 return;
6459
6460 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006461 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006462 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006463 if (list_append_number(l,
6464 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6465 return;
6466}
6467
6468/*
6469 * "term_scrape(buf, row)" function
6470 */
6471 void
6472f_term_scrape(typval_T *argvars, typval_T *rettv)
6473{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006474 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006475 VTermScreen *screen = NULL;
6476 VTermPos pos;
6477 list_T *l;
6478 term_T *term;
6479 char_u *p;
6480 sb_line_T *line;
6481
6482 if (rettv_list_alloc(rettv) == FAIL)
6483 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006484
6485 if (in_vim9script()
6486 && (check_for_buffer_arg(argvars, 0) == FAIL
6487 || check_for_lnum_arg(argvars, 1) == FAIL))
6488 return;
6489
6490 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006491 if (buf == NULL)
6492 return;
6493 term = buf->b_term;
6494
6495 l = rettv->vval.v_list;
6496 pos.row = get_row_number(&argvars[1], term);
6497
6498 if (term->tl_vterm != NULL)
6499 {
6500 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006501 if (screen == NULL) // can't really happen
6502 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006503 p = NULL;
6504 line = NULL;
6505 }
6506 else
6507 {
6508 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6509
6510 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6511 return;
6512 p = ml_get_buf(buf, lnum + 1, FALSE);
6513 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6514 }
6515
6516 for (pos.col = 0; pos.col < term->tl_cols; )
6517 {
6518 dict_T *dcell;
6519 int width;
6520 VTermScreenCellAttrs attrs;
6521 VTermColor fg, bg;
6522 char_u rgb[8];
6523 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6524 int off = 0;
6525 int i;
6526
6527 if (screen == NULL)
6528 {
6529 cellattr_T *cellattr;
6530 int len;
6531
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006532 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006533 if (pos.col >= line->sb_cols)
6534 break;
6535 cellattr = line->sb_cells + pos.col;
6536 width = cellattr->width;
6537 attrs = cellattr->attrs;
6538 fg = cellattr->fg;
6539 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006540 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006541 mch_memmove(mbs, p, len);
6542 mbs[len] = NUL;
6543 p += len;
6544 }
6545 else
6546 {
6547 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006548
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006549 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6550 break;
6551 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6552 {
6553 if (cell.chars[i] == 0)
6554 break;
6555 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6556 }
6557 mbs[off] = NUL;
6558 width = cell.width;
6559 attrs = cell.attrs;
6560 fg = cell.fg;
6561 bg = cell.bg;
6562 }
6563 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006564 if (dcell == NULL)
6565 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006566 list_append_dict(l, dcell);
6567
Bram Moolenaare0be1672018-07-08 16:50:37 +02006568 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006569
6570 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6571 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006572 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006573 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6574 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006575 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006576
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006577 dict_add_number(dcell, "attr",
6578 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006579 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006580
6581 ++pos.col;
6582 if (width == 2)
6583 ++pos.col;
6584 }
6585}
6586
6587/*
6588 * "term_sendkeys(buf, keys)" function
6589 */
6590 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006591f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006592{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006593 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006594 char_u *msg;
6595 term_T *term;
6596
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006597 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006598 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006599 || check_for_string_arg(argvars, 1) == FAIL))
6600 return;
6601
6602 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006603 if (buf == NULL)
6604 return;
6605
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006606 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006607 if (msg == NULL)
6608 return;
6609 term = buf->b_term;
6610 if (term->tl_vterm == NULL)
6611 return;
6612
6613 while (*msg != NUL)
6614 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006615 int c;
6616
6617 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6618 {
6619 c = TO_SPECIAL(msg[1], msg[2]);
6620 msg += 3;
6621 }
6622 else
6623 {
6624 c = PTR2CHAR(msg);
6625 msg += MB_CPTR2LEN(msg);
6626 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006627 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006628 }
6629}
6630
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006631#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6632/*
6633 * "term_getansicolors(buf)" function
6634 */
6635 void
6636f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6637{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006638 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006639 term_T *term;
6640 VTermState *state;
6641 VTermColor color;
6642 char_u hexbuf[10];
6643 int index;
6644 list_T *list;
6645
6646 if (rettv_list_alloc(rettv) == FAIL)
6647 return;
6648
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006649 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6650 return;
6651
6652 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006653 if (buf == NULL)
6654 return;
6655 term = buf->b_term;
6656 if (term->tl_vterm == NULL)
6657 return;
6658
6659 list = rettv->vval.v_list;
6660 state = vterm_obtain_state(term->tl_vterm);
6661 for (index = 0; index < 16; index++)
6662 {
6663 vterm_state_get_palette_color(state, index, &color);
6664 sprintf((char *)hexbuf, "#%02x%02x%02x",
6665 color.red, color.green, color.blue);
6666 if (list_append_string(list, hexbuf, 7) == FAIL)
6667 return;
6668 }
6669}
6670
6671/*
6672 * "term_setansicolors(buf, list)" function
6673 */
6674 void
6675f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6676{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006677 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006678 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006679 listitem_T *li;
6680 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006681
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006682 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006683 && (check_for_buffer_arg(argvars, 0) == FAIL
6684 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006685 return;
6686
6687 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006688 if (buf == NULL)
6689 return;
6690 term = buf->b_term;
6691 if (term->tl_vterm == NULL)
6692 return;
6693
Bram Moolenaard83392a2022-09-01 12:22:46 +01006694 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006695 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006696
LemonBoyb2b3acb2022-05-20 10:10:34 +01006697 if (argvars[1].vval.v_list->lv_first == &range_list_item
6698 || argvars[1].vval.v_list->lv_len != 16)
6699 {
Bram Moolenaar23919542023-05-05 22:12:22 +01006700 semsg(_(e_invalid_value_for_argument_str), "\"colors\"");
LemonBoyb2b3acb2022-05-20 10:10:34 +01006701 return;
6702 }
6703
6704 if (term->tl_palette == NULL)
6705 term->tl_palette = ALLOC_MULT(long_u, 16);
6706 if (term->tl_palette == NULL)
6707 return;
6708
6709 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6710 {
6711 char_u *color_name;
6712 guicolor_T guicolor;
6713
6714 color_name = tv_get_string_chk(&li->li_tv);
6715 if (color_name == NULL)
6716 return;
6717
6718 guicolor = GUI_GET_COLOR(color_name);
6719 if (guicolor == INVALCOLOR)
6720 {
6721 semsg(_(e_cannot_allocate_color_str), color_name);
6722 return;
6723 }
6724
6725 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6726 }
6727
6728 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006729}
6730#endif
6731
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006732/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006733 * "term_setapi(buf, api)" function
6734 */
6735 void
6736f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6737{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006738 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006739 term_T *term;
6740 char_u *api;
6741
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006742 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006743 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006744 || check_for_string_arg(argvars, 1) == FAIL))
6745 return;
6746
6747 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006748 if (buf == NULL)
6749 return;
6750 term = buf->b_term;
6751 vim_free(term->tl_api);
6752 api = tv_get_string_chk(&argvars[1]);
6753 if (api != NULL)
6754 term->tl_api = vim_strsave(api);
6755 else
6756 term->tl_api = NULL;
6757}
6758
6759/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006760 * "term_setrestore(buf, command)" function
6761 */
6762 void
6763f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6764{
6765#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006766 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006767 term_T *term;
6768 char_u *cmd;
6769
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006770 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006771 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006772 || check_for_string_arg(argvars, 1) == FAIL))
6773 return;
6774
6775 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006776 if (buf == NULL)
6777 return;
6778 term = buf->b_term;
6779 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006780 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006781 if (cmd != NULL)
6782 term->tl_command = vim_strsave(cmd);
6783 else
6784 term->tl_command = NULL;
6785#endif
6786}
6787
6788/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006789 * "term_setkill(buf, how)" function
6790 */
6791 void
6792f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6793{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006794 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006795 term_T *term;
6796 char_u *how;
6797
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006798 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006799 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006800 || check_for_string_arg(argvars, 1) == FAIL))
6801 return;
6802
6803 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006804 if (buf == NULL)
6805 return;
6806 term = buf->b_term;
6807 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006808 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006809 if (how != NULL)
6810 term->tl_kill = vim_strsave(how);
6811 else
6812 term->tl_kill = NULL;
6813}
6814
6815/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006816 * "term_start(command, options)" function
6817 */
6818 void
6819f_term_start(typval_T *argvars, typval_T *rettv)
6820{
6821 jobopt_T opt;
6822 buf_T *buf;
6823
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006824 if (in_vim9script()
6825 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6826 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6827 return;
6828
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006829 init_job_options(&opt);
6830 if (argvars[1].v_type != VAR_UNKNOWN
6831 && get_job_options(&argvars[1], &opt,
6832 JO_TIMEOUT_ALL + JO_STOPONEXIT
6833 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6834 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6835 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6836 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006837 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006838 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006839 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006840 return;
6841
Bram Moolenaar13568252018-03-16 20:46:58 +01006842 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006843
6844 if (buf != NULL && buf->b_term != NULL)
6845 rettv->vval.v_number = buf->b_fnum;
6846}
6847
6848/*
6849 * "term_wait" function
6850 */
6851 void
6852f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6853{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006854 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006855
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006856 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006857 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006858 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006859 return;
6860
6861 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006862 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006863 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006864 if (buf->b_term->tl_job == NULL)
6865 {
6866 ch_log(NULL, "term_wait(): no job to wait for");
6867 return;
6868 }
6869 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006870 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006871 return;
6872
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006873 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006874 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006875 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6876 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006877 // The job is dead, keep reading channel I/O until the channel is
6878 // closed. buf->b_term may become NULL if the terminal was closed while
6879 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006880 ch_log(NULL, "term_wait(): waiting for channel to close");
6881 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6882 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006883 term_flush_messages();
6884
Bram Moolenaard45aa552018-05-21 22:50:29 +02006885 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006886 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006887 // If the terminal is closed when the channel is closed the
6888 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006889 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006890 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6891 // came here from a close callback, only wait one time
6892 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006893 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006894
6895 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006896 }
6897 else
6898 {
6899 long wait = 10L;
6900
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006901 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006902
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006903 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006904 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006905 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006906 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006907
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006908 // Flushing messages on channels is hopefully sufficient.
6909 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006910 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006911 }
6912}
6913
6914/*
6915 * Called when a channel has sent all the lines to a terminal.
6916 * Send a CTRL-D to mark the end of the text.
6917 */
6918 void
6919term_send_eof(channel_T *ch)
6920{
6921 term_T *term;
6922
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006923 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006924 if (term->tl_job == ch->ch_job)
6925 {
6926 if (term->tl_eof_chars != NULL)
6927 {
6928 channel_send(ch, PART_IN, term->tl_eof_chars,
6929 (int)STRLEN(term->tl_eof_chars), NULL);
6930 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6931 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006932# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006933 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006934 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006935 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6936# endif
6937 }
6938}
6939
Bram Moolenaar113e1072019-01-20 15:30:40 +01006940#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006941 job_T *
6942term_getjob(term_T *term)
6943{
6944 return term != NULL ? term->tl_job : NULL;
6945}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006946#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006947
Bram Moolenaar4f974752019-02-17 17:44:42 +01006948# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006949
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006950///////////////////////////////////////
6951// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006952#ifdef PROTO
6953typedef int COORD;
6954typedef int DWORD;
6955typedef int HANDLE;
6956typedef int *DWORD_PTR;
6957typedef int HPCON;
6958typedef int HRESULT;
6959typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006960typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006961typedef int PSIZE_T;
6962typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006963typedef int BOOL;
6964# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006965#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006966
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006967HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6968HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6969HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006970BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6971BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6972void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006973
6974 static int
6975dyn_conpty_init(int verbose)
6976{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006977 static HMODULE hKerneldll = NULL;
6978 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006979 static struct
6980 {
6981 char *name;
6982 FARPROC *ptr;
6983 } conpty_entry[] =
6984 {
6985 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6986 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6987 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6988 {"InitializeProcThreadAttributeList",
6989 (FARPROC*)&pInitializeProcThreadAttributeList},
6990 {"UpdateProcThreadAttribute",
6991 (FARPROC*)&pUpdateProcThreadAttribute},
6992 {"DeleteProcThreadAttributeList",
6993 (FARPROC*)&pDeleteProcThreadAttributeList},
6994 {NULL, NULL}
6995 };
6996
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006997 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006998 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006999 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00007000 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007001 return FAIL;
7002 }
7003
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007004 // No need to initialize twice.
7005 if (hKerneldll)
7006 return OK;
7007
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007008 hKerneldll = vimLoadLib("kernel32.dll");
7009 for (i = 0; conpty_entry[i].name != NULL
7010 && conpty_entry[i].ptr != NULL; ++i)
7011 {
7012 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
7013 conpty_entry[i].name)) == NULL)
7014 {
7015 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007016 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007017 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007018 return FAIL;
7019 }
7020 }
7021
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007022 return OK;
7023}
7024
7025 static int
7026conpty_term_and_job_init(
7027 term_T *term,
7028 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007029 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007030 jobopt_T *opt,
7031 jobopt_T *orig_opt)
7032{
7033 WCHAR *cmd_wchar = NULL;
7034 WCHAR *cmd_wchar_copy = NULL;
7035 WCHAR *cwd_wchar = NULL;
7036 WCHAR *env_wchar = NULL;
7037 channel_T *channel = NULL;
7038 job_T *job = NULL;
7039 HANDLE jo = NULL;
7040 garray_T ga_cmd, ga_env;
7041 char_u *cmd = NULL;
7042 HRESULT hr;
7043 COORD consize;
7044 SIZE_T breq;
7045 PROCESS_INFORMATION proc_info;
7046 HANDLE i_theirs = NULL;
7047 HANDLE o_theirs = NULL;
7048 HANDLE i_ours = NULL;
7049 HANDLE o_ours = NULL;
7050
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007051 ga_init2(&ga_cmd, sizeof(char*), 20);
7052 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007053
7054 if (argvar->v_type == VAR_STRING)
7055 {
7056 cmd = argvar->vval.v_string;
7057 }
7058 else if (argvar->v_type == VAR_LIST)
7059 {
7060 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
7061 goto failed;
7062 cmd = ga_cmd.ga_data;
7063 }
7064 if (cmd == NULL || *cmd == NUL)
7065 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007066 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007067 goto failed;
7068 }
7069
7070 term->tl_arg0_cmd = vim_strsave(cmd);
7071
7072 cmd_wchar = enc_to_utf16(cmd, NULL);
7073
7074 if (cmd_wchar != NULL)
7075 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007076 // Request by CreateProcessW
7077 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007078 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007079 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
7080 }
7081
7082 ga_clear(&ga_cmd);
7083 if (cmd_wchar == NULL)
7084 goto failed;
7085 if (opt->jo_cwd != NULL)
7086 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
7087
7088 win32_build_env(opt->jo_env, &ga_env, TRUE);
7089 env_wchar = ga_env.ga_data;
7090
7091 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
7092 goto failed;
7093 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
7094 goto failed;
7095
7096 consize.X = term->tl_cols;
7097 consize.Y = term->tl_rows;
7098 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
7099 &term->tl_conpty);
7100 if (FAILED(hr))
7101 goto failed;
7102
7103 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
7104
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007105 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007106 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007107 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007108 if (!term->tl_siex.lpAttributeList)
7109 goto failed;
7110 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
7111 0, &breq))
7112 goto failed;
7113 if (!pUpdateProcThreadAttribute(
7114 term->tl_siex.lpAttributeList, 0,
7115 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
7116 sizeof(HPCON), NULL, NULL))
7117 goto failed;
7118
7119 channel = add_channel();
7120 if (channel == NULL)
7121 goto failed;
7122
7123 job = job_alloc();
7124 if (job == NULL)
7125 goto failed;
7126 if (argvar->v_type == VAR_STRING)
7127 {
7128 int argc;
7129
7130 build_argv_from_string(cmd, &job->jv_argv, &argc);
7131 }
7132 else
7133 {
7134 int argc;
7135
7136 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7137 }
7138
7139 if (opt->jo_set & JO_IN_BUF)
7140 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7141
7142 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
7143 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02007144 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007145 env_wchar, cwd_wchar,
7146 &term->tl_siex.StartupInfo, &proc_info))
7147 goto failed;
7148
7149 CloseHandle(i_theirs);
7150 CloseHandle(o_theirs);
7151
7152 channel_set_pipes(channel,
7153 (sock_T)i_ours,
7154 (sock_T)o_ours,
7155 (sock_T)o_ours);
7156
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007157 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007158 channel->ch_write_text_mode = TRUE;
7159
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007160 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007161 channel->ch_anonymous_pipe = TRUE;
7162
7163 jo = CreateJobObject(NULL, NULL);
7164 if (jo == NULL)
7165 goto failed;
7166
7167 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7168 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007169 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007170 CloseHandle(jo);
7171 jo = NULL;
7172 }
7173
7174 ResumeThread(proc_info.hThread);
7175 CloseHandle(proc_info.hThread);
7176
7177 vim_free(cmd_wchar);
7178 vim_free(cmd_wchar_copy);
7179 vim_free(cwd_wchar);
7180 vim_free(env_wchar);
7181
7182 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7183 goto failed;
7184
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007185#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007186 if (term_use_palette())
7187 {
7188 if (term->tl_palette != NULL)
7189 set_vterm_palette(term->tl_vterm, term->tl_palette);
7190 else
7191 init_vterm_ansi_colors(term->tl_vterm);
7192 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007193#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007194
7195 channel_set_job(channel, job, opt);
7196 job_set_options(job, opt);
7197
7198 job->jv_channel = channel;
7199 job->jv_proc_info = proc_info;
7200 job->jv_job_object = jo;
7201 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007202 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007203 ++job->jv_refcount;
7204 term->tl_job = job;
7205
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007206 // Redirecting stdout and stderr doesn't work at the job level. Instead
7207 // open the file here and handle it in. opt->jo_io was changed in
7208 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007209 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7210 {
7211 char_u *fname = opt->jo_io_name[PART_OUT];
7212
7213 ch_log(channel, "Opening output file %s", fname);
7214 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7215 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007216 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007217 }
7218
7219 return OK;
7220
7221failed:
7222 ga_clear(&ga_cmd);
7223 ga_clear(&ga_env);
7224 vim_free(cmd_wchar);
7225 vim_free(cmd_wchar_copy);
7226 vim_free(cwd_wchar);
7227 if (channel != NULL)
7228 channel_clear(channel);
7229 if (job != NULL)
7230 {
7231 job->jv_channel = NULL;
7232 job_cleanup(job);
7233 }
7234 term->tl_job = NULL;
7235 if (jo != NULL)
7236 CloseHandle(jo);
7237
7238 if (term->tl_siex.lpAttributeList != NULL)
7239 {
7240 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7241 vim_free(term->tl_siex.lpAttributeList);
7242 }
7243 term->tl_siex.lpAttributeList = NULL;
7244 if (o_theirs != NULL)
7245 CloseHandle(o_theirs);
7246 if (o_ours != NULL)
7247 CloseHandle(o_ours);
7248 if (i_ours != NULL)
7249 CloseHandle(i_ours);
7250 if (i_theirs != NULL)
7251 CloseHandle(i_theirs);
7252 if (term->tl_conpty != NULL)
7253 pClosePseudoConsole(term->tl_conpty);
7254 term->tl_conpty = NULL;
7255 return FAIL;
7256}
7257
7258 static void
7259conpty_term_report_winsize(term_T *term, int rows, int cols)
7260{
7261 COORD consize;
7262
7263 consize.X = cols;
7264 consize.Y = rows;
7265 pResizePseudoConsole(term->tl_conpty, consize);
7266}
7267
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007268 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007269term_free_conpty(term_T *term)
7270{
7271 if (term->tl_siex.lpAttributeList != NULL)
7272 {
7273 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7274 vim_free(term->tl_siex.lpAttributeList);
7275 }
7276 term->tl_siex.lpAttributeList = NULL;
7277 if (term->tl_conpty != NULL)
7278 pClosePseudoConsole(term->tl_conpty);
7279 term->tl_conpty = NULL;
7280}
7281
7282 int
7283use_conpty(void)
7284{
7285 return has_conpty;
7286}
7287
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007288# ifndef PROTO
7289
7290#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7291#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007292#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007293
7294void* (*winpty_config_new)(UINT64, void*);
7295void* (*winpty_open)(void*, void*);
7296void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7297BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7298void (*winpty_config_set_mouse_mode)(void*, int);
7299void (*winpty_config_set_initial_size)(void*, int, int);
7300LPCWSTR (*winpty_conin_name)(void*);
7301LPCWSTR (*winpty_conout_name)(void*);
7302LPCWSTR (*winpty_conerr_name)(void*);
7303void (*winpty_free)(void*);
7304void (*winpty_config_free)(void*);
7305void (*winpty_spawn_config_free)(void*);
7306void (*winpty_error_free)(void*);
7307LPCWSTR (*winpty_error_msg)(void*);
7308BOOL (*winpty_set_size)(void*, int, int, void*);
7309HANDLE (*winpty_agent_process)(void*);
7310
7311#define WINPTY_DLL "winpty.dll"
7312
7313static HINSTANCE hWinPtyDLL = NULL;
7314# endif
7315
7316 static int
7317dyn_winpty_init(int verbose)
7318{
7319 int i;
7320 static struct
7321 {
7322 char *name;
7323 FARPROC *ptr;
7324 } winpty_entry[] =
7325 {
7326 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7327 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7328 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7329 {"winpty_config_set_mouse_mode",
7330 (FARPROC*)&winpty_config_set_mouse_mode},
7331 {"winpty_config_set_initial_size",
7332 (FARPROC*)&winpty_config_set_initial_size},
7333 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7334 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7335 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7336 {"winpty_free", (FARPROC*)&winpty_free},
7337 {"winpty_open", (FARPROC*)&winpty_open},
7338 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7339 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7340 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7341 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7342 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7343 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7344 {NULL, NULL}
7345 };
7346
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007347 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007348 if (hWinPtyDLL)
7349 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007350 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7351 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007352 if (*p_winptydll != NUL)
7353 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7354 if (!hWinPtyDLL)
7355 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7356 if (!hWinPtyDLL)
7357 {
7358 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007359 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007360 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7361 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007362 return FAIL;
7363 }
7364 for (i = 0; winpty_entry[i].name != NULL
7365 && winpty_entry[i].ptr != NULL; ++i)
7366 {
7367 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7368 winpty_entry[i].name)) == NULL)
7369 {
7370 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007371 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007372 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007373 return FAIL;
7374 }
7375 }
7376
7377 return OK;
7378}
7379
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007380 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007381winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007382 term_T *term,
7383 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007384 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007385 jobopt_T *opt,
7386 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007387{
7388 WCHAR *cmd_wchar = NULL;
7389 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007390 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007391 channel_T *channel = NULL;
7392 job_T *job = NULL;
7393 DWORD error;
7394 HANDLE jo = NULL;
7395 HANDLE child_process_handle;
7396 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007397 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007398 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007399 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007400 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007401
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007402 ga_init2(&ga_cmd, sizeof(char*), 20);
7403 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007404
7405 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007406 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007407 cmd = argvar->vval.v_string;
7408 }
7409 else if (argvar->v_type == VAR_LIST)
7410 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007411 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007412 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007413 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007414 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007415 if (cmd == NULL || *cmd == NUL)
7416 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007417 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007418 goto failed;
7419 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007420
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007421 term->tl_arg0_cmd = vim_strsave(cmd);
7422
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007423 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007424 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007425 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007426 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007427 if (opt->jo_cwd != NULL)
7428 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007429
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007430 win32_build_env(opt->jo_env, &ga_env, TRUE);
7431 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007432
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007433 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7434 if (term->tl_winpty_config == NULL)
7435 goto failed;
7436
7437 winpty_config_set_mouse_mode(term->tl_winpty_config,
7438 WINPTY_MOUSE_MODE_FORCE);
7439 winpty_config_set_initial_size(term->tl_winpty_config,
7440 term->tl_cols, term->tl_rows);
7441 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7442 if (term->tl_winpty == NULL)
7443 goto failed;
7444
7445 spawn_config = winpty_spawn_config_new(
7446 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7447 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7448 NULL,
7449 cmd_wchar,
7450 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007451 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007452 &winpty_err);
7453 if (spawn_config == NULL)
7454 goto failed;
7455
7456 channel = add_channel();
7457 if (channel == NULL)
7458 goto failed;
7459
7460 job = job_alloc();
7461 if (job == NULL)
7462 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007463 if (argvar->v_type == VAR_STRING)
7464 {
7465 int argc;
7466
7467 build_argv_from_string(cmd, &job->jv_argv, &argc);
7468 }
7469 else
7470 {
7471 int argc;
7472
7473 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7474 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007475
7476 if (opt->jo_set & JO_IN_BUF)
7477 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7478
7479 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7480 &child_thread_handle, &error, &winpty_err))
7481 goto failed;
7482
7483 channel_set_pipes(channel,
7484 (sock_T)CreateFileW(
7485 winpty_conin_name(term->tl_winpty),
7486 GENERIC_WRITE, 0, NULL,
7487 OPEN_EXISTING, 0, NULL),
7488 (sock_T)CreateFileW(
7489 winpty_conout_name(term->tl_winpty),
7490 GENERIC_READ, 0, NULL,
7491 OPEN_EXISTING, 0, NULL),
7492 (sock_T)CreateFileW(
7493 winpty_conerr_name(term->tl_winpty),
7494 GENERIC_READ, 0, NULL,
7495 OPEN_EXISTING, 0, NULL));
7496
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007497 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007498 channel->ch_write_text_mode = TRUE;
7499
7500 jo = CreateJobObject(NULL, NULL);
7501 if (jo == NULL)
7502 goto failed;
7503
7504 if (!AssignProcessToJobObject(jo, child_process_handle))
7505 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007506 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007507 CloseHandle(jo);
7508 jo = NULL;
7509 }
7510
7511 winpty_spawn_config_free(spawn_config);
7512 vim_free(cmd_wchar);
7513 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007514 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007515
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007516 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7517 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007518
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007519#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007520 if (term_use_palette())
7521 {
7522 if (term->tl_palette != NULL)
7523 set_vterm_palette(term->tl_vterm, term->tl_palette);
7524 else
7525 init_vterm_ansi_colors(term->tl_vterm);
7526 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007527#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007528
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007529 channel_set_job(channel, job, opt);
7530 job_set_options(job, opt);
7531
7532 job->jv_channel = channel;
7533 job->jv_proc_info.hProcess = child_process_handle;
7534 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7535 job->jv_job_object = jo;
7536 job->jv_status = JOB_STARTED;
7537 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007538 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007539 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007540 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007541 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007542 ++job->jv_refcount;
7543 term->tl_job = job;
7544
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007545 // Redirecting stdout and stderr doesn't work at the job level. Instead
7546 // open the file here and handle it in. opt->jo_io was changed in
7547 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007548 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7549 {
7550 char_u *fname = opt->jo_io_name[PART_OUT];
7551
7552 ch_log(channel, "Opening output file %s", fname);
7553 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7554 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007555 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007556 }
7557
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007558 return OK;
7559
7560failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007561 ga_clear(&ga_cmd);
7562 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007563 vim_free(cmd_wchar);
7564 vim_free(cwd_wchar);
7565 if (spawn_config != NULL)
7566 winpty_spawn_config_free(spawn_config);
7567 if (channel != NULL)
7568 channel_clear(channel);
7569 if (job != NULL)
7570 {
7571 job->jv_channel = NULL;
7572 job_cleanup(job);
7573 }
7574 term->tl_job = NULL;
7575 if (jo != NULL)
7576 CloseHandle(jo);
7577 if (term->tl_winpty != NULL)
7578 winpty_free(term->tl_winpty);
7579 term->tl_winpty = NULL;
7580 if (term->tl_winpty_config != NULL)
7581 winpty_config_free(term->tl_winpty_config);
7582 term->tl_winpty_config = NULL;
7583 if (winpty_err != NULL)
7584 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007585 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007586 (short_u *)winpty_error_msg(winpty_err), NULL);
7587
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007588 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007589 winpty_error_free(winpty_err);
7590 }
7591 return FAIL;
7592}
7593
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007594/*
7595 * Create a new terminal of "rows" by "cols" cells.
7596 * Store a reference in "term".
7597 * Return OK or FAIL.
7598 */
7599 static int
7600term_and_job_init(
7601 term_T *term,
7602 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007603 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007604 jobopt_T *opt,
7605 jobopt_T *orig_opt)
7606{
7607 int use_winpty = FALSE;
7608 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007609 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007610
7611 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7612 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7613
7614 if (!has_winpty && !has_conpty)
7615 // If neither is available give the errors for winpty, since when
7616 // conpty is not available it can't be installed either.
7617 return dyn_winpty_init(TRUE);
7618
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007619 if (opt->jo_tty_type != NUL)
7620 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007621
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007622 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007623 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007624 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007625 use_conpty = TRUE;
7626 else if (has_winpty)
7627 use_winpty = TRUE;
7628 // else: error
7629 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007630 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007631 {
7632 if (has_winpty)
7633 use_winpty = TRUE;
7634 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007635 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007636 {
7637 if (has_conpty)
7638 use_conpty = TRUE;
7639 else
7640 return dyn_conpty_init(TRUE);
7641 }
7642
7643 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007644 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007645
7646 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007647 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007648
7649 // error
7650 return dyn_winpty_init(TRUE);
7651}
7652
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007653 static int
7654create_pty_only(term_T *term, jobopt_T *options)
7655{
7656 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7657 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7658 char in_name[80], out_name[80];
7659 channel_T *channel = NULL;
7660
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007661 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7662 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007663
7664 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7665 GetCurrentProcessId(),
7666 curbuf->b_fnum);
7667 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7668 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7669 PIPE_UNLIMITED_INSTANCES,
7670 0, 0, NMPWAIT_NOWAIT, NULL);
7671 if (hPipeIn == INVALID_HANDLE_VALUE)
7672 goto failed;
7673
7674 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7675 GetCurrentProcessId(),
7676 curbuf->b_fnum);
7677 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7678 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7679 PIPE_UNLIMITED_INSTANCES,
7680 0, 0, 0, NULL);
7681 if (hPipeOut == INVALID_HANDLE_VALUE)
7682 goto failed;
7683
7684 ConnectNamedPipe(hPipeIn, NULL);
7685 ConnectNamedPipe(hPipeOut, NULL);
7686
7687 term->tl_job = job_alloc();
7688 if (term->tl_job == NULL)
7689 goto failed;
7690 ++term->tl_job->jv_refcount;
7691
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007692 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007693 term->tl_job->jv_status = JOB_FINISHED;
7694
7695 channel = add_channel();
7696 if (channel == NULL)
7697 goto failed;
7698 term->tl_job->jv_channel = channel;
7699 channel->ch_keep_open = TRUE;
7700 channel->ch_named_pipe = TRUE;
7701
7702 channel_set_pipes(channel,
7703 (sock_T)hPipeIn,
7704 (sock_T)hPipeOut,
7705 (sock_T)hPipeOut);
7706 channel_set_job(channel, term->tl_job, options);
7707 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7708 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7709
7710 return OK;
7711
7712failed:
7713 if (hPipeIn != NULL)
7714 CloseHandle(hPipeIn);
7715 if (hPipeOut != NULL)
7716 CloseHandle(hPipeOut);
7717 return FAIL;
7718}
7719
7720/*
7721 * Free the terminal emulator part of "term".
7722 */
7723 static void
7724term_free_vterm(term_T *term)
7725{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007726 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007727 if (term->tl_winpty != NULL)
7728 winpty_free(term->tl_winpty);
7729 term->tl_winpty = NULL;
7730 if (term->tl_winpty_config != NULL)
7731 winpty_config_free(term->tl_winpty_config);
7732 term->tl_winpty_config = NULL;
7733 if (term->tl_vterm != NULL)
7734 vterm_free(term->tl_vterm);
7735 term->tl_vterm = NULL;
7736}
7737
7738/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007739 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007740 */
7741 static void
7742term_report_winsize(term_T *term, int rows, int cols)
7743{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007744 if (term->tl_conpty)
7745 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007746 if (term->tl_winpty)
7747 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7748}
7749
7750 int
7751terminal_enabled(void)
7752{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007753 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007754}
7755
7756# else
7757
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007758///////////////////////////////////////
7759// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007760
7761/*
7762 * Create a new terminal of "rows" by "cols" cells.
7763 * Start job for "cmd".
7764 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007765 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007766 * Return OK or FAIL.
7767 */
7768 static int
7769term_and_job_init(
7770 term_T *term,
7771 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007772 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007773 jobopt_T *opt,
7774 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007775{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007776 term->tl_arg0_cmd = NULL;
7777
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007778 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7779 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007780
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007781#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007782 if (term_use_palette())
7783 {
7784 if (term->tl_palette != NULL)
7785 set_vterm_palette(term->tl_vterm, term->tl_palette);
7786 else
7787 init_vterm_ansi_colors(term->tl_vterm);
7788 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007789#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007790
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007791 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007792 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007793 if (term->tl_job != NULL)
7794 ++term->tl_job->jv_refcount;
7795
7796 return term->tl_job != NULL
7797 && term->tl_job->jv_channel != NULL
7798 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7799}
7800
7801 static int
7802create_pty_only(term_T *term, jobopt_T *opt)
7803{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007804 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7805 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007806
7807 term->tl_job = job_alloc();
7808 if (term->tl_job == NULL)
7809 return FAIL;
7810 ++term->tl_job->jv_refcount;
7811
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007812 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007813 term->tl_job->jv_status = JOB_FINISHED;
7814
7815 return mch_create_pty_channel(term->tl_job, opt);
7816}
7817
7818/*
7819 * Free the terminal emulator part of "term".
7820 */
7821 static void
7822term_free_vterm(term_T *term)
7823{
7824 if (term->tl_vterm != NULL)
7825 vterm_free(term->tl_vterm);
7826 term->tl_vterm = NULL;
7827}
7828
7829/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007830 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007831 */
7832 static void
7833term_report_winsize(term_T *term, int rows, int cols)
7834{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007835 // Use an ioctl() to report the new window size to the job.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007836 if (term->tl_job == NULL || term->tl_job->jv_channel == NULL)
7837 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007838
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007839 int fd = -1;
7840 int part;
7841
7842 for (part = PART_OUT; part < PART_COUNT; ++part)
7843 {
7844 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
7845 if (mch_isatty(fd))
7846 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007847 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007848 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7849 mch_signal_job(term->tl_job, (char_u *)"winch");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007850}
7851
7852# endif
7853
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007854#endif // FEAT_TERMINAL