blob: f79d102e8cba97a26f3dd3ecff91b1fff61ddf9b [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020039 */
40
41#include "vim.h"
42
43#if defined(FEAT_TERMINAL) || defined(PROTO)
44
45#ifndef MIN
46# define MIN(x,y) ((x) < (y) ? (x) : (y))
47#endif
48#ifndef MAX
49# define MAX(x,y) ((x) > (y) ? (x) : (y))
50#endif
51
52#include "libvterm/include/vterm.h"
53
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010054// This is VTermScreenCell without the characters, thus much smaller.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055typedef struct {
56 VTermScreenCellAttrs attrs;
57 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010058 VTermColor fg;
59 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060} cellattr_T;
61
62typedef struct sb_line_S {
Bram Moolenaar29ae2232019-02-14 21:22:01 +010063 int sb_cols; // can differ per line
64 cellattr_T *sb_cells; // allocated
65 cellattr_T sb_fill_attr; // for short line
66 char_u *sb_text; // for tl_scrollback_postponed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067} sb_line_T;
68
Bram Moolenaar4f974752019-02-17 17:44:42 +010069#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010070# ifndef HPCON
71# define HPCON VOID*
72# endif
73# ifndef EXTENDED_STARTUPINFO_PRESENT
74# define EXTENDED_STARTUPINFO_PRESENT 0x00080000
75# endif
76# ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
77# define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE 0x00020016
78# endif
79typedef struct _DYN_STARTUPINFOEXW
80{
81 STARTUPINFOW StartupInfo;
82 LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
83} DYN_STARTUPINFOEXW, *PDYN_STARTUPINFOEXW;
84#endif
85
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010086// typedef term_T in structs.h
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020087struct terminal_S {
88 term_T *tl_next;
89
90 VTerm *tl_vterm;
91 job_T *tl_job;
92 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010093#if defined(FEAT_GUI)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010094 int tl_system; // when non-zero used for :!cmd output
95 int tl_toprow; // row with first line of system terminal
Bram Moolenaar13568252018-03-16 20:46:58 +010096#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010098 // Set when setting the size of a vterm, reset after redrawing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020099 int tl_vterm_size_changed;
100
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100101 int tl_normal_mode; // TRUE: Terminal-Normal mode
Bram Moolenaareea32af2021-11-21 14:51:13 +0000102 int tl_channel_closing;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200103 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200104 int tl_channel_recently_closed; // still need to handle tl_finish
105
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100106 int tl_finish;
107#define TL_FINISH_UNSET NUL
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100108#define TL_FINISH_CLOSE 'c' // ++close or :terminal without argument
109#define TL_FINISH_NOCLOSE 'n' // ++noclose
110#define TL_FINISH_OPEN 'o' // ++open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200111 char_u *tl_opencmd;
112 char_u *tl_eof_chars;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200113 char_u *tl_api; // prefix for terminal API function
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200114
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100115 char_u *tl_arg0_cmd; // To format the status bar
116
Bram Moolenaar4f974752019-02-17 17:44:42 +0100117#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200118 void *tl_winpty_config;
119 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200120
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100121 HPCON tl_conpty;
122 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
123
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200124 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200125#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100126#if defined(FEAT_SESSION)
127 char_u *tl_command;
128#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100129 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100131 // last known vterm size
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200132 int tl_rows;
133 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200134
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100135 char_u *tl_title; // NULL or allocated
136 char_u *tl_status_text; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200137
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100138 // Range of screen rows to update. Zero based.
139 int tl_dirty_row_start; // MAX_ROW if nothing dirty
140 int tl_dirty_row_end; // row below last one to update
141 int tl_dirty_snapshot; // text updated after making snapshot
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200142#ifdef FEAT_TIMERS
143 int tl_timer_set;
144 proftime_T tl_timer_due;
145#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100146 int tl_postponed_scroll; // to be scrolled up
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200148 garray_T tl_scrollback;
149 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100150 garray_T tl_scrollback_postponed;
151
Bram Moolenaar83d47902020-03-26 20:34:00 +0100152 char_u *tl_highlight_name; // replaces "Terminal"; allocated
153
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200154 cellattr_T tl_default_color;
155
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100156 linenr_T tl_top_diff_rows; // rows of top diff file or zero
157 linenr_T tl_bot_diff_rows; // rows of bottom diff file
Bram Moolenaard96ff162018-02-18 22:13:29 +0100158
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200159 VTermPos tl_cursor_pos;
160 int tl_cursor_visible;
161 int tl_cursor_blink;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100162 int tl_cursor_shape; // 1: block, 2: underline, 3: bar
163 char_u *tl_cursor_color; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200164
LemonBoyb2b3acb2022-05-20 10:10:34 +0100165 long_u *tl_palette; // array of 16 colors specified by term_start, can
166 // be NULL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167 int tl_using_altscreen;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200168 garray_T tl_osc_buf; // incomplete OSC string
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200169};
170
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100171#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
172#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200173
174/*
175 * List of all active terminals.
176 */
177static term_T *first_term = NULL;
178
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100179// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200180static term_T *in_terminal_loop = NULL;
181
Bram Moolenaar4f974752019-02-17 17:44:42 +0100182#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100183static BOOL has_winpty = FALSE;
184static BOOL has_conpty = FALSE;
185#endif
186
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100187#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188#define KEY_BUF_LEN 200
189
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200190#define FOR_ALL_TERMS(term) \
191 for ((term) = first_term; (term) != NULL; (term) = (term)->tl_next)
192
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193/*
194 * Functions with separate implementation for MS-Windows and Unix-like systems.
195 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200196static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200197static int create_pty_only(term_T *term, jobopt_T *opt);
198static void term_report_winsize(term_T *term, int rows, int cols);
199static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100200#ifdef FEAT_GUI
201static void update_system_term(term_T *term);
202#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200203
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100204static void handle_postponed_scrollback(term_T *term);
205
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100206// The character that we know (or assume) that the terminal expects for the
207// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200208static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200209
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100210// Store the last set and the desired cursor properties, so that we only update
211// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200212static char_u *last_set_cursor_color = NULL;
213static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100214static int last_set_cursor_shape = -1;
215static int desired_cursor_shape = -1;
216static int last_set_cursor_blink = -1;
217static int desired_cursor_blink = -1;
218
219
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100220///////////////////////////////////////
221// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200222
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200223 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200224cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
225{
226 if (lhs_color != NULL && rhs_color != NULL)
227 return STRCMP(lhs_color, rhs_color) == 0;
228 return lhs_color == NULL && rhs_color == NULL;
229}
230
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200231 static void
232cursor_color_copy(char_u **to_color, char_u *from_color)
233{
234 // Avoid a free & alloc if the value is already right.
235 if (cursor_color_equal(*to_color, from_color))
236 return;
237 vim_free(*to_color);
238 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
239}
240
241 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200242cursor_color_get(char_u *color)
243{
244 return (color == NULL) ? (char_u *)"" : color;
245}
246
247
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200248/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200249 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200250 * current window.
251 * Sets "rows" and/or "cols" to zero when it should follow the window size.
252 * Return TRUE if the size is the minimum size: "24*80".
253 */
254 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200255parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200256{
257 int minsize = FALSE;
258
259 *rows = 0;
260 *cols = 0;
261
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000262 if (*wp->w_p_tws == NUL)
263 return FALSE;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200264
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000265 char_u *p = vim_strchr(wp->w_p_tws, 'x');
266
267 // Syntax of value was already checked when it's set.
268 if (p == NULL)
269 {
270 minsize = TRUE;
271 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200272 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +0000273 *rows = atoi((char *)wp->w_p_tws);
274 *cols = atoi((char *)p + 1);
Christian Brabandtceee7a82023-09-21 16:55:06 +0200275 if (*rows > VTERM_MAX_ROWS)
276 *rows = VTERM_MAX_ROWS;
277 if (*cols > VTERM_MAX_COLS)
278 *cols = VTERM_MAX_COLS;
Bram Moolenaar498c2562018-04-15 23:45:15 +0200279 return minsize;
280}
281
282/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200283 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200284 */
285 static void
Bram Moolenaarb936b792020-09-04 18:34:09 +0200286set_term_and_win_size(term_T *term, jobopt_T *opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200287{
Bram Moolenaarb936b792020-09-04 18:34:09 +0200288 int rows, cols;
289 int minsize;
290
Bram Moolenaar13568252018-03-16 20:46:58 +0100291#ifdef FEAT_GUI
292 if (term->tl_system)
293 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100294 // Use the whole screen for the system command. However, it will start
295 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100296 term->tl_rows = Rows;
297 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200298 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100299 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100300#endif
Bram Moolenaarb936b792020-09-04 18:34:09 +0200301 term->tl_rows = curwin->w_height;
302 term->tl_cols = curwin->w_width;
303
304 minsize = parse_termwinsize(curwin, &rows, &cols);
305 if (minsize)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200306 {
Bram Moolenaarb936b792020-09-04 18:34:09 +0200307 if (term->tl_rows < rows)
308 term->tl_rows = rows;
309 if (term->tl_cols < cols)
310 term->tl_cols = cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200312 if ((opt->jo_set2 & JO2_TERM_ROWS))
313 term->tl_rows = opt->jo_term_rows;
314 else if (rows != 0)
315 term->tl_rows = rows;
316 if ((opt->jo_set2 & JO2_TERM_COLS))
317 term->tl_cols = opt->jo_term_cols;
318 else if (cols != 0)
319 term->tl_cols = cols;
320
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200321 if (!opt->jo_hidden)
Bram Moolenaarb936b792020-09-04 18:34:09 +0200322 {
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200323 if (term->tl_rows != curwin->w_height)
324 win_setheight_win(term->tl_rows, curwin);
325 if (term->tl_cols != curwin->w_width)
326 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaarb936b792020-09-04 18:34:09 +0200327
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200328 // Set 'winsize' now to avoid a resize at the next redraw.
329 if (!minsize && *curwin->w_p_tws != NUL)
330 {
331 char_u buf[100];
332
333 vim_snprintf((char *)buf, 100, "%dx%d",
334 term->tl_rows, term->tl_cols);
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100335 set_option_value_give_err((char_u *)"termwinsize",
336 0L, buf, OPT_LOCAL);
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200337 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200338 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200339}
340
341/*
342 * Initialize job options for a terminal job.
343 * Caller may overrule some of them.
344 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100345 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346init_job_options(jobopt_T *opt)
347{
348 clear_job_options(opt);
349
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100350 opt->jo_mode = CH_MODE_RAW;
351 opt->jo_out_mode = CH_MODE_RAW;
352 opt->jo_err_mode = CH_MODE_RAW;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200353 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
354}
355
356/*
357 * Set job options mandatory for a terminal job.
358 */
359 static void
360setup_job_options(jobopt_T *opt, int rows, int cols)
361{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100362#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100363 // Win32: Redirecting the job output won't work, thus always connect stdout
364 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200365 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200366#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200367 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100368 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200369 opt->jo_io[PART_OUT] = JIO_BUFFER;
370 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
371 opt->jo_modifiable[PART_OUT] = 0;
372 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
373 }
374
Bram Moolenaar4f974752019-02-17 17:44:42 +0100375#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100376 // Win32: Redirecting the job output won't work, thus always connect stderr
377 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200378 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200379#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200380 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100381 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200382 opt->jo_io[PART_ERR] = JIO_BUFFER;
383 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
384 opt->jo_modifiable[PART_ERR] = 0;
385 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
386 }
387
388 opt->jo_pty = TRUE;
389 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
390 opt->jo_term_rows = rows;
391 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
392 opt->jo_term_cols = cols;
393}
394
395/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200396 * Flush messages on channels.
397 */
398 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +0000399term_flush_messages(void)
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200400{
401 mch_check_messages();
402 parse_queued_messages();
403}
404
405/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100406 * Close a terminal buffer (and its window). Used when creating the terminal
407 * fails.
408 */
409 static void
410term_close_buffer(buf_T *buf, buf_T *old_curbuf)
411{
412 free_terminal(buf);
413 if (old_curbuf != NULL)
414 {
415 --curbuf->b_nwindows;
416 curbuf = old_curbuf;
417 curwin->w_buffer = curbuf;
418 ++curbuf->b_nwindows;
419 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100420 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100421
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100422 // Wiping out the buffer will also close the window and call
423 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100424 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
425}
426
427/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100429 * Use either "argvar" or "argv", the other must be NULL.
430 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
431 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200432 * Returns NULL when failed.
433 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100434 buf_T *
435term_start(
436 typval_T *argvar,
437 char **argv,
438 jobopt_T *opt,
439 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200440{
441 exarg_T split_ea;
442 win_T *old_curwin = curwin;
443 term_T *term;
444 buf_T *old_curbuf = NULL;
445 int res;
446 buf_T *newbuf;
Bram Moolenaare1004402020-10-24 20:49:43 +0200447 int vertical = opt->jo_vertical || (cmdmod.cmod_split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200448 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200449
450 if (check_restricted() || check_secure())
451 return NULL;
Bram Moolenaare5b44862021-05-30 13:54:03 +0200452 if (cmdwin_type != 0)
453 {
454 emsg(_(e_cannot_open_terminal_from_command_line_window));
455 return NULL;
456 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200457
458 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
459 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
460 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100461 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
462 || (argvar != NULL
463 && argvar->v_type == VAR_LIST
464 && argvar->vval.v_list != NULL
465 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200466 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000467 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200468 return NULL;
469 }
470
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200471 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200472 if (term == NULL)
473 return NULL;
474 term->tl_dirty_row_end = MAX_ROW;
475 term->tl_cursor_visible = TRUE;
476 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
477 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100478#ifdef FEAT_GUI
479 term->tl_system = (flags & TERM_START_SYSTEM);
480#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200481 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100482 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200483 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200484
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200485 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200486 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200487 if (opt->jo_curwin)
488 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100489 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100490 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200491 {
492 no_write_message();
493 vim_free(term);
494 return NULL;
495 }
496 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200497 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
498 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
499 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200500 {
501 vim_free(term);
502 return NULL;
503 }
504 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100505 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200506 {
507 buf_T *buf;
508
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100509 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100510 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200511 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
512 BLN_NEW | BLN_LISTED);
513 if (buf == NULL || ml_open(buf) == FAIL)
514 {
515 vim_free(term);
516 return NULL;
517 }
518 old_curbuf = curbuf;
519 --curbuf->b_nwindows;
520 curbuf = buf;
521 curwin->w_buffer = buf;
522 ++curbuf->b_nwindows;
523 }
524 else
525 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100526 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200527 split_ea.cmdidx = CMD_new;
528 split_ea.cmd = (char_u *)"new";
529 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100530 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200531 {
532 split_ea.line2 = opt->jo_term_rows;
533 split_ea.addr_count = 1;
534 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100535 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200536 {
537 split_ea.line2 = opt->jo_term_cols;
538 split_ea.addr_count = 1;
539 }
540
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100541 if (vertical)
Bram Moolenaare1004402020-10-24 20:49:43 +0200542 cmdmod.cmod_split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200543 ex_splitview(&split_ea);
544 if (curwin == old_curwin)
545 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100546 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200547 vim_free(term);
548 return NULL;
549 }
550 }
551 term->tl_buffer = curbuf;
552 curbuf->b_term = term;
553
554 if (!opt->jo_hidden)
555 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100556 // Only one size was taken care of with :new, do the other one. With
557 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100558 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200559 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100560 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200561 win_setwidth(opt->jo_term_cols);
562 }
563
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100564 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200565 term->tl_next = first_term;
566 first_term = term;
567
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100568 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
569
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200570 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100571 {
572 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200573 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100574 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100575 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100576 {
577 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100578 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100579 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200580 else
581 {
582 int i;
583 size_t len;
584 char_u *cmd, *p;
585
586 if (argvar->v_type == VAR_STRING)
587 {
588 cmd = argvar->vval.v_string;
589 if (cmd == NULL)
590 cmd = (char_u *)"";
591 else if (STRCMP(cmd, "NONE") == 0)
592 cmd = (char_u *)"pty";
593 }
594 else if (argvar->v_type != VAR_LIST
595 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100596 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100597 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200598 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
599 cmd = (char_u*)"";
600
601 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200602 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200603
604 for (i = 0; p != NULL; ++i)
605 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100606 // Prepend a ! to the command name to avoid the buffer name equals
607 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200608 if (i == 0)
609 vim_snprintf((char *)p, len, "!%s", cmd);
610 else
611 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
612 if (buflist_findname(p) == NULL)
613 {
614 vim_free(curbuf->b_ffname);
615 curbuf->b_ffname = p;
616 break;
617 }
618 }
619 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100620 vim_free(curbuf->b_sfname);
621 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200622 curbuf->b_fname = curbuf->b_ffname;
623
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100624 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
625
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200626 if (opt->jo_term_opencmd != NULL)
627 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
628
629 if (opt->jo_eof_chars != NULL)
630 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
631
632 set_string_option_direct((char_u *)"buftype", -1,
633 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200634 // Avoid that 'buftype' is reset when this buffer is entered.
635 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200636
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100637 // Mark the buffer as not modifiable. It can only be made modifiable after
638 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200639 curbuf->b_p_ma = FALSE;
640
Bram Moolenaarb936b792020-09-04 18:34:09 +0200641 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100642#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200643 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
644#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200645 setup_job_options(opt, term->tl_rows, term->tl_cols);
646
Bram Moolenaar13568252018-03-16 20:46:58 +0100647 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100648 return curbuf;
649
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100650#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100651 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100652 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100653 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100654 else if (argvar->v_type == VAR_STRING)
655 {
656 char_u *cmd = argvar->vval.v_string;
657
658 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
659 term->tl_command = vim_strsave(cmd);
660 }
661 else if (argvar->v_type == VAR_LIST
662 && argvar->vval.v_list != NULL
663 && argvar->vval.v_list->lv_len > 0)
664 {
665 garray_T ga;
666 listitem_T *item;
667
668 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200669 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100670 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100671 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100672 char_u *p;
673
674 if (s == NULL)
675 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100676 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100677 if (p == NULL)
678 break;
679 ga_concat(&ga, p);
680 vim_free(p);
681 ga_append(&ga, ' ');
682 }
683 if (item == NULL)
684 {
685 ga_append(&ga, NUL);
686 term->tl_command = ga.ga_data;
687 }
688 else
689 ga_clear(&ga);
690 }
691#endif
692
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100693 if (opt->jo_term_kill != NULL)
694 {
695 char_u *p = skiptowhite(opt->jo_term_kill);
696
697 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
698 }
699
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200700 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100701 {
702 char_u *p = skiptowhite(opt->jo_term_api);
703
704 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
705 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200706 else
707 term->tl_api = vim_strsave((char_u *)"Tapi_");
708
Bram Moolenaar83d47902020-03-26 20:34:00 +0100709 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
710 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
711
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100712#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100713 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
714 if (opt->jo_set2 & JO2_ANSI_COLORS)
715 {
716 term->tl_palette = ALLOC_MULT(long_u, 16);
717 if (term->tl_palette == NULL)
718 {
719 vim_free(term);
720 return NULL;
721 }
722 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
723 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100724#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100725
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100726 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100727 if (argv == NULL
728 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200729 && argvar->vval.v_string != NULL
730 && STRCMP(argvar->vval.v_string, "NONE") == 0)
731 res = create_pty_only(term, opt);
732 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200733 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200734
735 newbuf = curbuf;
736 if (res == OK)
737 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100738 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200739 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
740 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100741#ifdef FEAT_GUI
742 if (term->tl_system)
743 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100744 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100745 term->tl_toprow = msg_row + 1;
746 term->tl_dirty_row_end = 0;
747 }
748#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200749
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100750 // Make sure we don't get stuck on sending keys to the job, it leads to
751 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200752 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
753
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200754 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200755 {
756 --curbuf->b_nwindows;
757 curbuf = old_curbuf;
758 curwin->w_buffer = curbuf;
759 ++curbuf->b_nwindows;
760 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000761 else if (vgetc_busy
762#ifdef FEAT_TIMERS
763 || timer_busy
764#endif
765 || input_busy)
766 {
767 char_u ignore[4];
768
769 // When waiting for input need to return and possibly end up in
770 // terminal_loop() instead.
771 ignore[0] = K_SPECIAL;
772 ignore[1] = KS_EXTRA;
773 ignore[2] = KE_IGNORE;
774 ignore[3] = NUL;
775 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
776 typebuf_was_filled = TRUE;
777 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200778 }
779 else
780 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100781 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200782 return NULL;
783 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100784
Bram Moolenaar13568252018-03-16 20:46:58 +0100785 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200786 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
787 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788 return newbuf;
789}
790
791/*
792 * ":terminal": open a terminal window and execute a job in it.
793 */
794 void
795ex_terminal(exarg_T *eap)
796{
797 typval_T argvar[2];
798 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100799 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200800 char_u *cmd;
801 char_u *tofree = NULL;
802
803 init_job_options(&opt);
804
805 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100806 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200807 {
808 char_u *p, *ep;
809
810 cmd += 2;
811 p = skiptowhite(cmd);
812 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200813 if (ep != NULL)
814 {
815 if (ep < p)
816 p = ep;
817 else
818 ep = NULL;
819 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200820
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200821 // Note: Keep this in sync with get_terminalopt_name.
822
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200823# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
824 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
825 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200826 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200827 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100828 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200829 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200830 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200831 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200832 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200833 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200834 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200835 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100836 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100837 else if (OPTARG_HAS("shell"))
838 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200839 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100840 {
841 opt.jo_set2 |= JO2_TERM_KILL;
842 opt.jo_term_kill = ep + 1;
843 p = skiptowhite(cmd);
844 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200845 else if (OPTARG_HAS("api"))
846 {
847 opt.jo_set2 |= JO2_TERM_API;
848 if (ep != NULL)
849 {
850 opt.jo_term_api = ep + 1;
851 p = skiptowhite(cmd);
852 }
853 else
854 opt.jo_term_api = NULL;
855 }
856 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200857 {
858 opt.jo_set2 |= JO2_TERM_ROWS;
859 opt.jo_term_rows = atoi((char *)ep + 1);
860 p = skiptowhite(cmd);
861 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200862 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200863 {
864 opt.jo_set2 |= JO2_TERM_COLS;
865 opt.jo_term_cols = atoi((char *)ep + 1);
866 p = skiptowhite(cmd);
867 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200868 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200869 {
870 char_u *buf = NULL;
871 char_u *keys;
872
Bram Moolenaar21109272020-01-30 16:27:20 +0100873 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200874 p = skiptowhite(cmd);
875 *p = NUL;
zeertzjq7e0bae02023-08-11 23:15:38 +0200876 keys = replace_termcodes(ep + 1, &buf, 0,
Bram Moolenaar459fd782019-10-13 16:43:39 +0200877 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200878 opt.jo_set2 |= JO2_EOF_CHARS;
879 opt.jo_eof_chars = vim_strsave(keys);
880 vim_free(buf);
881 *p = ' ';
882 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100883#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100884 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
885 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100886 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100887 int tty_type = NUL;
888
889 p = skiptowhite(cmd);
890 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
891 tty_type = 'w';
892 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
893 tty_type = 'c';
894 else
895 {
Bram Moolenaar50809a42023-05-20 16:39:07 +0100896 semsg(_(e_invalid_value_for_argument_str), "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100897 goto theend;
898 }
899 opt.jo_set2 |= JO2_TTY_TYPE;
900 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100901 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100902#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200903 else
904 {
905 if (*p)
906 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000907 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100908 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200909 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200910# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200911 cmd = skipwhite(p);
912 }
913 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100914 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100915 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200916 tofree = cmd = vim_strsave(p_sh);
917
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100918 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100919 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200920 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100921 }
922
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200923 if (eap->addr_count > 0)
924 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100925 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200926 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
927 opt.jo_io[PART_IN] = JIO_BUFFER;
928 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
929 opt.jo_in_top = eap->line1;
930 opt.jo_in_bot = eap->line2;
931 }
932
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100933 if (opt_shell && tofree == NULL)
934 {
935#ifdef UNIX
936 char **argv = NULL;
937 char_u *tofree1 = NULL;
938 char_u *tofree2 = NULL;
939
940 // :term ++shell command
941 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
942 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100943 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100944 vim_free(tofree1);
945 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100946 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100947#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100948# ifdef MSWIN
949 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
950 char_u *newcmd;
951
952 newcmd = alloc(cmdlen);
953 if (newcmd == NULL)
954 goto theend;
955 tofree = newcmd;
956 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
957 cmd = newcmd;
958# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000959 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100960 goto theend;
961# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100962#endif
963 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100964 argvar[0].v_type = VAR_STRING;
965 argvar[0].vval.v_string = cmd;
966 argvar[1].v_type = VAR_UNKNOWN;
967 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100968
969theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100970 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200971 vim_free(opt.jo_eof_chars);
972}
973
Yee Cheng Chin989426b2023-10-14 11:46:51 +0200974 static char_u *
975get_terminalopt_name(expand_T *xp UNUSED, int idx)
976{
977 // Note: Keep this in sync with ex_terminal.
978 static char *(p_termopt_values[]) =
979 {
980 "close",
981 "noclose",
982 "open",
983 "curwin",
984 "hidden",
985 "norestore",
986 "shell",
987 "kill=",
988 "rows=",
989 "cols=",
990 "eof=",
991 "type=",
992 "api=",
993 };
994
995 if (idx < (int)ARRAY_LENGTH(p_termopt_values))
996 return (char_u*)p_termopt_values[idx];
997 return NULL;
998}
999
1000 static char_u *
1001get_termkill_name(expand_T *xp UNUSED, int idx)
1002{
1003 // These are platform-specific values used for job_stop(). They are defined
1004 // in each platform's mch_signal_job(). Just use a unified auto-complete
1005 // list for simplicity.
1006 static char *(p_termkill_values[]) =
1007 {
1008 "term",
1009 "hup",
1010 "quit",
1011 "int",
1012 "kill",
1013 "winch",
1014 };
1015
1016 if (idx < (int)ARRAY_LENGTH(p_termkill_values))
1017 return (char_u*)p_termkill_values[idx];
1018 return NULL;
1019}
1020
1021/*
1022 * Command-line expansion for :terminal [options]
1023 */
1024 int
1025expand_terminal_opt(
1026 char_u *pat,
1027 expand_T *xp,
1028 regmatch_T *rmp,
1029 char_u ***matches,
1030 int *numMatches)
1031{
1032 if (xp->xp_pattern > xp->xp_line && *(xp->xp_pattern-1) == '=')
1033 {
1034 char_u *(*cb)(expand_T *, int) = NULL;
1035
1036 char_u *name_end = xp->xp_pattern - 1;
1037 if (name_end - xp->xp_line >= 4
1038 && STRNCMP(name_end - 4, "kill", 4) == 0)
1039 cb = get_termkill_name;
1040
1041 if (cb != NULL)
1042 {
1043 return ExpandGeneric(
1044 pat,
1045 xp,
1046 rmp,
1047 matches,
1048 numMatches,
1049 cb,
1050 FALSE);
1051 }
1052 return FAIL;
1053 }
1054 return ExpandGeneric(
1055 pat,
1056 xp,
1057 rmp,
1058 matches,
1059 numMatches,
1060 get_terminalopt_name,
1061 FALSE);
1062}
1063
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001064#if defined(FEAT_SESSION) || defined(PROTO)
1065/*
1066 * Write a :terminal command to the session file to restore the terminal in
1067 * window "wp".
1068 * Return FAIL if writing fails.
1069 */
1070 int
Bram Moolenaar0e655112020-09-11 20:36:36 +02001071term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001072{
Bram Moolenaar0e655112020-09-11 20:36:36 +02001073 const int bufnr = wp->w_buffer->b_fnum;
1074 term_T *term = wp->w_buffer->b_term;
1075
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001076 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001077 {
1078 // There are multiple views into this terminal buffer. We don't want to
1079 // create the terminal multiple times. If it's the first time, create,
1080 // otherwise link to the first buffer.
1081 char id_as_str[NUMBUFLEN];
1082 hashitem_T *entry;
1083
1084 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
1085
1086 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
1087 if (!HASHITEM_EMPTY(entry))
1088 {
1089 // we've already opened this terminal buffer
1090 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
1091 return FAIL;
1092 return put_eol(fd);
1093 }
1094 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001095
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001096 // Create the terminal and run the command. This is not without
1097 // risk, but let's assume the user only creates a session when this
1098 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001099 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1100 term->tl_cols, term->tl_rows) < 0)
1101 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001102#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001103 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1104 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001105#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001106 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1107 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001108 if (put_eol(fd) != OK)
1109 return FAIL;
1110
1111 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1112 return FAIL;
1113
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001114 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001115 {
1116 char *hash_key = alloc(NUMBUFLEN);
1117
1118 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00001119 hash_add(terminal_bufs, (char_u *)hash_key, "terminal session");
Bram Moolenaar0e655112020-09-11 20:36:36 +02001120 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001121
1122 return put_eol(fd);
1123}
1124
1125/*
1126 * Return TRUE if "buf" has a terminal that should be restored.
1127 */
1128 int
1129term_should_restore(buf_T *buf)
1130{
1131 term_T *term = buf->b_term;
1132
1133 return term != NULL && (term->tl_command == NULL
1134 || STRCMP(term->tl_command, "NONE") != 0);
1135}
1136#endif
1137
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001138/*
1139 * Free the scrollback buffer for "term".
1140 */
1141 static void
1142free_scrollback(term_T *term)
1143{
1144 int i;
1145
1146 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1147 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1148 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001149 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1150 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1151 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001152}
1153
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001154
1155// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001156static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001157
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001158/*
1159 * Free a terminal and everything it refers to.
1160 * Kills the job if there is one.
1161 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001162 * The actual terminal structure is freed later in free_unused_terminals(),
1163 * because callbacks may wipe out a buffer while the terminal is still
1164 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001165 */
1166 void
1167free_terminal(buf_T *buf)
1168{
1169 term_T *term = buf->b_term;
1170 term_T *tp;
1171
1172 if (term == NULL)
1173 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001174
1175 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001176 if (first_term == term)
1177 first_term = term->tl_next;
1178 else
1179 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1180 if (tp->tl_next == term)
1181 {
1182 tp->tl_next = term->tl_next;
1183 break;
1184 }
1185
1186 if (term->tl_job != NULL)
1187 {
1188 if (term->tl_job->jv_status != JOB_ENDED
1189 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001190 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001191 job_stop(term->tl_job, NULL, "kill");
1192 job_unref(term->tl_job);
1193 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001194 term->tl_next = terminals_to_free;
1195 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001196
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001197 buf->b_term = NULL;
1198 if (in_terminal_loop == term)
1199 in_terminal_loop = NULL;
1200}
1201
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001202 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00001203free_unused_terminals(void)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001204{
1205 while (terminals_to_free != NULL)
1206 {
1207 term_T *term = terminals_to_free;
1208
1209 terminals_to_free = term->tl_next;
1210
1211 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001212 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001213
1214 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001215 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001216 vim_free(term->tl_title);
1217#ifdef FEAT_SESSION
1218 vim_free(term->tl_command);
1219#endif
1220 vim_free(term->tl_kill);
1221 vim_free(term->tl_status_text);
1222 vim_free(term->tl_opencmd);
1223 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001224 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001225#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001226 if (term->tl_out_fd != NULL)
1227 fclose(term->tl_out_fd);
1228#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001229 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001230 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001231 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001232 vim_free(term);
1233 }
1234}
1235
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001236/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001237 * Get the part that is connected to the tty. Normally this is PART_IN, but
1238 * when writing buffer lines to the job it can be another. This makes it
1239 * possible to do "1,5term vim -".
1240 */
1241 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001242get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001243{
1244#ifdef UNIX
1245 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1246 int i;
1247
1248 for (i = 0; i < 3; ++i)
1249 {
1250 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1251
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001252 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001253 return parts[i];
1254 }
1255#endif
1256 return PART_IN;
1257}
1258
1259/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001260 * Read any vterm output and send it on the channel.
1261 */
1262 static void
1263term_forward_output(term_T *term)
1264{
1265 VTerm *vterm = term->tl_vterm;
1266 char buf[KEY_BUF_LEN];
1267 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1268
1269 if (curlen > 0)
1270 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1271 (char_u *)buf, (int)curlen, NULL);
1272}
1273
1274/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001275 * Write job output "msg[len]" to the vterm.
1276 */
1277 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001278term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001279{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001280 char_u *msg = msg_arg;
1281 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001282 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001283 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001284 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1285
1286 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1287 // the end.
1288 if (len > limit)
1289 {
1290 char_u *p = msg + len - limit;
1291
1292 p -= (*mb_head_off)(msg, p);
1293 len -= p - msg;
1294 msg = p;
1295 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001296
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001297 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001298
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001299 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001300 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001301 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001302
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001303 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001304 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1305}
1306
1307 static void
Bram Moolenaar58806c12023-04-29 14:26:02 +01001308position_cursor(win_T *wp, VTermPos *pos)
1309{
1310 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1311 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1312#ifdef FEAT_PROP_POPUP
1313 if (popup_is_popup(wp))
1314 {
1315 wp->w_wrow += popup_top_extra(wp);
1316 wp->w_wcol += popup_left_extra(wp);
1317 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
1318 }
1319 else
1320 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
1321#endif
1322 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1323}
1324
1325 static void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001326update_cursor(term_T *term, int redraw)
1327{
1328 if (term->tl_normal_mode)
1329 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001330#ifdef FEAT_GUI
1331 if (term->tl_system)
1332 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1333 term->tl_cursor_pos.col);
1334 else
1335#endif
Bram Moolenaar58806c12023-04-29 14:26:02 +01001336 if (!term_job_running(term))
1337 // avoid the cursor positioned below the last used line
Bram Moolenaar13568252018-03-16 20:46:58 +01001338 setcursor();
Bram Moolenaar58806c12023-04-29 14:26:02 +01001339 else
1340 {
1341 // do not use the window cursor position
1342 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1343 windgoto(W_WINROW(curwin) + curwin->w_wrow,
1344 curwin->w_wincol + curwin->w_wcol);
1345 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001346 if (redraw)
1347 {
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001348 aco_save_T aco;
1349
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001350 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1351 cursor_on();
1352 out_flush();
1353#ifdef FEAT_GUI
1354 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001355 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001356 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001357 gui_mch_flush();
1358 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001359#endif
Bram Moolenaar24fe33a2022-11-24 00:09:02 +00001360 // Make sure an invoked autocmd doesn't delete the buffer (and the
1361 // terminal) under our fingers.
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001362 ++term->tl_buffer->b_locked;
1363
1364 // save and restore curwin and curbuf, in case the autocmd changes them
1365 aucmd_prepbuf(&aco, curbuf);
1366 apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, FALSE, term->tl_buffer);
1367 aucmd_restbuf(&aco);
1368
1369 --term->tl_buffer->b_locked;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001370 }
1371}
1372
1373/*
1374 * Invoked when "msg" output from a job was received. Write it to the terminal
1375 * of "buffer".
1376 */
1377 void
1378write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1379{
1380 size_t len = STRLEN(msg);
1381 term_T *term = buffer->b_term;
1382
Bram Moolenaar4f974752019-02-17 17:44:42 +01001383#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001384 // Win32: Cannot redirect output of the job, intercept it here and write to
1385 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001386 if (term->tl_out_fd != NULL)
1387 {
1388 ch_log(channel, "Writing %d bytes to output file", (int)len);
1389 fwrite(msg, len, 1, term->tl_out_fd);
1390 return;
1391 }
1392#endif
1393
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001394 if (term->tl_vterm == NULL)
1395 {
1396 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1397 return;
1398 }
1399 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001400 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001401 term_write_job_output(term, msg, len);
1402
Bram Moolenaar13568252018-03-16 20:46:58 +01001403#ifdef FEAT_GUI
1404 if (term->tl_system)
1405 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001406 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001407 update_system_term(term);
1408 update_cursor(term, TRUE);
1409 }
1410 else
1411#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001412 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1413 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001414 if (!term->tl_normal_mode)
1415 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001416 // Don't use update_screen() when editing the command line, it gets
1417 // cleared.
1418 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001419 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001420 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001421 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001422 update_screen(UPD_VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001423 // update_screen() can be slow, check the terminal wasn't closed
1424 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001425 if (buffer == curbuf && curbuf->b_term != NULL)
1426 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001427 }
1428 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001429 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001430 }
1431}
1432
1433/*
1434 * Send a mouse position and click to the vterm
1435 */
1436 static int
1437term_send_mouse(VTerm *vterm, int button, int pressed)
1438{
1439 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001440 int row = mouse_row - W_WINROW(curwin);
1441 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001442
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001443#ifdef FEAT_PROP_POPUP
1444 if (popup_is_popup(curwin))
1445 {
1446 row -= popup_top_extra(curwin);
1447 col -= popup_left_extra(curwin);
1448 }
1449#endif
1450 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001451 if (button != 0)
1452 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001453 return TRUE;
1454}
1455
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001456static int enter_mouse_col = -1;
1457static int enter_mouse_row = -1;
1458
1459/*
1460 * Handle a mouse click, drag or release.
1461 * Return TRUE when a mouse event is sent to the terminal.
1462 */
1463 static int
1464term_mouse_click(VTerm *vterm, int key)
1465{
1466#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001467 // For modeless selection mouse drag and release events are ignored, unless
1468 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001469 static int ignore_drag_release = TRUE;
1470 VTermMouseState mouse_state;
1471
1472 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1473 if (mouse_state.flags == 0)
1474 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001475 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001476 switch (key)
1477 {
1478 case K_LEFTDRAG:
1479 case K_LEFTRELEASE:
1480 case K_RIGHTDRAG:
1481 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001482 // Ignore drag and release events when the button-down wasn't
1483 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001484 if (ignore_drag_release)
1485 {
1486 int save_mouse_col, save_mouse_row;
1487
1488 if (enter_mouse_col < 0)
1489 break;
1490
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001491 // mouse click in the window gave us focus, handle that
1492 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001493 save_mouse_col = mouse_col;
1494 save_mouse_row = mouse_row;
1495 mouse_col = enter_mouse_col;
1496 mouse_row = enter_mouse_row;
1497 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1498 mouse_col = save_mouse_col;
1499 mouse_row = save_mouse_row;
1500 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001501 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001502 case K_LEFTMOUSE:
1503 case K_RIGHTMOUSE:
1504 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1505 ignore_drag_release = TRUE;
1506 else
1507 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001508 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001509 if (clip_star.available)
1510 {
1511 int button, is_click, is_drag;
1512
1513 button = get_mouse_button(KEY2TERMCAP1(key),
1514 &is_click, &is_drag);
1515 if (mouse_model_popup() && button == MOUSE_LEFT
1516 && (mod_mask & MOD_MASK_SHIFT))
1517 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001518 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001519 button = MOUSE_RIGHT;
1520 mod_mask &= ~MOD_MASK_SHIFT;
1521 }
1522 clip_modeless(button, is_click, is_drag);
1523 }
1524 break;
1525
1526 case K_MIDDLEMOUSE:
1527 if (clip_star.available)
1528 insert_reg('*', TRUE);
1529 break;
1530 }
1531 enter_mouse_col = -1;
1532 return FALSE;
1533 }
1534#endif
1535 enter_mouse_col = -1;
1536
1537 switch (key)
1538 {
1539 case K_LEFTMOUSE:
1540 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1541 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1542 case K_LEFTRELEASE:
1543 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1544 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1545 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1546 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1547 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1548 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1549 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1550 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1551 }
1552 return TRUE;
1553}
1554
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001555/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001556 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1557 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001558 * Return the number of bytes in "buf".
1559 */
1560 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001561term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001562{
1563 VTerm *vterm = term->tl_vterm;
1564 VTermKey key = VTERM_KEY_NONE;
1565 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001566 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001567
1568 switch (c)
1569 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001570 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001571
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001572 // don't use VTERM_KEY_BACKSPACE, it always
1573 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001574 case K_BS: c = term_backspace_char; break;
1575
1576 case ESC: key = VTERM_KEY_ESCAPE; break;
1577 case K_DEL: key = VTERM_KEY_DEL; break;
1578 case K_DOWN: key = VTERM_KEY_DOWN; break;
1579 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1580 key = VTERM_KEY_DOWN; break;
1581 case K_END: key = VTERM_KEY_END; break;
1582 case K_S_END: mod = VTERM_MOD_SHIFT;
1583 key = VTERM_KEY_END; break;
1584 case K_C_END: mod = VTERM_MOD_CTRL;
1585 key = VTERM_KEY_END; break;
1586 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1587 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1588 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1589 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1590 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1591 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1592 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1593 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1594 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1595 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1596 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1597 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1598 case K_HOME: key = VTERM_KEY_HOME; break;
1599 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1600 key = VTERM_KEY_HOME; break;
1601 case K_C_HOME: mod = VTERM_MOD_CTRL;
1602 key = VTERM_KEY_HOME; break;
1603 case K_INS: key = VTERM_KEY_INS; break;
1604 case K_K0: key = VTERM_KEY_KP_0; break;
1605 case K_K1: key = VTERM_KEY_KP_1; break;
1606 case K_K2: key = VTERM_KEY_KP_2; break;
1607 case K_K3: key = VTERM_KEY_KP_3; break;
1608 case K_K4: key = VTERM_KEY_KP_4; break;
1609 case K_K5: key = VTERM_KEY_KP_5; break;
1610 case K_K6: key = VTERM_KEY_KP_6; break;
1611 case K_K7: key = VTERM_KEY_KP_7; break;
1612 case K_K8: key = VTERM_KEY_KP_8; break;
1613 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001614 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001615 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001616 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001617 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001618 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1619 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001620 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1621 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001622 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1623 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001624 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1625 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1626 case K_LEFT: key = VTERM_KEY_LEFT; break;
1627 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1628 key = VTERM_KEY_LEFT; break;
1629 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1630 key = VTERM_KEY_LEFT; break;
1631 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1632 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1633 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1634 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1635 key = VTERM_KEY_RIGHT; break;
1636 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1637 key = VTERM_KEY_RIGHT; break;
1638 case K_UP: key = VTERM_KEY_UP; break;
1639 case K_S_UP: mod = VTERM_MOD_SHIFT;
1640 key = VTERM_KEY_UP; break;
1641 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001642 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1643 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001644
Bram Moolenaara42ad572017-11-16 13:08:04 +01001645 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1646 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001647 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1648 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001649
1650 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001651 case K_LEFTMOUSE_NM:
1652 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001653 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001654 case K_LEFTRELEASE_NM:
1655 case K_MOUSEMOVE:
1656 case K_MIDDLEMOUSE:
1657 case K_MIDDLEDRAG:
1658 case K_MIDDLERELEASE:
1659 case K_RIGHTMOUSE:
1660 case K_RIGHTDRAG:
1661 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1662 return 0;
1663 other = TRUE;
1664 break;
1665
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001666 case K_X1MOUSE: /* TODO */ return 0;
1667 case K_X1DRAG: /* TODO */ return 0;
1668 case K_X1RELEASE: /* TODO */ return 0;
1669 case K_X2MOUSE: /* TODO */ return 0;
1670 case K_X2DRAG: /* TODO */ return 0;
1671 case K_X2RELEASE: /* TODO */ return 0;
1672
1673 case K_IGNORE: return 0;
1674 case K_NOP: return 0;
1675 case K_UNDO: return 0;
1676 case K_HELP: return 0;
1677 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1678 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1679 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1680 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1681 case K_SELECT: return 0;
1682#ifdef FEAT_GUI
1683 case K_VER_SCROLLBAR: return 0;
1684 case K_HOR_SCROLLBAR: return 0;
1685#endif
1686#ifdef FEAT_GUI_TABLINE
1687 case K_TABLINE: return 0;
1688 case K_TABMENU: return 0;
1689#endif
1690#ifdef FEAT_NETBEANS_INTG
1691 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1692#endif
1693#ifdef FEAT_DND
1694 case K_DROP: return 0;
1695#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001696 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001697 case K_PS: vterm_keyboard_start_paste(vterm);
1698 other = TRUE;
1699 break;
1700 case K_PE: vterm_keyboard_end_paste(vterm);
1701 other = TRUE;
1702 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001703 }
1704
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001705 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001706 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001707 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001708 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001709 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001710 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001711 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001712
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001713 // Ctrl-Shift-i may have the key "I" instead of "i", but for the kitty
1714 // keyboard protocol should use "i". Applies to all ascii letters.
1715 if (ASCII_ISUPPER(c)
Bram Moolenaarebed1b02022-11-24 14:05:19 +00001716 && vterm_is_kitty_keyboard(vterm)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001717 && mod == (VTERM_MOD_CTRL | VTERM_MOD_SHIFT))
1718 c = TOLOWER_ASC(c);
1719
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001720 /*
1721 * Convert special keys to vterm keys:
1722 * - Write keys to vterm: vterm_keyboard_key()
1723 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001724 */
1725 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001726 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001727 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001728 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001729 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001730 vterm_keyboard_unichar(vterm, c, mod);
1731
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001732 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001733 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1734}
1735
1736/*
1737 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001738 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001739 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001740 */
1741 static int
1742term_job_running_check(term_T *term, int check_job_status)
1743{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001744 // Also consider the job finished when the channel is closed, to avoid a
1745 // race condition when updating the title.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001746 if (term == NULL
1747 || term->tl_job == NULL
1748 || !channel_is_open(term->tl_job->jv_channel))
1749 return FALSE;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001750
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001751 job_T *job = term->tl_job;
1752
1753 // Careful: Checking the job status may invoke callbacks, which close
1754 // the buffer and terminate "term". However, "job" will not be freed
1755 // yet.
1756 if (check_job_status)
1757 job_status(job);
1758 return (job->jv_status == JOB_STARTED
1759 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001760}
1761
1762/*
1763 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001764 */
1765 int
1766term_job_running(term_T *term)
1767{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001768 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001769}
1770
1771/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001772 * Return TRUE if the job for "term" is still running, ignoring the job was
1773 * "NONE".
1774 */
1775 int
1776term_job_running_not_none(term_T *term)
1777{
1778 return term_job_running(term) && !term_none_open(term);
1779}
1780
1781/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001782 * Return TRUE if "term" has an active channel and used ":term NONE".
1783 */
1784 int
1785term_none_open(term_T *term)
1786{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001787 // Also consider the job finished when the channel is closed, to avoid a
1788 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001789 return term != NULL
1790 && term->tl_job != NULL
1791 && channel_is_open(term->tl_job->jv_channel)
1792 && term->tl_job->jv_channel->ch_keep_open;
1793}
1794
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001795//
1796// Used to confirm whether we would like to kill a terminal.
1797// Return OK when the user confirms to kill it.
1798// Return FAIL if the user selects otherwise.
1799//
1800 int
1801term_confirm_stop(buf_T *buf)
1802{
1803 char_u buff[DIALOG_MSG_SIZE];
1804 int ret;
1805
1806 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1807 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1808 if (ret == VIM_YES)
1809 return OK;
1810 else
1811 return FAIL;
1812}
1813
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001814/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001815 * Used when exiting: kill the job in "buf" if so desired.
1816 * Return OK when the job finished.
1817 * Return FAIL when the job is still running.
1818 */
1819 int
1820term_try_stop_job(buf_T *buf)
1821{
1822 int count;
1823 char *how = (char *)buf->b_term->tl_kill;
1824
1825#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001826 if ((how == NULL || *how == NUL)
1827 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001828 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001829 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001830 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001831 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001832 return FAIL;
1833 }
1834#endif
1835 if (how == NULL || *how == NUL)
1836 return FAIL;
1837
1838 job_stop(buf->b_term->tl_job, NULL, how);
1839
Bram Moolenaar9172d232019-01-29 23:06:54 +01001840 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001841 for (count = 0; count < 100; ++count)
1842 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001843 job_T *job;
1844
1845 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001846 if (!buf_valid(buf)
1847 || buf->b_term == NULL
1848 || buf->b_term->tl_job == NULL)
1849 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001850 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001851
Bram Moolenaar9172d232019-01-29 23:06:54 +01001852 // Call job_status() to update jv_status. It may cause the job to be
1853 // cleaned up but it won't be freed.
1854 job_status(job);
1855 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001856 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001857
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001858 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001859 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001860 }
1861 return FAIL;
1862}
1863
1864/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001865 * Add the last line of the scrollback buffer to the buffer in the window.
1866 */
1867 static void
1868add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1869{
1870 buf_T *buf = term->tl_buffer;
1871 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1872 linenr_T lnum = buf->b_ml.ml_line_count;
1873
Bram Moolenaar4f974752019-02-17 17:44:42 +01001874#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875 if (!enc_utf8 && enc_codepage > 0)
1876 {
1877 WCHAR *ret = NULL;
1878 int length = 0;
1879
1880 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1881 &ret, &length);
1882 if (ret != NULL)
1883 {
1884 WideCharToMultiByte_alloc(enc_codepage, 0,
1885 ret, length, (char **)&text, &len, 0, 0);
1886 vim_free(ret);
1887 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1888 vim_free(text);
1889 }
1890 }
1891 else
1892#endif
1893 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1894 if (empty)
1895 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001896 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001898 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001899 curbuf = curwin->w_buffer;
1900 }
1901}
1902
1903 static void
1904cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1905{
1906 attr->width = cell->width;
1907 attr->attrs = cell->attrs;
1908 attr->fg = cell->fg;
1909 attr->bg = cell->bg;
1910}
1911
1912 static int
1913equal_celattr(cellattr_T *a, cellattr_T *b)
1914{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001915 // We only compare the RGB colors, ignoring the ANSI index and type.
1916 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001917 return a->fg.red == b->fg.red
1918 && a->fg.green == b->fg.green
1919 && a->fg.blue == b->fg.blue
1920 && a->bg.red == b->bg.red
1921 && a->bg.green == b->bg.green
1922 && a->bg.blue == b->bg.blue;
1923}
1924
Bram Moolenaard96ff162018-02-18 22:13:29 +01001925/*
1926 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1927 * line at this position. Otherwise at the end.
1928 */
1929 static int
1930add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1931{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001932 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
1933 return FALSE;
1934
1935 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1936 + term->tl_scrollback.ga_len;
1937
1938 if (lnum > 0)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001939 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001940 int i;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001941
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001942 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
Bram Moolenaard96ff162018-02-18 22:13:29 +01001943 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001944 *line = *(line - 1);
1945 --line;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001946 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01001947 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00001948 line->sb_cols = 0;
1949 line->sb_cells = NULL;
1950 line->sb_fill_attr = *fill_attr;
1951 ++term->tl_scrollback.ga_len;
1952 return OK;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001953}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001954
1955/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001956 * Remove the terminal contents from the scrollback and the buffer.
1957 * Used before adding a new scrollback line or updating the buffer for lines
1958 * displayed in the terminal.
1959 */
1960 static void
1961cleanup_scrollback(term_T *term)
1962{
1963 sb_line_T *line;
1964 garray_T *gap;
1965
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001966 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001967 gap = &term->tl_scrollback;
1968 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1969 && gap->ga_len > 0)
1970 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001971 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001972 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1973 vim_free(line->sb_cells);
1974 --gap->ga_len;
1975 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001976 curbuf = curwin->w_buffer;
1977 if (curbuf == term->tl_buffer)
1978 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001979}
1980
1981/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001982 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001983 */
1984 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001985update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001986{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001987 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001988 int len;
1989 int lines_skipped = 0;
1990 VTermPos pos;
1991 VTermScreenCell cell;
1992 cellattr_T fill_attr, new_fill_attr;
1993 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001994
1995 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1996 "Adding terminal window snapshot to buffer");
1997
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001998 // First remove the lines that were appended before, they might be
1999 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002000 cleanup_scrollback(term);
2001
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002002 screen = vterm_obtain_screen(term->tl_vterm);
2003 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002004 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
2005 {
2006 len = 0;
2007 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
2008 if (vterm_screen_get_cell(screen, pos, &cell) != 0
2009 && cell.chars[0] != NUL)
2010 {
2011 len = pos.col + 1;
2012 new_fill_attr = term->tl_default_color;
2013 }
2014 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002015 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016 cell2cellattr(&cell, &new_fill_attr);
2017
2018 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
2019 ++lines_skipped;
2020 else
2021 {
2022 while (lines_skipped > 0)
2023 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002024 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002025 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002026 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002027 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 }
2029
2030 if (len == 0)
2031 p = NULL;
2032 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002033 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002034 if ((p != NULL || len == 0)
2035 && ga_grow(&term->tl_scrollback, 1) == OK)
2036 {
2037 garray_T ga;
2038 int width;
2039 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
2040 + term->tl_scrollback.ga_len;
2041
2042 ga_init2(&ga, 1, 100);
2043 for (pos.col = 0; pos.col < len; pos.col += width)
2044 {
2045 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2046 {
2047 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02002048 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002049 if (ga_grow(&ga, 1) == OK)
2050 ga.ga_len += utf_char2bytes(' ',
2051 (char_u *)ga.ga_data + ga.ga_len);
2052 }
2053 else
2054 {
2055 width = cell.width;
2056
2057 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01002058 if (width == 2)
2059 // second cell of double-width character has the
2060 // same attributes.
2061 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002062
Bram Moolenaara79fd562018-12-20 20:47:32 +01002063 // Each character can be up to 6 bytes.
2064 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002065 {
2066 int i;
2067 int c;
2068
2069 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
2070 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2071 (char_u *)ga.ga_data + ga.ga_len);
2072 }
2073 }
2074 }
2075 line->sb_cols = len;
2076 line->sb_cells = p;
2077 line->sb_fill_attr = new_fill_attr;
2078 fill_attr = new_fill_attr;
2079 ++term->tl_scrollback.ga_len;
2080
2081 if (ga_grow(&ga, 1) == FAIL)
2082 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2083 else
2084 {
2085 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2086 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2087 }
2088 ga_clear(&ga);
2089 }
2090 else
2091 vim_free(p);
2092 }
2093 }
2094
Bram Moolenaarf3aea592018-11-11 22:18:21 +01002095 // Add trailing empty lines.
2096 for (pos.row = term->tl_scrollback.ga_len;
2097 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
2098 ++pos.row)
2099 {
2100 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
2101 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2102 }
2103
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002104 term->tl_dirty_snapshot = FALSE;
2105#ifdef FEAT_TIMERS
2106 term->tl_timer_set = FALSE;
2107#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002108}
2109
2110/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002111 * Loop over all windows in the current tab, and also curwin, which is not
2112 * encountered when using a terminal in a popup window.
2113 * Return TRUE if "*wp" was set to the next window.
2114 */
2115 static int
2116for_all_windows_and_curwin(win_T **wp, int *did_curwin)
2117{
2118 if (*wp == NULL)
2119 *wp = firstwin;
2120 else if ((*wp)->w_next != NULL)
2121 *wp = (*wp)->w_next;
2122 else if (!*did_curwin)
2123 *wp = curwin;
2124 else
2125 return FALSE;
2126 if (*wp == curwin)
2127 *did_curwin = TRUE;
2128 return TRUE;
2129}
2130
2131/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002132 * If needed, add the current lines of the terminal to scrollback and to the
2133 * buffer. Called after the job has ended and when switching to
2134 * Terminal-Normal mode.
2135 * When "redraw" is TRUE redraw the windows that show the terminal.
2136 */
2137 static void
2138may_move_terminal_to_buffer(term_T *term, int redraw)
2139{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002140 if (term->tl_vterm == NULL)
2141 return;
2142
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002143 // Update the snapshot only if something changes or the buffer does not
2144 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002145 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2146 <= term->tl_scrollback_scrolled)
2147 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002148
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002149 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002150 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2151 &term->tl_default_color.fg, &term->tl_default_color.bg);
2152
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002153 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002154 {
2155 win_T *wp = NULL;
2156 int did_curwin = FALSE;
2157
2158 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002159 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002160 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002161 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002162 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2163 wp->w_cursor.col = 0;
2164 wp->w_valid = 0;
2165 if (wp->w_cursor.lnum >= wp->w_height)
2166 {
2167 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002168
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002169 if (wp->w_topline < min_topline)
2170 wp->w_topline = min_topline;
2171 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002172 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002173 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002174 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002175 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002176}
2177
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002178#if defined(FEAT_TIMERS) || defined(PROTO)
2179/*
2180 * Check if any terminal timer expired. If so, copy text from the terminal to
2181 * the buffer.
2182 * Return the time until the next timer will expire.
2183 */
2184 int
2185term_check_timers(int next_due_arg, proftime_T *now)
2186{
2187 term_T *term;
2188 int next_due = next_due_arg;
2189
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002190 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002191 {
2192 if (term->tl_timer_set && !term->tl_normal_mode)
2193 {
2194 long this_due = proftime_time_left(&term->tl_timer_due, now);
2195
2196 if (this_due <= 1)
2197 {
2198 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002199 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002200 }
2201 else if (next_due == -1 || next_due > this_due)
2202 next_due = this_due;
2203 }
2204 }
2205
2206 return next_due;
2207}
2208#endif
2209
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002210/*
2211 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2212 * otherwise end it.
2213 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002214 static void
2215set_terminal_mode(term_T *term, int normal_mode)
2216{
2217 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002218 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002219 if (!normal_mode)
2220 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002221 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002222 if (term->tl_buffer == curbuf)
2223 maketitle();
2224}
2225
2226/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002227 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002228 * Move the vterm contents into the scrollback buffer and free the vterm.
2229 */
2230 static void
2231cleanup_vterm(term_T *term)
2232{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002233 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002234 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002235 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002237}
2238
2239/*
2240 * Switch from Terminal-Job mode to Terminal-Normal mode.
2241 * Suspends updating the terminal window.
2242 */
2243 static void
2244term_enter_normal_mode(void)
2245{
2246 term_T *term = curbuf->b_term;
2247
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002248 set_terminal_mode(term, TRUE);
2249
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002250 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002251 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002252
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002253 // Move the window cursor to the position of the cursor in the
2254 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002255 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2256 + term->tl_cursor_pos.row + 1;
2257 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002258 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2259 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002260 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002261
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002262 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002263 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2264}
2265
2266/*
2267 * Returns TRUE if the current window contains a terminal and we are in
2268 * Terminal-Normal mode.
2269 */
2270 int
2271term_in_normal_mode(void)
2272{
2273 term_T *term = curbuf->b_term;
2274
2275 return term != NULL && term->tl_normal_mode;
2276}
2277
2278/*
2279 * Switch from Terminal-Normal mode to Terminal-Job mode.
2280 * Restores updating the terminal window.
2281 */
2282 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002283term_enter_job_mode(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002284{
2285 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002286
2287 set_terminal_mode(term, FALSE);
2288
2289 if (term->tl_channel_closed)
2290 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002291 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002292#ifdef FEAT_PROP_POPUP
2293 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002294 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002295#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002296}
2297
2298/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002299 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2300 * modifiers into a basic key. However, we may only find out after calling
2301 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2302 * "no_reduce_keys" before using it.
2303 */
2304typedef enum {
2305 NRKS_NONE, // initial value
2306 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2307 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2308 // check_no_reduce_keys(), must be decremented.
2309} reduce_key_state_T;
2310
2311static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2312
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002313/*
2314 * Return TRUE if the term is using modifyOtherKeys level 2 or the kitty
2315 * keyboard protocol.
2316 */
2317 static int
2318vterm_using_key_protocol(void)
2319{
2320 return curbuf->b_term != NULL
2321 && curbuf->b_term->tl_vterm != NULL
2322 && (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm)
2323 || vterm_is_kitty_keyboard(curbuf->b_term->tl_vterm));
2324}
2325
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002326 void
2327check_no_reduce_keys(void)
2328{
2329 if (no_reduce_key_state != NRKS_CHECK
2330 || no_reduce_keys >= 1
2331 || curbuf->b_term == NULL
2332 || curbuf->b_term->tl_vterm == NULL)
2333 return;
2334
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002335 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002336 {
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002337 // "modify_other_keys" or kitty keyboard protocol was enabled while
2338 // waiting.
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002339 no_reduce_key_state = NRKS_SET;
2340 ++no_reduce_keys;
2341 }
2342}
2343
2344/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002345 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002346 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002347 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002348 */
2349 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002350term_vgetc(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002351{
2352 int c;
2353 int save_State = State;
2354
Bram Moolenaar24959102022-05-07 20:01:16 +01002355 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002356 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002357#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358 ctrl_break_was_pressed = FALSE;
2359#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002360
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002361 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002362 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002363 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002364 no_reduce_key_state = NRKS_SET;
2365 }
2366 else
2367 {
2368 no_reduce_key_state = NRKS_CHECK;
2369 }
2370
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002371 c = vgetc();
2372 got_int = FALSE;
2373 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002374
2375 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002376 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002377 no_reduce_key_state = NRKS_NONE;
2378
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002379 return c;
2380}
2381
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002382static int mouse_was_outside = FALSE;
2383
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002384/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002385 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002386 * Return FAIL when the key needs to be handled in Normal mode.
2387 * Return OK when the key was dropped or sent to the terminal.
2388 */
2389 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002390send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002391{
2392 char msg[KEY_BUF_LEN];
2393 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002394 int dragging_outside = FALSE;
2395
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002396 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002397 switch (c)
2398 {
2399 case NUL:
2400 case K_ZERO:
2401 if (typed)
2402 stuffcharReadbuff(c);
2403 return FAIL;
2404
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002405 case K_TABLINE:
2406 stuffcharReadbuff(c);
2407 return FAIL;
2408
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002409 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002410 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002411 return FAIL;
2412
2413 case K_LEFTDRAG:
2414 case K_MIDDLEDRAG:
2415 case K_RIGHTDRAG:
2416 case K_X1DRAG:
2417 case K_X2DRAG:
2418 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002419 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002420 case K_LEFTMOUSE:
2421 case K_LEFTMOUSE_NM:
2422 case K_LEFTRELEASE:
2423 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002424 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002425 case K_MIDDLEMOUSE:
2426 case K_MIDDLERELEASE:
2427 case K_RIGHTMOUSE:
2428 case K_RIGHTRELEASE:
2429 case K_X1MOUSE:
2430 case K_X1RELEASE:
2431 case K_X2MOUSE:
2432 case K_X2RELEASE:
2433
2434 case K_MOUSEUP:
2435 case K_MOUSEDOWN:
2436 case K_MOUSELEFT:
2437 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002438 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002439 int row = mouse_row;
2440 int col = mouse_col;
2441
2442#ifdef FEAT_PROP_POPUP
2443 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002444 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002445 row -= popup_top_extra(curwin);
2446 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002447 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002448#endif
2449 if (row < W_WINROW(curwin)
2450 || row >= (W_WINROW(curwin) + curwin->w_height)
2451 || col < curwin->w_wincol
2452 || col >= W_ENDCOL(curwin)
2453 || dragging_outside)
2454 {
2455 // click or scroll outside the current window or on status
2456 // line or vertical separator
2457 if (typed)
2458 {
2459 stuffcharReadbuff(c);
2460 mouse_was_outside = TRUE;
2461 }
2462 return FAIL;
2463 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002464 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002465 break;
2466
2467 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002468 case K_SCRIPT_COMMAND:
2469 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002470 }
2471 if (typed)
2472 mouse_was_outside = FALSE;
2473
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002474 // Convert the typed key to a sequence of bytes for the job.
2475 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002476 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002477 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002478 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2479 (char_u *)msg, (int)len, NULL);
2480
2481 return OK;
2482}
2483
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002484/*
2485 * Handle CTRL-W "": send register contents to the job.
2486 */
2487 static void
2488term_paste_register(int prev_c UNUSED)
2489{
2490 int c;
2491 list_T *l;
2492 listitem_T *item;
2493 long reglen = 0;
2494 int type;
2495
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002496 if (add_to_showcmd(prev_c))
2497 if (add_to_showcmd('"'))
2498 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002499
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002500 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002501 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002502
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002504 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002505 return;
2506
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002507 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002508 if (c == '=' && get_expr_register() != '=')
2509 return;
2510 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002511 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002512 return;
2513
2514 l = (list_T *)get_reg_contents(c, GREG_LIST);
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002515 if (l == NULL)
2516 return;
2517
2518 type = get_reg_type(c, &reglen);
2519 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002520 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002521 char_u *s = tv_get_string(&item->li_tv);
2522#ifdef MSWIN
2523 char_u *tmp = s;
2524
2525 if (!enc_utf8 && enc_codepage > 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002526 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002527 WCHAR *ret = NULL;
2528 int length = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002529
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002530 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2531 (int)STRLEN(s), &ret, &length);
2532 if (ret != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002533 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002534 WideCharToMultiByte_alloc(CP_UTF8, 0,
2535 ret, length, (char **)&s, &length, 0, 0);
2536 vim_free(ret);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002537 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002538 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539#endif
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002540 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2541 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002542#ifdef MSWIN
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002543 if (tmp != s)
2544 vim_free(s);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002545#endif
2546
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002547 if (item->li_next != NULL || type == MLINE)
2548 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2549 (char_u *)"\r", 1, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002550 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002551 list_free(l);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002552}
2553
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002554/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002555 * Return TRUE when waiting for a character in the terminal, the cursor of the
2556 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002557 */
2558 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002559terminal_is_active(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002560{
2561 return in_terminal_loop != NULL;
2562}
2563
Bram Moolenaar83d47902020-03-26 20:34:00 +01002564/*
dundargocc57b5bc2022-11-02 13:30:51 +00002565 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002566 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002567 static int
2568term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002569{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002570 char_u *name;
2571
2572 if (wp != NULL && *wp->w_p_wcr != NUL)
2573 name = wp->w_p_wcr;
2574 else if (term->tl_highlight_name != NULL)
2575 name = term->tl_highlight_name;
2576 else
2577 name = (char_u*)"Terminal";
2578
2579 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002580}
2581
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002582#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002583 cursorentry_T *
2584term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2585{
2586 term_T *term = in_terminal_loop;
2587 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002588 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002589 guicolor_T term_fg = INVALCOLOR;
2590 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002591
Bram Moolenaara80faa82020-04-12 19:37:17 +02002592 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 entry.shape = entry.mshape =
2594 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2595 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2596 SHAPE_BLOCK;
2597 entry.percentage = 20;
2598 if (term->tl_cursor_blink)
2599 {
2600 entry.blinkwait = 700;
2601 entry.blinkon = 400;
2602 entry.blinkoff = 250;
2603 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002604
Bram Moolenaar83d47902020-03-26 20:34:00 +01002605 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002606 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002607 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002608 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002609 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002610 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002611 else
2612 *fg = gui.back_pixel;
2613
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002614 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002615 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002616 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002617 *bg = term_fg;
2618 else
2619 *bg = gui.norm_pixel;
2620 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002621 else
2622 *bg = color_name2handle(term->tl_cursor_color);
2623 entry.name = "n";
2624 entry.used_for = SHAPE_CURSOR;
2625
2626 return &entry;
2627}
2628#endif
2629
Bram Moolenaard317b382018-02-08 22:33:31 +01002630 static void
2631may_output_cursor_props(void)
2632{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002633 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002634 || last_set_cursor_shape != desired_cursor_shape
2635 || last_set_cursor_blink != desired_cursor_blink)
2636 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002637 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002638 last_set_cursor_shape = desired_cursor_shape;
2639 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002640 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002641 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002642 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002643 ui_cursor_shape_forced(TRUE);
2644 else
2645 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2646 }
2647}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002648
Bram Moolenaard317b382018-02-08 22:33:31 +01002649/*
2650 * Set the cursor color and shape, if not last set to these.
2651 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002652 static void
2653may_set_cursor_props(term_T *term)
2654{
2655#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002656 // For the GUI the cursor properties are obtained with
2657 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002658 if (gui.in_use)
2659 return;
2660#endif
2661 if (in_terminal_loop == term)
2662 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002663 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002664 desired_cursor_shape = term->tl_cursor_shape;
2665 desired_cursor_blink = term->tl_cursor_blink;
2666 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002667 }
2668}
2669
Bram Moolenaard317b382018-02-08 22:33:31 +01002670/*
2671 * Reset the desired cursor properties and restore them when needed.
2672 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002673 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002674prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002675{
2676#ifdef FEAT_GUI
2677 if (gui.in_use)
2678 return;
2679#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002680 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002681 desired_cursor_shape = -1;
2682 desired_cursor_blink = -1;
2683 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002684}
2685
2686/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002687 * Returns TRUE if the current window contains a terminal and we are sending
2688 * keys to the job.
2689 * If "check_job_status" is TRUE update the job status.
2690 */
2691 static int
2692term_use_loop_check(int check_job_status)
2693{
2694 term_T *term = curbuf->b_term;
2695
2696 return term != NULL
2697 && !term->tl_normal_mode
2698 && term->tl_vterm != NULL
2699 && term_job_running_check(term, check_job_status);
2700}
2701
2702/*
2703 * Returns TRUE if the current window contains a terminal and we are sending
2704 * keys to the job.
2705 */
2706 int
2707term_use_loop(void)
2708{
2709 return term_use_loop_check(FALSE);
2710}
2711
2712/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002713 * Called when entering a window with the mouse. If this is a terminal window
2714 * we may want to change state.
2715 */
2716 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00002717term_win_entered(void)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002718{
2719 term_T *term = curbuf->b_term;
2720
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002721 if (term == NULL)
2722 return;
2723
2724 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002725 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002726 reset_VIsual_and_resel();
2727 if (State & MODE_INSERT)
2728 stop_insert_mode = TRUE;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002729 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002730 mouse_was_outside = FALSE;
2731 enter_mouse_col = mouse_col;
2732 enter_mouse_row = mouse_row;
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002733}
2734
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002735 void
2736term_focus_change(int in_focus)
2737{
2738 term_T *term = curbuf->b_term;
2739
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002740 if (term == NULL || term->tl_vterm == NULL)
2741 return;
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002742
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002743 VTermState *state = vterm_obtain_state(term->tl_vterm);
2744
2745 if (in_focus)
2746 vterm_state_focus_in(state);
2747 else
2748 vterm_state_focus_out(state);
2749 term_forward_output(term);
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002750}
2751
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002752/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002753 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2754 * Return the Ctrl-key value in that case.
2755 */
2756 static int
2757raw_c_to_ctrl(int c)
2758{
2759 if ((mod_mask & MOD_MASK_CTRL)
2760 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2761 return c & 0x1f;
2762 return c;
2763}
2764
2765/*
2766 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002767 * Also when the Kitty keyboard protocol is used.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002768 * May set "mod_mask".
2769 */
2770 static int
2771ctrl_to_raw_c(int c)
2772{
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002773 if (c < 0x20 && vterm_using_key_protocol())
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002774 {
2775 mod_mask |= MOD_MASK_CTRL;
2776 return c + '@';
2777 }
2778 return c;
2779}
2780
2781/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002782 * Wait for input and send it to the job.
2783 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2784 * when there is no more typahead.
2785 * Return when the start of a CTRL-W command is typed or anything else that
2786 * should be handled as a Normal mode command.
2787 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2788 * the terminal was closed.
2789 */
2790 int
2791terminal_loop(int blocking)
2792{
2793 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002794 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002795 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002796 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002797#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002798 int tty_fd = curbuf->b_term->tl_job->jv_channel
2799 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002800#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002801 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002802
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002803 // Remember the terminal we are sending keys to. However, the terminal
2804 // might be closed while waiting for a character, e.g. typing "exit" in a
2805 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2806 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002807 in_terminal_loop = curbuf->b_term;
2808
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002809 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002810 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002811 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002812 if (termwinkey == Ctrl_W)
2813 termwinkey = 0;
2814 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002815 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002816 may_set_cursor_props(curbuf->b_term);
2817
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002818 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002819 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002820#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002821 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002822#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002823 // TODO: skip screen update when handling a sequence of keys.
2824 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002825 while (must_redraw != 0)
2826 if (update_screen(0) == FAIL)
2827 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002828 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002829 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002830 break;
2831
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002832 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002833 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002834
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002835 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002836 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002837 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002838 // Job finished while waiting for a character. Push back the
2839 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002840 if (raw_c != K_IGNORE)
2841 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002842 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002843 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002844 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002845 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002846 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002847
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002848#ifdef UNIX
2849 /*
2850 * The shell or another program may change the tty settings. Getting
2851 * them for every typed character is a bit of overhead, but it's needed
2852 * for the first character typed, e.g. when Vim starts in a shell.
2853 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002854 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002855 {
2856 ttyinfo_T info;
2857
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002858 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002859 if (get_tty_info(tty_fd, &info) == OK)
2860 term_backspace_char = info.backspace;
2861 }
2862#endif
2863
Bram Moolenaar4f974752019-02-17 17:44:42 +01002864#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002865 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2866 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002867 if (ctrl_break_was_pressed)
2868 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2869#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002870 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2871 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002872 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002873#ifdef FEAT_GUI
2874 && !curbuf->b_term->tl_system
2875#endif
2876 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002877 {
2878 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002879 int prev_raw_c = raw_c;
2880 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002881
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002882 if (add_to_showcmd(c))
2883 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002884
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002885 raw_c = term_vgetc();
2886 c = raw_c_to_ctrl(raw_c);
2887
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002889
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002890 if (!term_use_loop_check(TRUE)
2891 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002892 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002893 break;
2894
2895 if (prev_c == Ctrl_BSL)
2896 {
2897 if (c == Ctrl_N)
2898 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002899 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002900 term_enter_normal_mode();
2901 ret = FAIL;
2902 goto theend;
2903 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002904 // Send both keys to the terminal, first one here, second one
2905 // below.
2906 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2907 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002908 }
2909 else if (c == Ctrl_C)
2910 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002911 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002912 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2913 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002914 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002915 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002916 // "CTRL-W .": send CTRL-W to the job
2917 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002918 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002919 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002920 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002921 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002922 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002923 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002924 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 else if (c == 'N')
2926 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002927 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002928 term_enter_normal_mode();
2929 ret = FAIL;
2930 goto theend;
2931 }
2932 else if (c == '"')
2933 {
2934 term_paste_register(prev_c);
2935 continue;
2936 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002937 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002938 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002939 // space for CTRL-W, modifier, multi-byte char and NUL
2940 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002941
2942 // Put the command into the typeahead buffer, when using the
2943 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2944 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002945 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002946 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002947 ret = OK;
2948 goto theend;
2949 }
2950 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002951# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002952 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002953 {
2954 WCHAR wc;
2955 char_u mb[3];
2956
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002957 mb[0] = (unsigned)raw_c >> 8;
2958 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002959 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002960 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002961 }
2962# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002963 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002964 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002965 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002966 // We are sure to come back here, don't reset the cursor color
2967 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002968 restore_cursor = FALSE;
2969
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002970 ret = OK;
2971 goto theend;
2972 }
2973 }
2974 ret = FAIL;
2975
2976theend:
2977 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002978 if (restore_cursor)
2979 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002980
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002981 // Move a snapshot of the screen contents to the buffer, so that completion
2982 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002983 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2984 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002985
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002986 return ret;
2987}
2988
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002989 static void
2990may_toggle_cursor(term_T *term)
2991{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00002992 if (in_terminal_loop != term)
2993 return;
2994
2995 if (term->tl_cursor_visible)
2996 cursor_on();
2997 else
2998 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002999}
3000
3001/*
3002 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01003003 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003004 */
3005 static int
3006color2index(VTermColor *color, int fg, int *boldp)
3007{
3008 int red = color->red;
3009 int blue = color->blue;
3010 int green = color->green;
3011
LemonBoyb2b3acb2022-05-20 10:10:34 +01003012 *boldp = FALSE;
3013
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003014 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003015 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01003016
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003017 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003018 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003019 // Use the color as-is if possible, give up otherwise.
3020 if (color->index < t_colors)
3021 return color->index + 1;
3022 // 8-color terminals can actually display twice as many colors by
3023 // setting the high-intensity/bold bit.
3024 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003025 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01003026 *boldp = TRUE;
3027 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003028 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01003029 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003030 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01003031
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003032 if (t_colors >= 256)
3033 {
3034 if (red == blue && red == green)
3035 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003036 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003037 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003038 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
3039 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
3040 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003041 int i;
3042
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003043 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003044 return 17; // 00/00/00
3045 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003046 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003047 for (i = 0; i < 23; ++i)
3048 if (red < cutoff[i])
3049 return i + 233;
3050 return 256;
3051 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003052 {
3053 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
3054 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003055
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003056 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003057 for (ri = 0; ri < 5; ++ri)
3058 if (red < cutoff[ri])
3059 break;
3060 for (gi = 0; gi < 5; ++gi)
3061 if (green < cutoff[gi])
3062 break;
3063 for (bi = 0; bi < 5; ++bi)
3064 if (blue < cutoff[bi])
3065 break;
3066 return 17 + ri * 36 + gi * 6 + bi;
3067 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003068 }
3069 return 0;
3070}
3071
3072/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01003073 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003074 */
3075 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003076vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003077{
3078 int attr = 0;
3079
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003080 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003081 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003082 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003083 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003084 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003085 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003086 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003087 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003088 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003089 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003090 return attr;
3091}
3092
3093/*
3094 * Store Vterm attributes in "cell" from highlight flags.
3095 */
3096 static void
3097hl2vtermAttr(int attr, cellattr_T *cell)
3098{
Bram Moolenaara80faa82020-04-12 19:37:17 +02003099 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003100 if (attr & HL_BOLD)
3101 cell->attrs.bold = 1;
3102 if (attr & HL_UNDERLINE)
3103 cell->attrs.underline = 1;
3104 if (attr & HL_ITALIC)
3105 cell->attrs.italic = 1;
3106 if (attr & HL_STRIKETHROUGH)
3107 cell->attrs.strike = 1;
3108 if (attr & HL_INVERSE)
3109 cell->attrs.reverse = 1;
3110}
3111
3112/*
3113 * Convert the attributes of a vterm cell into an attribute index.
3114 */
3115 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003116cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003117 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003118 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003119 VTermScreenCellAttrs *cellattrs,
3120 VTermColor *cellfg,
3121 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003122{
3123 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003124 VTermColor *fg = cellfg;
3125 VTermColor *bg = cellbg;
3126 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3127 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3128
3129 if (is_default_fg || is_default_bg)
3130 {
3131 if (wp != NULL && *wp->w_p_wcr != NUL)
3132 {
3133 if (is_default_fg)
3134 fg = &wp->w_term_wincolor.fg;
3135 if (is_default_bg)
3136 bg = &wp->w_term_wincolor.bg;
3137 }
3138 else
3139 {
3140 if (is_default_fg)
3141 fg = &term->tl_default_color.fg;
3142 if (is_default_bg)
3143 bg = &term->tl_default_color.bg;
3144 }
3145 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003146
3147#ifdef FEAT_GUI
3148 if (gui.in_use)
3149 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003150 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3151 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3152 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153 }
3154 else
3155#endif
3156#ifdef FEAT_TERMGUICOLORS
3157 if (p_tgc)
3158 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003159 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3160 ? INVALCOLOR
3161 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3162 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3163 ? INVALCOLOR
3164 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3165 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003166 }
3167 else
3168#endif
3169 {
3170 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003171 int ctermfg = color2index(fg, TRUE, &bold);
3172 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003173
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003174 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003175 if (bold == TRUE)
3176 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003177
3178 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003179 }
3180 return 0;
3181}
3182
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003183 static void
3184set_dirty_snapshot(term_T *term)
3185{
3186 term->tl_dirty_snapshot = TRUE;
3187#ifdef FEAT_TIMERS
3188 if (!term->tl_normal_mode)
3189 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003190 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003191 profile_setlimit(100L, &term->tl_timer_due);
3192 term->tl_timer_set = TRUE;
3193 }
3194#endif
3195}
3196
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003197 static int
3198handle_damage(VTermRect rect, void *user)
3199{
3200 term_T *term = (term_T *)user;
3201
3202 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3203 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003204 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003205 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003206 return 1;
3207}
3208
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003209 static void
3210term_scroll_up(term_T *term, int start_row, int count)
3211{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003212 win_T *wp = NULL;
3213 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003214 VTermColor fg, bg;
3215 VTermScreenCellAttrs attr;
3216 int clear_attr;
3217
Bram Moolenaara80faa82020-04-12 19:37:17 +02003218 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003219
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003220 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003221 {
3222 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003223 {
3224 // Set the color to clear lines with.
3225 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3226 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003227 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003228 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003229 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003230 }
3231}
3232
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003233 static int
3234handle_moverect(VTermRect dest, VTermRect src, void *user)
3235{
3236 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003237 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003238
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003239 // Scrolling up is done much more efficiently by deleting lines instead of
3240 // redrawing the text. But avoid doing this multiple times, postpone until
3241 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003242 if (dest.start_col == src.start_col
3243 && dest.end_col == src.end_col
3244 && dest.start_row < src.start_row)
3245 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003246 if (dest.start_row == 0)
3247 term->tl_postponed_scroll += count;
3248 else
3249 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003250 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003251
3252 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3253 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003254 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003255
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003256 // Note sure if the scrolling will work correctly, let's do a complete
3257 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003258 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003259 return 1;
3260}
3261
3262 static int
3263handle_movecursor(
3264 VTermPos pos,
3265 VTermPos oldpos UNUSED,
3266 int visible,
3267 void *user)
3268{
3269 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003270 win_T *wp = NULL;
3271 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003272
3273 term->tl_cursor_pos = pos;
3274 term->tl_cursor_visible = visible;
3275
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003276 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003277 {
3278 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003279 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003280 }
3281 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003282 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003283
3284 return 1;
3285}
3286
3287 static int
3288handle_settermprop(
3289 VTermProp prop,
3290 VTermValue *value,
3291 void *user)
3292{
3293 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003294 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003295
3296 switch (prop)
3297 {
3298 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003299 if (disable_vterm_title_for_testing)
3300 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003301 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003302 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003303 if (strval == NULL)
3304 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003305 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003306 // a blank title isn't useful, make it empty, so that "running" is
3307 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003308 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003309 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003310 // Same as blank
3311 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003312 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003313 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3314 term->tl_title = NULL;
3315 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003316 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003317 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003318#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003319 else if (!enc_utf8 && enc_codepage > 0)
3320 {
3321 WCHAR *ret = NULL;
3322 int length = 0;
3323
3324 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003325 (char*)value->string.str,
3326 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003327 if (ret != NULL)
3328 {
3329 WideCharToMultiByte_alloc(enc_codepage, 0,
3330 ret, length, (char**)&term->tl_title,
3331 &length, 0, 0);
3332 vim_free(ret);
3333 }
3334 }
3335#endif
3336 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003337 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003338 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003339 strval = NULL;
3340 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003341 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003342 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003343 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003344 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003345 curwin->w_redr_status = TRUE;
3346 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003347 break;
3348
3349 case VTERM_PROP_CURSORVISIBLE:
3350 term->tl_cursor_visible = value->boolean;
3351 may_toggle_cursor(term);
3352 out_flush();
3353 break;
3354
3355 case VTERM_PROP_CURSORBLINK:
3356 term->tl_cursor_blink = value->boolean;
3357 may_set_cursor_props(term);
3358 break;
3359
3360 case VTERM_PROP_CURSORSHAPE:
3361 term->tl_cursor_shape = value->number;
3362 may_set_cursor_props(term);
3363 break;
3364
3365 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003366 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003367 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003368 if (strval == NULL)
3369 break;
3370 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003371 may_set_cursor_props(term);
3372 break;
3373
3374 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003375 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003376 term->tl_using_altscreen = value->boolean;
3377 break;
3378
3379 default:
3380 break;
3381 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003382 vim_free(strval);
3383
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003384 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003385 return 1;
3386}
3387
3388/*
3389 * The job running in the terminal resized the terminal.
3390 */
3391 static int
3392handle_resize(int rows, int cols, void *user)
3393{
3394 term_T *term = (term_T *)user;
3395 win_T *wp;
3396
3397 term->tl_rows = rows;
3398 term->tl_cols = cols;
3399 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003400 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003401 term->tl_vterm_size_changed = FALSE;
3402 else
3403 {
3404 FOR_ALL_WINDOWS(wp)
3405 {
3406 if (wp->w_buffer == term->tl_buffer)
3407 {
3408 win_setheight_win(rows, wp);
3409 win_setwidth_win(cols, wp);
3410 }
3411 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003412 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003413 }
3414 return 1;
3415}
3416
3417/*
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003418 * If the number of lines that are stored goes over 'termwinscroll' then
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003419 * delete the first 10%.
3420 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3421 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003422 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003423 static void
3424limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003425{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003426 if (gap->ga_len < term->tl_buffer->b_p_twsl)
3427 return;
3428
3429 int todo = term->tl_buffer->b_p_twsl / 10;
3430 int i;
3431
3432 curbuf = term->tl_buffer;
3433 for (i = 0; i < todo; ++i)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003434 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003435 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003436 if (update_buffer)
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003437 ml_delete(1);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003438 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003439 curbuf = curwin->w_buffer;
3440
3441 gap->ga_len -= todo;
3442 mch_memmove(gap->ga_data,
3443 (sb_line_T *)gap->ga_data + todo,
3444 sizeof(sb_line_T) * gap->ga_len);
3445 if (update_buffer)
3446 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003447}
3448
3449/*
3450 * Handle a line that is pushed off the top of the screen.
3451 */
3452 static int
3453handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3454{
3455 term_T *term = (term_T *)user;
3456 garray_T *gap;
3457 int update_buffer;
3458
3459 if (term->tl_normal_mode)
3460 {
3461 // In Terminal-Normal mode the user interacts with the buffer, thus we
3462 // must not change it. Postpone adding the scrollback lines.
3463 gap = &term->tl_scrollback_postponed;
3464 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003465 }
3466 else
3467 {
3468 // First remove the lines that were appended before, the pushed line
3469 // goes above it.
3470 cleanup_scrollback(term);
3471 gap = &term->tl_scrollback;
3472 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003473 }
3474
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003475 limit_scrollback(term, gap, update_buffer);
3476
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003477 if (ga_grow(gap, 1) == FAIL)
3478 return 0;
3479
3480 cellattr_T *p = NULL;
3481 int len = 0;
3482 int i;
3483 int c;
3484 int col;
3485 int text_len;
3486 char_u *text;
3487 sb_line_T *line;
3488 garray_T ga;
3489 cellattr_T fill_attr = term->tl_default_color;
3490
3491 // do not store empty cells at the end
3492 for (i = 0; i < cols; ++i)
3493 if (cells[i].chars[0] != 0)
3494 len = i + 1;
3495 else
3496 cell2cellattr(&cells[i], &fill_attr);
3497
3498 ga_init2(&ga, 1, 100);
3499 if (len > 0)
3500 p = ALLOC_MULT(cellattr_T, len);
3501 if (p != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003502 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003503 for (col = 0; col < len; col += cells[col].width)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003504 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003505 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003506 {
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003507 ga.ga_len = 0;
3508 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003509 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003510 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3511 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3512 (char_u *)ga.ga_data + ga.ga_len);
3513 cell2cellattr(&cells[col], &p[col]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003514 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003515 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003516 if (ga_grow(&ga, 1) == FAIL)
3517 {
3518 if (update_buffer)
3519 text = (char_u *)"";
3520 else
3521 text = vim_strsave((char_u *)"");
3522 text_len = 0;
3523 }
3524 else
3525 {
3526 text = ga.ga_data;
3527 text_len = ga.ga_len;
3528 *(text + text_len) = NUL;
3529 }
3530 if (update_buffer)
3531 add_scrollback_line_to_buffer(term, text, text_len);
3532
3533 line = (sb_line_T *)gap->ga_data + gap->ga_len;
3534 line->sb_cols = len;
3535 line->sb_cells = p;
3536 line->sb_fill_attr = fill_attr;
3537 if (update_buffer)
3538 {
3539 line->sb_text = NULL;
3540 ++term->tl_scrollback_scrolled;
3541 ga_clear(&ga); // free the text
3542 }
3543 else
3544 {
3545 line->sb_text = text;
3546 ga_init(&ga); // text is kept in tl_scrollback_postponed
3547 }
3548 ++gap->ga_len;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003549 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003550}
3551
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003552/*
3553 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3554 * received and stored in tl_scrollback_postponed.
3555 */
3556 static void
3557handle_postponed_scrollback(term_T *term)
3558{
3559 int i;
3560
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003561 if (term->tl_scrollback_postponed.ga_len == 0)
3562 return;
3563 ch_log(NULL, "Moving postponed scrollback to scrollback");
3564
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003565 // First remove the lines that were appended before, the pushed lines go
3566 // above it.
3567 cleanup_scrollback(term);
3568
3569 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3570 {
3571 char_u *text;
3572 sb_line_T *pp_line;
3573 sb_line_T *line;
3574
3575 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3576 break;
3577 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3578
3579 text = pp_line->sb_text;
3580 if (text == NULL)
3581 text = (char_u *)"";
3582 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3583 vim_free(pp_line->sb_text);
3584
3585 line = (sb_line_T *)term->tl_scrollback.ga_data
3586 + term->tl_scrollback.ga_len;
3587 line->sb_cols = pp_line->sb_cols;
3588 line->sb_cells = pp_line->sb_cells;
3589 line->sb_fill_attr = pp_line->sb_fill_attr;
3590 line->sb_text = NULL;
3591 ++term->tl_scrollback_scrolled;
3592 ++term->tl_scrollback.ga_len;
3593 }
3594
3595 ga_clear(&term->tl_scrollback_postponed);
3596 limit_scrollback(term, &term->tl_scrollback, TRUE);
3597}
3598
LemonBoy77771d32022-04-13 11:47:25 +01003599/*
3600 * Called when the terminal wants to ring the system bell.
3601 */
3602 static int
3603handle_bell(void *user UNUSED)
3604{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003605 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003606 return 0;
3607}
3608
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003609static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003610 handle_damage, // damage
3611 handle_moverect, // moverect
3612 handle_movecursor, // movecursor
3613 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003614 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003615 handle_resize, // resize
3616 handle_pushline, // sb_pushline
Bram Moolenaar6a12d262022-10-16 19:26:52 +01003617 NULL, // sb_popline
3618 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003619};
3620
3621/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003622 * Do the work after the channel of a terminal was closed.
3623 * Must be called only when updating_screen is FALSE.
3624 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3625 */
3626 static int
3627term_after_channel_closed(term_T *term)
3628{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003629 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003630 if (!term->tl_normal_mode)
3631 {
3632 int fnum = term->tl_buffer->b_fnum;
3633
3634 cleanup_vterm(term);
3635
3636 if (term->tl_finish == TL_FINISH_CLOSE)
3637 {
3638 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003639 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003640#ifdef FEAT_PROP_POPUP
3641 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003642
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003643 // If this was a terminal in a popup window, go back to the
3644 // previous window.
3645 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3646 {
3647 pwin = curwin;
3648 if (win_valid(prevwin))
3649 win_enter(prevwin, FALSE);
3650 }
3651 else
3652#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003653 // If this is the last normal window: exit Vim.
3654 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3655 {
3656 exarg_T ea;
3657
Bram Moolenaara80faa82020-04-12 19:37:17 +02003658 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003659 ex_quit(&ea);
3660 return TRUE;
3661 }
3662
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003663 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003664 ch_log(NULL, "terminal job finished, closing window");
3665 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaare76062c2022-11-28 18:51:43 +00003666 if (curbuf == term->tl_buffer)
3667 {
3668 // Avoid closing the window if we temporarily use it.
3669 if (is_aucmd_win(curwin))
3670 do_set_w_closing = TRUE;
3671 if (do_set_w_closing)
3672 curwin->w_closing = TRUE;
3673 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
3674 if (do_set_w_closing)
3675 curwin->w_closing = FALSE;
3676 aucmd_restbuf(&aco);
3677 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003678#ifdef FEAT_PROP_POPUP
3679 if (pwin != NULL)
3680 popup_close_with_retval(pwin, 0);
3681#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003682 return TRUE;
3683 }
3684 if (term->tl_finish == TL_FINISH_OPEN
3685 && term->tl_buffer->b_nwindows == 0)
3686 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003687 char *cmd = term->tl_opencmd == NULL
3688 ? "botright sbuf %d"
3689 : (char *)term->tl_opencmd;
3690 size_t len = strlen(cmd) + 50;
3691 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003692
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003693 if (buf != NULL)
3694 {
3695 ch_log(NULL, "terminal job finished, opening window");
3696 vim_snprintf(buf, len, cmd, fnum);
3697 do_cmdline_cmd((char_u *)buf);
3698 vim_free(buf);
3699 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003700 }
3701 else
3702 ch_log(NULL, "terminal job finished");
3703 }
3704
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003705 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003706 return FALSE;
3707}
3708
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003709#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3710/*
3711 * If the current window is a terminal in a popup window and the job has
3712 * finished, close the popup window and to back to the previous window.
3713 * Otherwise return FAIL.
3714 */
3715 int
3716may_close_term_popup(void)
3717{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003718 if (!popup_is_popup(curwin) || curbuf->b_term == NULL
3719 || term_job_running_not_none(curbuf->b_term))
3720 return FAIL;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003721
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00003722 win_T *pwin = curwin;
3723
3724 if (win_valid(prevwin))
3725 win_enter(prevwin, FALSE);
3726 popup_close_with_retval(pwin, 0);
3727 return OK;
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003728}
3729#endif
3730
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003731/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003732 * Called when a channel is going to be closed, before invoking the close
3733 * callback.
3734 */
3735 void
3736term_channel_closing(channel_T *ch)
3737{
3738 term_T *term;
3739
3740 for (term = first_term; term != NULL; term = term->tl_next)
3741 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3742 term->tl_channel_closing = TRUE;
3743}
3744
3745/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003746 * Called when a channel has been closed.
3747 * If this was a channel for a terminal window then finish it up.
3748 */
3749 void
3750term_channel_closed(channel_T *ch)
3751{
3752 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003753 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003754 int did_one = FALSE;
3755
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003756 for (term = first_term; term != NULL; term = next_term)
3757 {
3758 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003759 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003760 {
3761 term->tl_channel_closed = TRUE;
3762 did_one = TRUE;
3763
Bram Moolenaard23a8232018-02-10 18:45:26 +01003764 VIM_CLEAR(term->tl_title);
3765 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003766#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003767 if (term->tl_out_fd != NULL)
3768 {
3769 fclose(term->tl_out_fd);
3770 term->tl_out_fd = NULL;
3771 }
3772#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003773
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003774 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003775 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003776 // Cannot open or close windows now. Can happen when
3777 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003778 term->tl_channel_recently_closed = TRUE;
3779 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003780 }
3781
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003782 if (term_after_channel_closed(term))
3783 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003784 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003785 }
3786
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003787 if (did_one)
3788 {
3789 redraw_statuslines();
3790
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003791 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003792 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003793 typebuf_was_filled = TRUE;
3794
3795 term = curbuf->b_term;
3796 if (term != NULL)
3797 {
3798 if (term->tl_job == ch->ch_job)
3799 maketitle();
3800 update_cursor(term, term->tl_cursor_visible);
3801 }
3802 }
3803}
3804
3805/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003806 * To be called after resetting updating_screen: handle any terminal where the
3807 * channel was closed.
3808 */
3809 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003810term_check_channel_closed_recently(void)
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003811{
3812 term_T *term;
3813 term_T *next_term;
3814
3815 for (term = first_term; term != NULL; term = next_term)
3816 {
3817 next_term = term->tl_next;
3818 if (term->tl_channel_recently_closed)
3819 {
3820 term->tl_channel_recently_closed = FALSE;
3821 if (term_after_channel_closed(term))
3822 // start over, the list may have changed
3823 next_term = first_term;
3824 }
3825 }
3826}
3827
3828/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003829 * Fill one screen line from a line of the terminal.
3830 * Advances "pos" to past the last column.
3831 */
3832 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003833term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003834 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003835 win_T *wp,
3836 VTermScreen *screen,
3837 VTermPos *pos,
3838 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003839{
3840 int off = screen_get_current_line_off();
3841
3842 for (pos->col = 0; pos->col < max_col; )
3843 {
3844 VTermScreenCell cell;
3845 int c;
3846
3847 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003848 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003849
3850 c = cell.chars[0];
3851 if (c == NUL)
3852 {
3853 ScreenLines[off] = ' ';
3854 if (enc_utf8)
3855 ScreenLinesUC[off] = NUL;
3856 }
3857 else
3858 {
3859 if (enc_utf8)
3860 {
3861 int i;
3862
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003863 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003864 for (i = 0; i < Screen_mco
3865 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3866 {
3867 ScreenLinesC[i][off] = cell.chars[i + 1];
3868 if (cell.chars[i + 1] == 0)
3869 break;
3870 }
3871 if (c >= 0x80 || (Screen_mco > 0
3872 && ScreenLinesC[0][off] != 0))
3873 {
3874 ScreenLines[off] = ' ';
3875 ScreenLinesUC[off] = c;
3876 }
3877 else
3878 {
3879 ScreenLines[off] = c;
3880 ScreenLinesUC[off] = NUL;
3881 }
3882 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003883#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003884 else if (has_mbyte && c >= 0x80)
3885 {
3886 char_u mb[MB_MAXBYTES+1];
3887 WCHAR wc = c;
3888
3889 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3890 (char*)mb, 2, 0, 0) > 1)
3891 {
3892 ScreenLines[off] = mb[0];
3893 ScreenLines[off + 1] = mb[1];
3894 cell.width = mb_ptr2cells(mb);
3895 }
3896 else
3897 ScreenLines[off] = c;
3898 }
3899#endif
3900 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003901 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003902 ScreenLines[off] = c;
3903 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003904 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3905 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003906
3907 ++pos->col;
3908 ++off;
3909 if (cell.width == 2)
3910 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003911 // don't set the second byte to NUL for a DBCS encoding, it
3912 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003913 if (enc_utf8)
3914 {
3915 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003916 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003917 }
3918 else if (!has_mbyte)
3919 {
3920 // Can't show a double-width character with a single-byte
3921 // 'encoding', just use a space.
3922 ScreenLines[off] = ' ';
3923 ScreenAttrs[off] = ScreenAttrs[off - 1];
3924 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003925
3926 ++pos->col;
3927 ++off;
3928 }
3929 }
3930}
3931
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003932#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003933 static void
3934update_system_term(term_T *term)
3935{
3936 VTermPos pos;
3937 VTermScreen *screen;
3938
3939 if (term->tl_vterm == NULL)
3940 return;
3941 screen = vterm_obtain_screen(term->tl_vterm);
3942
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003943 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003944 while (term->tl_toprow > 0
3945 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3946 {
3947 int save_p_more = p_more;
3948
3949 p_more = FALSE;
3950 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003951 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003952 p_more = save_p_more;
3953 --term->tl_toprow;
3954 }
3955
3956 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3957 && pos.row < Rows; ++pos.row)
3958 {
3959 if (pos.row < term->tl_rows)
3960 {
3961 int max_col = MIN(Columns, term->tl_cols);
3962
Bram Moolenaar83d47902020-03-26 20:34:00 +01003963 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003964 }
3965 else
3966 pos.col = 0;
3967
Bram Moolenaar510f0372022-07-04 17:46:22 +01003968 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003969 }
3970
3971 term->tl_dirty_row_start = MAX_ROW;
3972 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003973}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003974#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003975
3976/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003977 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3978 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003979 * Terminal-Normal mode.
3980 */
3981 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003982term_do_update_window(win_T *wp)
3983{
3984 term_T *term = wp->w_buffer->b_term;
3985
3986 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3987}
3988
3989/*
3990 * Called to update a window that contains an active terminal.
3991 */
3992 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003993term_update_window(win_T *wp)
3994{
3995 term_T *term = wp->w_buffer->b_term;
3996 VTerm *vterm;
3997 VTermScreen *screen;
3998 VTermState *state;
3999 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004000 int rows, cols;
4001 int newrows, newcols;
4002 int minsize;
4003 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004004
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004005 vterm = term->tl_vterm;
4006 screen = vterm_obtain_screen(vterm);
4007 state = vterm_obtain_state(vterm);
4008
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004009 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
4010 // With UPD_SOME_VALID only redraw what was marked dirty.
4011 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004012 {
4013 term->tl_dirty_row_start = 0;
4014 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004015
4016 if (term->tl_postponed_scroll > 0
4017 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004018 // Scrolling is usually faster than redrawing, when there are only
4019 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02004020 term_scroll_up(term, 0, term->tl_postponed_scroll);
4021 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02004022 }
4023
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004024 /*
4025 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004026 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004027 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02004028 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004029
Bram Moolenaar498c2562018-04-15 23:45:15 +02004030 newrows = 99999;
4031 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004032 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02004033 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004034 // Always use curwin, it may be a popup window.
4035 win_T *wwp = twp == NULL ? curwin : twp;
4036
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004037 // When more than one window shows the same terminal, use the
4038 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004039 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004040 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004041 newrows = MIN(newrows, wwp->w_height);
4042 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004043 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004044 if (twp == NULL)
4045 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004046 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02004047 if (newrows == 99999 || newcols == 99999)
4048 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02004049 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
4050 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
4051
Bram Moolenaareba13e42021-02-23 17:47:23 +01004052 // If no cell is visible there is no point in resizing. Also, vterm can't
4053 // handle a zero height.
4054 if (newrows == 0 || newcols == 0)
4055 return;
4056
Bram Moolenaar498c2562018-04-15 23:45:15 +02004057 if (term->tl_rows != newrows || term->tl_cols != newcols)
4058 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004059 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02004060 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004061 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02004062 newrows);
4063 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02004064
4065 // Updating the terminal size will cause the snapshot to be cleared.
4066 // When not in terminal_loop() we need to restore it.
4067 if (term != in_terminal_loop)
4068 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004069 }
4070
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004071 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004072 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01004073 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004074
Bram Moolenaar3a497e12017-09-30 20:40:27 +02004075 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
4076 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004077 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004078 if (pos.row < term->tl_rows)
4079 {
Bram Moolenaar13568252018-03-16 20:46:58 +01004080 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004081
Bram Moolenaar83d47902020-03-26 20:34:00 +01004082 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004083 }
4084 else
4085 pos.col = 0;
4086
Bram Moolenaar510f0372022-07-04 17:46:22 +01004087 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01004088#ifdef FEAT_MENU
4089 + winbar_height(wp)
4090#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004091 , wp->w_wincol, pos.col, wp->w_width,
4092#ifdef FEAT_PROP_POPUP
4093 popup_is_popup(wp) ? SLF_POPUP :
4094#endif
4095 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004096 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00004097}
4098
4099/*
4100 * Called after updating all windows: may reset dirty rows.
4101 */
4102 void
4103term_did_update_window(win_T *wp)
4104{
4105 term_T *term = wp->w_buffer->b_term;
4106
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004107 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode
4108 || wp->w_redr_type != 0)
4109 return;
4110
4111 term->tl_dirty_row_start = MAX_ROW;
4112 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004113}
4114
4115/*
4116 * Return TRUE if "wp" is a terminal window where the job has finished.
4117 */
4118 int
4119term_is_finished(buf_T *buf)
4120{
4121 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
4122}
4123
4124/*
4125 * Return TRUE if "wp" is a terminal window where the job has finished or we
4126 * are in Terminal-Normal mode, thus we show the buffer contents.
4127 */
4128 int
4129term_show_buffer(buf_T *buf)
4130{
4131 term_T *term = buf->b_term;
4132
4133 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4134}
4135
4136/*
4137 * The current buffer is going to be changed. If there is terminal
4138 * highlighting remove it now.
4139 */
4140 void
4141term_change_in_curbuf(void)
4142{
4143 term_T *term = curbuf->b_term;
4144
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004145 if (!term_is_finished(curbuf) || term->tl_scrollback.ga_len <= 0)
4146 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004147
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00004148 free_scrollback(term);
4149 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
4150
4151 // The buffer is now like a normal buffer, it cannot be easily
4152 // abandoned when changed.
4153 set_string_option_direct((char_u *)"buftype", -1,
4154 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004155}
4156
4157/*
4158 * Get the screen attribute for a position in the buffer.
4159 * Use a negative "col" to get the filler background color.
4160 */
4161 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004162term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004163{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004164 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004165 term_T *term = buf->b_term;
4166 sb_line_T *line;
4167 cellattr_T *cellattr;
4168
4169 if (lnum > term->tl_scrollback.ga_len)
4170 cellattr = &term->tl_default_color;
4171 else
4172 {
4173 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4174 if (col < 0 || col >= line->sb_cols)
4175 cellattr = &line->sb_fill_attr;
4176 else
4177 cellattr = line->sb_cells + col;
4178 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004179 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004180}
4181
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004182/*
4183 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004184 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004185 */
4186 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004187cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004188{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004189 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4190 if (rgb->index == 0)
4191 rgb->type = VTERM_COLOR_RGB;
4192 else
4193 {
4194 rgb->type = VTERM_COLOR_INDEXED;
4195 --rgb->index;
4196 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004197}
4198
4199/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004200 * Initialize vterm color from the synID.
4201 * Returns TRUE if color is set to "fg" and "bg".
4202 * Otherwise returns FALSE.
4203 */
4204 static int
4205get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4206{
4207#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4208 // Use the actual color for the GUI and when 'termguicolors' is set.
4209 if (0
4210# ifdef FEAT_GUI
4211 || gui.in_use
4212# endif
4213# ifdef FEAT_TERMGUICOLORS
4214 || p_tgc
4215# ifdef FEAT_VTP
4216 // Finally get INVALCOLOR on this execution path
4217 || (!p_tgc && t_colors >= 256)
4218# endif
4219# endif
4220 )
4221 {
4222 guicolor_T fg_rgb = INVALCOLOR;
4223 guicolor_T bg_rgb = INVALCOLOR;
4224
4225 if (id > 0)
4226 syn_id2colors(id, &fg_rgb, &bg_rgb);
4227
4228 if (fg_rgb != INVALCOLOR)
4229 {
4230 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4231 fg->red = (unsigned)(rgb >> 16);
4232 fg->green = (unsigned)(rgb >> 8) & 255;
4233 fg->blue = (unsigned)rgb & 255;
4234 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4235 }
4236 else
4237 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4238
4239 if (bg_rgb != INVALCOLOR)
4240 {
4241 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4242 bg->red = (unsigned)(rgb >> 16);
4243 bg->green = (unsigned)(rgb >> 8) & 255;
4244 bg->blue = (unsigned)rgb & 255;
4245 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4246 }
4247 else
4248 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4249
4250 return TRUE;
4251 }
4252 else
4253#endif
4254 if (t_colors >= 16)
4255 {
4256 int cterm_fg = -1;
4257 int cterm_bg = -1;
4258
4259 if (id > 0)
4260 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4261
4262 if (cterm_fg >= 0)
4263 {
4264 cterm_color2vterm(cterm_fg, fg);
4265 fg->type |= VTERM_COLOR_DEFAULT_FG;
4266 }
4267 else
4268 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4269
4270 if (cterm_bg >= 0)
4271 {
4272 cterm_color2vterm(cterm_bg, bg);
4273 bg->type |= VTERM_COLOR_DEFAULT_BG;
4274 }
4275 else
4276 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4277
4278 return TRUE;
4279 }
4280
4281 return FALSE;
4282}
4283
4284 void
4285term_reset_wincolor(win_T *wp)
4286{
4287 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4288 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4289}
4290
4291/*
4292 * Cache the color of 'wincolor'.
4293 */
4294 void
4295term_update_wincolor(win_T *wp)
4296{
4297 int id = 0;
4298
4299 if (*wp->w_p_wcr != NUL)
4300 id = syn_name2id(wp->w_p_wcr);
4301 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4302 &wp->w_term_wincolor.bg))
4303 term_reset_wincolor(wp);
4304}
4305
4306/*
4307 * Called when option 'termguicolors' was set,
4308 * or when any highlight is changed.
4309 */
4310 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004311term_update_wincolor_all(void)
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004312{
4313 win_T *wp = NULL;
4314 int did_curwin = FALSE;
4315
4316 while (for_all_windows_and_curwin(&wp, &did_curwin))
4317 term_update_wincolor(wp);
4318}
4319
4320/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004321 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004322 */
4323 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004324init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004325{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004326 VTermColor *fg, *bg;
4327 int fgval, bgval;
4328 int id;
4329
Bram Moolenaara80faa82020-04-12 19:37:17 +02004330 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004331 term->tl_default_color.width = 1;
4332 fg = &term->tl_default_color.fg;
4333 bg = &term->tl_default_color.bg;
4334
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004335 // Vterm uses a default black background. Set it to white when
4336 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004337 if (*p_bg == 'l')
4338 {
4339 fgval = 0;
4340 bgval = 255;
4341 }
4342 else
4343 {
4344 fgval = 255;
4345 bgval = 0;
4346 }
4347 fg->red = fg->green = fg->blue = fgval;
4348 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004349 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4350 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004351
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004352 // The highlight group overrules the defaults.
4353 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004354
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004355 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004356 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004357#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004358 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004359#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004360
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004361 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004362 if (cterm_normal_fg_color > 0)
4363 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004364 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004365# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4366# ifdef VIMDLL
4367 if (!gui.in_use)
4368# endif
4369 {
4370 tmp = fg->red;
4371 fg->red = fg->blue;
4372 fg->blue = tmp;
4373 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004374# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004375 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004376# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004377 else
4378 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004379# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004380
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004381 if (cterm_normal_bg_color > 0)
4382 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004383 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004384# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4385# ifdef VIMDLL
4386 if (!gui.in_use)
4387# endif
4388 {
4389 tmp = fg->red;
4390 fg->red = fg->blue;
4391 fg->blue = tmp;
4392 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004393# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004394 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004395# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004396 else
4397 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004398# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004399 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004400}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004401
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004402#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4403/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004404 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4405 * "ansi_colors" argument in term_start()) shall be applied.
4406 */
4407 static int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004408term_use_palette(void)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004409{
4410 if (0
4411#ifdef FEAT_GUI
4412 || gui.in_use
4413#endif
4414#ifdef FEAT_TERMGUICOLORS
4415 || p_tgc
4416#endif
4417 )
4418 return TRUE;
4419 return FALSE;
4420}
4421
4422/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004423 * Set the 16 ANSI colors from array of RGB values
4424 */
4425 static void
4426set_vterm_palette(VTerm *vterm, long_u *rgb)
4427{
4428 int index = 0;
4429 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004430
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004431 for (; index < 16; index++)
4432 {
4433 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004434
Millyb771b6b2021-11-23 12:07:25 +00004435 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004436 color.red = (unsigned)(rgb[index] >> 16);
4437 color.green = (unsigned)(rgb[index] >> 8) & 255;
4438 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004439 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004440 vterm_state_set_palette_color(state, index, &color);
4441 }
4442}
4443
4444/*
4445 * Set the ANSI color palette from a list of colors
4446 */
4447 static int
4448set_ansi_colors_list(VTerm *vterm, list_T *list)
4449{
4450 int n = 0;
4451 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004452 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004453
Bram Moolenaarb0992022020-01-30 14:55:42 +01004454 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004455 {
4456 char_u *color_name;
4457 guicolor_T guicolor;
4458
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004459 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004460 if (color_name == NULL)
4461 return FAIL;
4462
4463 guicolor = GUI_GET_COLOR(color_name);
4464 if (guicolor == INVALCOLOR)
4465 return FAIL;
4466
4467 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4468 }
4469
4470 if (n != 16 || li != NULL)
4471 return FAIL;
4472
4473 set_vterm_palette(vterm, rgb);
4474
4475 return OK;
4476}
4477
4478/*
4479 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4480 */
4481 static void
4482init_vterm_ansi_colors(VTerm *vterm)
4483{
4484 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4485
LemonBoyb2b3acb2022-05-20 10:10:34 +01004486 if (var == NULL)
4487 return;
4488
4489 if (var->di_tv.v_type != VAR_LIST
4490 || var->di_tv.vval.v_list == NULL
4491 || var->di_tv.vval.v_list->lv_first == &range_list_item
4492 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004493 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004494}
4495#endif
4496
Bram Moolenaar52acb112018-03-18 19:20:22 +01004497/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004498 * Handles a "drop" command from the job in the terminal.
4499 * "item" is the file name, "item->li_next" may have options.
4500 */
4501 static void
4502handle_drop_command(listitem_T *item)
4503{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004504 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004505 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004506 int bufnr;
4507 win_T *wp;
4508 tabpage_T *tp;
4509 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004510 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004511
4512 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4513 FOR_ALL_TAB_WINDOWS(tp, wp)
4514 {
4515 if (wp->w_buffer->b_fnum == bufnr)
4516 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004517 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004518 goto_tabpage_win(tp, wp);
4519 return;
4520 }
4521 }
4522
Bram Moolenaara80faa82020-04-12 19:37:17 +02004523 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004524
4525 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4526 && opt_item->li_tv.vval.v_dict != NULL)
4527 {
4528 dict_T *dict = opt_item->li_tv.vval.v_dict;
4529 char_u *p;
4530
Bram Moolenaard61efa52022-07-23 09:52:04 +01004531 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004532 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004533 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004534 if (p != NULL)
4535 {
4536 if (check_ff_value(p) == FAIL)
4537 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4538 else
4539 ea.force_ff = *p;
4540 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004541 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004542 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004543 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004544 if (p != NULL)
4545 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004546 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004547 if (ea.cmd != NULL)
4548 {
4549 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4550 ea.force_enc = 11;
4551 tofree = ea.cmd;
4552 }
4553 }
4554
Bram Moolenaard61efa52022-07-23 09:52:04 +01004555 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004556 if (p != NULL)
4557 get_bad_opt(p, &ea);
4558
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004559 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004560 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004561 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004562 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004563 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004564 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004565 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004566 ea.force_bin = FORCE_NOBIN;
4567 }
4568
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004569 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004570 if (ea.cmd == NULL)
4571 ea.cmd = (char_u *)"split";
4572 ea.arg = fname;
4573 ea.cmdidx = CMD_split;
4574 ex_splitview(&ea);
4575
4576 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004577}
4578
4579/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004580 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4581 */
4582 static int
4583is_permitted_term_api(char_u *func, char_u *pat)
4584{
4585 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4586}
4587
4588/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004589 * Handles a function call from the job running in a terminal.
4590 * "item" is the function name, "item->li_next" has the arguments.
4591 */
4592 static void
4593handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4594{
4595 char_u *func;
4596 typval_T argvars[2];
4597 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004598 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004599
4600 if (item->li_next == NULL)
4601 {
4602 ch_log(channel, "Missing function arguments for call");
4603 return;
4604 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004605 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004606
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004607 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004608 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004609 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004610 return;
4611 }
4612
4613 argvars[0].v_type = VAR_NUMBER;
4614 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4615 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004616 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004617 funcexe.fe_firstline = 1L;
4618 funcexe.fe_lastline = 1L;
4619 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004620 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004621 {
4622 clear_tv(&rettv);
4623 ch_log(channel, "Function %s called", func);
4624 }
4625 else
4626 ch_log(channel, "Calling function %s failed", func);
4627}
4628
4629/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004630 * URL decoding (also know as Percent-encoding).
4631 *
4632 * Note this function currently is only used for decoding shell's
4633 * OSC 7 escape sequence which we can assume all bytes are valid
4634 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4635 * encoding bytes like 0xfe, 0xff.
4636 */
4637 static size_t
4638url_decode(const char *src, const size_t len, char_u *dst)
4639{
4640 size_t i = 0, j = 0;
4641
4642 while (i < len)
4643 {
4644 if (src[i] == '%' && i + 2 < len)
4645 {
4646 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4647 j++;
4648 i += 3;
4649 }
4650 else
4651 {
4652 dst[j] = src[i];
4653 i++;
4654 j++;
4655 }
4656 }
4657 dst[j] = '\0';
4658 return j;
4659}
4660
4661/*
4662 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4663 *
4664 * The OSC 7 sequence has the format of
4665 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4666 * and what VTerm provides via VTermStringFragment is
4667 * "file://HOSTNAME/CURRENT/DIR"
4668 */
4669 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004670sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004671{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004672 int offset = 7; // len of "file://" is 7
4673 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004674 char_u *new_dir;
4675
4676 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004677 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004678 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004679 ++offset;
4680 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004681 }
4682
Bram Moolenaar474ad392022-08-21 11:37:17 +01004683 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004684 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004685 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004686 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004687 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004688 }
4689
Bram Moolenaar474ad392022-08-21 11:37:17 +01004690 new_dir = alloc(gap->ga_len - offset + 1);
4691 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004692 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4693 vim_free(new_dir);
4694}
4695
4696/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004697 * Called by libvterm when it cannot recognize an OSC sequence.
4698 * We recognize a terminal API command.
4699 */
4700 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004701parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004702{
4703 term_T *term = (term_T *)user;
4704 js_read_T reader;
4705 typval_T tv;
4706 channel_T *channel = term->tl_job == NULL ? NULL
4707 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004708 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004709
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004710 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004711 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004712 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004713
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004714 // Concatenate what was received until the final piece is found.
4715 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4716 {
4717 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004718 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004719 }
4720 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004721 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004722 if (!frag.final)
4723 return 1;
4724
4725 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004726
4727 if (command == 7)
4728 {
4729 sync_shell_dir(gap);
4730 ga_clear(gap);
4731 return 1;
4732 }
4733
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004734 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004735 reader.js_fill = NULL;
4736 reader.js_used = 0;
4737 if (json_decode(&reader, &tv, 0) == OK
4738 && tv.v_type == VAR_LIST
4739 && tv.vval.v_list != NULL)
4740 {
4741 listitem_T *item = tv.vval.v_list->lv_first;
4742
4743 if (item == NULL)
4744 ch_log(channel, "Missing command");
4745 else
4746 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004747 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004748
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004749 // Make sure an invoked command doesn't delete the buffer (and the
4750 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004751 ++term->tl_buffer->b_locked;
4752
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004753 item = item->li_next;
4754 if (item == NULL)
4755 ch_log(channel, "Missing argument for %s", cmd);
4756 else if (STRCMP(cmd, "drop") == 0)
4757 handle_drop_command(item);
4758 else if (STRCMP(cmd, "call") == 0)
4759 handle_call_command(term, channel, item);
4760 else
4761 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004762 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004763 }
4764 }
4765 else
4766 ch_log(channel, "Invalid JSON received");
4767
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004768 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004769 clear_tv(&tv);
4770 return 1;
4771}
4772
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004773/*
4774 * Called by libvterm when it cannot recognize a CSI sequence.
4775 * We recognize the window position report.
4776 */
4777 static int
4778parse_csi(
4779 const char *leader UNUSED,
4780 const long args[],
4781 int argcount,
4782 const char *intermed UNUSED,
4783 char command,
4784 void *user)
4785{
4786 term_T *term = (term_T *)user;
4787 char buf[100];
4788 int len;
4789 int x = 0;
4790 int y = 0;
4791 win_T *wp;
4792
4793 // We recognize only CSI 13 t
4794 if (command != 't' || argcount != 1 || args[0] != 13)
4795 return 0; // not handled
4796
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004797 // When getting the window position is not possible or it fails it results
4798 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004799#if defined(FEAT_GUI) \
4800 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4801 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004802 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004803#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004804
4805 FOR_ALL_WINDOWS(wp)
4806 if (wp->w_buffer == term->tl_buffer)
4807 break;
4808 if (wp != NULL)
4809 {
4810#ifdef FEAT_GUI
4811 if (gui.in_use)
4812 {
4813 x += wp->w_wincol * gui.char_width;
4814 y += W_WINROW(wp) * gui.char_height;
4815 }
4816 else
4817#endif
4818 {
4819 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004820 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004821 x += wp->w_wincol * 7;
4822 y += W_WINROW(wp) * 10;
4823 }
4824 }
4825
4826 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4827 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4828 (char_u *)buf, len, NULL);
4829 return 1;
4830}
4831
Bram Moolenaard8637282020-05-20 18:41:41 +02004832static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004833 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004834 parse_csi, // csi
4835 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004836 NULL, // dcs
4837 NULL, // apc
4838 NULL, // pm
4839 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004840};
4841
4842/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004843 * Use Vim's allocation functions for vterm so profiling works.
4844 */
4845 static void *
4846vterm_malloc(size_t size, void *data UNUSED)
4847{
Bram Moolenaar88137392021-11-12 16:01:15 +00004848 // make sure that the length is not zero
4849 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004850}
4851
4852 static void
4853vterm_memfree(void *ptr, void *data UNUSED)
4854{
4855 vim_free(ptr);
4856}
4857
4858static VTermAllocatorFunctions vterm_allocator = {
4859 &vterm_malloc,
4860 &vterm_memfree
4861};
4862
4863/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004864 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004865 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004866 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004867 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004868create_vterm(term_T *term, int rows, int cols)
4869{
4870 VTerm *vterm;
4871 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004872 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004873 VTermValue value;
4874
Bram Moolenaar756ef112018-04-10 12:04:27 +02004875 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004876 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004877 if (vterm == NULL)
4878 return FAIL;
4879
4880 // Allocate screen and state here, so we can bail out if that fails.
4881 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004882 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004883 if (state == NULL || screen == NULL)
4884 {
4885 vterm_free(vterm);
4886 return FAIL;
4887 }
4888
Bram Moolenaar52acb112018-03-18 19:20:22 +01004889 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004890 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004891 vterm_set_utf8(vterm, 1);
4892
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004893 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004894
4895 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004896 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004897 &term->tl_default_color.fg,
4898 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004899
Bram Moolenaar9e587872019-05-13 20:27:23 +02004900 if (t_colors < 16)
4901 // Less than 16 colors: assume that bold means using a bright color for
4902 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004903 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4904
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004905 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004906 vterm_screen_reset(screen, 1 /* hard */);
4907
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004908 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004909 vterm_screen_enable_altscreen(screen, 1);
4910
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004911 // For unix do not use a blinking cursor. In an xterm this causes the
4912 // cursor to blink if it's blinking in the xterm.
4913 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004914#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004915 if (GetCaretBlinkTime() == INFINITE)
4916 value.boolean = 0;
4917 else
4918 value.boolean = 1;
4919#else
4920 value.boolean = 0;
4921#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004922 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004923 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004924
4925 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004926}
4927
4928/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004929 * Reset the terminal palette to its default value.
4930 */
4931 static void
4932term_reset_palette(VTerm *vterm)
4933{
4934 VTermState *state = vterm_obtain_state(vterm);
4935 int index;
4936
4937 for (index = 0; index < 16; index++)
4938 {
4939 VTermColor color;
4940
4941 color.type = VTERM_COLOR_INDEXED;
4942 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4943 &color.index);
4944 // The first valid index starts at 1.
4945 color.index -= 1;
4946
4947 vterm_state_set_palette_color(state, index, &color);
4948 }
4949}
4950
4951 static void
4952term_update_palette(term_T *term)
4953{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004954#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004955 if (term_use_palette()
4956 && (term->tl_palette != NULL
4957 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004958 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004959 {
4960 if (term->tl_palette != NULL)
4961 set_vterm_palette(term->tl_vterm, term->tl_palette);
4962 else
4963 init_vterm_ansi_colors(term->tl_vterm);
4964 }
4965 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004966#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004967 term_reset_palette(term->tl_vterm);
4968}
4969
4970/*
4971 * Called when option 'termguicolors' is changed.
4972 */
4973 void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004974term_update_palette_all(void)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004975{
4976 term_T *term;
4977
4978 FOR_ALL_TERMS(term)
4979 {
4980 if (term->tl_vterm == NULL)
4981 continue;
4982 term_update_palette(term);
4983 }
4984}
4985
4986/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004987 * Called when option 'background' or 'termguicolors' was set,
4988 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02004989 */
4990 void
4991term_update_colors_all(void)
4992{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004993 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02004994
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004995 FOR_ALL_TERMS(term)
4996 {
4997 if (term->tl_vterm == NULL)
4998 continue;
4999 init_default_colors(term);
5000 vterm_state_set_default_colors(
5001 vterm_obtain_state(term->tl_vterm),
5002 &term->tl_default_color.fg,
5003 &term->tl_default_color.bg);
5004 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005005}
5006
5007/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005008 * Return the text to show for the buffer name and status.
5009 */
5010 char_u *
5011term_get_status_text(term_T *term)
5012{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005013 if (term->tl_status_text != NULL)
5014 return term->tl_status_text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005015
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005016 char_u *txt;
5017 size_t len;
5018 char_u *fname;
5019
5020 if (term->tl_normal_mode)
5021 {
5022 if (term_job_running(term))
5023 txt = (char_u *)_("Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005024 else
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005025 txt = (char_u *)_("Terminal-finished");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005026 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005027 else if (term->tl_title != NULL)
5028 txt = term->tl_title;
5029 else if (term_none_open(term))
5030 txt = (char_u *)_("active");
5031 else if (term_job_running(term))
5032 txt = (char_u *)_("running");
5033 else
5034 txt = (char_u *)_("finished");
5035 fname = buf_get_fname(term->tl_buffer);
5036 len = 9 + STRLEN(fname) + STRLEN(txt);
5037 term->tl_status_text = alloc(len);
5038 if (term->tl_status_text != NULL)
5039 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
5040 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005041 return term->tl_status_text;
5042}
5043
5044/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00005045 * Clear the cached value of the status text.
5046 */
5047 void
5048term_clear_status_text(term_T *term)
5049{
5050 VIM_CLEAR(term->tl_status_text);
5051}
5052
5053/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005054 * Mark references in jobs of terminals.
5055 */
5056 int
5057set_ref_in_term(int copyID)
5058{
5059 int abort = FALSE;
5060 term_T *term;
5061 typval_T tv;
5062
Bram Moolenaar75a1a942019-06-20 03:45:36 +02005063 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005064 if (term->tl_job != NULL)
5065 {
5066 tv.v_type = VAR_JOB;
5067 tv.vval.v_job = term->tl_job;
5068 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
5069 }
5070 return abort;
5071}
5072
5073/*
5074 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005075 * Returns NULL when the buffer is not for a terminal window and logs a message
5076 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005077 */
5078 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005079term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005080{
5081 buf_T *buf;
5082
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005083 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01005084 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005085 --emsg_off;
5086 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005087 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01005088 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005089 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005090 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005091 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005092 return buf;
5093}
5094
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005095 static void
5096clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005097{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005098 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005099 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
5100 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005101}
5102
5103 static void
5104dump_term_color(FILE *fd, VTermColor *color)
5105{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005106 int index;
5107
5108 if (VTERM_COLOR_IS_INDEXED(color))
5109 index = color->index + 1;
5110 else if (color->type == 0)
5111 // use RGB values
5112 index = 255;
5113 else
5114 // default color
5115 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005116 fprintf(fd, "%02x%02x%02x%d",
5117 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005118 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005119}
5120
5121/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005122 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01005123 *
5124 * Each screen cell in full is:
5125 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5126 * {characters} is a space for an empty cell
5127 * For a double-width character "+" is changed to "*" and the next cell is
5128 * skipped.
5129 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5130 * when "&" use the same as the previous cell.
5131 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5132 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5133 * {color-idx} is a number from 0 to 255
5134 *
5135 * Screen cell with same width, attributes and color as the previous one:
5136 * |{characters}
5137 *
5138 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5139 *
5140 * Repeating the previous screen cell:
5141 * @{count}
5142 */
5143 void
5144f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5145{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005146 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005147 term_T *term;
5148 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005149 int max_height = 0;
5150 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005151 stat_T st;
5152 FILE *fd;
5153 VTermPos pos;
5154 VTermScreen *screen;
5155 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005156 VTermState *state;
5157 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005158
5159 if (check_restricted() || check_secure())
5160 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005161
5162 if (in_vim9script()
5163 && (check_for_buffer_arg(argvars, 0) == FAIL
5164 || check_for_string_arg(argvars, 1) == FAIL
5165 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5166 return;
5167
5168 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005169 if (buf == NULL)
5170 return;
5171 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005172 if (term->tl_vterm == NULL)
5173 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005174 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005175 return;
5176 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005177
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005178 if (argvars[2].v_type != VAR_UNKNOWN)
5179 {
5180 dict_T *d;
5181
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005182 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005183 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005184 d = argvars[2].vval.v_dict;
5185 if (d != NULL)
5186 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005187 max_height = dict_get_number(d, "rows");
5188 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005189 }
5190 }
5191
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005192 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005193 if (fname == NULL)
5194 return;
5195 if (mch_stat((char *)fname, &st) >= 0)
5196 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005197 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005198 return;
5199 }
5200
Bram Moolenaard96ff162018-02-18 22:13:29 +01005201 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5202 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005203 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005204 return;
5205 }
5206
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005207 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005208
5209 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005210 state = vterm_obtain_state(term->tl_vterm);
5211 vterm_state_get_cursorpos(state, &cursor_pos);
5212
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005213 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5214 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005215 {
5216 int repeat = 0;
5217
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005218 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5219 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005220 {
5221 VTermScreenCell cell;
5222 int same_attr;
5223 int same_chars = TRUE;
5224 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005225 int is_cursor_pos = (pos.col == cursor_pos.col
5226 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005227
5228 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005229 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005230
5231 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5232 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005233 int c = cell.chars[i];
5234 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005235 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005236
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005237 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005238 if (i == 0)
5239 {
5240 c = (c == NUL) ? ' ' : c;
5241 pc = (pc == NUL) ? ' ' : pc;
5242 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005243 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005244 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005245 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005246 break;
5247 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005248 same_attr = vtermAttr2hl(&cell.attrs)
5249 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005250 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5251 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005252 if (same_chars && cell.width == prev_cell.width && same_attr
5253 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005254 {
5255 ++repeat;
5256 }
5257 else
5258 {
5259 if (repeat > 0)
5260 {
5261 fprintf(fd, "@%d", repeat);
5262 repeat = 0;
5263 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005264 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005265
5266 if (cell.chars[0] == NUL)
5267 fputs(" ", fd);
5268 else
5269 {
5270 char_u charbuf[10];
5271 int len;
5272
5273 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5274 && cell.chars[i] != NUL; ++i)
5275 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005276 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005277 fwrite(charbuf, len, 1, fd);
5278 }
5279 }
5280
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005281 // When only the characters differ we don't write anything, the
5282 // following "|", "@" or NL will indicate using the same
5283 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005284 if (cell.width != prev_cell.width || !same_attr)
5285 {
5286 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005287 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005288 else
5289 fputs("+", fd);
5290
5291 if (same_attr)
5292 {
5293 fputs("&", fd);
5294 }
5295 else
5296 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005297 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005298 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005299 fputs("&", fd);
5300 else
5301 {
5302 fputs("#", fd);
5303 dump_term_color(fd, &cell.fg);
5304 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005305 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005306 fputs("&", fd);
5307 else
5308 {
5309 fputs("#", fd);
5310 dump_term_color(fd, &cell.bg);
5311 }
5312 }
5313 }
5314
5315 prev_cell = cell;
5316 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005317
5318 if (cell.width == 2)
5319 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005320 }
5321 if (repeat > 0)
5322 fprintf(fd, "@%d", repeat);
5323 fputs("\n", fd);
5324 }
5325
5326 fclose(fd);
5327}
5328
5329/*
5330 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5331 */
5332 static void
5333dump_is_corrupt(garray_T *gap)
5334{
5335 ga_concat(gap, (char_u *)"CORRUPT");
5336}
5337
5338 static void
5339append_cell(garray_T *gap, cellattr_T *cell)
5340{
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00005341 if (ga_grow(gap, 1) == FAIL)
5342 return;
5343
5344 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5345 ++gap->ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005346}
5347
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005348 static void
5349clear_cellattr(cellattr_T *cell)
5350{
5351 CLEAR_FIELD(*cell);
5352 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5353 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5354}
5355
Bram Moolenaard96ff162018-02-18 22:13:29 +01005356/*
5357 * Read the dump file from "fd" and append lines to the current buffer.
5358 * Return the cell width of the longest line.
5359 */
5360 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005361read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005362{
5363 int c;
5364 garray_T ga_text;
5365 garray_T ga_cell;
5366 char_u *prev_char = NULL;
5367 int attr = 0;
5368 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005369 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005370 term_T *term = curbuf->b_term;
5371 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005372 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005373
5374 ga_init2(&ga_text, 1, 90);
5375 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005376 clear_cellattr(&cell);
5377 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005378 cursor_pos->row = -1;
5379 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005380
5381 c = fgetc(fd);
5382 for (;;)
5383 {
5384 if (c == EOF)
5385 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005386 if (c == '\r')
5387 {
5388 // DOS line endings? Ignore.
5389 c = fgetc(fd);
5390 }
5391 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005392 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005393 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005394 if (ga_text.ga_data == NULL)
5395 dump_is_corrupt(&ga_text);
5396 if (ga_grow(&term->tl_scrollback, 1) == OK)
5397 {
5398 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5399 + term->tl_scrollback.ga_len;
5400
5401 if (max_cells < ga_cell.ga_len)
5402 max_cells = ga_cell.ga_len;
5403 line->sb_cols = ga_cell.ga_len;
5404 line->sb_cells = ga_cell.ga_data;
5405 line->sb_fill_attr = term->tl_default_color;
5406 ++term->tl_scrollback.ga_len;
5407 ga_init(&ga_cell);
5408
5409 ga_append(&ga_text, NUL);
5410 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5411 ga_text.ga_len, FALSE);
5412 }
5413 else
5414 ga_clear(&ga_cell);
5415 ga_text.ga_len = 0;
5416
5417 c = fgetc(fd);
5418 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005419 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005420 {
5421 int prev_len = ga_text.ga_len;
5422
Bram Moolenaar9271d052018-02-25 21:39:46 +01005423 if (c == '>')
5424 {
5425 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005426 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005427 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5428 cursor_pos->col = ga_cell.ga_len;
5429 }
5430
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005431 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005432 c = fgetc(fd);
5433 if (c != EOF)
5434 ga_append(&ga_text, c);
5435 for (;;)
5436 {
5437 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005438 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005439 || c == EOF || c == '\n')
5440 break;
5441 ga_append(&ga_text, c);
5442 }
5443
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005444 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005445 vim_free(prev_char);
5446 if (ga_text.ga_data != NULL)
5447 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5448 ga_text.ga_len - prev_len);
5449
Bram Moolenaar9271d052018-02-25 21:39:46 +01005450 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005451 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005452 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005453 }
5454 else if (c == '+' || c == '*')
5455 {
5456 int is_bg;
5457
5458 cell.width = c == '+' ? 1 : 2;
5459
5460 c = fgetc(fd);
5461 if (c == '&')
5462 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005463 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005464 c = fgetc(fd);
5465 }
5466 else if (isdigit(c))
5467 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005468 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005469 attr = 0;
5470 while (isdigit(c))
5471 {
5472 attr = attr * 10 + (c - '0');
5473 c = fgetc(fd);
5474 }
5475 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005476
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005477 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005478 for (is_bg = 0; is_bg <= 1; ++is_bg)
5479 {
5480 if (c == '&')
5481 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005482 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005483 c = fgetc(fd);
5484 }
5485 else if (c == '#')
5486 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005487 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005488
5489 c = fgetc(fd);
5490 red = hex2nr(c);
5491 c = fgetc(fd);
5492 red = (red << 4) + hex2nr(c);
5493 c = fgetc(fd);
5494 green = hex2nr(c);
5495 c = fgetc(fd);
5496 green = (green << 4) + hex2nr(c);
5497 c = fgetc(fd);
5498 blue = hex2nr(c);
5499 c = fgetc(fd);
5500 blue = (blue << 4) + hex2nr(c);
5501 c = fgetc(fd);
5502 if (!isdigit(c))
5503 dump_is_corrupt(&ga_text);
5504 while (isdigit(c))
5505 {
5506 index = index * 10 + (c - '0');
5507 c = fgetc(fd);
5508 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005509 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005510 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005511 type = VTERM_COLOR_RGB;
5512 if (index == 0)
5513 {
5514 if (is_bg)
5515 type |= VTERM_COLOR_DEFAULT_BG;
5516 else
5517 type |= VTERM_COLOR_DEFAULT_FG;
5518 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005519 }
5520 else
5521 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005522 type = VTERM_COLOR_INDEXED;
5523 index -= 1;
5524 }
5525 if (is_bg)
5526 {
5527 cell.bg.type = type;
5528 cell.bg.red = red;
5529 cell.bg.green = green;
5530 cell.bg.blue = blue;
5531 cell.bg.index = index;
5532 }
5533 else
5534 {
5535 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005536 cell.fg.red = red;
5537 cell.fg.green = green;
5538 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005539 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005540 }
5541 }
5542 else
5543 dump_is_corrupt(&ga_text);
5544 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005545 }
5546 else
5547 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005548 }
5549 else
5550 dump_is_corrupt(&ga_text);
5551
5552 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005553 if (cell.width == 2)
5554 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005555 }
5556 else if (c == '@')
5557 {
5558 if (prev_char == NULL)
5559 dump_is_corrupt(&ga_text);
5560 else
5561 {
5562 int count = 0;
5563
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005564 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005565 for (;;)
5566 {
5567 c = fgetc(fd);
5568 if (!isdigit(c))
5569 break;
5570 count = count * 10 + (c - '0');
5571 }
5572
5573 while (count-- > 0)
5574 {
5575 ga_concat(&ga_text, prev_char);
5576 append_cell(&ga_cell, &cell);
5577 }
5578 }
5579 }
5580 else
5581 {
5582 dump_is_corrupt(&ga_text);
5583 c = fgetc(fd);
5584 }
5585 }
5586
5587 if (ga_text.ga_len > 0)
5588 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005589 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005590 dump_is_corrupt(&ga_text);
5591 ga_append(&ga_text, NUL);
5592 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5593 ga_text.ga_len, FALSE);
5594 }
5595
5596 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005597 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005598 vim_free(prev_char);
5599
5600 return max_cells;
5601}
5602
5603/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005604 * Return an allocated string with at least "text_width" "=" characters and
5605 * "fname" inserted in the middle.
5606 */
5607 static char_u *
5608get_separator(int text_width, char_u *fname)
5609{
5610 int width = MAX(text_width, curwin->w_width);
5611 char_u *textline;
5612 int fname_size;
5613 char_u *p = fname;
5614 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005615 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005616
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005617 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005618 if (textline == NULL)
5619 return NULL;
5620
5621 fname_size = vim_strsize(fname);
5622 if (fname_size < width - 8)
5623 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005624 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005625 width = MAX(text_width, fname_size + 8);
5626 }
5627 else if (fname_size > width - 8)
5628 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005629 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005630 p = gettail(fname);
5631 fname_size = vim_strsize(p);
5632 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005633 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005634 while (fname_size > width - 8)
5635 {
5636 p += (*mb_ptr2len)(p);
5637 fname_size = vim_strsize(p);
5638 }
5639
5640 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5641 textline[i] = '=';
5642 textline[i++] = ' ';
5643
5644 STRCPY(textline + i, p);
5645 off = STRLEN(textline);
5646 textline[off] = ' ';
5647 for (i = 1; i < (width - fname_size) / 2; ++i)
5648 textline[off + i] = '=';
5649 textline[off + i] = NUL;
5650
5651 return textline;
5652}
5653
5654/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005655 * Common for "term_dumpdiff()" and "term_dumpload()".
5656 */
5657 static void
5658term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5659{
5660 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005661 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005662 char_u buf1[NUMBUFLEN];
5663 char_u buf2[NUMBUFLEN];
5664 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005665 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005666 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005667 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005668 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005669 char_u *textline = NULL;
5670
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005671 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005672 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005673 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005674 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005675 if (fname1 == NULL || (do_diff && fname2 == NULL))
5676 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005677 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005678 return;
5679 }
5680 fd1 = mch_fopen((char *)fname1, READBIN);
5681 if (fd1 == NULL)
5682 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005683 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005684 return;
5685 }
5686 if (do_diff)
5687 {
5688 fd2 = mch_fopen((char *)fname2, READBIN);
5689 if (fd2 == NULL)
5690 {
5691 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005692 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005693 return;
5694 }
5695 }
5696
5697 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005698 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5699 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5700 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5701 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5702 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005703
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005704 if (opt.jo_term_name == NULL)
5705 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005706 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005707
Bram Moolenaar51e14382019-05-25 20:21:28 +02005708 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005709 if (fname_tofree != NULL)
5710 {
5711 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5712 opt.jo_term_name = fname_tofree;
5713 }
5714 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005715
Bram Moolenaar87abab92019-06-03 21:14:59 +02005716 if (opt.jo_bufnr_buf != NULL)
5717 {
5718 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5719
5720 // With "bufnr" argument: enter the window with this buffer and make it
5721 // empty.
5722 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005723 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005724 else
5725 {
5726 buf = curbuf;
5727 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005728 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005729 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005730 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005731 }
5732 }
5733 else
5734 // Create a new terminal window.
5735 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5736
Bram Moolenaard96ff162018-02-18 22:13:29 +01005737 if (buf != NULL && buf->b_term != NULL)
5738 {
5739 int i;
5740 linenr_T bot_lnum;
5741 linenr_T lnum;
5742 term_T *term = buf->b_term;
5743 int width;
5744 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005745 VTermPos cursor_pos1;
5746 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005747
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005748 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005749
Bram Moolenaard96ff162018-02-18 22:13:29 +01005750 rettv->vval.v_number = buf->b_fnum;
5751
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005752 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005753 width = read_dump_file(fd1, &cursor_pos1);
5754
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005755 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005756 if (cursor_pos1.row >= 0)
5757 {
5758 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5759 coladvance(cursor_pos1.col);
5760 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005761
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005762 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005763 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005764
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005765 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005766 if (!do_diff)
5767 goto theend;
5768
5769 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5770
Bram Moolenaar4a696342018-04-05 18:45:26 +02005771 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005772 if (textline == NULL)
5773 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005774 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5775 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5776 vim_free(textline);
5777
5778 textline = get_separator(width, fname2);
5779 if (textline == NULL)
5780 goto theend;
5781 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5782 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005783 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005784
5785 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005786 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005787 if (width2 > width)
5788 {
5789 vim_free(textline);
5790 textline = alloc(width2 + 1);
5791 if (textline == NULL)
5792 goto theend;
5793 width = width2;
5794 textline[width] = NUL;
5795 }
5796 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5797
5798 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5799 {
5800 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5801 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005802 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005803 for (i = 0; i < width; ++i)
5804 textline[i] = '-';
5805 }
5806 else
5807 {
5808 char_u *line1;
5809 char_u *line2;
5810 char_u *p1;
5811 char_u *p2;
5812 int col;
5813 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5814 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5815 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5816 ->sb_cells;
5817
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005818 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005819 line1 = vim_strsave(ml_get(lnum));
5820 if (line1 == NULL)
5821 break;
5822 p1 = line1;
5823
5824 line2 = ml_get(lnum + bot_lnum);
5825 p2 = line2;
5826 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5827 {
5828 int len1 = utfc_ptr2len(p1);
5829 int len2 = utfc_ptr2len(p2);
5830
5831 textline[col] = ' ';
5832 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005833 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005834 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005835 else if (lnum == cursor_pos1.row + 1
5836 && col == cursor_pos1.col
5837 && (cursor_pos1.row != cursor_pos2.row
5838 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005839 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005840 textline[col] = '>';
5841 else if (lnum == cursor_pos2.row + 1
5842 && col == cursor_pos2.col
5843 && (cursor_pos1.row != cursor_pos2.row
5844 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005845 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005846 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005847 else if (cellattr1 != NULL && cellattr2 != NULL)
5848 {
5849 if ((cellattr1 + col)->width
5850 != (cellattr2 + col)->width)
5851 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005852 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005853 &(cellattr2 + col)->fg))
5854 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005855 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005856 &(cellattr2 + col)->bg))
5857 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005858 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5859 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005860 textline[col] = 'a';
5861 }
5862 p1 += len1;
5863 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005864 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005865 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005866
5867 while (col < width)
5868 {
5869 if (*p1 == NUL && *p2 == NUL)
5870 textline[col] = '?';
5871 else if (*p1 == NUL)
5872 {
5873 textline[col] = '+';
5874 p2 += utfc_ptr2len(p2);
5875 }
5876 else
5877 {
5878 textline[col] = '-';
5879 p1 += utfc_ptr2len(p1);
5880 }
5881 ++col;
5882 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005883
5884 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005885 }
5886 if (add_empty_scrollback(term, &term->tl_default_color,
5887 term->tl_top_diff_rows) == OK)
5888 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5889 ++bot_lnum;
5890 }
5891
5892 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5893 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005894 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005895 for (i = 0; i < width; ++i)
5896 textline[i] = '+';
5897 if (add_empty_scrollback(term, &term->tl_default_color,
5898 term->tl_top_diff_rows) == OK)
5899 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5900 ++lnum;
5901 ++bot_lnum;
5902 }
5903
5904 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005905
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005906 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005907 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005908 }
5909
5910theend:
5911 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005912 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005913 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005914 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005915 fclose(fd2);
5916}
5917
5918/*
5919 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5920 * bottom files.
5921 * Return FAIL when this is not possible.
5922 */
5923 int
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00005924term_swap_diff(void)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005925{
5926 term_T *term = curbuf->b_term;
5927 linenr_T line_count;
5928 linenr_T top_rows;
5929 linenr_T bot_rows;
5930 linenr_T bot_start;
5931 linenr_T lnum;
5932 char_u *p;
5933 sb_line_T *sb_line;
5934
5935 if (term == NULL
5936 || !term_is_finished(curbuf)
5937 || term->tl_top_diff_rows == 0
5938 || term->tl_scrollback.ga_len == 0)
5939 return FAIL;
5940
5941 line_count = curbuf->b_ml.ml_line_count;
5942 top_rows = term->tl_top_diff_rows;
5943 bot_rows = term->tl_bot_diff_rows;
5944 bot_start = line_count - bot_rows;
5945 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5946
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005947 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005948 for (lnum = 1; lnum <= top_rows; ++lnum)
5949 {
5950 p = vim_strsave(ml_get(1));
5951 if (p == NULL)
5952 return OK;
5953 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005954 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005955 vim_free(p);
5956 }
5957
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005958 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005959 for (lnum = 1; lnum <= bot_rows; ++lnum)
5960 {
5961 p = vim_strsave(ml_get(bot_start + lnum));
5962 if (p == NULL)
5963 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005964 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005965 ml_append(lnum - 1, p, 0, FALSE);
5966 vim_free(p);
5967 }
5968
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005969 // move top title to bottom
5970 p = vim_strsave(ml_get(bot_rows + 1));
5971 if (p == NULL)
5972 return OK;
5973 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005974 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005975 vim_free(p);
5976
5977 // move bottom title to top
5978 p = vim_strsave(ml_get(line_count - top_rows));
5979 if (p == NULL)
5980 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005981 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005982 ml_append(bot_rows, p, 0, FALSE);
5983 vim_free(p);
5984
Bram Moolenaard96ff162018-02-18 22:13:29 +01005985 if (top_rows == bot_rows)
5986 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005987 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005988 for (lnum = 0; lnum < top_rows; ++lnum)
5989 {
5990 sb_line_T temp;
5991
5992 temp = *(sb_line + lnum);
5993 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5994 *(sb_line + bot_start + lnum) = temp;
5995 }
5996 }
5997 else
5998 {
5999 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006000 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006001
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006002 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01006003 if (temp != NULL)
6004 {
6005 mch_memmove(temp, term->tl_scrollback.ga_data, size);
6006 mch_memmove(term->tl_scrollback.ga_data,
6007 temp + bot_start,
6008 sizeof(sb_line_T) * bot_rows);
6009 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
6010 temp + top_rows,
6011 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
6012 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
6013 + line_count - top_rows,
6014 temp,
6015 sizeof(sb_line_T) * top_rows);
6016 vim_free(temp);
6017 }
6018 }
6019
6020 term->tl_top_diff_rows = bot_rows;
6021 term->tl_bot_diff_rows = top_rows;
6022
Bram Moolenaara4d158b2022-08-14 14:17:45 +01006023 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01006024 return OK;
6025}
6026
6027/*
6028 * "term_dumpdiff(filename, filename, options)" function
6029 */
6030 void
6031f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
6032{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02006033 if (in_vim9script()
6034 && (check_for_string_arg(argvars, 0) == FAIL
6035 || check_for_string_arg(argvars, 1) == FAIL
6036 || check_for_opt_dict_arg(argvars, 2) == FAIL))
6037 return;
6038
Bram Moolenaard96ff162018-02-18 22:13:29 +01006039 term_load_dump(argvars, rettv, TRUE);
6040}
6041
6042/*
6043 * "term_dumpload(filename, options)" function
6044 */
6045 void
6046f_term_dumpload(typval_T *argvars, typval_T *rettv)
6047{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006048 if (in_vim9script()
6049 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02006050 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006051 return;
6052
Bram Moolenaard96ff162018-02-18 22:13:29 +01006053 term_load_dump(argvars, rettv, FALSE);
6054}
6055
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006056/*
6057 * "term_getaltscreen(buf)" function
6058 */
6059 void
6060f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
6061{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006062 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006063
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006064 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6065 return;
6066
6067 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006068 if (buf == NULL)
6069 return;
6070 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
6071}
6072
6073/*
6074 * "term_getattr(attr, name)" function
6075 */
6076 void
6077f_term_getattr(typval_T *argvars, typval_T *rettv)
6078{
6079 int attr;
6080 size_t i;
6081 char_u *name;
6082
6083 static struct {
6084 char *name;
6085 int attr;
6086 } attrs[] = {
6087 {"bold", HL_BOLD},
6088 {"italic", HL_ITALIC},
6089 {"underline", HL_UNDERLINE},
6090 {"strike", HL_STRIKETHROUGH},
6091 {"reverse", HL_INVERSE},
6092 };
6093
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02006094 if (in_vim9script()
6095 && (check_for_number_arg(argvars, 0) == FAIL
6096 || check_for_string_arg(argvars, 1) == FAIL))
6097 return;
6098
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006099 attr = tv_get_number(&argvars[0]);
6100 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006101 if (name == NULL)
6102 return;
6103
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02006104 if (attr > HL_ALL)
6105 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02006106 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006107 if (STRCMP(name, attrs[i].name) == 0)
6108 {
6109 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
6110 break;
6111 }
6112}
6113
6114/*
6115 * "term_getcursor(buf)" function
6116 */
6117 void
6118f_term_getcursor(typval_T *argvars, typval_T *rettv)
6119{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006120 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006121 term_T *term;
6122 list_T *l;
6123 dict_T *d;
6124
6125 if (rettv_list_alloc(rettv) == FAIL)
6126 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006127
6128 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6129 return;
6130
6131 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006132 if (buf == NULL)
6133 return;
6134 term = buf->b_term;
6135
6136 l = rettv->vval.v_list;
6137 list_append_number(l, term->tl_cursor_pos.row + 1);
6138 list_append_number(l, term->tl_cursor_pos.col + 1);
6139
6140 d = dict_alloc();
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00006141 if (d == NULL)
6142 return;
6143
6144 dict_add_number(d, "visible", term->tl_cursor_visible);
6145 dict_add_number(d, "blink", blink_state_is_inverted()
6146 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6147 dict_add_number(d, "shape", term->tl_cursor_shape);
6148 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
6149 list_append_dict(l, d);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006150}
6151
6152/*
6153 * "term_getjob(buf)" function
6154 */
6155 void
6156f_term_getjob(typval_T *argvars, typval_T *rettv)
6157{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006158 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006159
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006160 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6161 return;
6162
6163 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006164 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006165 {
6166 rettv->v_type = VAR_SPECIAL;
6167 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006168 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006169 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006170
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006171 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006172 rettv->vval.v_job = buf->b_term->tl_job;
6173 if (rettv->vval.v_job != NULL)
6174 ++rettv->vval.v_job->jv_refcount;
6175}
6176
6177 static int
6178get_row_number(typval_T *tv, term_T *term)
6179{
6180 if (tv->v_type == VAR_STRING
6181 && tv->vval.v_string != NULL
6182 && STRCMP(tv->vval.v_string, ".") == 0)
6183 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006184 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006185}
6186
6187/*
6188 * "term_getline(buf, row)" function
6189 */
6190 void
6191f_term_getline(typval_T *argvars, typval_T *rettv)
6192{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006193 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006194 term_T *term;
6195 int row;
6196
6197 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006198
6199 if (in_vim9script()
6200 && (check_for_buffer_arg(argvars, 0) == FAIL
6201 || check_for_lnum_arg(argvars, 1) == FAIL))
6202 return;
6203
6204 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006205 if (buf == NULL)
6206 return;
6207 term = buf->b_term;
6208 row = get_row_number(&argvars[1], term);
6209
6210 if (term->tl_vterm == NULL)
6211 {
6212 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6213
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006214 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006215 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6216 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6217 }
6218 else
6219 {
6220 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6221 VTermRect rect;
6222 int len;
6223 char_u *p;
6224
6225 if (row < 0 || row >= term->tl_rows)
6226 return;
6227 len = term->tl_cols * MB_MAXBYTES + 1;
6228 p = alloc(len);
6229 if (p == NULL)
6230 return;
6231 rettv->vval.v_string = p;
6232
6233 rect.start_col = 0;
6234 rect.end_col = term->tl_cols;
6235 rect.start_row = row;
6236 rect.end_row = row + 1;
6237 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6238 }
6239}
6240
6241/*
6242 * "term_getscrolled(buf)" function
6243 */
6244 void
6245f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6246{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006247 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006248
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006249 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6250 return;
6251
6252 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006253 if (buf == NULL)
6254 return;
6255 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6256}
6257
6258/*
6259 * "term_getsize(buf)" function
6260 */
6261 void
6262f_term_getsize(typval_T *argvars, typval_T *rettv)
6263{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006264 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006265 list_T *l;
6266
6267 if (rettv_list_alloc(rettv) == FAIL)
6268 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006269
6270 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6271 return;
6272
6273 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006274 if (buf == NULL)
6275 return;
6276
6277 l = rettv->vval.v_list;
6278 list_append_number(l, buf->b_term->tl_rows);
6279 list_append_number(l, buf->b_term->tl_cols);
6280}
6281
6282/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006283 * "term_setsize(buf, rows, cols)" function
6284 */
6285 void
6286f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6287{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006288 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006289 term_T *term;
6290 varnumber_T rows, cols;
6291
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006292 if (in_vim9script()
6293 && (check_for_buffer_arg(argvars, 0) == FAIL
6294 || check_for_number_arg(argvars, 1) == FAIL
6295 || check_for_number_arg(argvars, 2) == FAIL))
6296 return;
6297
6298 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006299 if (buf == NULL)
6300 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006301 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006302 return;
6303 }
6304 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006305 return;
6306 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006307 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006308 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006309 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006310 cols = cols <= 0 ? term->tl_cols : cols;
6311 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006312 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006313
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006314 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006315 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6316 term_report_winsize(term, term->tl_rows, term->tl_cols);
6317}
6318
6319/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006320 * "term_getstatus(buf)" function
6321 */
6322 void
6323f_term_getstatus(typval_T *argvars, typval_T *rettv)
6324{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006325 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006326 term_T *term;
6327 char_u val[100];
6328
6329 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006330
6331 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6332 return;
6333
6334 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006335 if (buf == NULL)
6336 return;
6337 term = buf->b_term;
6338
6339 if (term_job_running(term))
6340 STRCPY(val, "running");
6341 else
6342 STRCPY(val, "finished");
6343 if (term->tl_normal_mode)
6344 STRCAT(val, ",normal");
6345 rettv->vval.v_string = vim_strsave(val);
6346}
6347
6348/*
6349 * "term_gettitle(buf)" function
6350 */
6351 void
6352f_term_gettitle(typval_T *argvars, typval_T *rettv)
6353{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006354 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006355
6356 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006357
6358 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6359 return;
6360
6361 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006362 if (buf == NULL)
6363 return;
6364
6365 if (buf->b_term->tl_title != NULL)
6366 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6367}
6368
6369/*
6370 * "term_gettty(buf)" function
6371 */
6372 void
6373f_term_gettty(typval_T *argvars, typval_T *rettv)
6374{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006375 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006376 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006377 int num = 0;
6378
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006379 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006380 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006381 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6382 return;
6383
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006384 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006385 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006386 if (buf == NULL)
6387 return;
6388 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006389 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006390
6391 switch (num)
6392 {
6393 case 0:
6394 if (buf->b_term->tl_job != NULL)
6395 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006396 break;
6397 case 1:
6398 if (buf->b_term->tl_job != NULL)
6399 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006400 break;
6401 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006402 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006403 return;
6404 }
6405 if (p != NULL)
6406 rettv->vval.v_string = vim_strsave(p);
6407}
6408
6409/*
6410 * "term_list()" function
6411 */
6412 void
6413f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6414{
6415 term_T *tp;
6416 list_T *l;
6417
6418 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6419 return;
6420
6421 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006422 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006423 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006424 if (list_append_number(l,
6425 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6426 return;
6427}
6428
6429/*
6430 * "term_scrape(buf, row)" function
6431 */
6432 void
6433f_term_scrape(typval_T *argvars, typval_T *rettv)
6434{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006435 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006436 VTermScreen *screen = NULL;
6437 VTermPos pos;
6438 list_T *l;
6439 term_T *term;
6440 char_u *p;
6441 sb_line_T *line;
6442
6443 if (rettv_list_alloc(rettv) == FAIL)
6444 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006445
6446 if (in_vim9script()
6447 && (check_for_buffer_arg(argvars, 0) == FAIL
6448 || check_for_lnum_arg(argvars, 1) == FAIL))
6449 return;
6450
6451 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006452 if (buf == NULL)
6453 return;
6454 term = buf->b_term;
6455
6456 l = rettv->vval.v_list;
6457 pos.row = get_row_number(&argvars[1], term);
6458
6459 if (term->tl_vterm != NULL)
6460 {
6461 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006462 if (screen == NULL) // can't really happen
6463 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006464 p = NULL;
6465 line = NULL;
6466 }
6467 else
6468 {
6469 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6470
6471 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6472 return;
6473 p = ml_get_buf(buf, lnum + 1, FALSE);
6474 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6475 }
6476
6477 for (pos.col = 0; pos.col < term->tl_cols; )
6478 {
6479 dict_T *dcell;
6480 int width;
6481 VTermScreenCellAttrs attrs;
6482 VTermColor fg, bg;
6483 char_u rgb[8];
6484 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6485 int off = 0;
6486 int i;
6487
6488 if (screen == NULL)
6489 {
6490 cellattr_T *cellattr;
6491 int len;
6492
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006493 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006494 if (pos.col >= line->sb_cols)
6495 break;
6496 cellattr = line->sb_cells + pos.col;
6497 width = cellattr->width;
6498 attrs = cellattr->attrs;
6499 fg = cellattr->fg;
6500 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006501 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006502 mch_memmove(mbs, p, len);
6503 mbs[len] = NUL;
6504 p += len;
6505 }
6506 else
6507 {
6508 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006509
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006510 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6511 break;
6512 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6513 {
6514 if (cell.chars[i] == 0)
6515 break;
6516 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6517 }
6518 mbs[off] = NUL;
6519 width = cell.width;
6520 attrs = cell.attrs;
6521 fg = cell.fg;
6522 bg = cell.bg;
6523 }
6524 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006525 if (dcell == NULL)
6526 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006527 list_append_dict(l, dcell);
6528
Bram Moolenaare0be1672018-07-08 16:50:37 +02006529 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006530
6531 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6532 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006533 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006534 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6535 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006536 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006537
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006538 dict_add_number(dcell, "attr",
6539 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006540 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006541
6542 ++pos.col;
6543 if (width == 2)
6544 ++pos.col;
6545 }
6546}
6547
6548/*
6549 * "term_sendkeys(buf, keys)" function
6550 */
6551 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006552f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006553{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006554 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006555 char_u *msg;
6556 term_T *term;
6557
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006558 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006559 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006560 || check_for_string_arg(argvars, 1) == FAIL))
6561 return;
6562
6563 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006564 if (buf == NULL)
6565 return;
6566
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006567 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006568 if (msg == NULL)
6569 return;
6570 term = buf->b_term;
6571 if (term->tl_vterm == NULL)
6572 return;
6573
6574 while (*msg != NUL)
6575 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006576 int c;
6577
6578 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6579 {
6580 c = TO_SPECIAL(msg[1], msg[2]);
6581 msg += 3;
6582 }
6583 else
6584 {
6585 c = PTR2CHAR(msg);
6586 msg += MB_CPTR2LEN(msg);
6587 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006588 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006589 }
6590}
6591
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006592#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6593/*
6594 * "term_getansicolors(buf)" function
6595 */
6596 void
6597f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6598{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006599 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006600 term_T *term;
6601 VTermState *state;
6602 VTermColor color;
6603 char_u hexbuf[10];
6604 int index;
6605 list_T *list;
6606
6607 if (rettv_list_alloc(rettv) == FAIL)
6608 return;
6609
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006610 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6611 return;
6612
6613 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006614 if (buf == NULL)
6615 return;
6616 term = buf->b_term;
6617 if (term->tl_vterm == NULL)
6618 return;
6619
6620 list = rettv->vval.v_list;
6621 state = vterm_obtain_state(term->tl_vterm);
6622 for (index = 0; index < 16; index++)
6623 {
6624 vterm_state_get_palette_color(state, index, &color);
6625 sprintf((char *)hexbuf, "#%02x%02x%02x",
6626 color.red, color.green, color.blue);
6627 if (list_append_string(list, hexbuf, 7) == FAIL)
6628 return;
6629 }
6630}
6631
6632/*
6633 * "term_setansicolors(buf, list)" function
6634 */
6635 void
6636f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6637{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006638 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006639 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006640 listitem_T *li;
6641 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006642
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006643 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006644 && (check_for_buffer_arg(argvars, 0) == FAIL
6645 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006646 return;
6647
6648 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006649 if (buf == NULL)
6650 return;
6651 term = buf->b_term;
6652 if (term->tl_vterm == NULL)
6653 return;
6654
Bram Moolenaard83392a2022-09-01 12:22:46 +01006655 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006656 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006657
LemonBoyb2b3acb2022-05-20 10:10:34 +01006658 if (argvars[1].vval.v_list->lv_first == &range_list_item
6659 || argvars[1].vval.v_list->lv_len != 16)
6660 {
Bram Moolenaar23919542023-05-05 22:12:22 +01006661 semsg(_(e_invalid_value_for_argument_str), "\"colors\"");
LemonBoyb2b3acb2022-05-20 10:10:34 +01006662 return;
6663 }
6664
6665 if (term->tl_palette == NULL)
6666 term->tl_palette = ALLOC_MULT(long_u, 16);
6667 if (term->tl_palette == NULL)
6668 return;
6669
6670 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6671 {
6672 char_u *color_name;
6673 guicolor_T guicolor;
6674
6675 color_name = tv_get_string_chk(&li->li_tv);
6676 if (color_name == NULL)
6677 return;
6678
6679 guicolor = GUI_GET_COLOR(color_name);
6680 if (guicolor == INVALCOLOR)
6681 {
6682 semsg(_(e_cannot_allocate_color_str), color_name);
6683 return;
6684 }
6685
6686 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6687 }
6688
6689 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006690}
6691#endif
6692
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006693/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006694 * "term_setapi(buf, api)" function
6695 */
6696 void
6697f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6698{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006699 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006700 term_T *term;
6701 char_u *api;
6702
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006703 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006704 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006705 || check_for_string_arg(argvars, 1) == FAIL))
6706 return;
6707
6708 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006709 if (buf == NULL)
6710 return;
6711 term = buf->b_term;
6712 vim_free(term->tl_api);
6713 api = tv_get_string_chk(&argvars[1]);
6714 if (api != NULL)
6715 term->tl_api = vim_strsave(api);
6716 else
6717 term->tl_api = NULL;
6718}
6719
6720/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006721 * "term_setrestore(buf, command)" function
6722 */
6723 void
6724f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6725{
6726#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006727 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006728 term_T *term;
6729 char_u *cmd;
6730
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006731 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006732 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006733 || check_for_string_arg(argvars, 1) == FAIL))
6734 return;
6735
6736 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006737 if (buf == NULL)
6738 return;
6739 term = buf->b_term;
6740 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006741 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006742 if (cmd != NULL)
6743 term->tl_command = vim_strsave(cmd);
6744 else
6745 term->tl_command = NULL;
6746#endif
6747}
6748
6749/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006750 * "term_setkill(buf, how)" function
6751 */
6752 void
6753f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6754{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006755 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006756 term_T *term;
6757 char_u *how;
6758
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006759 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006760 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006761 || check_for_string_arg(argvars, 1) == FAIL))
6762 return;
6763
6764 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006765 if (buf == NULL)
6766 return;
6767 term = buf->b_term;
6768 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006769 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006770 if (how != NULL)
6771 term->tl_kill = vim_strsave(how);
6772 else
6773 term->tl_kill = NULL;
6774}
6775
6776/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006777 * "term_start(command, options)" function
6778 */
6779 void
6780f_term_start(typval_T *argvars, typval_T *rettv)
6781{
6782 jobopt_T opt;
6783 buf_T *buf;
6784
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006785 if (in_vim9script()
6786 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6787 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6788 return;
6789
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006790 init_job_options(&opt);
6791 if (argvars[1].v_type != VAR_UNKNOWN
6792 && get_job_options(&argvars[1], &opt,
6793 JO_TIMEOUT_ALL + JO_STOPONEXIT
6794 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6795 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6796 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6797 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006798 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006799 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006800 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006801 return;
6802
Bram Moolenaar13568252018-03-16 20:46:58 +01006803 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006804
6805 if (buf != NULL && buf->b_term != NULL)
6806 rettv->vval.v_number = buf->b_fnum;
6807}
6808
6809/*
6810 * "term_wait" function
6811 */
6812 void
6813f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6814{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006815 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006816
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006817 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006818 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006819 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006820 return;
6821
6822 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006823 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006824 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006825 if (buf->b_term->tl_job == NULL)
6826 {
6827 ch_log(NULL, "term_wait(): no job to wait for");
6828 return;
6829 }
6830 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006831 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006832 return;
6833
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006834 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006835 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006836 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6837 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006838 // The job is dead, keep reading channel I/O until the channel is
6839 // closed. buf->b_term may become NULL if the terminal was closed while
6840 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006841 ch_log(NULL, "term_wait(): waiting for channel to close");
6842 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6843 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006844 term_flush_messages();
6845
Bram Moolenaard45aa552018-05-21 22:50:29 +02006846 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006847 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006848 // If the terminal is closed when the channel is closed the
6849 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006850 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006851 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6852 // came here from a close callback, only wait one time
6853 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006854 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006855
6856 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006857 }
6858 else
6859 {
6860 long wait = 10L;
6861
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006862 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006863
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006864 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006865 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006866 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006867 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006868
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006869 // Flushing messages on channels is hopefully sufficient.
6870 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006871 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006872 }
6873}
6874
6875/*
6876 * Called when a channel has sent all the lines to a terminal.
6877 * Send a CTRL-D to mark the end of the text.
6878 */
6879 void
6880term_send_eof(channel_T *ch)
6881{
6882 term_T *term;
6883
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006884 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006885 if (term->tl_job == ch->ch_job)
6886 {
6887 if (term->tl_eof_chars != NULL)
6888 {
6889 channel_send(ch, PART_IN, term->tl_eof_chars,
6890 (int)STRLEN(term->tl_eof_chars), NULL);
6891 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6892 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006893# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006894 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006895 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006896 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6897# endif
6898 }
6899}
6900
Bram Moolenaar113e1072019-01-20 15:30:40 +01006901#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006902 job_T *
6903term_getjob(term_T *term)
6904{
6905 return term != NULL ? term->tl_job : NULL;
6906}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006907#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006908
Bram Moolenaar4f974752019-02-17 17:44:42 +01006909# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006910
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006911///////////////////////////////////////
6912// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006913#ifdef PROTO
6914typedef int COORD;
6915typedef int DWORD;
6916typedef int HANDLE;
6917typedef int *DWORD_PTR;
6918typedef int HPCON;
6919typedef int HRESULT;
6920typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006921typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006922typedef int PSIZE_T;
6923typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006924typedef int BOOL;
6925# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006926#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006927
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006928HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6929HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6930HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006931BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6932BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6933void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006934
6935 static int
6936dyn_conpty_init(int verbose)
6937{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006938 static HMODULE hKerneldll = NULL;
6939 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006940 static struct
6941 {
6942 char *name;
6943 FARPROC *ptr;
6944 } conpty_entry[] =
6945 {
6946 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6947 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6948 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6949 {"InitializeProcThreadAttributeList",
6950 (FARPROC*)&pInitializeProcThreadAttributeList},
6951 {"UpdateProcThreadAttribute",
6952 (FARPROC*)&pUpdateProcThreadAttribute},
6953 {"DeleteProcThreadAttributeList",
6954 (FARPROC*)&pDeleteProcThreadAttributeList},
6955 {NULL, NULL}
6956 };
6957
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006958 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006959 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006960 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006961 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006962 return FAIL;
6963 }
6964
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006965 // No need to initialize twice.
6966 if (hKerneldll)
6967 return OK;
6968
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006969 hKerneldll = vimLoadLib("kernel32.dll");
6970 for (i = 0; conpty_entry[i].name != NULL
6971 && conpty_entry[i].ptr != NULL; ++i)
6972 {
6973 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6974 conpty_entry[i].name)) == NULL)
6975 {
6976 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006977 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006978 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006979 return FAIL;
6980 }
6981 }
6982
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006983 return OK;
6984}
6985
6986 static int
6987conpty_term_and_job_init(
6988 term_T *term,
6989 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006990 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006991 jobopt_T *opt,
6992 jobopt_T *orig_opt)
6993{
6994 WCHAR *cmd_wchar = NULL;
6995 WCHAR *cmd_wchar_copy = NULL;
6996 WCHAR *cwd_wchar = NULL;
6997 WCHAR *env_wchar = NULL;
6998 channel_T *channel = NULL;
6999 job_T *job = NULL;
7000 HANDLE jo = NULL;
7001 garray_T ga_cmd, ga_env;
7002 char_u *cmd = NULL;
7003 HRESULT hr;
7004 COORD consize;
7005 SIZE_T breq;
7006 PROCESS_INFORMATION proc_info;
7007 HANDLE i_theirs = NULL;
7008 HANDLE o_theirs = NULL;
7009 HANDLE i_ours = NULL;
7010 HANDLE o_ours = NULL;
7011
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007012 ga_init2(&ga_cmd, sizeof(char*), 20);
7013 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007014
7015 if (argvar->v_type == VAR_STRING)
7016 {
7017 cmd = argvar->vval.v_string;
7018 }
7019 else if (argvar->v_type == VAR_LIST)
7020 {
7021 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
7022 goto failed;
7023 cmd = ga_cmd.ga_data;
7024 }
7025 if (cmd == NULL || *cmd == NUL)
7026 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007027 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007028 goto failed;
7029 }
7030
7031 term->tl_arg0_cmd = vim_strsave(cmd);
7032
7033 cmd_wchar = enc_to_utf16(cmd, NULL);
7034
7035 if (cmd_wchar != NULL)
7036 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007037 // Request by CreateProcessW
7038 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007039 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007040 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
7041 }
7042
7043 ga_clear(&ga_cmd);
7044 if (cmd_wchar == NULL)
7045 goto failed;
7046 if (opt->jo_cwd != NULL)
7047 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
7048
7049 win32_build_env(opt->jo_env, &ga_env, TRUE);
7050 env_wchar = ga_env.ga_data;
7051
7052 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
7053 goto failed;
7054 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
7055 goto failed;
7056
7057 consize.X = term->tl_cols;
7058 consize.Y = term->tl_rows;
7059 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
7060 &term->tl_conpty);
7061 if (FAILED(hr))
7062 goto failed;
7063
7064 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
7065
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007066 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007067 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007068 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007069 if (!term->tl_siex.lpAttributeList)
7070 goto failed;
7071 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
7072 0, &breq))
7073 goto failed;
7074 if (!pUpdateProcThreadAttribute(
7075 term->tl_siex.lpAttributeList, 0,
7076 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
7077 sizeof(HPCON), NULL, NULL))
7078 goto failed;
7079
7080 channel = add_channel();
7081 if (channel == NULL)
7082 goto failed;
7083
7084 job = job_alloc();
7085 if (job == NULL)
7086 goto failed;
7087 if (argvar->v_type == VAR_STRING)
7088 {
7089 int argc;
7090
7091 build_argv_from_string(cmd, &job->jv_argv, &argc);
7092 }
7093 else
7094 {
7095 int argc;
7096
7097 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7098 }
7099
7100 if (opt->jo_set & JO_IN_BUF)
7101 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7102
7103 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
7104 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02007105 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007106 env_wchar, cwd_wchar,
7107 &term->tl_siex.StartupInfo, &proc_info))
7108 goto failed;
7109
7110 CloseHandle(i_theirs);
7111 CloseHandle(o_theirs);
7112
7113 channel_set_pipes(channel,
7114 (sock_T)i_ours,
7115 (sock_T)o_ours,
7116 (sock_T)o_ours);
7117
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007118 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007119 channel->ch_write_text_mode = TRUE;
7120
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007121 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007122 channel->ch_anonymous_pipe = TRUE;
7123
7124 jo = CreateJobObject(NULL, NULL);
7125 if (jo == NULL)
7126 goto failed;
7127
7128 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7129 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007130 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007131 CloseHandle(jo);
7132 jo = NULL;
7133 }
7134
7135 ResumeThread(proc_info.hThread);
7136 CloseHandle(proc_info.hThread);
7137
7138 vim_free(cmd_wchar);
7139 vim_free(cmd_wchar_copy);
7140 vim_free(cwd_wchar);
7141 vim_free(env_wchar);
7142
7143 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7144 goto failed;
7145
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007146#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007147 if (term_use_palette())
7148 {
7149 if (term->tl_palette != NULL)
7150 set_vterm_palette(term->tl_vterm, term->tl_palette);
7151 else
7152 init_vterm_ansi_colors(term->tl_vterm);
7153 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007154#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007155
7156 channel_set_job(channel, job, opt);
7157 job_set_options(job, opt);
7158
7159 job->jv_channel = channel;
7160 job->jv_proc_info = proc_info;
7161 job->jv_job_object = jo;
7162 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007163 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007164 ++job->jv_refcount;
7165 term->tl_job = job;
7166
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007167 // Redirecting stdout and stderr doesn't work at the job level. Instead
7168 // open the file here and handle it in. opt->jo_io was changed in
7169 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007170 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7171 {
7172 char_u *fname = opt->jo_io_name[PART_OUT];
7173
7174 ch_log(channel, "Opening output file %s", fname);
7175 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7176 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007177 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007178 }
7179
7180 return OK;
7181
7182failed:
7183 ga_clear(&ga_cmd);
7184 ga_clear(&ga_env);
7185 vim_free(cmd_wchar);
7186 vim_free(cmd_wchar_copy);
7187 vim_free(cwd_wchar);
7188 if (channel != NULL)
7189 channel_clear(channel);
7190 if (job != NULL)
7191 {
7192 job->jv_channel = NULL;
7193 job_cleanup(job);
7194 }
7195 term->tl_job = NULL;
7196 if (jo != NULL)
7197 CloseHandle(jo);
7198
7199 if (term->tl_siex.lpAttributeList != NULL)
7200 {
7201 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7202 vim_free(term->tl_siex.lpAttributeList);
7203 }
7204 term->tl_siex.lpAttributeList = NULL;
7205 if (o_theirs != NULL)
7206 CloseHandle(o_theirs);
7207 if (o_ours != NULL)
7208 CloseHandle(o_ours);
7209 if (i_ours != NULL)
7210 CloseHandle(i_ours);
7211 if (i_theirs != NULL)
7212 CloseHandle(i_theirs);
7213 if (term->tl_conpty != NULL)
7214 pClosePseudoConsole(term->tl_conpty);
7215 term->tl_conpty = NULL;
7216 return FAIL;
7217}
7218
7219 static void
7220conpty_term_report_winsize(term_T *term, int rows, int cols)
7221{
7222 COORD consize;
7223
7224 consize.X = cols;
7225 consize.Y = rows;
7226 pResizePseudoConsole(term->tl_conpty, consize);
7227}
7228
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007229 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007230term_free_conpty(term_T *term)
7231{
7232 if (term->tl_siex.lpAttributeList != NULL)
7233 {
7234 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7235 vim_free(term->tl_siex.lpAttributeList);
7236 }
7237 term->tl_siex.lpAttributeList = NULL;
7238 if (term->tl_conpty != NULL)
7239 pClosePseudoConsole(term->tl_conpty);
7240 term->tl_conpty = NULL;
7241}
7242
7243 int
7244use_conpty(void)
7245{
7246 return has_conpty;
7247}
7248
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007249# ifndef PROTO
7250
7251#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7252#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007253#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007254
7255void* (*winpty_config_new)(UINT64, void*);
7256void* (*winpty_open)(void*, void*);
7257void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7258BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7259void (*winpty_config_set_mouse_mode)(void*, int);
7260void (*winpty_config_set_initial_size)(void*, int, int);
7261LPCWSTR (*winpty_conin_name)(void*);
7262LPCWSTR (*winpty_conout_name)(void*);
7263LPCWSTR (*winpty_conerr_name)(void*);
7264void (*winpty_free)(void*);
7265void (*winpty_config_free)(void*);
7266void (*winpty_spawn_config_free)(void*);
7267void (*winpty_error_free)(void*);
7268LPCWSTR (*winpty_error_msg)(void*);
7269BOOL (*winpty_set_size)(void*, int, int, void*);
7270HANDLE (*winpty_agent_process)(void*);
7271
7272#define WINPTY_DLL "winpty.dll"
7273
7274static HINSTANCE hWinPtyDLL = NULL;
7275# endif
7276
7277 static int
7278dyn_winpty_init(int verbose)
7279{
7280 int i;
7281 static struct
7282 {
7283 char *name;
7284 FARPROC *ptr;
7285 } winpty_entry[] =
7286 {
7287 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7288 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7289 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7290 {"winpty_config_set_mouse_mode",
7291 (FARPROC*)&winpty_config_set_mouse_mode},
7292 {"winpty_config_set_initial_size",
7293 (FARPROC*)&winpty_config_set_initial_size},
7294 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7295 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7296 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7297 {"winpty_free", (FARPROC*)&winpty_free},
7298 {"winpty_open", (FARPROC*)&winpty_open},
7299 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7300 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7301 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7302 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7303 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7304 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7305 {NULL, NULL}
7306 };
7307
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007308 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007309 if (hWinPtyDLL)
7310 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007311 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7312 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007313 if (*p_winptydll != NUL)
7314 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7315 if (!hWinPtyDLL)
7316 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7317 if (!hWinPtyDLL)
7318 {
7319 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007320 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007321 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7322 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007323 return FAIL;
7324 }
7325 for (i = 0; winpty_entry[i].name != NULL
7326 && winpty_entry[i].ptr != NULL; ++i)
7327 {
7328 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7329 winpty_entry[i].name)) == NULL)
7330 {
7331 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007332 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007333 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007334 return FAIL;
7335 }
7336 }
7337
7338 return OK;
7339}
7340
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007341 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007342winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007343 term_T *term,
7344 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007345 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007346 jobopt_T *opt,
7347 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007348{
7349 WCHAR *cmd_wchar = NULL;
7350 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007351 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007352 channel_T *channel = NULL;
7353 job_T *job = NULL;
7354 DWORD error;
7355 HANDLE jo = NULL;
7356 HANDLE child_process_handle;
7357 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007358 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007359 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007360 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007361 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007362
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007363 ga_init2(&ga_cmd, sizeof(char*), 20);
7364 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007365
7366 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007367 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007368 cmd = argvar->vval.v_string;
7369 }
7370 else if (argvar->v_type == VAR_LIST)
7371 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007372 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007373 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007374 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007375 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007376 if (cmd == NULL || *cmd == NUL)
7377 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007378 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007379 goto failed;
7380 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007381
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007382 term->tl_arg0_cmd = vim_strsave(cmd);
7383
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007384 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007385 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007386 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007387 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007388 if (opt->jo_cwd != NULL)
7389 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007390
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007391 win32_build_env(opt->jo_env, &ga_env, TRUE);
7392 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007393
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007394 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7395 if (term->tl_winpty_config == NULL)
7396 goto failed;
7397
7398 winpty_config_set_mouse_mode(term->tl_winpty_config,
7399 WINPTY_MOUSE_MODE_FORCE);
7400 winpty_config_set_initial_size(term->tl_winpty_config,
7401 term->tl_cols, term->tl_rows);
7402 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7403 if (term->tl_winpty == NULL)
7404 goto failed;
7405
7406 spawn_config = winpty_spawn_config_new(
7407 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7408 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7409 NULL,
7410 cmd_wchar,
7411 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007412 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007413 &winpty_err);
7414 if (spawn_config == NULL)
7415 goto failed;
7416
7417 channel = add_channel();
7418 if (channel == NULL)
7419 goto failed;
7420
7421 job = job_alloc();
7422 if (job == NULL)
7423 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007424 if (argvar->v_type == VAR_STRING)
7425 {
7426 int argc;
7427
7428 build_argv_from_string(cmd, &job->jv_argv, &argc);
7429 }
7430 else
7431 {
7432 int argc;
7433
7434 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7435 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007436
7437 if (opt->jo_set & JO_IN_BUF)
7438 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7439
7440 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7441 &child_thread_handle, &error, &winpty_err))
7442 goto failed;
7443
7444 channel_set_pipes(channel,
7445 (sock_T)CreateFileW(
7446 winpty_conin_name(term->tl_winpty),
7447 GENERIC_WRITE, 0, NULL,
7448 OPEN_EXISTING, 0, NULL),
7449 (sock_T)CreateFileW(
7450 winpty_conout_name(term->tl_winpty),
7451 GENERIC_READ, 0, NULL,
7452 OPEN_EXISTING, 0, NULL),
7453 (sock_T)CreateFileW(
7454 winpty_conerr_name(term->tl_winpty),
7455 GENERIC_READ, 0, NULL,
7456 OPEN_EXISTING, 0, NULL));
7457
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007458 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007459 channel->ch_write_text_mode = TRUE;
7460
7461 jo = CreateJobObject(NULL, NULL);
7462 if (jo == NULL)
7463 goto failed;
7464
7465 if (!AssignProcessToJobObject(jo, child_process_handle))
7466 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007467 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007468 CloseHandle(jo);
7469 jo = NULL;
7470 }
7471
7472 winpty_spawn_config_free(spawn_config);
7473 vim_free(cmd_wchar);
7474 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007475 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007476
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007477 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7478 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007479
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007480#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007481 if (term_use_palette())
7482 {
7483 if (term->tl_palette != NULL)
7484 set_vterm_palette(term->tl_vterm, term->tl_palette);
7485 else
7486 init_vterm_ansi_colors(term->tl_vterm);
7487 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007488#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007489
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007490 channel_set_job(channel, job, opt);
7491 job_set_options(job, opt);
7492
7493 job->jv_channel = channel;
7494 job->jv_proc_info.hProcess = child_process_handle;
7495 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7496 job->jv_job_object = jo;
7497 job->jv_status = JOB_STARTED;
7498 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007499 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007500 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007501 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007502 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007503 ++job->jv_refcount;
7504 term->tl_job = job;
7505
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007506 // Redirecting stdout and stderr doesn't work at the job level. Instead
7507 // open the file here and handle it in. opt->jo_io was changed in
7508 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007509 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7510 {
7511 char_u *fname = opt->jo_io_name[PART_OUT];
7512
7513 ch_log(channel, "Opening output file %s", fname);
7514 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7515 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007516 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007517 }
7518
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007519 return OK;
7520
7521failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007522 ga_clear(&ga_cmd);
7523 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007524 vim_free(cmd_wchar);
7525 vim_free(cwd_wchar);
7526 if (spawn_config != NULL)
7527 winpty_spawn_config_free(spawn_config);
7528 if (channel != NULL)
7529 channel_clear(channel);
7530 if (job != NULL)
7531 {
7532 job->jv_channel = NULL;
7533 job_cleanup(job);
7534 }
7535 term->tl_job = NULL;
7536 if (jo != NULL)
7537 CloseHandle(jo);
7538 if (term->tl_winpty != NULL)
7539 winpty_free(term->tl_winpty);
7540 term->tl_winpty = NULL;
7541 if (term->tl_winpty_config != NULL)
7542 winpty_config_free(term->tl_winpty_config);
7543 term->tl_winpty_config = NULL;
7544 if (winpty_err != NULL)
7545 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007546 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007547 (short_u *)winpty_error_msg(winpty_err), NULL);
7548
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007549 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007550 winpty_error_free(winpty_err);
7551 }
7552 return FAIL;
7553}
7554
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007555/*
7556 * Create a new terminal of "rows" by "cols" cells.
7557 * Store a reference in "term".
7558 * Return OK or FAIL.
7559 */
7560 static int
7561term_and_job_init(
7562 term_T *term,
7563 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007564 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007565 jobopt_T *opt,
7566 jobopt_T *orig_opt)
7567{
7568 int use_winpty = FALSE;
7569 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007570 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007571
7572 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7573 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7574
7575 if (!has_winpty && !has_conpty)
7576 // If neither is available give the errors for winpty, since when
7577 // conpty is not available it can't be installed either.
7578 return dyn_winpty_init(TRUE);
7579
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007580 if (opt->jo_tty_type != NUL)
7581 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007582
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007583 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007584 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007585 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007586 use_conpty = TRUE;
7587 else if (has_winpty)
7588 use_winpty = TRUE;
7589 // else: error
7590 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007591 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007592 {
7593 if (has_winpty)
7594 use_winpty = TRUE;
7595 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007596 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007597 {
7598 if (has_conpty)
7599 use_conpty = TRUE;
7600 else
7601 return dyn_conpty_init(TRUE);
7602 }
7603
7604 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007605 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007606
7607 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007608 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007609
7610 // error
7611 return dyn_winpty_init(TRUE);
7612}
7613
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007614 static int
7615create_pty_only(term_T *term, jobopt_T *options)
7616{
7617 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7618 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7619 char in_name[80], out_name[80];
7620 channel_T *channel = NULL;
7621
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007622 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7623 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007624
7625 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7626 GetCurrentProcessId(),
7627 curbuf->b_fnum);
7628 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7629 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7630 PIPE_UNLIMITED_INSTANCES,
7631 0, 0, NMPWAIT_NOWAIT, NULL);
7632 if (hPipeIn == INVALID_HANDLE_VALUE)
7633 goto failed;
7634
7635 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7636 GetCurrentProcessId(),
7637 curbuf->b_fnum);
7638 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7639 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7640 PIPE_UNLIMITED_INSTANCES,
7641 0, 0, 0, NULL);
7642 if (hPipeOut == INVALID_HANDLE_VALUE)
7643 goto failed;
7644
7645 ConnectNamedPipe(hPipeIn, NULL);
7646 ConnectNamedPipe(hPipeOut, NULL);
7647
7648 term->tl_job = job_alloc();
7649 if (term->tl_job == NULL)
7650 goto failed;
7651 ++term->tl_job->jv_refcount;
7652
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007653 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007654 term->tl_job->jv_status = JOB_FINISHED;
7655
7656 channel = add_channel();
7657 if (channel == NULL)
7658 goto failed;
7659 term->tl_job->jv_channel = channel;
7660 channel->ch_keep_open = TRUE;
7661 channel->ch_named_pipe = TRUE;
7662
7663 channel_set_pipes(channel,
7664 (sock_T)hPipeIn,
7665 (sock_T)hPipeOut,
7666 (sock_T)hPipeOut);
7667 channel_set_job(channel, term->tl_job, options);
7668 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7669 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7670
7671 return OK;
7672
7673failed:
7674 if (hPipeIn != NULL)
7675 CloseHandle(hPipeIn);
7676 if (hPipeOut != NULL)
7677 CloseHandle(hPipeOut);
7678 return FAIL;
7679}
7680
7681/*
7682 * Free the terminal emulator part of "term".
7683 */
7684 static void
7685term_free_vterm(term_T *term)
7686{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007687 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007688 if (term->tl_winpty != NULL)
7689 winpty_free(term->tl_winpty);
7690 term->tl_winpty = NULL;
7691 if (term->tl_winpty_config != NULL)
7692 winpty_config_free(term->tl_winpty_config);
7693 term->tl_winpty_config = NULL;
7694 if (term->tl_vterm != NULL)
7695 vterm_free(term->tl_vterm);
7696 term->tl_vterm = NULL;
7697}
7698
7699/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007700 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007701 */
7702 static void
7703term_report_winsize(term_T *term, int rows, int cols)
7704{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007705 if (term->tl_conpty)
7706 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007707 if (term->tl_winpty)
7708 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7709}
7710
7711 int
7712terminal_enabled(void)
7713{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007714 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007715}
7716
7717# else
7718
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007719///////////////////////////////////////
7720// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007721
7722/*
7723 * Create a new terminal of "rows" by "cols" cells.
7724 * Start job for "cmd".
7725 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007726 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007727 * Return OK or FAIL.
7728 */
7729 static int
7730term_and_job_init(
7731 term_T *term,
7732 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007733 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007734 jobopt_T *opt,
7735 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007736{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007737 term->tl_arg0_cmd = NULL;
7738
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007739 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7740 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007741
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007742#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007743 if (term_use_palette())
7744 {
7745 if (term->tl_palette != NULL)
7746 set_vterm_palette(term->tl_vterm, term->tl_palette);
7747 else
7748 init_vterm_ansi_colors(term->tl_vterm);
7749 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007750#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007751
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007752 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007753 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007754 if (term->tl_job != NULL)
7755 ++term->tl_job->jv_refcount;
7756
7757 return term->tl_job != NULL
7758 && term->tl_job->jv_channel != NULL
7759 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7760}
7761
7762 static int
7763create_pty_only(term_T *term, jobopt_T *opt)
7764{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007765 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7766 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007767
7768 term->tl_job = job_alloc();
7769 if (term->tl_job == NULL)
7770 return FAIL;
7771 ++term->tl_job->jv_refcount;
7772
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007773 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007774 term->tl_job->jv_status = JOB_FINISHED;
7775
7776 return mch_create_pty_channel(term->tl_job, opt);
7777}
7778
7779/*
7780 * Free the terminal emulator part of "term".
7781 */
7782 static void
7783term_free_vterm(term_T *term)
7784{
7785 if (term->tl_vterm != NULL)
7786 vterm_free(term->tl_vterm);
7787 term->tl_vterm = NULL;
7788}
7789
7790/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007791 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007792 */
7793 static void
7794term_report_winsize(term_T *term, int rows, int cols)
7795{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007796 // Use an ioctl() to report the new window size to the job.
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007797 if (term->tl_job == NULL || term->tl_job->jv_channel == NULL)
7798 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007799
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007800 int fd = -1;
7801 int part;
7802
7803 for (part = PART_OUT; part < PART_COUNT; ++part)
7804 {
7805 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
7806 if (mch_isatty(fd))
7807 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007808 }
Yegappan Lakshmanan032713f2023-01-25 21:05:38 +00007809 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7810 mch_signal_job(term->tl_job, (char_u *)"winch");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007811}
7812
7813# endif
7814
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007815#endif // FEAT_TERMINAL