blob: 18f9c626026ff025cc5e50fa65c735c10c25e31b [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
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200262 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200263 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200264 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200265
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100266 // Syntax of value was already checked when it's set.
Bram Moolenaar498c2562018-04-15 23:45:15 +0200267 if (p == NULL)
268 {
269 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200270 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200271 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200272 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200273 *cols = atoi((char *)p + 1);
274 }
275 return minsize;
276}
277
278/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200279 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200280 */
281 static void
Bram Moolenaarb936b792020-09-04 18:34:09 +0200282set_term_and_win_size(term_T *term, jobopt_T *opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200283{
Bram Moolenaarb936b792020-09-04 18:34:09 +0200284 int rows, cols;
285 int minsize;
286
Bram Moolenaar13568252018-03-16 20:46:58 +0100287#ifdef FEAT_GUI
288 if (term->tl_system)
289 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100290 // Use the whole screen for the system command. However, it will start
291 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100292 term->tl_rows = Rows;
293 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200294 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100295 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100296#endif
Bram Moolenaarb936b792020-09-04 18:34:09 +0200297 term->tl_rows = curwin->w_height;
298 term->tl_cols = curwin->w_width;
299
300 minsize = parse_termwinsize(curwin, &rows, &cols);
301 if (minsize)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200302 {
Bram Moolenaarb936b792020-09-04 18:34:09 +0200303 if (term->tl_rows < rows)
304 term->tl_rows = rows;
305 if (term->tl_cols < cols)
306 term->tl_cols = cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200307 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200308 if ((opt->jo_set2 & JO2_TERM_ROWS))
309 term->tl_rows = opt->jo_term_rows;
310 else if (rows != 0)
311 term->tl_rows = rows;
312 if ((opt->jo_set2 & JO2_TERM_COLS))
313 term->tl_cols = opt->jo_term_cols;
314 else if (cols != 0)
315 term->tl_cols = cols;
316
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200317 if (!opt->jo_hidden)
Bram Moolenaarb936b792020-09-04 18:34:09 +0200318 {
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200319 if (term->tl_rows != curwin->w_height)
320 win_setheight_win(term->tl_rows, curwin);
321 if (term->tl_cols != curwin->w_width)
322 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaarb936b792020-09-04 18:34:09 +0200323
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200324 // Set 'winsize' now to avoid a resize at the next redraw.
325 if (!minsize && *curwin->w_p_tws != NUL)
326 {
327 char_u buf[100];
328
329 vim_snprintf((char *)buf, 100, "%dx%d",
330 term->tl_rows, term->tl_cols);
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100331 set_option_value_give_err((char_u *)"termwinsize",
332 0L, buf, OPT_LOCAL);
Bram Moolenaar2ce14582020-09-05 16:08:49 +0200333 }
Bram Moolenaarb936b792020-09-04 18:34:09 +0200334 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200335}
336
337/*
338 * Initialize job options for a terminal job.
339 * Caller may overrule some of them.
340 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100341 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200342init_job_options(jobopt_T *opt)
343{
344 clear_job_options(opt);
345
Bram Moolenaarac4174e2022-05-07 16:38:24 +0100346 opt->jo_mode = CH_MODE_RAW;
347 opt->jo_out_mode = CH_MODE_RAW;
348 opt->jo_err_mode = CH_MODE_RAW;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200349 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
350}
351
352/*
353 * Set job options mandatory for a terminal job.
354 */
355 static void
356setup_job_options(jobopt_T *opt, int rows, int cols)
357{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100358#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100359 // Win32: Redirecting the job output won't work, thus always connect stdout
360 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200361 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200362#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200363 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100364 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200365 opt->jo_io[PART_OUT] = JIO_BUFFER;
366 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
367 opt->jo_modifiable[PART_OUT] = 0;
368 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
369 }
370
Bram Moolenaar4f974752019-02-17 17:44:42 +0100371#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100372 // Win32: Redirecting the job output won't work, thus always connect stderr
373 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200374 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200375#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200376 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100377 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200378 opt->jo_io[PART_ERR] = JIO_BUFFER;
379 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
380 opt->jo_modifiable[PART_ERR] = 0;
381 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
382 }
383
384 opt->jo_pty = TRUE;
385 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
386 opt->jo_term_rows = rows;
387 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
388 opt->jo_term_cols = cols;
389}
390
391/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200392 * Flush messages on channels.
393 */
394 static void
395term_flush_messages()
396{
397 mch_check_messages();
398 parse_queued_messages();
399}
400
401/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100402 * Close a terminal buffer (and its window). Used when creating the terminal
403 * fails.
404 */
405 static void
406term_close_buffer(buf_T *buf, buf_T *old_curbuf)
407{
408 free_terminal(buf);
409 if (old_curbuf != NULL)
410 {
411 --curbuf->b_nwindows;
412 curbuf = old_curbuf;
413 curwin->w_buffer = curbuf;
414 ++curbuf->b_nwindows;
415 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100416 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100417
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100418 // Wiping out the buffer will also close the window and call
419 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100420 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
421}
422
423/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200424 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100425 * Use either "argvar" or "argv", the other must be NULL.
426 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
427 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 * Returns NULL when failed.
429 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100430 buf_T *
431term_start(
432 typval_T *argvar,
433 char **argv,
434 jobopt_T *opt,
435 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200436{
437 exarg_T split_ea;
438 win_T *old_curwin = curwin;
439 term_T *term;
440 buf_T *old_curbuf = NULL;
441 int res;
442 buf_T *newbuf;
Bram Moolenaare1004402020-10-24 20:49:43 +0200443 int vertical = opt->jo_vertical || (cmdmod.cmod_split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200444 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200445
446 if (check_restricted() || check_secure())
447 return NULL;
Bram Moolenaare5b44862021-05-30 13:54:03 +0200448 if (cmdwin_type != 0)
449 {
450 emsg(_(e_cannot_open_terminal_from_command_line_window));
451 return NULL;
452 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200453
454 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
455 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
456 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100457 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
458 || (argvar != NULL
459 && argvar->v_type == VAR_LIST
460 && argvar->vval.v_list != NULL
461 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200462 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000463 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200464 return NULL;
465 }
466
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200467 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200468 if (term == NULL)
469 return NULL;
470 term->tl_dirty_row_end = MAX_ROW;
471 term->tl_cursor_visible = TRUE;
472 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
473 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100474#ifdef FEAT_GUI
475 term->tl_system = (flags & TERM_START_SYSTEM);
476#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200477 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100478 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200479 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200480
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200481 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200482 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200483 if (opt->jo_curwin)
484 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100485 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100486 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200487 {
488 no_write_message();
489 vim_free(term);
490 return NULL;
491 }
492 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200493 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
494 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
495 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200496 {
497 vim_free(term);
498 return NULL;
499 }
500 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100501 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200502 {
503 buf_T *buf;
504
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100505 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100506 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200507 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
508 BLN_NEW | BLN_LISTED);
509 if (buf == NULL || ml_open(buf) == FAIL)
510 {
511 vim_free(term);
512 return NULL;
513 }
514 old_curbuf = curbuf;
515 --curbuf->b_nwindows;
516 curbuf = buf;
517 curwin->w_buffer = buf;
518 ++curbuf->b_nwindows;
519 }
520 else
521 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100522 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200523 split_ea.cmdidx = CMD_new;
524 split_ea.cmd = (char_u *)"new";
525 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100526 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200527 {
528 split_ea.line2 = opt->jo_term_rows;
529 split_ea.addr_count = 1;
530 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100531 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200532 {
533 split_ea.line2 = opt->jo_term_cols;
534 split_ea.addr_count = 1;
535 }
536
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100537 if (vertical)
Bram Moolenaare1004402020-10-24 20:49:43 +0200538 cmdmod.cmod_split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200539 ex_splitview(&split_ea);
540 if (curwin == old_curwin)
541 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100542 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200543 vim_free(term);
544 return NULL;
545 }
546 }
547 term->tl_buffer = curbuf;
548 curbuf->b_term = term;
549
550 if (!opt->jo_hidden)
551 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100552 // Only one size was taken care of with :new, do the other one. With
553 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100554 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200555 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100556 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200557 win_setwidth(opt->jo_term_cols);
558 }
559
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100560 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200561 term->tl_next = first_term;
562 first_term = term;
563
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100564 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
565
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200566 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100567 {
568 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200569 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100570 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100571 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100572 {
573 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100574 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100575 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200576 else
577 {
578 int i;
579 size_t len;
580 char_u *cmd, *p;
581
582 if (argvar->v_type == VAR_STRING)
583 {
584 cmd = argvar->vval.v_string;
585 if (cmd == NULL)
586 cmd = (char_u *)"";
587 else if (STRCMP(cmd, "NONE") == 0)
588 cmd = (char_u *)"pty";
589 }
590 else if (argvar->v_type != VAR_LIST
591 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100592 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100593 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200594 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
595 cmd = (char_u*)"";
596
597 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200598 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200599
600 for (i = 0; p != NULL; ++i)
601 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100602 // Prepend a ! to the command name to avoid the buffer name equals
603 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200604 if (i == 0)
605 vim_snprintf((char *)p, len, "!%s", cmd);
606 else
607 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
608 if (buflist_findname(p) == NULL)
609 {
610 vim_free(curbuf->b_ffname);
611 curbuf->b_ffname = p;
612 break;
613 }
614 }
615 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100616 vim_free(curbuf->b_sfname);
617 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200618 curbuf->b_fname = curbuf->b_ffname;
619
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100620 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
621
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200622 if (opt->jo_term_opencmd != NULL)
623 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
624
625 if (opt->jo_eof_chars != NULL)
626 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
627
628 set_string_option_direct((char_u *)"buftype", -1,
629 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200630 // Avoid that 'buftype' is reset when this buffer is entered.
631 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200632
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100633 // Mark the buffer as not modifiable. It can only be made modifiable after
634 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200635 curbuf->b_p_ma = FALSE;
636
Bram Moolenaarb936b792020-09-04 18:34:09 +0200637 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100638#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200639 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
640#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200641 setup_job_options(opt, term->tl_rows, term->tl_cols);
642
Bram Moolenaar13568252018-03-16 20:46:58 +0100643 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100644 return curbuf;
645
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100646#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100647 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100648 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100649 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100650 else if (argvar->v_type == VAR_STRING)
651 {
652 char_u *cmd = argvar->vval.v_string;
653
654 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
655 term->tl_command = vim_strsave(cmd);
656 }
657 else if (argvar->v_type == VAR_LIST
658 && argvar->vval.v_list != NULL
659 && argvar->vval.v_list->lv_len > 0)
660 {
661 garray_T ga;
662 listitem_T *item;
663
664 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200665 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100666 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100667 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100668 char_u *p;
669
670 if (s == NULL)
671 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100672 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100673 if (p == NULL)
674 break;
675 ga_concat(&ga, p);
676 vim_free(p);
677 ga_append(&ga, ' ');
678 }
679 if (item == NULL)
680 {
681 ga_append(&ga, NUL);
682 term->tl_command = ga.ga_data;
683 }
684 else
685 ga_clear(&ga);
686 }
687#endif
688
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100689 if (opt->jo_term_kill != NULL)
690 {
691 char_u *p = skiptowhite(opt->jo_term_kill);
692
693 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
694 }
695
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200696 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100697 {
698 char_u *p = skiptowhite(opt->jo_term_api);
699
700 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
701 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200702 else
703 term->tl_api = vim_strsave((char_u *)"Tapi_");
704
Bram Moolenaar83d47902020-03-26 20:34:00 +0100705 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
706 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
707
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100708#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100709 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
710 if (opt->jo_set2 & JO2_ANSI_COLORS)
711 {
712 term->tl_palette = ALLOC_MULT(long_u, 16);
713 if (term->tl_palette == NULL)
714 {
715 vim_free(term);
716 return NULL;
717 }
718 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
719 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100720#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100721
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100722 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100723 if (argv == NULL
724 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200725 && argvar->vval.v_string != NULL
726 && STRCMP(argvar->vval.v_string, "NONE") == 0)
727 res = create_pty_only(term, opt);
728 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200729 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200730
731 newbuf = curbuf;
732 if (res == OK)
733 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100734 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200735 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
736 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100737#ifdef FEAT_GUI
738 if (term->tl_system)
739 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100740 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100741 term->tl_toprow = msg_row + 1;
742 term->tl_dirty_row_end = 0;
743 }
744#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200745
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100746 // Make sure we don't get stuck on sending keys to the job, it leads to
747 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200748 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
749
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200750 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200751 {
752 --curbuf->b_nwindows;
753 curbuf = old_curbuf;
754 curwin->w_buffer = curbuf;
755 ++curbuf->b_nwindows;
756 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000757 else if (vgetc_busy
758#ifdef FEAT_TIMERS
759 || timer_busy
760#endif
761 || input_busy)
762 {
763 char_u ignore[4];
764
765 // When waiting for input need to return and possibly end up in
766 // terminal_loop() instead.
767 ignore[0] = K_SPECIAL;
768 ignore[1] = KS_EXTRA;
769 ignore[2] = KE_IGNORE;
770 ignore[3] = NUL;
771 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
772 typebuf_was_filled = TRUE;
773 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200774 }
775 else
776 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100777 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200778 return NULL;
779 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100780
Bram Moolenaar13568252018-03-16 20:46:58 +0100781 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200782 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
783 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200784 return newbuf;
785}
786
787/*
788 * ":terminal": open a terminal window and execute a job in it.
789 */
790 void
791ex_terminal(exarg_T *eap)
792{
793 typval_T argvar[2];
794 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100795 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200796 char_u *cmd;
797 char_u *tofree = NULL;
798
799 init_job_options(&opt);
800
801 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100802 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200803 {
804 char_u *p, *ep;
805
806 cmd += 2;
807 p = skiptowhite(cmd);
808 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200809 if (ep != NULL)
810 {
811 if (ep < p)
812 p = ep;
813 else
814 ep = NULL;
815 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200816
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200817# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
818 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
819 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200820 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200821 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100822 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200823 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200824 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200825 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200826 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200827 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200828 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200829 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100830 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100831 else if (OPTARG_HAS("shell"))
832 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200833 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100834 {
835 opt.jo_set2 |= JO2_TERM_KILL;
836 opt.jo_term_kill = ep + 1;
837 p = skiptowhite(cmd);
838 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200839 else if (OPTARG_HAS("api"))
840 {
841 opt.jo_set2 |= JO2_TERM_API;
842 if (ep != NULL)
843 {
844 opt.jo_term_api = ep + 1;
845 p = skiptowhite(cmd);
846 }
847 else
848 opt.jo_term_api = NULL;
849 }
850 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200851 {
852 opt.jo_set2 |= JO2_TERM_ROWS;
853 opt.jo_term_rows = atoi((char *)ep + 1);
854 p = skiptowhite(cmd);
855 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200856 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200857 {
858 opt.jo_set2 |= JO2_TERM_COLS;
859 opt.jo_term_cols = atoi((char *)ep + 1);
860 p = skiptowhite(cmd);
861 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200862 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200863 {
864 char_u *buf = NULL;
865 char_u *keys;
866
Bram Moolenaar21109272020-01-30 16:27:20 +0100867 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200868 p = skiptowhite(cmd);
869 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200870 keys = replace_termcodes(ep + 1, &buf,
871 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200872 opt.jo_set2 |= JO2_EOF_CHARS;
873 opt.jo_eof_chars = vim_strsave(keys);
874 vim_free(buf);
875 *p = ' ';
876 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100877#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100878 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
879 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100880 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100881 int tty_type = NUL;
882
883 p = skiptowhite(cmd);
884 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
885 tty_type = 'w';
886 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
887 tty_type = 'c';
888 else
889 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000890 semsg(e_invalid_value_for_argument_str, "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100891 goto theend;
892 }
893 opt.jo_set2 |= JO2_TTY_TYPE;
894 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100895 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100896#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200897 else
898 {
899 if (*p)
900 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000901 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100902 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200903 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200904# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200905 cmd = skipwhite(p);
906 }
907 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100908 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100909 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200910 tofree = cmd = vim_strsave(p_sh);
911
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100912 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100913 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200914 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100915 }
916
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200917 if (eap->addr_count > 0)
918 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100919 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200920 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
921 opt.jo_io[PART_IN] = JIO_BUFFER;
922 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
923 opt.jo_in_top = eap->line1;
924 opt.jo_in_bot = eap->line2;
925 }
926
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100927 if (opt_shell && tofree == NULL)
928 {
929#ifdef UNIX
930 char **argv = NULL;
931 char_u *tofree1 = NULL;
932 char_u *tofree2 = NULL;
933
934 // :term ++shell command
935 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
936 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100937 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100938 vim_free(tofree1);
939 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100940 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100941#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100942# ifdef MSWIN
943 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
944 char_u *newcmd;
945
946 newcmd = alloc(cmdlen);
947 if (newcmd == NULL)
948 goto theend;
949 tofree = newcmd;
950 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
951 cmd = newcmd;
952# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000953 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100954 goto theend;
955# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100956#endif
957 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100958 argvar[0].v_type = VAR_STRING;
959 argvar[0].vval.v_string = cmd;
960 argvar[1].v_type = VAR_UNKNOWN;
961 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100962
963theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100964 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200965 vim_free(opt.jo_eof_chars);
966}
967
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100968#if defined(FEAT_SESSION) || defined(PROTO)
969/*
970 * Write a :terminal command to the session file to restore the terminal in
971 * window "wp".
972 * Return FAIL if writing fails.
973 */
974 int
Bram Moolenaar0e655112020-09-11 20:36:36 +0200975term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100976{
Bram Moolenaar0e655112020-09-11 20:36:36 +0200977 const int bufnr = wp->w_buffer->b_fnum;
978 term_T *term = wp->w_buffer->b_term;
979
Bram Moolenaarc2c82052020-09-11 22:10:22 +0200980 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +0200981 {
982 // There are multiple views into this terminal buffer. We don't want to
983 // create the terminal multiple times. If it's the first time, create,
984 // otherwise link to the first buffer.
985 char id_as_str[NUMBUFLEN];
986 hashitem_T *entry;
987
988 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
989
990 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
991 if (!HASHITEM_EMPTY(entry))
992 {
993 // we've already opened this terminal buffer
994 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
995 return FAIL;
996 return put_eol(fd);
997 }
998 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100999
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001000 // Create the terminal and run the command. This is not without
1001 // risk, but let's assume the user only creates a session when this
1002 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001003 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1004 term->tl_cols, term->tl_rows) < 0)
1005 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001006#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001007 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1008 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001009#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001010 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1011 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001012 if (put_eol(fd) != OK)
1013 return FAIL;
1014
1015 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1016 return FAIL;
1017
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001018 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001019 {
1020 char *hash_key = alloc(NUMBUFLEN);
1021
1022 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
Bram Moolenaaref2c3252022-11-25 16:31:51 +00001023 hash_add(terminal_bufs, (char_u *)hash_key, "terminal session");
Bram Moolenaar0e655112020-09-11 20:36:36 +02001024 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001025
1026 return put_eol(fd);
1027}
1028
1029/*
1030 * Return TRUE if "buf" has a terminal that should be restored.
1031 */
1032 int
1033term_should_restore(buf_T *buf)
1034{
1035 term_T *term = buf->b_term;
1036
1037 return term != NULL && (term->tl_command == NULL
1038 || STRCMP(term->tl_command, "NONE") != 0);
1039}
1040#endif
1041
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001042/*
1043 * Free the scrollback buffer for "term".
1044 */
1045 static void
1046free_scrollback(term_T *term)
1047{
1048 int i;
1049
1050 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1051 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1052 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001053 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1054 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1055 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001056}
1057
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001058
1059// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001060static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001061
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001062/*
1063 * Free a terminal and everything it refers to.
1064 * Kills the job if there is one.
1065 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001066 * The actual terminal structure is freed later in free_unused_terminals(),
1067 * because callbacks may wipe out a buffer while the terminal is still
1068 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001069 */
1070 void
1071free_terminal(buf_T *buf)
1072{
1073 term_T *term = buf->b_term;
1074 term_T *tp;
1075
1076 if (term == NULL)
1077 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001078
1079 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001080 if (first_term == term)
1081 first_term = term->tl_next;
1082 else
1083 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1084 if (tp->tl_next == term)
1085 {
1086 tp->tl_next = term->tl_next;
1087 break;
1088 }
1089
1090 if (term->tl_job != NULL)
1091 {
1092 if (term->tl_job->jv_status != JOB_ENDED
1093 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001094 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001095 job_stop(term->tl_job, NULL, "kill");
1096 job_unref(term->tl_job);
1097 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001098 term->tl_next = terminals_to_free;
1099 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001100
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001101 buf->b_term = NULL;
1102 if (in_terminal_loop == term)
1103 in_terminal_loop = NULL;
1104}
1105
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001106 void
1107free_unused_terminals()
1108{
1109 while (terminals_to_free != NULL)
1110 {
1111 term_T *term = terminals_to_free;
1112
1113 terminals_to_free = term->tl_next;
1114
1115 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001116 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001117
1118 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001119 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001120 vim_free(term->tl_title);
1121#ifdef FEAT_SESSION
1122 vim_free(term->tl_command);
1123#endif
1124 vim_free(term->tl_kill);
1125 vim_free(term->tl_status_text);
1126 vim_free(term->tl_opencmd);
1127 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001128 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001129#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001130 if (term->tl_out_fd != NULL)
1131 fclose(term->tl_out_fd);
1132#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001133 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001134 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001135 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001136 vim_free(term);
1137 }
1138}
1139
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001140/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001141 * Get the part that is connected to the tty. Normally this is PART_IN, but
1142 * when writing buffer lines to the job it can be another. This makes it
1143 * possible to do "1,5term vim -".
1144 */
1145 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001146get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001147{
1148#ifdef UNIX
1149 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1150 int i;
1151
1152 for (i = 0; i < 3; ++i)
1153 {
1154 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1155
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001156 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001157 return parts[i];
1158 }
1159#endif
1160 return PART_IN;
1161}
1162
1163/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001164 * Read any vterm output and send it on the channel.
1165 */
1166 static void
1167term_forward_output(term_T *term)
1168{
1169 VTerm *vterm = term->tl_vterm;
1170 char buf[KEY_BUF_LEN];
1171 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1172
1173 if (curlen > 0)
1174 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1175 (char_u *)buf, (int)curlen, NULL);
1176}
1177
1178/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001179 * Write job output "msg[len]" to the vterm.
1180 */
1181 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001182term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001183{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001184 char_u *msg = msg_arg;
1185 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001186 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001187 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001188 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1189
1190 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1191 // the end.
1192 if (len > limit)
1193 {
1194 char_u *p = msg + len - limit;
1195
1196 p -= (*mb_head_off)(msg, p);
1197 len -= p - msg;
1198 msg = p;
1199 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001200
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001201 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001202
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001203 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001204 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001205 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001206
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001207 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001208 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1209}
1210
1211 static void
1212update_cursor(term_T *term, int redraw)
1213{
1214 if (term->tl_normal_mode)
1215 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001216#ifdef FEAT_GUI
1217 if (term->tl_system)
1218 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1219 term->tl_cursor_pos.col);
1220 else
1221#endif
1222 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001223 if (redraw)
1224 {
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001225 aco_save_T aco;
1226
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001227 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1228 cursor_on();
1229 out_flush();
1230#ifdef FEAT_GUI
1231 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001232 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001233 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001234 gui_mch_flush();
1235 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001236#endif
Bram Moolenaar24fe33a2022-11-24 00:09:02 +00001237 // Make sure an invoked autocmd doesn't delete the buffer (and the
1238 // terminal) under our fingers.
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001239 ++term->tl_buffer->b_locked;
1240
1241 // save and restore curwin and curbuf, in case the autocmd changes them
1242 aucmd_prepbuf(&aco, curbuf);
1243 apply_autocmds(EVENT_TEXTCHANGEDT, NULL, NULL, FALSE, term->tl_buffer);
1244 aucmd_restbuf(&aco);
1245
1246 --term->tl_buffer->b_locked;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001247 }
1248}
1249
1250/*
1251 * Invoked when "msg" output from a job was received. Write it to the terminal
1252 * of "buffer".
1253 */
1254 void
1255write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1256{
1257 size_t len = STRLEN(msg);
1258 term_T *term = buffer->b_term;
1259
Bram Moolenaar4f974752019-02-17 17:44:42 +01001260#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001261 // Win32: Cannot redirect output of the job, intercept it here and write to
1262 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001263 if (term->tl_out_fd != NULL)
1264 {
1265 ch_log(channel, "Writing %d bytes to output file", (int)len);
1266 fwrite(msg, len, 1, term->tl_out_fd);
1267 return;
1268 }
1269#endif
1270
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001271 if (term->tl_vterm == NULL)
1272 {
1273 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1274 return;
1275 }
1276 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001277 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001278 term_write_job_output(term, msg, len);
1279
Bram Moolenaar13568252018-03-16 20:46:58 +01001280#ifdef FEAT_GUI
1281 if (term->tl_system)
1282 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001283 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001284 update_system_term(term);
1285 update_cursor(term, TRUE);
1286 }
1287 else
1288#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001289 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1290 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001291 if (!term->tl_normal_mode)
1292 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001293 // Don't use update_screen() when editing the command line, it gets
1294 // cleared.
1295 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001296 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001297 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001298 {
Bram Moolenaara4d158b2022-08-14 14:17:45 +01001299 update_screen(UPD_VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001300 // update_screen() can be slow, check the terminal wasn't closed
1301 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001302 if (buffer == curbuf && curbuf->b_term != NULL)
1303 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001304 }
1305 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001306 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001307 }
1308}
1309
1310/*
1311 * Send a mouse position and click to the vterm
1312 */
1313 static int
1314term_send_mouse(VTerm *vterm, int button, int pressed)
1315{
1316 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001317 int row = mouse_row - W_WINROW(curwin);
1318 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001319
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001320#ifdef FEAT_PROP_POPUP
1321 if (popup_is_popup(curwin))
1322 {
1323 row -= popup_top_extra(curwin);
1324 col -= popup_left_extra(curwin);
1325 }
1326#endif
1327 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001328 if (button != 0)
1329 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001330 return TRUE;
1331}
1332
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001333static int enter_mouse_col = -1;
1334static int enter_mouse_row = -1;
1335
1336/*
1337 * Handle a mouse click, drag or release.
1338 * Return TRUE when a mouse event is sent to the terminal.
1339 */
1340 static int
1341term_mouse_click(VTerm *vterm, int key)
1342{
1343#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001344 // For modeless selection mouse drag and release events are ignored, unless
1345 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001346 static int ignore_drag_release = TRUE;
1347 VTermMouseState mouse_state;
1348
1349 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1350 if (mouse_state.flags == 0)
1351 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001352 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001353 switch (key)
1354 {
1355 case K_LEFTDRAG:
1356 case K_LEFTRELEASE:
1357 case K_RIGHTDRAG:
1358 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001359 // Ignore drag and release events when the button-down wasn't
1360 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001361 if (ignore_drag_release)
1362 {
1363 int save_mouse_col, save_mouse_row;
1364
1365 if (enter_mouse_col < 0)
1366 break;
1367
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001368 // mouse click in the window gave us focus, handle that
1369 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001370 save_mouse_col = mouse_col;
1371 save_mouse_row = mouse_row;
1372 mouse_col = enter_mouse_col;
1373 mouse_row = enter_mouse_row;
1374 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1375 mouse_col = save_mouse_col;
1376 mouse_row = save_mouse_row;
1377 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001378 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001379 case K_LEFTMOUSE:
1380 case K_RIGHTMOUSE:
1381 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1382 ignore_drag_release = TRUE;
1383 else
1384 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001385 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001386 if (clip_star.available)
1387 {
1388 int button, is_click, is_drag;
1389
1390 button = get_mouse_button(KEY2TERMCAP1(key),
1391 &is_click, &is_drag);
1392 if (mouse_model_popup() && button == MOUSE_LEFT
1393 && (mod_mask & MOD_MASK_SHIFT))
1394 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001395 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001396 button = MOUSE_RIGHT;
1397 mod_mask &= ~MOD_MASK_SHIFT;
1398 }
1399 clip_modeless(button, is_click, is_drag);
1400 }
1401 break;
1402
1403 case K_MIDDLEMOUSE:
1404 if (clip_star.available)
1405 insert_reg('*', TRUE);
1406 break;
1407 }
1408 enter_mouse_col = -1;
1409 return FALSE;
1410 }
1411#endif
1412 enter_mouse_col = -1;
1413
1414 switch (key)
1415 {
1416 case K_LEFTMOUSE:
1417 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1418 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1419 case K_LEFTRELEASE:
1420 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1421 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1422 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1423 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1424 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1425 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1426 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1427 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1428 }
1429 return TRUE;
1430}
1431
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001432/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001433 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1434 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001435 * Return the number of bytes in "buf".
1436 */
1437 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001438term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001439{
1440 VTerm *vterm = term->tl_vterm;
1441 VTermKey key = VTERM_KEY_NONE;
1442 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001443 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001444
1445 switch (c)
1446 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001447 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001448
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001449 // don't use VTERM_KEY_BACKSPACE, it always
1450 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001451 case K_BS: c = term_backspace_char; break;
1452
1453 case ESC: key = VTERM_KEY_ESCAPE; break;
1454 case K_DEL: key = VTERM_KEY_DEL; break;
1455 case K_DOWN: key = VTERM_KEY_DOWN; break;
1456 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1457 key = VTERM_KEY_DOWN; break;
1458 case K_END: key = VTERM_KEY_END; break;
1459 case K_S_END: mod = VTERM_MOD_SHIFT;
1460 key = VTERM_KEY_END; break;
1461 case K_C_END: mod = VTERM_MOD_CTRL;
1462 key = VTERM_KEY_END; break;
1463 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1464 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1465 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1466 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1467 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1468 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1469 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1470 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1471 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1472 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1473 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1474 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1475 case K_HOME: key = VTERM_KEY_HOME; break;
1476 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1477 key = VTERM_KEY_HOME; break;
1478 case K_C_HOME: mod = VTERM_MOD_CTRL;
1479 key = VTERM_KEY_HOME; break;
1480 case K_INS: key = VTERM_KEY_INS; break;
1481 case K_K0: key = VTERM_KEY_KP_0; break;
1482 case K_K1: key = VTERM_KEY_KP_1; break;
1483 case K_K2: key = VTERM_KEY_KP_2; break;
1484 case K_K3: key = VTERM_KEY_KP_3; break;
1485 case K_K4: key = VTERM_KEY_KP_4; break;
1486 case K_K5: key = VTERM_KEY_KP_5; break;
1487 case K_K6: key = VTERM_KEY_KP_6; break;
1488 case K_K7: key = VTERM_KEY_KP_7; break;
1489 case K_K8: key = VTERM_KEY_KP_8; break;
1490 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001491 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001492 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001493 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001494 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001495 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1496 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001497 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1498 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001499 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1500 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001501 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1502 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1503 case K_LEFT: key = VTERM_KEY_LEFT; break;
1504 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1505 key = VTERM_KEY_LEFT; break;
1506 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1507 key = VTERM_KEY_LEFT; break;
1508 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1509 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1510 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1511 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1512 key = VTERM_KEY_RIGHT; break;
1513 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1514 key = VTERM_KEY_RIGHT; break;
1515 case K_UP: key = VTERM_KEY_UP; break;
1516 case K_S_UP: mod = VTERM_MOD_SHIFT;
1517 key = VTERM_KEY_UP; break;
1518 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001519 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1520 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001521
Bram Moolenaara42ad572017-11-16 13:08:04 +01001522 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1523 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001524 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1525 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001526
1527 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001528 case K_LEFTMOUSE_NM:
1529 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001530 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001531 case K_LEFTRELEASE_NM:
1532 case K_MOUSEMOVE:
1533 case K_MIDDLEMOUSE:
1534 case K_MIDDLEDRAG:
1535 case K_MIDDLERELEASE:
1536 case K_RIGHTMOUSE:
1537 case K_RIGHTDRAG:
1538 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1539 return 0;
1540 other = TRUE;
1541 break;
1542
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001543 case K_X1MOUSE: /* TODO */ return 0;
1544 case K_X1DRAG: /* TODO */ return 0;
1545 case K_X1RELEASE: /* TODO */ return 0;
1546 case K_X2MOUSE: /* TODO */ return 0;
1547 case K_X2DRAG: /* TODO */ return 0;
1548 case K_X2RELEASE: /* TODO */ return 0;
1549
1550 case K_IGNORE: return 0;
1551 case K_NOP: return 0;
1552 case K_UNDO: return 0;
1553 case K_HELP: return 0;
1554 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1555 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1556 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1557 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1558 case K_SELECT: return 0;
1559#ifdef FEAT_GUI
1560 case K_VER_SCROLLBAR: return 0;
1561 case K_HOR_SCROLLBAR: return 0;
1562#endif
1563#ifdef FEAT_GUI_TABLINE
1564 case K_TABLINE: return 0;
1565 case K_TABMENU: return 0;
1566#endif
1567#ifdef FEAT_NETBEANS_INTG
1568 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1569#endif
1570#ifdef FEAT_DND
1571 case K_DROP: return 0;
1572#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001573 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001574 case K_PS: vterm_keyboard_start_paste(vterm);
1575 other = TRUE;
1576 break;
1577 case K_PE: vterm_keyboard_end_paste(vterm);
1578 other = TRUE;
1579 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001580 }
1581
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001582 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001583 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001584 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001585 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001586 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001587 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001588 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001589
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001590 // Ctrl-Shift-i may have the key "I" instead of "i", but for the kitty
1591 // keyboard protocol should use "i". Applies to all ascii letters.
1592 if (ASCII_ISUPPER(c)
Bram Moolenaarebed1b02022-11-24 14:05:19 +00001593 && vterm_is_kitty_keyboard(vterm)
Bram Moolenaar63a2e362022-11-23 20:20:18 +00001594 && mod == (VTERM_MOD_CTRL | VTERM_MOD_SHIFT))
1595 c = TOLOWER_ASC(c);
1596
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001597 /*
1598 * Convert special keys to vterm keys:
1599 * - Write keys to vterm: vterm_keyboard_key()
1600 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001601 */
1602 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001603 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001604 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001605 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001606 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001607 vterm_keyboard_unichar(vterm, c, mod);
1608
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001609 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001610 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1611}
1612
1613/*
1614 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001615 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001616 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001617 */
1618 static int
1619term_job_running_check(term_T *term, int check_job_status)
1620{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001621 // Also consider the job finished when the channel is closed, to avoid a
1622 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001623 if (term != NULL
1624 && term->tl_job != NULL
1625 && channel_is_open(term->tl_job->jv_channel))
1626 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001627 job_T *job = term->tl_job;
1628
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00001629 // Careful: Checking the job status may invoke callbacks, which close
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001630 // the buffer and terminate "term". However, "job" will not be freed
1631 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001632 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001633 job_status(job);
1634 return (job->jv_status == JOB_STARTED
1635 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001636 }
1637 return FALSE;
1638}
1639
1640/*
1641 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001642 */
1643 int
1644term_job_running(term_T *term)
1645{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001646 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001647}
1648
1649/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001650 * Return TRUE if the job for "term" is still running, ignoring the job was
1651 * "NONE".
1652 */
1653 int
1654term_job_running_not_none(term_T *term)
1655{
1656 return term_job_running(term) && !term_none_open(term);
1657}
1658
1659/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001660 * Return TRUE if "term" has an active channel and used ":term NONE".
1661 */
1662 int
1663term_none_open(term_T *term)
1664{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001665 // Also consider the job finished when the channel is closed, to avoid a
1666 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001667 return term != NULL
1668 && term->tl_job != NULL
1669 && channel_is_open(term->tl_job->jv_channel)
1670 && term->tl_job->jv_channel->ch_keep_open;
1671}
1672
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001673//
1674// Used to confirm whether we would like to kill a terminal.
1675// Return OK when the user confirms to kill it.
1676// Return FAIL if the user selects otherwise.
1677//
1678 int
1679term_confirm_stop(buf_T *buf)
1680{
1681 char_u buff[DIALOG_MSG_SIZE];
1682 int ret;
1683
1684 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1685 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1686 if (ret == VIM_YES)
1687 return OK;
1688 else
1689 return FAIL;
1690}
1691
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001692/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001693 * Used when exiting: kill the job in "buf" if so desired.
1694 * Return OK when the job finished.
1695 * Return FAIL when the job is still running.
1696 */
1697 int
1698term_try_stop_job(buf_T *buf)
1699{
1700 int count;
1701 char *how = (char *)buf->b_term->tl_kill;
1702
1703#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001704 if ((how == NULL || *how == NUL)
1705 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001706 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001707 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001708 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001709 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001710 return FAIL;
1711 }
1712#endif
1713 if (how == NULL || *how == NUL)
1714 return FAIL;
1715
1716 job_stop(buf->b_term->tl_job, NULL, how);
1717
Bram Moolenaar9172d232019-01-29 23:06:54 +01001718 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001719 for (count = 0; count < 100; ++count)
1720 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001721 job_T *job;
1722
1723 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001724 if (!buf_valid(buf)
1725 || buf->b_term == NULL
1726 || buf->b_term->tl_job == NULL)
1727 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001728 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001729
Bram Moolenaar9172d232019-01-29 23:06:54 +01001730 // Call job_status() to update jv_status. It may cause the job to be
1731 // cleaned up but it won't be freed.
1732 job_status(job);
1733 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001734 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001735
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001736 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001737 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001738 }
1739 return FAIL;
1740}
1741
1742/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001743 * Add the last line of the scrollback buffer to the buffer in the window.
1744 */
1745 static void
1746add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1747{
1748 buf_T *buf = term->tl_buffer;
1749 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1750 linenr_T lnum = buf->b_ml.ml_line_count;
1751
Bram Moolenaar4f974752019-02-17 17:44:42 +01001752#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001753 if (!enc_utf8 && enc_codepage > 0)
1754 {
1755 WCHAR *ret = NULL;
1756 int length = 0;
1757
1758 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1759 &ret, &length);
1760 if (ret != NULL)
1761 {
1762 WideCharToMultiByte_alloc(enc_codepage, 0,
1763 ret, length, (char **)&text, &len, 0, 0);
1764 vim_free(ret);
1765 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1766 vim_free(text);
1767 }
1768 }
1769 else
1770#endif
1771 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1772 if (empty)
1773 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001774 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001775 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001776 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001777 curbuf = curwin->w_buffer;
1778 }
1779}
1780
1781 static void
1782cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1783{
1784 attr->width = cell->width;
1785 attr->attrs = cell->attrs;
1786 attr->fg = cell->fg;
1787 attr->bg = cell->bg;
1788}
1789
1790 static int
1791equal_celattr(cellattr_T *a, cellattr_T *b)
1792{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001793 // We only compare the RGB colors, ignoring the ANSI index and type.
1794 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001795 return a->fg.red == b->fg.red
1796 && a->fg.green == b->fg.green
1797 && a->fg.blue == b->fg.blue
1798 && a->bg.red == b->bg.red
1799 && a->bg.green == b->bg.green
1800 && a->bg.blue == b->bg.blue;
1801}
1802
Bram Moolenaard96ff162018-02-18 22:13:29 +01001803/*
1804 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1805 * line at this position. Otherwise at the end.
1806 */
1807 static int
1808add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1809{
1810 if (ga_grow(&term->tl_scrollback, 1) == OK)
1811 {
1812 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1813 + term->tl_scrollback.ga_len;
1814
1815 if (lnum > 0)
1816 {
1817 int i;
1818
1819 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1820 {
1821 *line = *(line - 1);
1822 --line;
1823 }
1824 }
1825 line->sb_cols = 0;
1826 line->sb_cells = NULL;
1827 line->sb_fill_attr = *fill_attr;
1828 ++term->tl_scrollback.ga_len;
1829 return OK;
1830 }
1831 return FALSE;
1832}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001833
1834/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001835 * Remove the terminal contents from the scrollback and the buffer.
1836 * Used before adding a new scrollback line or updating the buffer for lines
1837 * displayed in the terminal.
1838 */
1839 static void
1840cleanup_scrollback(term_T *term)
1841{
1842 sb_line_T *line;
1843 garray_T *gap;
1844
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001845 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001846 gap = &term->tl_scrollback;
1847 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1848 && gap->ga_len > 0)
1849 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001850 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001851 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1852 vim_free(line->sb_cells);
1853 --gap->ga_len;
1854 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001855 curbuf = curwin->w_buffer;
1856 if (curbuf == term->tl_buffer)
1857 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001858}
1859
1860/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001861 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001862 */
1863 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001864update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001865{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001866 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001867 int len;
1868 int lines_skipped = 0;
1869 VTermPos pos;
1870 VTermScreenCell cell;
1871 cellattr_T fill_attr, new_fill_attr;
1872 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001873
1874 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1875 "Adding terminal window snapshot to buffer");
1876
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001877 // First remove the lines that were appended before, they might be
1878 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001879 cleanup_scrollback(term);
1880
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001881 screen = vterm_obtain_screen(term->tl_vterm);
1882 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001883 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1884 {
1885 len = 0;
1886 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1887 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1888 && cell.chars[0] != NUL)
1889 {
1890 len = pos.col + 1;
1891 new_fill_attr = term->tl_default_color;
1892 }
1893 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001894 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001895 cell2cellattr(&cell, &new_fill_attr);
1896
1897 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1898 ++lines_skipped;
1899 else
1900 {
1901 while (lines_skipped > 0)
1902 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001903 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001904 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001905 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001906 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001907 }
1908
1909 if (len == 0)
1910 p = NULL;
1911 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001912 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913 if ((p != NULL || len == 0)
1914 && ga_grow(&term->tl_scrollback, 1) == OK)
1915 {
1916 garray_T ga;
1917 int width;
1918 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1919 + term->tl_scrollback.ga_len;
1920
1921 ga_init2(&ga, 1, 100);
1922 for (pos.col = 0; pos.col < len; pos.col += width)
1923 {
1924 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1925 {
1926 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02001927 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001928 if (ga_grow(&ga, 1) == OK)
1929 ga.ga_len += utf_char2bytes(' ',
1930 (char_u *)ga.ga_data + ga.ga_len);
1931 }
1932 else
1933 {
1934 width = cell.width;
1935
1936 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01001937 if (width == 2)
1938 // second cell of double-width character has the
1939 // same attributes.
1940 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001941
Bram Moolenaara79fd562018-12-20 20:47:32 +01001942 // Each character can be up to 6 bytes.
1943 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001944 {
1945 int i;
1946 int c;
1947
1948 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1949 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1950 (char_u *)ga.ga_data + ga.ga_len);
1951 }
1952 }
1953 }
1954 line->sb_cols = len;
1955 line->sb_cells = p;
1956 line->sb_fill_attr = new_fill_attr;
1957 fill_attr = new_fill_attr;
1958 ++term->tl_scrollback.ga_len;
1959
1960 if (ga_grow(&ga, 1) == FAIL)
1961 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1962 else
1963 {
1964 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1965 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1966 }
1967 ga_clear(&ga);
1968 }
1969 else
1970 vim_free(p);
1971 }
1972 }
1973
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001974 // Add trailing empty lines.
1975 for (pos.row = term->tl_scrollback.ga_len;
1976 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1977 ++pos.row)
1978 {
1979 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1980 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1981 }
1982
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001983 term->tl_dirty_snapshot = FALSE;
1984#ifdef FEAT_TIMERS
1985 term->tl_timer_set = FALSE;
1986#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001987}
1988
1989/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001990 * Loop over all windows in the current tab, and also curwin, which is not
1991 * encountered when using a terminal in a popup window.
1992 * Return TRUE if "*wp" was set to the next window.
1993 */
1994 static int
1995for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1996{
1997 if (*wp == NULL)
1998 *wp = firstwin;
1999 else if ((*wp)->w_next != NULL)
2000 *wp = (*wp)->w_next;
2001 else if (!*did_curwin)
2002 *wp = curwin;
2003 else
2004 return FALSE;
2005 if (*wp == curwin)
2006 *did_curwin = TRUE;
2007 return TRUE;
2008}
2009
2010/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002011 * If needed, add the current lines of the terminal to scrollback and to the
2012 * buffer. Called after the job has ended and when switching to
2013 * Terminal-Normal mode.
2014 * When "redraw" is TRUE redraw the windows that show the terminal.
2015 */
2016 static void
2017may_move_terminal_to_buffer(term_T *term, int redraw)
2018{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002019 if (term->tl_vterm == NULL)
2020 return;
2021
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002022 // Update the snapshot only if something changes or the buffer does not
2023 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002024 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2025 <= term->tl_scrollback_scrolled)
2026 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002027
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002028 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002029 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2030 &term->tl_default_color.fg, &term->tl_default_color.bg);
2031
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002032 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002033 {
2034 win_T *wp = NULL;
2035 int did_curwin = FALSE;
2036
2037 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002038 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002039 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002040 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002041 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2042 wp->w_cursor.col = 0;
2043 wp->w_valid = 0;
2044 if (wp->w_cursor.lnum >= wp->w_height)
2045 {
2046 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002047
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002048 if (wp->w_topline < min_topline)
2049 wp->w_topline = min_topline;
2050 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002051 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002052 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002053 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002054 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002055}
2056
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002057#if defined(FEAT_TIMERS) || defined(PROTO)
2058/*
2059 * Check if any terminal timer expired. If so, copy text from the terminal to
2060 * the buffer.
2061 * Return the time until the next timer will expire.
2062 */
2063 int
2064term_check_timers(int next_due_arg, proftime_T *now)
2065{
2066 term_T *term;
2067 int next_due = next_due_arg;
2068
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002069 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002070 {
2071 if (term->tl_timer_set && !term->tl_normal_mode)
2072 {
2073 long this_due = proftime_time_left(&term->tl_timer_due, now);
2074
2075 if (this_due <= 1)
2076 {
2077 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002078 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002079 }
2080 else if (next_due == -1 || next_due > this_due)
2081 next_due = this_due;
2082 }
2083 }
2084
2085 return next_due;
2086}
2087#endif
2088
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002089/*
2090 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2091 * otherwise end it.
2092 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002093 static void
2094set_terminal_mode(term_T *term, int normal_mode)
2095{
2096 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002097 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002098 if (!normal_mode)
2099 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002100 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002101 if (term->tl_buffer == curbuf)
2102 maketitle();
2103}
2104
2105/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002106 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002107 * Move the vterm contents into the scrollback buffer and free the vterm.
2108 */
2109 static void
2110cleanup_vterm(term_T *term)
2111{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002112 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002113 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002114 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002115 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002116}
2117
2118/*
2119 * Switch from Terminal-Job mode to Terminal-Normal mode.
2120 * Suspends updating the terminal window.
2121 */
2122 static void
2123term_enter_normal_mode(void)
2124{
2125 term_T *term = curbuf->b_term;
2126
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002127 set_terminal_mode(term, TRUE);
2128
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002129 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002130 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002131
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002132 // Move the window cursor to the position of the cursor in the
2133 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002134 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2135 + term->tl_cursor_pos.row + 1;
2136 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002137 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2138 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002139 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002140
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002141 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002142 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2143}
2144
2145/*
2146 * Returns TRUE if the current window contains a terminal and we are in
2147 * Terminal-Normal mode.
2148 */
2149 int
2150term_in_normal_mode(void)
2151{
2152 term_T *term = curbuf->b_term;
2153
2154 return term != NULL && term->tl_normal_mode;
2155}
2156
2157/*
2158 * Switch from Terminal-Normal mode to Terminal-Job mode.
2159 * Restores updating the terminal window.
2160 */
2161 void
2162term_enter_job_mode()
2163{
2164 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002165
2166 set_terminal_mode(term, FALSE);
2167
2168 if (term->tl_channel_closed)
2169 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002170 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002171#ifdef FEAT_PROP_POPUP
2172 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002173 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002174#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175}
2176
2177/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002178 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2179 * modifiers into a basic key. However, we may only find out after calling
2180 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2181 * "no_reduce_keys" before using it.
2182 */
2183typedef enum {
2184 NRKS_NONE, // initial value
2185 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2186 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2187 // check_no_reduce_keys(), must be decremented.
2188} reduce_key_state_T;
2189
2190static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2191
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002192/*
2193 * Return TRUE if the term is using modifyOtherKeys level 2 or the kitty
2194 * keyboard protocol.
2195 */
2196 static int
2197vterm_using_key_protocol(void)
2198{
2199 return curbuf->b_term != NULL
2200 && curbuf->b_term->tl_vterm != NULL
2201 && (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm)
2202 || vterm_is_kitty_keyboard(curbuf->b_term->tl_vterm));
2203}
2204
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002205 void
2206check_no_reduce_keys(void)
2207{
2208 if (no_reduce_key_state != NRKS_CHECK
2209 || no_reduce_keys >= 1
2210 || curbuf->b_term == NULL
2211 || curbuf->b_term->tl_vterm == NULL)
2212 return;
2213
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002214 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002215 {
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002216 // "modify_other_keys" or kitty keyboard protocol was enabled while
2217 // waiting.
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002218 no_reduce_key_state = NRKS_SET;
2219 ++no_reduce_keys;
2220 }
2221}
2222
2223/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002224 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002225 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002226 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002227 */
2228 static int
2229term_vgetc()
2230{
2231 int c;
2232 int save_State = State;
2233
Bram Moolenaar24959102022-05-07 20:01:16 +01002234 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002235 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002236#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002237 ctrl_break_was_pressed = FALSE;
2238#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002239
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002240 if (vterm_using_key_protocol())
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002241 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002242 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002243 no_reduce_key_state = NRKS_SET;
2244 }
2245 else
2246 {
2247 no_reduce_key_state = NRKS_CHECK;
2248 }
2249
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002250 c = vgetc();
2251 got_int = FALSE;
2252 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002253
2254 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002255 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002256 no_reduce_key_state = NRKS_NONE;
2257
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002258 return c;
2259}
2260
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002261static int mouse_was_outside = FALSE;
2262
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002263/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002264 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002265 * Return FAIL when the key needs to be handled in Normal mode.
2266 * Return OK when the key was dropped or sent to the terminal.
2267 */
2268 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002269send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002270{
2271 char msg[KEY_BUF_LEN];
2272 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002273 int dragging_outside = FALSE;
2274
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002275 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002276 switch (c)
2277 {
2278 case NUL:
2279 case K_ZERO:
2280 if (typed)
2281 stuffcharReadbuff(c);
2282 return FAIL;
2283
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002284 case K_TABLINE:
2285 stuffcharReadbuff(c);
2286 return FAIL;
2287
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002288 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002289 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002290 return FAIL;
2291
2292 case K_LEFTDRAG:
2293 case K_MIDDLEDRAG:
2294 case K_RIGHTDRAG:
2295 case K_X1DRAG:
2296 case K_X2DRAG:
2297 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002298 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002299 case K_LEFTMOUSE:
2300 case K_LEFTMOUSE_NM:
2301 case K_LEFTRELEASE:
2302 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002303 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002304 case K_MIDDLEMOUSE:
2305 case K_MIDDLERELEASE:
2306 case K_RIGHTMOUSE:
2307 case K_RIGHTRELEASE:
2308 case K_X1MOUSE:
2309 case K_X1RELEASE:
2310 case K_X2MOUSE:
2311 case K_X2RELEASE:
2312
2313 case K_MOUSEUP:
2314 case K_MOUSEDOWN:
2315 case K_MOUSELEFT:
2316 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002317 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002318 int row = mouse_row;
2319 int col = mouse_col;
2320
2321#ifdef FEAT_PROP_POPUP
2322 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002323 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002324 row -= popup_top_extra(curwin);
2325 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002326 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002327#endif
2328 if (row < W_WINROW(curwin)
2329 || row >= (W_WINROW(curwin) + curwin->w_height)
2330 || col < curwin->w_wincol
2331 || col >= W_ENDCOL(curwin)
2332 || dragging_outside)
2333 {
2334 // click or scroll outside the current window or on status
2335 // line or vertical separator
2336 if (typed)
2337 {
2338 stuffcharReadbuff(c);
2339 mouse_was_outside = TRUE;
2340 }
2341 return FAIL;
2342 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002343 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002344 break;
2345
2346 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002347 case K_SCRIPT_COMMAND:
2348 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002349 }
2350 if (typed)
2351 mouse_was_outside = FALSE;
2352
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002353 // Convert the typed key to a sequence of bytes for the job.
2354 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002355 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002356 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002357 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2358 (char_u *)msg, (int)len, NULL);
2359
2360 return OK;
2361}
2362
2363 static void
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002364position_cursor(win_T *wp, VTermPos *pos)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002365{
2366 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2367 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002368#ifdef FEAT_PROP_POPUP
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002369 if (popup_is_popup(wp))
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002370 {
Bram Moolenaarf5452692020-11-28 21:56:06 +01002371 wp->w_wrow += popup_top_extra(wp);
2372 wp->w_wcol += popup_left_extra(wp);
Bram Moolenaar6a076442020-11-15 20:32:58 +01002373 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002374 }
Bram Moolenaar6a076442020-11-15 20:32:58 +01002375 else
2376 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002377#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002378 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2379}
2380
2381/*
2382 * Handle CTRL-W "": send register contents to the job.
2383 */
2384 static void
2385term_paste_register(int prev_c UNUSED)
2386{
2387 int c;
2388 list_T *l;
2389 listitem_T *item;
2390 long reglen = 0;
2391 int type;
2392
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002393 if (add_to_showcmd(prev_c))
2394 if (add_to_showcmd('"'))
2395 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002396
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002397 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002398 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002399
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002400 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002401 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002402 return;
2403
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002404 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002405 if (c == '=' && get_expr_register() != '=')
2406 return;
2407 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002408 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002409 return;
2410
2411 l = (list_T *)get_reg_contents(c, GREG_LIST);
2412 if (l != NULL)
2413 {
2414 type = get_reg_type(c, &reglen);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002415 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002416 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002417 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002418#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002419 char_u *tmp = s;
2420
2421 if (!enc_utf8 && enc_codepage > 0)
2422 {
2423 WCHAR *ret = NULL;
2424 int length = 0;
2425
2426 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2427 (int)STRLEN(s), &ret, &length);
2428 if (ret != NULL)
2429 {
2430 WideCharToMultiByte_alloc(CP_UTF8, 0,
2431 ret, length, (char **)&s, &length, 0, 0);
2432 vim_free(ret);
2433 }
2434 }
2435#endif
2436 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2437 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002438#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002439 if (tmp != s)
2440 vim_free(s);
2441#endif
2442
2443 if (item->li_next != NULL || type == MLINE)
2444 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2445 (char_u *)"\r", 1, NULL);
2446 }
2447 list_free(l);
2448 }
2449}
2450
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002451/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002452 * Return TRUE when waiting for a character in the terminal, the cursor of the
2453 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002454 */
2455 int
2456terminal_is_active()
2457{
2458 return in_terminal_loop != NULL;
2459}
2460
Bram Moolenaar83d47902020-03-26 20:34:00 +01002461/*
dundargocc57b5bc2022-11-02 13:30:51 +00002462 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002463 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002464 static int
2465term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002466{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002467 char_u *name;
2468
2469 if (wp != NULL && *wp->w_p_wcr != NUL)
2470 name = wp->w_p_wcr;
2471 else if (term->tl_highlight_name != NULL)
2472 name = term->tl_highlight_name;
2473 else
2474 name = (char_u*)"Terminal";
2475
2476 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002477}
2478
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002479#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002480 cursorentry_T *
2481term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2482{
2483 term_T *term = in_terminal_loop;
2484 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002485 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002486 guicolor_T term_fg = INVALCOLOR;
2487 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002488
Bram Moolenaara80faa82020-04-12 19:37:17 +02002489 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002490 entry.shape = entry.mshape =
2491 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2492 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2493 SHAPE_BLOCK;
2494 entry.percentage = 20;
2495 if (term->tl_cursor_blink)
2496 {
2497 entry.blinkwait = 700;
2498 entry.blinkon = 400;
2499 entry.blinkoff = 250;
2500 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002501
Bram Moolenaar83d47902020-03-26 20:34:00 +01002502 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002503 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002504 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002505 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002506 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002507 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002508 else
2509 *fg = gui.back_pixel;
2510
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002511 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002512 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002513 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002514 *bg = term_fg;
2515 else
2516 *bg = gui.norm_pixel;
2517 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002518 else
2519 *bg = color_name2handle(term->tl_cursor_color);
2520 entry.name = "n";
2521 entry.used_for = SHAPE_CURSOR;
2522
2523 return &entry;
2524}
2525#endif
2526
Bram Moolenaard317b382018-02-08 22:33:31 +01002527 static void
2528may_output_cursor_props(void)
2529{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002530 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002531 || last_set_cursor_shape != desired_cursor_shape
2532 || last_set_cursor_blink != desired_cursor_blink)
2533 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002534 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002535 last_set_cursor_shape = desired_cursor_shape;
2536 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002537 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002538 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002539 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002540 ui_cursor_shape_forced(TRUE);
2541 else
2542 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2543 }
2544}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002545
Bram Moolenaard317b382018-02-08 22:33:31 +01002546/*
2547 * Set the cursor color and shape, if not last set to these.
2548 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002549 static void
2550may_set_cursor_props(term_T *term)
2551{
2552#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002553 // For the GUI the cursor properties are obtained with
2554 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002555 if (gui.in_use)
2556 return;
2557#endif
2558 if (in_terminal_loop == term)
2559 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002560 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002561 desired_cursor_shape = term->tl_cursor_shape;
2562 desired_cursor_blink = term->tl_cursor_blink;
2563 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002564 }
2565}
2566
Bram Moolenaard317b382018-02-08 22:33:31 +01002567/*
2568 * Reset the desired cursor properties and restore them when needed.
2569 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002570 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002571prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002572{
2573#ifdef FEAT_GUI
2574 if (gui.in_use)
2575 return;
2576#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002577 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002578 desired_cursor_shape = -1;
2579 desired_cursor_blink = -1;
2580 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002581}
2582
2583/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002584 * Returns TRUE if the current window contains a terminal and we are sending
2585 * keys to the job.
2586 * If "check_job_status" is TRUE update the job status.
2587 */
2588 static int
2589term_use_loop_check(int check_job_status)
2590{
2591 term_T *term = curbuf->b_term;
2592
2593 return term != NULL
2594 && !term->tl_normal_mode
2595 && term->tl_vterm != NULL
2596 && term_job_running_check(term, check_job_status);
2597}
2598
2599/*
2600 * Returns TRUE if the current window contains a terminal and we are sending
2601 * keys to the job.
2602 */
2603 int
2604term_use_loop(void)
2605{
2606 return term_use_loop_check(FALSE);
2607}
2608
2609/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002610 * Called when entering a window with the mouse. If this is a terminal window
2611 * we may want to change state.
2612 */
2613 void
2614term_win_entered()
2615{
2616 term_T *term = curbuf->b_term;
2617
2618 if (term != NULL)
2619 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002620 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002621 {
2622 reset_VIsual_and_resel();
Bram Moolenaar24959102022-05-07 20:01:16 +01002623 if (State & MODE_INSERT)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002624 stop_insert_mode = TRUE;
2625 }
2626 mouse_was_outside = FALSE;
2627 enter_mouse_col = mouse_col;
2628 enter_mouse_row = mouse_row;
2629 }
2630}
2631
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002632 void
2633term_focus_change(int in_focus)
2634{
2635 term_T *term = curbuf->b_term;
2636
2637 if (term != NULL && term->tl_vterm != NULL)
2638 {
2639 VTermState *state = vterm_obtain_state(term->tl_vterm);
2640
2641 if (in_focus)
2642 vterm_state_focus_in(state);
2643 else
2644 vterm_state_focus_out(state);
2645 term_forward_output(term);
2646 }
2647}
2648
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002649/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002650 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2651 * Return the Ctrl-key value in that case.
2652 */
2653 static int
2654raw_c_to_ctrl(int c)
2655{
2656 if ((mod_mask & MOD_MASK_CTRL)
2657 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2658 return c & 0x1f;
2659 return c;
2660}
2661
2662/*
2663 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002664 * Also when the Kitty keyboard protocol is used.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002665 * May set "mod_mask".
2666 */
2667 static int
2668ctrl_to_raw_c(int c)
2669{
Bram Moolenaar63a2e362022-11-23 20:20:18 +00002670 if (c < 0x20 && vterm_using_key_protocol())
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002671 {
2672 mod_mask |= MOD_MASK_CTRL;
2673 return c + '@';
2674 }
2675 return c;
2676}
2677
2678/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002679 * Wait for input and send it to the job.
2680 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2681 * when there is no more typahead.
2682 * Return when the start of a CTRL-W command is typed or anything else that
2683 * should be handled as a Normal mode command.
2684 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2685 * the terminal was closed.
2686 */
2687 int
2688terminal_loop(int blocking)
2689{
2690 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002691 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002692 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002693 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002694#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002695 int tty_fd = curbuf->b_term->tl_job->jv_channel
2696 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002697#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002698 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002699
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002700 // Remember the terminal we are sending keys to. However, the terminal
2701 // might be closed while waiting for a character, e.g. typing "exit" in a
2702 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2703 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002704 in_terminal_loop = curbuf->b_term;
2705
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002706 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002707 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002708 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002709 if (termwinkey == Ctrl_W)
2710 termwinkey = 0;
2711 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002712 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002713 may_set_cursor_props(curbuf->b_term);
2714
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002715 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002716 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002717#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002718 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002719#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002720 // TODO: skip screen update when handling a sequence of keys.
2721 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002722 while (must_redraw != 0)
2723 if (update_screen(0) == FAIL)
2724 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002725 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002726 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002727 break;
2728
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002729 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002730 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002731
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002732 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002733 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002734 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002735 // Job finished while waiting for a character. Push back the
2736 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002737 if (raw_c != K_IGNORE)
2738 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002739 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002740 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002741 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002742 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002743 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002744
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002745#ifdef UNIX
2746 /*
2747 * The shell or another program may change the tty settings. Getting
2748 * them for every typed character is a bit of overhead, but it's needed
2749 * for the first character typed, e.g. when Vim starts in a shell.
2750 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002751 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002752 {
2753 ttyinfo_T info;
2754
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002755 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002756 if (get_tty_info(tty_fd, &info) == OK)
2757 term_backspace_char = info.backspace;
2758 }
2759#endif
2760
Bram Moolenaar4f974752019-02-17 17:44:42 +01002761#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002762 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2763 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002764 if (ctrl_break_was_pressed)
2765 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2766#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002767 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2768 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002769 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002770#ifdef FEAT_GUI
2771 && !curbuf->b_term->tl_system
2772#endif
2773 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002774 {
2775 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002776 int prev_raw_c = raw_c;
2777 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002778
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002779 if (add_to_showcmd(c))
2780 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002781
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002782 raw_c = term_vgetc();
2783 c = raw_c_to_ctrl(raw_c);
2784
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002785 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002786
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002787 if (!term_use_loop_check(TRUE)
2788 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002789 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002790 break;
2791
2792 if (prev_c == Ctrl_BSL)
2793 {
2794 if (c == Ctrl_N)
2795 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002796 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002797 term_enter_normal_mode();
2798 ret = FAIL;
2799 goto theend;
2800 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002801 // Send both keys to the terminal, first one here, second one
2802 // below.
2803 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2804 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002805 }
2806 else if (c == Ctrl_C)
2807 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002808 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002809 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2810 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002811 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002812 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002813 // "CTRL-W .": send CTRL-W to the job
2814 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002815 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002816 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002817 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002818 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002819 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002820 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002821 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002822 else if (c == 'N')
2823 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002824 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002825 term_enter_normal_mode();
2826 ret = FAIL;
2827 goto theend;
2828 }
2829 else if (c == '"')
2830 {
2831 term_paste_register(prev_c);
2832 continue;
2833 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002834 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002835 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002836 // space for CTRL-W, modifier, multi-byte char and NUL
2837 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002838
2839 // Put the command into the typeahead buffer, when using the
2840 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2841 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002842 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002843 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002844 ret = OK;
2845 goto theend;
2846 }
2847 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002848# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002849 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002850 {
2851 WCHAR wc;
2852 char_u mb[3];
2853
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002854 mb[0] = (unsigned)raw_c >> 8;
2855 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002856 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002857 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002858 }
2859# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002860 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002861 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002862 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002863 // We are sure to come back here, don't reset the cursor color
2864 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002865 restore_cursor = FALSE;
2866
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002867 ret = OK;
2868 goto theend;
2869 }
2870 }
2871 ret = FAIL;
2872
2873theend:
2874 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002875 if (restore_cursor)
2876 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002877
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002878 // Move a snapshot of the screen contents to the buffer, so that completion
2879 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002880 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2881 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002882
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002883 return ret;
2884}
2885
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002886 static void
2887may_toggle_cursor(term_T *term)
2888{
2889 if (in_terminal_loop == term)
2890 {
2891 if (term->tl_cursor_visible)
2892 cursor_on();
2893 else
2894 cursor_off();
2895 }
2896}
2897
2898/*
2899 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002900 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002901 */
2902 static int
2903color2index(VTermColor *color, int fg, int *boldp)
2904{
2905 int red = color->red;
2906 int blue = color->blue;
2907 int green = color->green;
2908
LemonBoyb2b3acb2022-05-20 10:10:34 +01002909 *boldp = FALSE;
2910
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002911 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002912 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01002913
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002914 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002915 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01002916 // Use the color as-is if possible, give up otherwise.
2917 if (color->index < t_colors)
2918 return color->index + 1;
2919 // 8-color terminals can actually display twice as many colors by
2920 // setting the high-intensity/bold bit.
2921 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01002923 *boldp = TRUE;
2924 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01002926 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002927 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002928
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002929 if (t_colors >= 256)
2930 {
2931 if (red == blue && red == green)
2932 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002933 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002934 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002935 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2936 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2937 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002938 int i;
2939
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002940 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002941 return 17; // 00/00/00
2942 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002943 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002944 for (i = 0; i < 23; ++i)
2945 if (red < cutoff[i])
2946 return i + 233;
2947 return 256;
2948 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002949 {
2950 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2951 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002952
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002953 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002954 for (ri = 0; ri < 5; ++ri)
2955 if (red < cutoff[ri])
2956 break;
2957 for (gi = 0; gi < 5; ++gi)
2958 if (green < cutoff[gi])
2959 break;
2960 for (bi = 0; bi < 5; ++bi)
2961 if (blue < cutoff[bi])
2962 break;
2963 return 17 + ri * 36 + gi * 6 + bi;
2964 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002965 }
2966 return 0;
2967}
2968
2969/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002970 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002971 */
2972 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002973vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002974{
2975 int attr = 0;
2976
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002977 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002978 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002979 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002980 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002981 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002982 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002983 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002984 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002985 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002986 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002987 return attr;
2988}
2989
2990/*
2991 * Store Vterm attributes in "cell" from highlight flags.
2992 */
2993 static void
2994hl2vtermAttr(int attr, cellattr_T *cell)
2995{
Bram Moolenaara80faa82020-04-12 19:37:17 +02002996 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002997 if (attr & HL_BOLD)
2998 cell->attrs.bold = 1;
2999 if (attr & HL_UNDERLINE)
3000 cell->attrs.underline = 1;
3001 if (attr & HL_ITALIC)
3002 cell->attrs.italic = 1;
3003 if (attr & HL_STRIKETHROUGH)
3004 cell->attrs.strike = 1;
3005 if (attr & HL_INVERSE)
3006 cell->attrs.reverse = 1;
3007}
3008
3009/*
3010 * Convert the attributes of a vterm cell into an attribute index.
3011 */
3012 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003013cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003014 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003015 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003016 VTermScreenCellAttrs *cellattrs,
3017 VTermColor *cellfg,
3018 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003019{
3020 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003021 VTermColor *fg = cellfg;
3022 VTermColor *bg = cellbg;
3023 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3024 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3025
3026 if (is_default_fg || is_default_bg)
3027 {
3028 if (wp != NULL && *wp->w_p_wcr != NUL)
3029 {
3030 if (is_default_fg)
3031 fg = &wp->w_term_wincolor.fg;
3032 if (is_default_bg)
3033 bg = &wp->w_term_wincolor.bg;
3034 }
3035 else
3036 {
3037 if (is_default_fg)
3038 fg = &term->tl_default_color.fg;
3039 if (is_default_bg)
3040 bg = &term->tl_default_color.bg;
3041 }
3042 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003043
3044#ifdef FEAT_GUI
3045 if (gui.in_use)
3046 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003047 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3048 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3049 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003050 }
3051 else
3052#endif
3053#ifdef FEAT_TERMGUICOLORS
3054 if (p_tgc)
3055 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003056 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3057 ? INVALCOLOR
3058 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3059 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3060 ? INVALCOLOR
3061 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3062 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003063 }
3064 else
3065#endif
3066 {
3067 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003068 int ctermfg = color2index(fg, TRUE, &bold);
3069 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003070
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003071 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003072 if (bold == TRUE)
3073 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003074
3075 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003076 }
3077 return 0;
3078}
3079
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003080 static void
3081set_dirty_snapshot(term_T *term)
3082{
3083 term->tl_dirty_snapshot = TRUE;
3084#ifdef FEAT_TIMERS
3085 if (!term->tl_normal_mode)
3086 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003087 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003088 profile_setlimit(100L, &term->tl_timer_due);
3089 term->tl_timer_set = TRUE;
3090 }
3091#endif
3092}
3093
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003094 static int
3095handle_damage(VTermRect rect, void *user)
3096{
3097 term_T *term = (term_T *)user;
3098
3099 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3100 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003101 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003102 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003103 return 1;
3104}
3105
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003106 static void
3107term_scroll_up(term_T *term, int start_row, int count)
3108{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003109 win_T *wp = NULL;
3110 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003111 VTermColor fg, bg;
3112 VTermScreenCellAttrs attr;
3113 int clear_attr;
3114
Bram Moolenaara80faa82020-04-12 19:37:17 +02003115 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003116
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003117 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003118 {
3119 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003120 {
3121 // Set the color to clear lines with.
3122 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3123 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003124 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003125 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003126 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003127 }
3128}
3129
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130 static int
3131handle_moverect(VTermRect dest, VTermRect src, void *user)
3132{
3133 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003134 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003135
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003136 // Scrolling up is done much more efficiently by deleting lines instead of
3137 // redrawing the text. But avoid doing this multiple times, postpone until
3138 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003139 if (dest.start_col == src.start_col
3140 && dest.end_col == src.end_col
3141 && dest.start_row < src.start_row)
3142 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003143 if (dest.start_row == 0)
3144 term->tl_postponed_scroll += count;
3145 else
3146 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003147 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003148
3149 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3150 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003151 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003152
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003153 // Note sure if the scrolling will work correctly, let's do a complete
3154 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003155 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156 return 1;
3157}
3158
3159 static int
3160handle_movecursor(
3161 VTermPos pos,
3162 VTermPos oldpos UNUSED,
3163 int visible,
3164 void *user)
3165{
3166 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003167 win_T *wp = NULL;
3168 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003169
3170 term->tl_cursor_pos = pos;
3171 term->tl_cursor_visible = visible;
3172
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003173 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003174 {
3175 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003176 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003177 }
3178 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003179 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003180
3181 return 1;
3182}
3183
3184 static int
3185handle_settermprop(
3186 VTermProp prop,
3187 VTermValue *value,
3188 void *user)
3189{
3190 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003191 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003192
3193 switch (prop)
3194 {
3195 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003196 if (disable_vterm_title_for_testing)
3197 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003198 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003199 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003200 if (strval == NULL)
3201 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003202 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003203 // a blank title isn't useful, make it empty, so that "running" is
3204 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003205 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003206 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003207 // Same as blank
3208 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003209 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003210 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3211 term->tl_title = NULL;
3212 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003213 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003214 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003215#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003216 else if (!enc_utf8 && enc_codepage > 0)
3217 {
3218 WCHAR *ret = NULL;
3219 int length = 0;
3220
3221 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003222 (char*)value->string.str,
3223 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003224 if (ret != NULL)
3225 {
3226 WideCharToMultiByte_alloc(enc_codepage, 0,
3227 ret, length, (char**)&term->tl_title,
3228 &length, 0, 0);
3229 vim_free(ret);
3230 }
3231 }
3232#endif
3233 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003234 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003235 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003236 strval = NULL;
3237 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003238 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003239 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003240 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003241 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003242 curwin->w_redr_status = TRUE;
3243 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003244 break;
3245
3246 case VTERM_PROP_CURSORVISIBLE:
3247 term->tl_cursor_visible = value->boolean;
3248 may_toggle_cursor(term);
3249 out_flush();
3250 break;
3251
3252 case VTERM_PROP_CURSORBLINK:
3253 term->tl_cursor_blink = value->boolean;
3254 may_set_cursor_props(term);
3255 break;
3256
3257 case VTERM_PROP_CURSORSHAPE:
3258 term->tl_cursor_shape = value->number;
3259 may_set_cursor_props(term);
3260 break;
3261
3262 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003263 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003264 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003265 if (strval == NULL)
3266 break;
3267 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003268 may_set_cursor_props(term);
3269 break;
3270
3271 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003272 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003273 term->tl_using_altscreen = value->boolean;
3274 break;
3275
3276 default:
3277 break;
3278 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003279 vim_free(strval);
3280
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003281 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003282 return 1;
3283}
3284
3285/*
3286 * The job running in the terminal resized the terminal.
3287 */
3288 static int
3289handle_resize(int rows, int cols, void *user)
3290{
3291 term_T *term = (term_T *)user;
3292 win_T *wp;
3293
3294 term->tl_rows = rows;
3295 term->tl_cols = cols;
3296 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003297 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003298 term->tl_vterm_size_changed = FALSE;
3299 else
3300 {
3301 FOR_ALL_WINDOWS(wp)
3302 {
3303 if (wp->w_buffer == term->tl_buffer)
3304 {
3305 win_setheight_win(rows, wp);
3306 win_setwidth_win(cols, wp);
3307 }
3308 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003309 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003310 }
3311 return 1;
3312}
3313
3314/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003315 * If the number of lines that are stored goes over 'termscrollback' then
3316 * delete the first 10%.
3317 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3318 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003319 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003320 static void
3321limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003322{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003323 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003324 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003325 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003326 int i;
3327
3328 curbuf = term->tl_buffer;
3329 for (i = 0; i < todo; ++i)
3330 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003331 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3332 if (update_buffer)
Bram Moolenaarca70c072020-05-30 20:30:46 +02003333 ml_delete(1);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003334 }
3335 curbuf = curwin->w_buffer;
3336
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003337 gap->ga_len -= todo;
3338 mch_memmove(gap->ga_data,
3339 (sb_line_T *)gap->ga_data + todo,
3340 sizeof(sb_line_T) * gap->ga_len);
3341 if (update_buffer)
3342 term->tl_scrollback_scrolled -= todo;
3343 }
3344}
3345
3346/*
3347 * Handle a line that is pushed off the top of the screen.
3348 */
3349 static int
3350handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3351{
3352 term_T *term = (term_T *)user;
3353 garray_T *gap;
3354 int update_buffer;
3355
3356 if (term->tl_normal_mode)
3357 {
3358 // In Terminal-Normal mode the user interacts with the buffer, thus we
3359 // must not change it. Postpone adding the scrollback lines.
3360 gap = &term->tl_scrollback_postponed;
3361 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003362 }
3363 else
3364 {
3365 // First remove the lines that were appended before, the pushed line
3366 // goes above it.
3367 cleanup_scrollback(term);
3368 gap = &term->tl_scrollback;
3369 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003370 }
3371
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003372 limit_scrollback(term, gap, update_buffer);
3373
3374 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003375 {
3376 cellattr_T *p = NULL;
3377 int len = 0;
3378 int i;
3379 int c;
3380 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003381 int text_len;
3382 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003383 sb_line_T *line;
3384 garray_T ga;
3385 cellattr_T fill_attr = term->tl_default_color;
3386
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003387 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003388 for (i = 0; i < cols; ++i)
3389 if (cells[i].chars[0] != 0)
3390 len = i + 1;
3391 else
3392 cell2cellattr(&cells[i], &fill_attr);
3393
3394 ga_init2(&ga, 1, 100);
3395 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003396 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003397 if (p != NULL)
3398 {
3399 for (col = 0; col < len; col += cells[col].width)
3400 {
3401 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3402 {
3403 ga.ga_len = 0;
3404 break;
3405 }
3406 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3407 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3408 (char_u *)ga.ga_data + ga.ga_len);
3409 cell2cellattr(&cells[col], &p[col]);
3410 }
3411 }
3412 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003413 {
3414 if (update_buffer)
3415 text = (char_u *)"";
3416 else
3417 text = vim_strsave((char_u *)"");
3418 text_len = 0;
3419 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003420 else
3421 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003422 text = ga.ga_data;
3423 text_len = ga.ga_len;
3424 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003425 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003426 if (update_buffer)
3427 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003428
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003429 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003430 line->sb_cols = len;
3431 line->sb_cells = p;
3432 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003433 if (update_buffer)
3434 {
3435 line->sb_text = NULL;
3436 ++term->tl_scrollback_scrolled;
3437 ga_clear(&ga); // free the text
3438 }
3439 else
3440 {
3441 line->sb_text = text;
3442 ga_init(&ga); // text is kept in tl_scrollback_postponed
3443 }
3444 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003445 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003446 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003447}
3448
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003449/*
3450 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3451 * received and stored in tl_scrollback_postponed.
3452 */
3453 static void
3454handle_postponed_scrollback(term_T *term)
3455{
3456 int i;
3457
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003458 if (term->tl_scrollback_postponed.ga_len == 0)
3459 return;
3460 ch_log(NULL, "Moving postponed scrollback to scrollback");
3461
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003462 // First remove the lines that were appended before, the pushed lines go
3463 // above it.
3464 cleanup_scrollback(term);
3465
3466 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3467 {
3468 char_u *text;
3469 sb_line_T *pp_line;
3470 sb_line_T *line;
3471
3472 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3473 break;
3474 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3475
3476 text = pp_line->sb_text;
3477 if (text == NULL)
3478 text = (char_u *)"";
3479 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3480 vim_free(pp_line->sb_text);
3481
3482 line = (sb_line_T *)term->tl_scrollback.ga_data
3483 + term->tl_scrollback.ga_len;
3484 line->sb_cols = pp_line->sb_cols;
3485 line->sb_cells = pp_line->sb_cells;
3486 line->sb_fill_attr = pp_line->sb_fill_attr;
3487 line->sb_text = NULL;
3488 ++term->tl_scrollback_scrolled;
3489 ++term->tl_scrollback.ga_len;
3490 }
3491
3492 ga_clear(&term->tl_scrollback_postponed);
3493 limit_scrollback(term, &term->tl_scrollback, TRUE);
3494}
3495
LemonBoy77771d32022-04-13 11:47:25 +01003496/*
3497 * Called when the terminal wants to ring the system bell.
3498 */
3499 static int
3500handle_bell(void *user UNUSED)
3501{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003502 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003503 return 0;
3504}
3505
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003506static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003507 handle_damage, // damage
3508 handle_moverect, // moverect
3509 handle_movecursor, // movecursor
3510 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003511 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003512 handle_resize, // resize
3513 handle_pushline, // sb_pushline
Bram Moolenaar6a12d262022-10-16 19:26:52 +01003514 NULL, // sb_popline
3515 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003516};
3517
3518/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003519 * Do the work after the channel of a terminal was closed.
3520 * Must be called only when updating_screen is FALSE.
3521 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3522 */
3523 static int
3524term_after_channel_closed(term_T *term)
3525{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003526 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003527 if (!term->tl_normal_mode)
3528 {
3529 int fnum = term->tl_buffer->b_fnum;
3530
3531 cleanup_vterm(term);
3532
3533 if (term->tl_finish == TL_FINISH_CLOSE)
3534 {
3535 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003536 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003537#ifdef FEAT_PROP_POPUP
3538 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003539
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003540 // If this was a terminal in a popup window, go back to the
3541 // previous window.
3542 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3543 {
3544 pwin = curwin;
3545 if (win_valid(prevwin))
3546 win_enter(prevwin, FALSE);
3547 }
3548 else
3549#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003550 // If this is the last normal window: exit Vim.
3551 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3552 {
3553 exarg_T ea;
3554
Bram Moolenaara80faa82020-04-12 19:37:17 +02003555 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003556 ex_quit(&ea);
3557 return TRUE;
3558 }
3559
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003560 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003561 ch_log(NULL, "terminal job finished, closing window");
3562 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaare76062c2022-11-28 18:51:43 +00003563 if (curbuf == term->tl_buffer)
3564 {
3565 // Avoid closing the window if we temporarily use it.
3566 if (is_aucmd_win(curwin))
3567 do_set_w_closing = TRUE;
3568 if (do_set_w_closing)
3569 curwin->w_closing = TRUE;
3570 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
3571 if (do_set_w_closing)
3572 curwin->w_closing = FALSE;
3573 aucmd_restbuf(&aco);
3574 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003575#ifdef FEAT_PROP_POPUP
3576 if (pwin != NULL)
3577 popup_close_with_retval(pwin, 0);
3578#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003579 return TRUE;
3580 }
3581 if (term->tl_finish == TL_FINISH_OPEN
3582 && term->tl_buffer->b_nwindows == 0)
3583 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003584 char *cmd = term->tl_opencmd == NULL
3585 ? "botright sbuf %d"
3586 : (char *)term->tl_opencmd;
3587 size_t len = strlen(cmd) + 50;
3588 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003589
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003590 if (buf != NULL)
3591 {
3592 ch_log(NULL, "terminal job finished, opening window");
3593 vim_snprintf(buf, len, cmd, fnum);
3594 do_cmdline_cmd((char_u *)buf);
3595 vim_free(buf);
3596 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003597 }
3598 else
3599 ch_log(NULL, "terminal job finished");
3600 }
3601
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003602 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003603 return FALSE;
3604}
3605
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003606#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3607/*
3608 * If the current window is a terminal in a popup window and the job has
3609 * finished, close the popup window and to back to the previous window.
3610 * Otherwise return FAIL.
3611 */
3612 int
3613may_close_term_popup(void)
3614{
3615 if (popup_is_popup(curwin) && curbuf->b_term != NULL
Bram Moolenaar9e636b92022-05-29 22:37:05 +01003616 && !term_job_running_not_none(curbuf->b_term))
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003617 {
3618 win_T *pwin = curwin;
3619
3620 if (win_valid(prevwin))
3621 win_enter(prevwin, FALSE);
3622 popup_close_with_retval(pwin, 0);
3623 return OK;
3624 }
3625 return FAIL;
3626}
3627#endif
3628
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003629/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003630 * Called when a channel is going to be closed, before invoking the close
3631 * callback.
3632 */
3633 void
3634term_channel_closing(channel_T *ch)
3635{
3636 term_T *term;
3637
3638 for (term = first_term; term != NULL; term = term->tl_next)
3639 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3640 term->tl_channel_closing = TRUE;
3641}
3642
3643/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003644 * Called when a channel has been closed.
3645 * If this was a channel for a terminal window then finish it up.
3646 */
3647 void
3648term_channel_closed(channel_T *ch)
3649{
3650 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003651 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003652 int did_one = FALSE;
3653
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003654 for (term = first_term; term != NULL; term = next_term)
3655 {
3656 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003657 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003658 {
3659 term->tl_channel_closed = TRUE;
3660 did_one = TRUE;
3661
Bram Moolenaard23a8232018-02-10 18:45:26 +01003662 VIM_CLEAR(term->tl_title);
3663 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003664#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003665 if (term->tl_out_fd != NULL)
3666 {
3667 fclose(term->tl_out_fd);
3668 term->tl_out_fd = NULL;
3669 }
3670#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003671
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003672 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003673 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003674 // Cannot open or close windows now. Can happen when
3675 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003676 term->tl_channel_recently_closed = TRUE;
3677 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003678 }
3679
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003680 if (term_after_channel_closed(term))
3681 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003682 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003683 }
3684
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003685 if (did_one)
3686 {
3687 redraw_statuslines();
3688
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003689 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003690 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003691 typebuf_was_filled = TRUE;
3692
3693 term = curbuf->b_term;
3694 if (term != NULL)
3695 {
3696 if (term->tl_job == ch->ch_job)
3697 maketitle();
3698 update_cursor(term, term->tl_cursor_visible);
3699 }
3700 }
3701}
3702
3703/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003704 * To be called after resetting updating_screen: handle any terminal where the
3705 * channel was closed.
3706 */
3707 void
3708term_check_channel_closed_recently()
3709{
3710 term_T *term;
3711 term_T *next_term;
3712
3713 for (term = first_term; term != NULL; term = next_term)
3714 {
3715 next_term = term->tl_next;
3716 if (term->tl_channel_recently_closed)
3717 {
3718 term->tl_channel_recently_closed = FALSE;
3719 if (term_after_channel_closed(term))
3720 // start over, the list may have changed
3721 next_term = first_term;
3722 }
3723 }
3724}
3725
3726/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003727 * Fill one screen line from a line of the terminal.
3728 * Advances "pos" to past the last column.
3729 */
3730 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003731term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003732 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003733 win_T *wp,
3734 VTermScreen *screen,
3735 VTermPos *pos,
3736 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003737{
3738 int off = screen_get_current_line_off();
3739
3740 for (pos->col = 0; pos->col < max_col; )
3741 {
3742 VTermScreenCell cell;
3743 int c;
3744
3745 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003746 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003747
3748 c = cell.chars[0];
3749 if (c == NUL)
3750 {
3751 ScreenLines[off] = ' ';
3752 if (enc_utf8)
3753 ScreenLinesUC[off] = NUL;
3754 }
3755 else
3756 {
3757 if (enc_utf8)
3758 {
3759 int i;
3760
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003761 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003762 for (i = 0; i < Screen_mco
3763 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3764 {
3765 ScreenLinesC[i][off] = cell.chars[i + 1];
3766 if (cell.chars[i + 1] == 0)
3767 break;
3768 }
3769 if (c >= 0x80 || (Screen_mco > 0
3770 && ScreenLinesC[0][off] != 0))
3771 {
3772 ScreenLines[off] = ' ';
3773 ScreenLinesUC[off] = c;
3774 }
3775 else
3776 {
3777 ScreenLines[off] = c;
3778 ScreenLinesUC[off] = NUL;
3779 }
3780 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003781#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003782 else if (has_mbyte && c >= 0x80)
3783 {
3784 char_u mb[MB_MAXBYTES+1];
3785 WCHAR wc = c;
3786
3787 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3788 (char*)mb, 2, 0, 0) > 1)
3789 {
3790 ScreenLines[off] = mb[0];
3791 ScreenLines[off + 1] = mb[1];
3792 cell.width = mb_ptr2cells(mb);
3793 }
3794 else
3795 ScreenLines[off] = c;
3796 }
3797#endif
3798 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003799 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003800 ScreenLines[off] = c;
3801 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003802 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3803 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003804
3805 ++pos->col;
3806 ++off;
3807 if (cell.width == 2)
3808 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003809 // don't set the second byte to NUL for a DBCS encoding, it
3810 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003811 if (enc_utf8)
3812 {
3813 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003814 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003815 }
3816 else if (!has_mbyte)
3817 {
3818 // Can't show a double-width character with a single-byte
3819 // 'encoding', just use a space.
3820 ScreenLines[off] = ' ';
3821 ScreenAttrs[off] = ScreenAttrs[off - 1];
3822 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003823
3824 ++pos->col;
3825 ++off;
3826 }
3827 }
3828}
3829
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003830#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003831 static void
3832update_system_term(term_T *term)
3833{
3834 VTermPos pos;
3835 VTermScreen *screen;
3836
3837 if (term->tl_vterm == NULL)
3838 return;
3839 screen = vterm_obtain_screen(term->tl_vterm);
3840
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003841 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003842 while (term->tl_toprow > 0
3843 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3844 {
3845 int save_p_more = p_more;
3846
3847 p_more = FALSE;
3848 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003849 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003850 p_more = save_p_more;
3851 --term->tl_toprow;
3852 }
3853
3854 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3855 && pos.row < Rows; ++pos.row)
3856 {
3857 if (pos.row < term->tl_rows)
3858 {
3859 int max_col = MIN(Columns, term->tl_cols);
3860
Bram Moolenaar83d47902020-03-26 20:34:00 +01003861 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003862 }
3863 else
3864 pos.col = 0;
3865
Bram Moolenaar510f0372022-07-04 17:46:22 +01003866 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003867 }
3868
3869 term->tl_dirty_row_start = MAX_ROW;
3870 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003871}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003872#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003873
3874/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003875 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3876 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003877 * Terminal-Normal mode.
3878 */
3879 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003880term_do_update_window(win_T *wp)
3881{
3882 term_T *term = wp->w_buffer->b_term;
3883
3884 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3885}
3886
3887/*
3888 * Called to update a window that contains an active terminal.
3889 */
3890 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003891term_update_window(win_T *wp)
3892{
3893 term_T *term = wp->w_buffer->b_term;
3894 VTerm *vterm;
3895 VTermScreen *screen;
3896 VTermState *state;
3897 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003898 int rows, cols;
3899 int newrows, newcols;
3900 int minsize;
3901 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003902
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003903 vterm = term->tl_vterm;
3904 screen = vterm_obtain_screen(vterm);
3905 state = vterm_obtain_state(vterm);
3906
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003907 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
3908 // With UPD_SOME_VALID only redraw what was marked dirty.
3909 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003910 {
3911 term->tl_dirty_row_start = 0;
3912 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003913
3914 if (term->tl_postponed_scroll > 0
3915 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003916 // Scrolling is usually faster than redrawing, when there are only
3917 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003918 term_scroll_up(term, 0, term->tl_postponed_scroll);
3919 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003920 }
3921
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003922 /*
3923 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003924 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003925 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003926 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003927
Bram Moolenaar498c2562018-04-15 23:45:15 +02003928 newrows = 99999;
3929 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003930 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003931 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003932 // Always use curwin, it may be a popup window.
3933 win_T *wwp = twp == NULL ? curwin : twp;
3934
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003935 // When more than one window shows the same terminal, use the
3936 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003937 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003938 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003939 newrows = MIN(newrows, wwp->w_height);
3940 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003941 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003942 if (twp == NULL)
3943 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003944 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003945 if (newrows == 99999 || newcols == 99999)
3946 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003947 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3948 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3949
Bram Moolenaareba13e42021-02-23 17:47:23 +01003950 // If no cell is visible there is no point in resizing. Also, vterm can't
3951 // handle a zero height.
3952 if (newrows == 0 || newcols == 0)
3953 return;
3954
Bram Moolenaar498c2562018-04-15 23:45:15 +02003955 if (term->tl_rows != newrows || term->tl_cols != newcols)
3956 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003957 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003958 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003959 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003960 newrows);
3961 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003962
3963 // Updating the terminal size will cause the snapshot to be cleared.
3964 // When not in terminal_loop() we need to restore it.
3965 if (term != in_terminal_loop)
3966 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003967 }
3968
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003969 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003970 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003971 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003972
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003973 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3974 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003975 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003976 if (pos.row < term->tl_rows)
3977 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003978 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003979
Bram Moolenaar83d47902020-03-26 20:34:00 +01003980 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003981 }
3982 else
3983 pos.col = 0;
3984
Bram Moolenaar510f0372022-07-04 17:46:22 +01003985 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01003986#ifdef FEAT_MENU
3987 + winbar_height(wp)
3988#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003989 , wp->w_wincol, pos.col, wp->w_width,
3990#ifdef FEAT_PROP_POPUP
3991 popup_is_popup(wp) ? SLF_POPUP :
3992#endif
3993 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003994 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00003995}
3996
3997/*
3998 * Called after updating all windows: may reset dirty rows.
3999 */
4000 void
4001term_did_update_window(win_T *wp)
4002{
4003 term_T *term = wp->w_buffer->b_term;
4004
4005 if (term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode
4006 && wp->w_redr_type == 0)
4007 {
4008 term->tl_dirty_row_start = MAX_ROW;
4009 term->tl_dirty_row_end = 0;
4010 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004011}
4012
4013/*
4014 * Return TRUE if "wp" is a terminal window where the job has finished.
4015 */
4016 int
4017term_is_finished(buf_T *buf)
4018{
4019 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
4020}
4021
4022/*
4023 * Return TRUE if "wp" is a terminal window where the job has finished or we
4024 * are in Terminal-Normal mode, thus we show the buffer contents.
4025 */
4026 int
4027term_show_buffer(buf_T *buf)
4028{
4029 term_T *term = buf->b_term;
4030
4031 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4032}
4033
4034/*
4035 * The current buffer is going to be changed. If there is terminal
4036 * highlighting remove it now.
4037 */
4038 void
4039term_change_in_curbuf(void)
4040{
4041 term_T *term = curbuf->b_term;
4042
4043 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
4044 {
4045 free_scrollback(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004046 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004047
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004048 // The buffer is now like a normal buffer, it cannot be easily
4049 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004050 set_string_option_direct((char_u *)"buftype", -1,
4051 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
4052 }
4053}
4054
4055/*
4056 * Get the screen attribute for a position in the buffer.
4057 * Use a negative "col" to get the filler background color.
4058 */
4059 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004060term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004061{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004062 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004063 term_T *term = buf->b_term;
4064 sb_line_T *line;
4065 cellattr_T *cellattr;
4066
4067 if (lnum > term->tl_scrollback.ga_len)
4068 cellattr = &term->tl_default_color;
4069 else
4070 {
4071 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4072 if (col < 0 || col >= line->sb_cols)
4073 cellattr = &line->sb_fill_attr;
4074 else
4075 cellattr = line->sb_cells + col;
4076 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004077 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004078}
4079
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004080/*
4081 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004082 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004083 */
4084 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004085cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004086{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004087 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4088 if (rgb->index == 0)
4089 rgb->type = VTERM_COLOR_RGB;
4090 else
4091 {
4092 rgb->type = VTERM_COLOR_INDEXED;
4093 --rgb->index;
4094 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004095}
4096
4097/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004098 * Initialize vterm color from the synID.
4099 * Returns TRUE if color is set to "fg" and "bg".
4100 * Otherwise returns FALSE.
4101 */
4102 static int
4103get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4104{
4105#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4106 // Use the actual color for the GUI and when 'termguicolors' is set.
4107 if (0
4108# ifdef FEAT_GUI
4109 || gui.in_use
4110# endif
4111# ifdef FEAT_TERMGUICOLORS
4112 || p_tgc
4113# ifdef FEAT_VTP
4114 // Finally get INVALCOLOR on this execution path
4115 || (!p_tgc && t_colors >= 256)
4116# endif
4117# endif
4118 )
4119 {
4120 guicolor_T fg_rgb = INVALCOLOR;
4121 guicolor_T bg_rgb = INVALCOLOR;
4122
4123 if (id > 0)
4124 syn_id2colors(id, &fg_rgb, &bg_rgb);
4125
4126 if (fg_rgb != INVALCOLOR)
4127 {
4128 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4129 fg->red = (unsigned)(rgb >> 16);
4130 fg->green = (unsigned)(rgb >> 8) & 255;
4131 fg->blue = (unsigned)rgb & 255;
4132 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4133 }
4134 else
4135 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4136
4137 if (bg_rgb != INVALCOLOR)
4138 {
4139 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4140 bg->red = (unsigned)(rgb >> 16);
4141 bg->green = (unsigned)(rgb >> 8) & 255;
4142 bg->blue = (unsigned)rgb & 255;
4143 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4144 }
4145 else
4146 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4147
4148 return TRUE;
4149 }
4150 else
4151#endif
4152 if (t_colors >= 16)
4153 {
4154 int cterm_fg = -1;
4155 int cterm_bg = -1;
4156
4157 if (id > 0)
4158 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4159
4160 if (cterm_fg >= 0)
4161 {
4162 cterm_color2vterm(cterm_fg, fg);
4163 fg->type |= VTERM_COLOR_DEFAULT_FG;
4164 }
4165 else
4166 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4167
4168 if (cterm_bg >= 0)
4169 {
4170 cterm_color2vterm(cterm_bg, bg);
4171 bg->type |= VTERM_COLOR_DEFAULT_BG;
4172 }
4173 else
4174 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4175
4176 return TRUE;
4177 }
4178
4179 return FALSE;
4180}
4181
4182 void
4183term_reset_wincolor(win_T *wp)
4184{
4185 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4186 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4187}
4188
4189/*
4190 * Cache the color of 'wincolor'.
4191 */
4192 void
4193term_update_wincolor(win_T *wp)
4194{
4195 int id = 0;
4196
4197 if (*wp->w_p_wcr != NUL)
4198 id = syn_name2id(wp->w_p_wcr);
4199 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4200 &wp->w_term_wincolor.bg))
4201 term_reset_wincolor(wp);
4202}
4203
4204/*
4205 * Called when option 'termguicolors' was set,
4206 * or when any highlight is changed.
4207 */
4208 void
4209term_update_wincolor_all()
4210{
4211 win_T *wp = NULL;
4212 int did_curwin = FALSE;
4213
4214 while (for_all_windows_and_curwin(&wp, &did_curwin))
4215 term_update_wincolor(wp);
4216}
4217
4218/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004219 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004220 */
4221 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004222init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004223{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004224 VTermColor *fg, *bg;
4225 int fgval, bgval;
4226 int id;
4227
Bram Moolenaara80faa82020-04-12 19:37:17 +02004228 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004229 term->tl_default_color.width = 1;
4230 fg = &term->tl_default_color.fg;
4231 bg = &term->tl_default_color.bg;
4232
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004233 // Vterm uses a default black background. Set it to white when
4234 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004235 if (*p_bg == 'l')
4236 {
4237 fgval = 0;
4238 bgval = 255;
4239 }
4240 else
4241 {
4242 fgval = 255;
4243 bgval = 0;
4244 }
4245 fg->red = fg->green = fg->blue = fgval;
4246 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004247 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4248 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004249
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004250 // The highlight group overrules the defaults.
4251 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004252
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004253 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004254 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004255#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004256 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004257#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004258
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004259 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004260 if (cterm_normal_fg_color > 0)
4261 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004262 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004263# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4264# ifdef VIMDLL
4265 if (!gui.in_use)
4266# endif
4267 {
4268 tmp = fg->red;
4269 fg->red = fg->blue;
4270 fg->blue = tmp;
4271 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004272# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004273 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004274# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004275 else
4276 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004277# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004278
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004279 if (cterm_normal_bg_color > 0)
4280 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004281 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004282# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4283# ifdef VIMDLL
4284 if (!gui.in_use)
4285# endif
4286 {
4287 tmp = fg->red;
4288 fg->red = fg->blue;
4289 fg->blue = tmp;
4290 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004291# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004292 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004293# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004294 else
4295 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004296# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004297 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004298}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004299
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004300#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4301/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004302 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4303 * "ansi_colors" argument in term_start()) shall be applied.
4304 */
4305 static int
4306term_use_palette()
4307{
4308 if (0
4309#ifdef FEAT_GUI
4310 || gui.in_use
4311#endif
4312#ifdef FEAT_TERMGUICOLORS
4313 || p_tgc
4314#endif
4315 )
4316 return TRUE;
4317 return FALSE;
4318}
4319
4320/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004321 * Set the 16 ANSI colors from array of RGB values
4322 */
4323 static void
4324set_vterm_palette(VTerm *vterm, long_u *rgb)
4325{
4326 int index = 0;
4327 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004328
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004329 for (; index < 16; index++)
4330 {
4331 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004332
Millyb771b6b2021-11-23 12:07:25 +00004333 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004334 color.red = (unsigned)(rgb[index] >> 16);
4335 color.green = (unsigned)(rgb[index] >> 8) & 255;
4336 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004337 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004338 vterm_state_set_palette_color(state, index, &color);
4339 }
4340}
4341
4342/*
4343 * Set the ANSI color palette from a list of colors
4344 */
4345 static int
4346set_ansi_colors_list(VTerm *vterm, list_T *list)
4347{
4348 int n = 0;
4349 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004350 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004351
Bram Moolenaarb0992022020-01-30 14:55:42 +01004352 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004353 {
4354 char_u *color_name;
4355 guicolor_T guicolor;
4356
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004357 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004358 if (color_name == NULL)
4359 return FAIL;
4360
4361 guicolor = GUI_GET_COLOR(color_name);
4362 if (guicolor == INVALCOLOR)
4363 return FAIL;
4364
4365 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4366 }
4367
4368 if (n != 16 || li != NULL)
4369 return FAIL;
4370
4371 set_vterm_palette(vterm, rgb);
4372
4373 return OK;
4374}
4375
4376/*
4377 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4378 */
4379 static void
4380init_vterm_ansi_colors(VTerm *vterm)
4381{
4382 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4383
LemonBoyb2b3acb2022-05-20 10:10:34 +01004384 if (var == NULL)
4385 return;
4386
4387 if (var->di_tv.v_type != VAR_LIST
4388 || var->di_tv.vval.v_list == NULL
4389 || var->di_tv.vval.v_list->lv_first == &range_list_item
4390 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004391 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004392}
4393#endif
4394
Bram Moolenaar52acb112018-03-18 19:20:22 +01004395/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004396 * Handles a "drop" command from the job in the terminal.
4397 * "item" is the file name, "item->li_next" may have options.
4398 */
4399 static void
4400handle_drop_command(listitem_T *item)
4401{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004402 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004403 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004404 int bufnr;
4405 win_T *wp;
4406 tabpage_T *tp;
4407 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004408 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004409
4410 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4411 FOR_ALL_TAB_WINDOWS(tp, wp)
4412 {
4413 if (wp->w_buffer->b_fnum == bufnr)
4414 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004415 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004416 goto_tabpage_win(tp, wp);
4417 return;
4418 }
4419 }
4420
Bram Moolenaara80faa82020-04-12 19:37:17 +02004421 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004422
4423 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4424 && opt_item->li_tv.vval.v_dict != NULL)
4425 {
4426 dict_T *dict = opt_item->li_tv.vval.v_dict;
4427 char_u *p;
4428
Bram Moolenaard61efa52022-07-23 09:52:04 +01004429 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004430 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004431 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004432 if (p != NULL)
4433 {
4434 if (check_ff_value(p) == FAIL)
4435 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4436 else
4437 ea.force_ff = *p;
4438 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004439 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004440 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004441 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004442 if (p != NULL)
4443 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004444 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004445 if (ea.cmd != NULL)
4446 {
4447 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4448 ea.force_enc = 11;
4449 tofree = ea.cmd;
4450 }
4451 }
4452
Bram Moolenaard61efa52022-07-23 09:52:04 +01004453 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004454 if (p != NULL)
4455 get_bad_opt(p, &ea);
4456
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004457 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004458 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004459 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004460 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004461 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004462 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004463 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004464 ea.force_bin = FORCE_NOBIN;
4465 }
4466
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004467 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004468 if (ea.cmd == NULL)
4469 ea.cmd = (char_u *)"split";
4470 ea.arg = fname;
4471 ea.cmdidx = CMD_split;
4472 ex_splitview(&ea);
4473
4474 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004475}
4476
4477/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004478 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4479 */
4480 static int
4481is_permitted_term_api(char_u *func, char_u *pat)
4482{
4483 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4484}
4485
4486/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004487 * Handles a function call from the job running in a terminal.
4488 * "item" is the function name, "item->li_next" has the arguments.
4489 */
4490 static void
4491handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4492{
4493 char_u *func;
4494 typval_T argvars[2];
4495 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004496 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004497
4498 if (item->li_next == NULL)
4499 {
4500 ch_log(channel, "Missing function arguments for call");
4501 return;
4502 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004503 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004504
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004505 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004506 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004507 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004508 return;
4509 }
4510
4511 argvars[0].v_type = VAR_NUMBER;
4512 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4513 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004514 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004515 funcexe.fe_firstline = 1L;
4516 funcexe.fe_lastline = 1L;
4517 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004518 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004519 {
4520 clear_tv(&rettv);
4521 ch_log(channel, "Function %s called", func);
4522 }
4523 else
4524 ch_log(channel, "Calling function %s failed", func);
4525}
4526
4527/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004528 * URL decoding (also know as Percent-encoding).
4529 *
4530 * Note this function currently is only used for decoding shell's
4531 * OSC 7 escape sequence which we can assume all bytes are valid
4532 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4533 * encoding bytes like 0xfe, 0xff.
4534 */
4535 static size_t
4536url_decode(const char *src, const size_t len, char_u *dst)
4537{
4538 size_t i = 0, j = 0;
4539
4540 while (i < len)
4541 {
4542 if (src[i] == '%' && i + 2 < len)
4543 {
4544 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4545 j++;
4546 i += 3;
4547 }
4548 else
4549 {
4550 dst[j] = src[i];
4551 i++;
4552 j++;
4553 }
4554 }
4555 dst[j] = '\0';
4556 return j;
4557}
4558
4559/*
4560 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4561 *
4562 * The OSC 7 sequence has the format of
4563 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4564 * and what VTerm provides via VTermStringFragment is
4565 * "file://HOSTNAME/CURRENT/DIR"
4566 */
4567 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004568sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004569{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004570 int offset = 7; // len of "file://" is 7
4571 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004572 char_u *new_dir;
4573
4574 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004575 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004576 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004577 ++offset;
4578 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004579 }
4580
Bram Moolenaar474ad392022-08-21 11:37:17 +01004581 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004582 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004583 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004584 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004585 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004586 }
4587
Bram Moolenaar474ad392022-08-21 11:37:17 +01004588 new_dir = alloc(gap->ga_len - offset + 1);
4589 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004590 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4591 vim_free(new_dir);
4592}
4593
4594/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004595 * Called by libvterm when it cannot recognize an OSC sequence.
4596 * We recognize a terminal API command.
4597 */
4598 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004599parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004600{
4601 term_T *term = (term_T *)user;
4602 js_read_T reader;
4603 typval_T tv;
4604 channel_T *channel = term->tl_job == NULL ? NULL
4605 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004606 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004607
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004608 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004609 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004610 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004611
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004612 // Concatenate what was received until the final piece is found.
4613 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4614 {
4615 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004616 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004617 }
4618 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004619 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004620 if (!frag.final)
4621 return 1;
4622
4623 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004624
4625 if (command == 7)
4626 {
4627 sync_shell_dir(gap);
4628 ga_clear(gap);
4629 return 1;
4630 }
4631
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004632 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004633 reader.js_fill = NULL;
4634 reader.js_used = 0;
4635 if (json_decode(&reader, &tv, 0) == OK
4636 && tv.v_type == VAR_LIST
4637 && tv.vval.v_list != NULL)
4638 {
4639 listitem_T *item = tv.vval.v_list->lv_first;
4640
4641 if (item == NULL)
4642 ch_log(channel, "Missing command");
4643 else
4644 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004645 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004646
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004647 // Make sure an invoked command doesn't delete the buffer (and the
4648 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004649 ++term->tl_buffer->b_locked;
4650
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004651 item = item->li_next;
4652 if (item == NULL)
4653 ch_log(channel, "Missing argument for %s", cmd);
4654 else if (STRCMP(cmd, "drop") == 0)
4655 handle_drop_command(item);
4656 else if (STRCMP(cmd, "call") == 0)
4657 handle_call_command(term, channel, item);
4658 else
4659 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004660 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004661 }
4662 }
4663 else
4664 ch_log(channel, "Invalid JSON received");
4665
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004666 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004667 clear_tv(&tv);
4668 return 1;
4669}
4670
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004671/*
4672 * Called by libvterm when it cannot recognize a CSI sequence.
4673 * We recognize the window position report.
4674 */
4675 static int
4676parse_csi(
4677 const char *leader UNUSED,
4678 const long args[],
4679 int argcount,
4680 const char *intermed UNUSED,
4681 char command,
4682 void *user)
4683{
4684 term_T *term = (term_T *)user;
4685 char buf[100];
4686 int len;
4687 int x = 0;
4688 int y = 0;
4689 win_T *wp;
4690
4691 // We recognize only CSI 13 t
4692 if (command != 't' || argcount != 1 || args[0] != 13)
4693 return 0; // not handled
4694
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004695 // When getting the window position is not possible or it fails it results
4696 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004697#if defined(FEAT_GUI) \
4698 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4699 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004700 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004701#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004702
4703 FOR_ALL_WINDOWS(wp)
4704 if (wp->w_buffer == term->tl_buffer)
4705 break;
4706 if (wp != NULL)
4707 {
4708#ifdef FEAT_GUI
4709 if (gui.in_use)
4710 {
4711 x += wp->w_wincol * gui.char_width;
4712 y += W_WINROW(wp) * gui.char_height;
4713 }
4714 else
4715#endif
4716 {
4717 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004718 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004719 x += wp->w_wincol * 7;
4720 y += W_WINROW(wp) * 10;
4721 }
4722 }
4723
4724 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4725 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4726 (char_u *)buf, len, NULL);
4727 return 1;
4728}
4729
Bram Moolenaard8637282020-05-20 18:41:41 +02004730static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004731 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004732 parse_csi, // csi
4733 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004734 NULL, // dcs
4735 NULL, // apc
4736 NULL, // pm
4737 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004738};
4739
4740/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004741 * Use Vim's allocation functions for vterm so profiling works.
4742 */
4743 static void *
4744vterm_malloc(size_t size, void *data UNUSED)
4745{
Bram Moolenaar88137392021-11-12 16:01:15 +00004746 // make sure that the length is not zero
4747 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004748}
4749
4750 static void
4751vterm_memfree(void *ptr, void *data UNUSED)
4752{
4753 vim_free(ptr);
4754}
4755
4756static VTermAllocatorFunctions vterm_allocator = {
4757 &vterm_malloc,
4758 &vterm_memfree
4759};
4760
4761/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004762 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004763 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004764 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004765 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004766create_vterm(term_T *term, int rows, int cols)
4767{
4768 VTerm *vterm;
4769 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004770 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004771 VTermValue value;
4772
Bram Moolenaar756ef112018-04-10 12:04:27 +02004773 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004774 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004775 if (vterm == NULL)
4776 return FAIL;
4777
4778 // Allocate screen and state here, so we can bail out if that fails.
4779 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004780 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004781 if (state == NULL || screen == NULL)
4782 {
4783 vterm_free(vterm);
4784 return FAIL;
4785 }
4786
Bram Moolenaar52acb112018-03-18 19:20:22 +01004787 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004788 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004789 vterm_set_utf8(vterm, 1);
4790
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004791 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004792
4793 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004794 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004795 &term->tl_default_color.fg,
4796 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004797
Bram Moolenaar9e587872019-05-13 20:27:23 +02004798 if (t_colors < 16)
4799 // Less than 16 colors: assume that bold means using a bright color for
4800 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004801 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4802
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004803 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004804 vterm_screen_reset(screen, 1 /* hard */);
4805
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004806 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004807 vterm_screen_enable_altscreen(screen, 1);
4808
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004809 // For unix do not use a blinking cursor. In an xterm this causes the
4810 // cursor to blink if it's blinking in the xterm.
4811 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004812#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004813 if (GetCaretBlinkTime() == INFINITE)
4814 value.boolean = 0;
4815 else
4816 value.boolean = 1;
4817#else
4818 value.boolean = 0;
4819#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004820 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004821 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004822
4823 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004824}
4825
4826/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004827 * Reset the terminal palette to its default value.
4828 */
4829 static void
4830term_reset_palette(VTerm *vterm)
4831{
4832 VTermState *state = vterm_obtain_state(vterm);
4833 int index;
4834
4835 for (index = 0; index < 16; index++)
4836 {
4837 VTermColor color;
4838
4839 color.type = VTERM_COLOR_INDEXED;
4840 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4841 &color.index);
4842 // The first valid index starts at 1.
4843 color.index -= 1;
4844
4845 vterm_state_set_palette_color(state, index, &color);
4846 }
4847}
4848
4849 static void
4850term_update_palette(term_T *term)
4851{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004852#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004853 if (term_use_palette()
4854 && (term->tl_palette != NULL
4855 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004856 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004857 {
4858 if (term->tl_palette != NULL)
4859 set_vterm_palette(term->tl_vterm, term->tl_palette);
4860 else
4861 init_vterm_ansi_colors(term->tl_vterm);
4862 }
4863 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004864#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004865 term_reset_palette(term->tl_vterm);
4866}
4867
4868/*
4869 * Called when option 'termguicolors' is changed.
4870 */
4871 void
4872term_update_palette_all()
4873{
4874 term_T *term;
4875
4876 FOR_ALL_TERMS(term)
4877 {
4878 if (term->tl_vterm == NULL)
4879 continue;
4880 term_update_palette(term);
4881 }
4882}
4883
4884/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004885 * Called when option 'background' or 'termguicolors' was set,
4886 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02004887 */
4888 void
4889term_update_colors_all(void)
4890{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004891 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02004892
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004893 FOR_ALL_TERMS(term)
4894 {
4895 if (term->tl_vterm == NULL)
4896 continue;
4897 init_default_colors(term);
4898 vterm_state_set_default_colors(
4899 vterm_obtain_state(term->tl_vterm),
4900 &term->tl_default_color.fg,
4901 &term->tl_default_color.bg);
4902 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004903}
4904
4905/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004906 * Return the text to show for the buffer name and status.
4907 */
4908 char_u *
4909term_get_status_text(term_T *term)
4910{
4911 if (term->tl_status_text == NULL)
4912 {
4913 char_u *txt;
4914 size_t len;
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004915 char_u *fname;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004916
4917 if (term->tl_normal_mode)
4918 {
4919 if (term_job_running(term))
4920 txt = (char_u *)_("Terminal");
4921 else
4922 txt = (char_u *)_("Terminal-finished");
4923 }
4924 else if (term->tl_title != NULL)
4925 txt = term->tl_title;
4926 else if (term_none_open(term))
4927 txt = (char_u *)_("active");
4928 else if (term_job_running(term))
4929 txt = (char_u *)_("running");
4930 else
4931 txt = (char_u *)_("finished");
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004932 fname = buf_get_fname(term->tl_buffer);
4933 len = 9 + STRLEN(fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004934 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004935 if (term->tl_status_text != NULL)
4936 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004937 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004938 }
4939 return term->tl_status_text;
4940}
4941
4942/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00004943 * Clear the cached value of the status text.
4944 */
4945 void
4946term_clear_status_text(term_T *term)
4947{
4948 VIM_CLEAR(term->tl_status_text);
4949}
4950
4951/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004952 * Mark references in jobs of terminals.
4953 */
4954 int
4955set_ref_in_term(int copyID)
4956{
4957 int abort = FALSE;
4958 term_T *term;
4959 typval_T tv;
4960
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004961 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004962 if (term->tl_job != NULL)
4963 {
4964 tv.v_type = VAR_JOB;
4965 tv.vval.v_job = term->tl_job;
4966 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4967 }
4968 return abort;
4969}
4970
4971/*
4972 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004973 * Returns NULL when the buffer is not for a terminal window and logs a message
4974 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004975 */
4976 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004977term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004978{
4979 buf_T *buf;
4980
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004981 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004982 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004983 --emsg_off;
4984 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004985 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01004986 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004987 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004988 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004989 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004990 return buf;
4991}
4992
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004993 static void
4994clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004995{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004996 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004997 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4998 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004999}
5000
5001 static void
5002dump_term_color(FILE *fd, VTermColor *color)
5003{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005004 int index;
5005
5006 if (VTERM_COLOR_IS_INDEXED(color))
5007 index = color->index + 1;
5008 else if (color->type == 0)
5009 // use RGB values
5010 index = 255;
5011 else
5012 // default color
5013 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005014 fprintf(fd, "%02x%02x%02x%d",
5015 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005016 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005017}
5018
5019/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005020 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01005021 *
5022 * Each screen cell in full is:
5023 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5024 * {characters} is a space for an empty cell
5025 * For a double-width character "+" is changed to "*" and the next cell is
5026 * skipped.
5027 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5028 * when "&" use the same as the previous cell.
5029 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5030 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5031 * {color-idx} is a number from 0 to 255
5032 *
5033 * Screen cell with same width, attributes and color as the previous one:
5034 * |{characters}
5035 *
5036 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5037 *
5038 * Repeating the previous screen cell:
5039 * @{count}
5040 */
5041 void
5042f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5043{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005044 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005045 term_T *term;
5046 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005047 int max_height = 0;
5048 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005049 stat_T st;
5050 FILE *fd;
5051 VTermPos pos;
5052 VTermScreen *screen;
5053 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005054 VTermState *state;
5055 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005056
5057 if (check_restricted() || check_secure())
5058 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005059
5060 if (in_vim9script()
5061 && (check_for_buffer_arg(argvars, 0) == FAIL
5062 || check_for_string_arg(argvars, 1) == FAIL
5063 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5064 return;
5065
5066 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005067 if (buf == NULL)
5068 return;
5069 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005070 if (term->tl_vterm == NULL)
5071 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005072 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005073 return;
5074 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005075
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005076 if (argvars[2].v_type != VAR_UNKNOWN)
5077 {
5078 dict_T *d;
5079
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005080 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005081 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005082 d = argvars[2].vval.v_dict;
5083 if (d != NULL)
5084 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005085 max_height = dict_get_number(d, "rows");
5086 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005087 }
5088 }
5089
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005090 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005091 if (fname == NULL)
5092 return;
5093 if (mch_stat((char *)fname, &st) >= 0)
5094 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005095 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005096 return;
5097 }
5098
Bram Moolenaard96ff162018-02-18 22:13:29 +01005099 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5100 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005101 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005102 return;
5103 }
5104
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005105 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005106
5107 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005108 state = vterm_obtain_state(term->tl_vterm);
5109 vterm_state_get_cursorpos(state, &cursor_pos);
5110
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005111 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5112 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005113 {
5114 int repeat = 0;
5115
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005116 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5117 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005118 {
5119 VTermScreenCell cell;
5120 int same_attr;
5121 int same_chars = TRUE;
5122 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005123 int is_cursor_pos = (pos.col == cursor_pos.col
5124 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005125
5126 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005127 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005128
5129 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5130 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005131 int c = cell.chars[i];
5132 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005133 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005134
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005135 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005136 if (i == 0)
5137 {
5138 c = (c == NUL) ? ' ' : c;
5139 pc = (pc == NUL) ? ' ' : pc;
5140 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005141 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005142 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005143 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005144 break;
5145 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005146 same_attr = vtermAttr2hl(&cell.attrs)
5147 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005148 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5149 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005150 if (same_chars && cell.width == prev_cell.width && same_attr
5151 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005152 {
5153 ++repeat;
5154 }
5155 else
5156 {
5157 if (repeat > 0)
5158 {
5159 fprintf(fd, "@%d", repeat);
5160 repeat = 0;
5161 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005162 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005163
5164 if (cell.chars[0] == NUL)
5165 fputs(" ", fd);
5166 else
5167 {
5168 char_u charbuf[10];
5169 int len;
5170
5171 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5172 && cell.chars[i] != NUL; ++i)
5173 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005174 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005175 fwrite(charbuf, len, 1, fd);
5176 }
5177 }
5178
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005179 // When only the characters differ we don't write anything, the
5180 // following "|", "@" or NL will indicate using the same
5181 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005182 if (cell.width != prev_cell.width || !same_attr)
5183 {
5184 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005185 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005186 else
5187 fputs("+", fd);
5188
5189 if (same_attr)
5190 {
5191 fputs("&", fd);
5192 }
5193 else
5194 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005195 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005196 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005197 fputs("&", fd);
5198 else
5199 {
5200 fputs("#", fd);
5201 dump_term_color(fd, &cell.fg);
5202 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005203 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005204 fputs("&", fd);
5205 else
5206 {
5207 fputs("#", fd);
5208 dump_term_color(fd, &cell.bg);
5209 }
5210 }
5211 }
5212
5213 prev_cell = cell;
5214 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005215
5216 if (cell.width == 2)
5217 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005218 }
5219 if (repeat > 0)
5220 fprintf(fd, "@%d", repeat);
5221 fputs("\n", fd);
5222 }
5223
5224 fclose(fd);
5225}
5226
5227/*
5228 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5229 */
5230 static void
5231dump_is_corrupt(garray_T *gap)
5232{
5233 ga_concat(gap, (char_u *)"CORRUPT");
5234}
5235
5236 static void
5237append_cell(garray_T *gap, cellattr_T *cell)
5238{
5239 if (ga_grow(gap, 1) == OK)
5240 {
5241 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5242 ++gap->ga_len;
5243 }
5244}
5245
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005246 static void
5247clear_cellattr(cellattr_T *cell)
5248{
5249 CLEAR_FIELD(*cell);
5250 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5251 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5252}
5253
Bram Moolenaard96ff162018-02-18 22:13:29 +01005254/*
5255 * Read the dump file from "fd" and append lines to the current buffer.
5256 * Return the cell width of the longest line.
5257 */
5258 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005259read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005260{
5261 int c;
5262 garray_T ga_text;
5263 garray_T ga_cell;
5264 char_u *prev_char = NULL;
5265 int attr = 0;
5266 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005267 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005268 term_T *term = curbuf->b_term;
5269 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005270 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005271
5272 ga_init2(&ga_text, 1, 90);
5273 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005274 clear_cellattr(&cell);
5275 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005276 cursor_pos->row = -1;
5277 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005278
5279 c = fgetc(fd);
5280 for (;;)
5281 {
5282 if (c == EOF)
5283 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005284 if (c == '\r')
5285 {
5286 // DOS line endings? Ignore.
5287 c = fgetc(fd);
5288 }
5289 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005290 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005291 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005292 if (ga_text.ga_data == NULL)
5293 dump_is_corrupt(&ga_text);
5294 if (ga_grow(&term->tl_scrollback, 1) == OK)
5295 {
5296 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5297 + term->tl_scrollback.ga_len;
5298
5299 if (max_cells < ga_cell.ga_len)
5300 max_cells = ga_cell.ga_len;
5301 line->sb_cols = ga_cell.ga_len;
5302 line->sb_cells = ga_cell.ga_data;
5303 line->sb_fill_attr = term->tl_default_color;
5304 ++term->tl_scrollback.ga_len;
5305 ga_init(&ga_cell);
5306
5307 ga_append(&ga_text, NUL);
5308 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5309 ga_text.ga_len, FALSE);
5310 }
5311 else
5312 ga_clear(&ga_cell);
5313 ga_text.ga_len = 0;
5314
5315 c = fgetc(fd);
5316 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005317 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005318 {
5319 int prev_len = ga_text.ga_len;
5320
Bram Moolenaar9271d052018-02-25 21:39:46 +01005321 if (c == '>')
5322 {
5323 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005324 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005325 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5326 cursor_pos->col = ga_cell.ga_len;
5327 }
5328
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005329 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005330 c = fgetc(fd);
5331 if (c != EOF)
5332 ga_append(&ga_text, c);
5333 for (;;)
5334 {
5335 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005336 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005337 || c == EOF || c == '\n')
5338 break;
5339 ga_append(&ga_text, c);
5340 }
5341
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005342 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005343 vim_free(prev_char);
5344 if (ga_text.ga_data != NULL)
5345 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5346 ga_text.ga_len - prev_len);
5347
Bram Moolenaar9271d052018-02-25 21:39:46 +01005348 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005349 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005350 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005351 }
5352 else if (c == '+' || c == '*')
5353 {
5354 int is_bg;
5355
5356 cell.width = c == '+' ? 1 : 2;
5357
5358 c = fgetc(fd);
5359 if (c == '&')
5360 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005361 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005362 c = fgetc(fd);
5363 }
5364 else if (isdigit(c))
5365 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005366 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005367 attr = 0;
5368 while (isdigit(c))
5369 {
5370 attr = attr * 10 + (c - '0');
5371 c = fgetc(fd);
5372 }
5373 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005374
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005375 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005376 for (is_bg = 0; is_bg <= 1; ++is_bg)
5377 {
5378 if (c == '&')
5379 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005380 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005381 c = fgetc(fd);
5382 }
5383 else if (c == '#')
5384 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005385 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005386
5387 c = fgetc(fd);
5388 red = hex2nr(c);
5389 c = fgetc(fd);
5390 red = (red << 4) + hex2nr(c);
5391 c = fgetc(fd);
5392 green = hex2nr(c);
5393 c = fgetc(fd);
5394 green = (green << 4) + hex2nr(c);
5395 c = fgetc(fd);
5396 blue = hex2nr(c);
5397 c = fgetc(fd);
5398 blue = (blue << 4) + hex2nr(c);
5399 c = fgetc(fd);
5400 if (!isdigit(c))
5401 dump_is_corrupt(&ga_text);
5402 while (isdigit(c))
5403 {
5404 index = index * 10 + (c - '0');
5405 c = fgetc(fd);
5406 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005407 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005408 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005409 type = VTERM_COLOR_RGB;
5410 if (index == 0)
5411 {
5412 if (is_bg)
5413 type |= VTERM_COLOR_DEFAULT_BG;
5414 else
5415 type |= VTERM_COLOR_DEFAULT_FG;
5416 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005417 }
5418 else
5419 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005420 type = VTERM_COLOR_INDEXED;
5421 index -= 1;
5422 }
5423 if (is_bg)
5424 {
5425 cell.bg.type = type;
5426 cell.bg.red = red;
5427 cell.bg.green = green;
5428 cell.bg.blue = blue;
5429 cell.bg.index = index;
5430 }
5431 else
5432 {
5433 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005434 cell.fg.red = red;
5435 cell.fg.green = green;
5436 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005437 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005438 }
5439 }
5440 else
5441 dump_is_corrupt(&ga_text);
5442 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005443 }
5444 else
5445 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005446 }
5447 else
5448 dump_is_corrupt(&ga_text);
5449
5450 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005451 if (cell.width == 2)
5452 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005453 }
5454 else if (c == '@')
5455 {
5456 if (prev_char == NULL)
5457 dump_is_corrupt(&ga_text);
5458 else
5459 {
5460 int count = 0;
5461
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005462 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005463 for (;;)
5464 {
5465 c = fgetc(fd);
5466 if (!isdigit(c))
5467 break;
5468 count = count * 10 + (c - '0');
5469 }
5470
5471 while (count-- > 0)
5472 {
5473 ga_concat(&ga_text, prev_char);
5474 append_cell(&ga_cell, &cell);
5475 }
5476 }
5477 }
5478 else
5479 {
5480 dump_is_corrupt(&ga_text);
5481 c = fgetc(fd);
5482 }
5483 }
5484
5485 if (ga_text.ga_len > 0)
5486 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005487 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005488 dump_is_corrupt(&ga_text);
5489 ga_append(&ga_text, NUL);
5490 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5491 ga_text.ga_len, FALSE);
5492 }
5493
5494 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005495 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005496 vim_free(prev_char);
5497
5498 return max_cells;
5499}
5500
5501/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005502 * Return an allocated string with at least "text_width" "=" characters and
5503 * "fname" inserted in the middle.
5504 */
5505 static char_u *
5506get_separator(int text_width, char_u *fname)
5507{
5508 int width = MAX(text_width, curwin->w_width);
5509 char_u *textline;
5510 int fname_size;
5511 char_u *p = fname;
5512 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005513 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005514
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005515 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005516 if (textline == NULL)
5517 return NULL;
5518
5519 fname_size = vim_strsize(fname);
5520 if (fname_size < width - 8)
5521 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005522 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005523 width = MAX(text_width, fname_size + 8);
5524 }
5525 else if (fname_size > width - 8)
5526 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005527 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005528 p = gettail(fname);
5529 fname_size = vim_strsize(p);
5530 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005531 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005532 while (fname_size > width - 8)
5533 {
5534 p += (*mb_ptr2len)(p);
5535 fname_size = vim_strsize(p);
5536 }
5537
5538 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5539 textline[i] = '=';
5540 textline[i++] = ' ';
5541
5542 STRCPY(textline + i, p);
5543 off = STRLEN(textline);
5544 textline[off] = ' ';
5545 for (i = 1; i < (width - fname_size) / 2; ++i)
5546 textline[off + i] = '=';
5547 textline[off + i] = NUL;
5548
5549 return textline;
5550}
5551
5552/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005553 * Common for "term_dumpdiff()" and "term_dumpload()".
5554 */
5555 static void
5556term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5557{
5558 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005559 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005560 char_u buf1[NUMBUFLEN];
5561 char_u buf2[NUMBUFLEN];
5562 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005563 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005564 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005565 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005566 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005567 char_u *textline = NULL;
5568
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005569 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005570 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005571 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005572 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005573 if (fname1 == NULL || (do_diff && fname2 == NULL))
5574 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005575 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005576 return;
5577 }
5578 fd1 = mch_fopen((char *)fname1, READBIN);
5579 if (fd1 == NULL)
5580 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005581 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005582 return;
5583 }
5584 if (do_diff)
5585 {
5586 fd2 = mch_fopen((char *)fname2, READBIN);
5587 if (fd2 == NULL)
5588 {
5589 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005590 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005591 return;
5592 }
5593 }
5594
5595 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005596 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5597 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5598 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5599 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5600 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005601
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005602 if (opt.jo_term_name == NULL)
5603 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005604 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005605
Bram Moolenaar51e14382019-05-25 20:21:28 +02005606 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005607 if (fname_tofree != NULL)
5608 {
5609 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5610 opt.jo_term_name = fname_tofree;
5611 }
5612 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005613
Bram Moolenaar87abab92019-06-03 21:14:59 +02005614 if (opt.jo_bufnr_buf != NULL)
5615 {
5616 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5617
5618 // With "bufnr" argument: enter the window with this buffer and make it
5619 // empty.
5620 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005621 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005622 else
5623 {
5624 buf = curbuf;
5625 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005626 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005627 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005628 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005629 }
5630 }
5631 else
5632 // Create a new terminal window.
5633 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5634
Bram Moolenaard96ff162018-02-18 22:13:29 +01005635 if (buf != NULL && buf->b_term != NULL)
5636 {
5637 int i;
5638 linenr_T bot_lnum;
5639 linenr_T lnum;
5640 term_T *term = buf->b_term;
5641 int width;
5642 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005643 VTermPos cursor_pos1;
5644 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005645
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005646 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005647
Bram Moolenaard96ff162018-02-18 22:13:29 +01005648 rettv->vval.v_number = buf->b_fnum;
5649
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005650 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005651 width = read_dump_file(fd1, &cursor_pos1);
5652
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005653 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005654 if (cursor_pos1.row >= 0)
5655 {
5656 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5657 coladvance(cursor_pos1.col);
5658 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005659
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005660 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005661 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005662
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005663 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005664 if (!do_diff)
5665 goto theend;
5666
5667 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5668
Bram Moolenaar4a696342018-04-05 18:45:26 +02005669 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005670 if (textline == NULL)
5671 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005672 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5673 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5674 vim_free(textline);
5675
5676 textline = get_separator(width, fname2);
5677 if (textline == NULL)
5678 goto theend;
5679 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5680 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005681 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005682
5683 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005684 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005685 if (width2 > width)
5686 {
5687 vim_free(textline);
5688 textline = alloc(width2 + 1);
5689 if (textline == NULL)
5690 goto theend;
5691 width = width2;
5692 textline[width] = NUL;
5693 }
5694 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5695
5696 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5697 {
5698 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5699 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005700 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005701 for (i = 0; i < width; ++i)
5702 textline[i] = '-';
5703 }
5704 else
5705 {
5706 char_u *line1;
5707 char_u *line2;
5708 char_u *p1;
5709 char_u *p2;
5710 int col;
5711 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5712 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5713 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5714 ->sb_cells;
5715
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005716 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005717 line1 = vim_strsave(ml_get(lnum));
5718 if (line1 == NULL)
5719 break;
5720 p1 = line1;
5721
5722 line2 = ml_get(lnum + bot_lnum);
5723 p2 = line2;
5724 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5725 {
5726 int len1 = utfc_ptr2len(p1);
5727 int len2 = utfc_ptr2len(p2);
5728
5729 textline[col] = ' ';
5730 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005731 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005732 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005733 else if (lnum == cursor_pos1.row + 1
5734 && col == cursor_pos1.col
5735 && (cursor_pos1.row != cursor_pos2.row
5736 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005737 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005738 textline[col] = '>';
5739 else if (lnum == cursor_pos2.row + 1
5740 && col == cursor_pos2.col
5741 && (cursor_pos1.row != cursor_pos2.row
5742 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005743 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005744 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005745 else if (cellattr1 != NULL && cellattr2 != NULL)
5746 {
5747 if ((cellattr1 + col)->width
5748 != (cellattr2 + col)->width)
5749 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005750 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005751 &(cellattr2 + col)->fg))
5752 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005753 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005754 &(cellattr2 + col)->bg))
5755 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005756 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5757 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005758 textline[col] = 'a';
5759 }
5760 p1 += len1;
5761 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005762 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005763 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005764
5765 while (col < width)
5766 {
5767 if (*p1 == NUL && *p2 == NUL)
5768 textline[col] = '?';
5769 else if (*p1 == NUL)
5770 {
5771 textline[col] = '+';
5772 p2 += utfc_ptr2len(p2);
5773 }
5774 else
5775 {
5776 textline[col] = '-';
5777 p1 += utfc_ptr2len(p1);
5778 }
5779 ++col;
5780 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005781
5782 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005783 }
5784 if (add_empty_scrollback(term, &term->tl_default_color,
5785 term->tl_top_diff_rows) == OK)
5786 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5787 ++bot_lnum;
5788 }
5789
5790 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5791 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005792 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005793 for (i = 0; i < width; ++i)
5794 textline[i] = '+';
5795 if (add_empty_scrollback(term, &term->tl_default_color,
5796 term->tl_top_diff_rows) == OK)
5797 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5798 ++lnum;
5799 ++bot_lnum;
5800 }
5801
5802 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005803
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005804 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005805 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005806 }
5807
5808theend:
5809 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005810 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005811 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005812 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005813 fclose(fd2);
5814}
5815
5816/*
5817 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5818 * bottom files.
5819 * Return FAIL when this is not possible.
5820 */
5821 int
5822term_swap_diff()
5823{
5824 term_T *term = curbuf->b_term;
5825 linenr_T line_count;
5826 linenr_T top_rows;
5827 linenr_T bot_rows;
5828 linenr_T bot_start;
5829 linenr_T lnum;
5830 char_u *p;
5831 sb_line_T *sb_line;
5832
5833 if (term == NULL
5834 || !term_is_finished(curbuf)
5835 || term->tl_top_diff_rows == 0
5836 || term->tl_scrollback.ga_len == 0)
5837 return FAIL;
5838
5839 line_count = curbuf->b_ml.ml_line_count;
5840 top_rows = term->tl_top_diff_rows;
5841 bot_rows = term->tl_bot_diff_rows;
5842 bot_start = line_count - bot_rows;
5843 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5844
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005845 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005846 for (lnum = 1; lnum <= top_rows; ++lnum)
5847 {
5848 p = vim_strsave(ml_get(1));
5849 if (p == NULL)
5850 return OK;
5851 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005852 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005853 vim_free(p);
5854 }
5855
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005856 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005857 for (lnum = 1; lnum <= bot_rows; ++lnum)
5858 {
5859 p = vim_strsave(ml_get(bot_start + lnum));
5860 if (p == NULL)
5861 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005862 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005863 ml_append(lnum - 1, p, 0, FALSE);
5864 vim_free(p);
5865 }
5866
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005867 // move top title to bottom
5868 p = vim_strsave(ml_get(bot_rows + 1));
5869 if (p == NULL)
5870 return OK;
5871 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005872 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005873 vim_free(p);
5874
5875 // move bottom title to top
5876 p = vim_strsave(ml_get(line_count - top_rows));
5877 if (p == NULL)
5878 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005879 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005880 ml_append(bot_rows, p, 0, FALSE);
5881 vim_free(p);
5882
Bram Moolenaard96ff162018-02-18 22:13:29 +01005883 if (top_rows == bot_rows)
5884 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005885 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005886 for (lnum = 0; lnum < top_rows; ++lnum)
5887 {
5888 sb_line_T temp;
5889
5890 temp = *(sb_line + lnum);
5891 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5892 *(sb_line + bot_start + lnum) = temp;
5893 }
5894 }
5895 else
5896 {
5897 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005898 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005899
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005900 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005901 if (temp != NULL)
5902 {
5903 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5904 mch_memmove(term->tl_scrollback.ga_data,
5905 temp + bot_start,
5906 sizeof(sb_line_T) * bot_rows);
5907 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5908 temp + top_rows,
5909 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5910 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5911 + line_count - top_rows,
5912 temp,
5913 sizeof(sb_line_T) * top_rows);
5914 vim_free(temp);
5915 }
5916 }
5917
5918 term->tl_top_diff_rows = bot_rows;
5919 term->tl_bot_diff_rows = top_rows;
5920
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005921 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005922 return OK;
5923}
5924
5925/*
5926 * "term_dumpdiff(filename, filename, options)" function
5927 */
5928 void
5929f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5930{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005931 if (in_vim9script()
5932 && (check_for_string_arg(argvars, 0) == FAIL
5933 || check_for_string_arg(argvars, 1) == FAIL
5934 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5935 return;
5936
Bram Moolenaard96ff162018-02-18 22:13:29 +01005937 term_load_dump(argvars, rettv, TRUE);
5938}
5939
5940/*
5941 * "term_dumpload(filename, options)" function
5942 */
5943 void
5944f_term_dumpload(typval_T *argvars, typval_T *rettv)
5945{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005946 if (in_vim9script()
5947 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02005948 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005949 return;
5950
Bram Moolenaard96ff162018-02-18 22:13:29 +01005951 term_load_dump(argvars, rettv, FALSE);
5952}
5953
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005954/*
5955 * "term_getaltscreen(buf)" function
5956 */
5957 void
5958f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5959{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005960 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005961
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005962 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5963 return;
5964
5965 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005966 if (buf == NULL)
5967 return;
5968 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5969}
5970
5971/*
5972 * "term_getattr(attr, name)" function
5973 */
5974 void
5975f_term_getattr(typval_T *argvars, typval_T *rettv)
5976{
5977 int attr;
5978 size_t i;
5979 char_u *name;
5980
5981 static struct {
5982 char *name;
5983 int attr;
5984 } attrs[] = {
5985 {"bold", HL_BOLD},
5986 {"italic", HL_ITALIC},
5987 {"underline", HL_UNDERLINE},
5988 {"strike", HL_STRIKETHROUGH},
5989 {"reverse", HL_INVERSE},
5990 };
5991
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02005992 if (in_vim9script()
5993 && (check_for_number_arg(argvars, 0) == FAIL
5994 || check_for_string_arg(argvars, 1) == FAIL))
5995 return;
5996
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005997 attr = tv_get_number(&argvars[0]);
5998 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005999 if (name == NULL)
6000 return;
6001
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02006002 if (attr > HL_ALL)
6003 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02006004 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006005 if (STRCMP(name, attrs[i].name) == 0)
6006 {
6007 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
6008 break;
6009 }
6010}
6011
6012/*
6013 * "term_getcursor(buf)" function
6014 */
6015 void
6016f_term_getcursor(typval_T *argvars, typval_T *rettv)
6017{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006018 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006019 term_T *term;
6020 list_T *l;
6021 dict_T *d;
6022
6023 if (rettv_list_alloc(rettv) == FAIL)
6024 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006025
6026 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6027 return;
6028
6029 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006030 if (buf == NULL)
6031 return;
6032 term = buf->b_term;
6033
6034 l = rettv->vval.v_list;
6035 list_append_number(l, term->tl_cursor_pos.row + 1);
6036 list_append_number(l, term->tl_cursor_pos.col + 1);
6037
6038 d = dict_alloc();
6039 if (d != NULL)
6040 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02006041 dict_add_number(d, "visible", term->tl_cursor_visible);
6042 dict_add_number(d, "blink", blink_state_is_inverted()
6043 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6044 dict_add_number(d, "shape", term->tl_cursor_shape);
6045 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006046 list_append_dict(l, d);
6047 }
6048}
6049
6050/*
6051 * "term_getjob(buf)" function
6052 */
6053 void
6054f_term_getjob(typval_T *argvars, typval_T *rettv)
6055{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006056 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006057
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006058 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6059 return;
6060
6061 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006062 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006063 {
6064 rettv->v_type = VAR_SPECIAL;
6065 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006066 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006067 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006068
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006069 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006070 rettv->vval.v_job = buf->b_term->tl_job;
6071 if (rettv->vval.v_job != NULL)
6072 ++rettv->vval.v_job->jv_refcount;
6073}
6074
6075 static int
6076get_row_number(typval_T *tv, term_T *term)
6077{
6078 if (tv->v_type == VAR_STRING
6079 && tv->vval.v_string != NULL
6080 && STRCMP(tv->vval.v_string, ".") == 0)
6081 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006082 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006083}
6084
6085/*
6086 * "term_getline(buf, row)" function
6087 */
6088 void
6089f_term_getline(typval_T *argvars, typval_T *rettv)
6090{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006091 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006092 term_T *term;
6093 int row;
6094
6095 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006096
6097 if (in_vim9script()
6098 && (check_for_buffer_arg(argvars, 0) == FAIL
6099 || check_for_lnum_arg(argvars, 1) == FAIL))
6100 return;
6101
6102 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006103 if (buf == NULL)
6104 return;
6105 term = buf->b_term;
6106 row = get_row_number(&argvars[1], term);
6107
6108 if (term->tl_vterm == NULL)
6109 {
6110 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6111
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006112 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006113 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6114 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6115 }
6116 else
6117 {
6118 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6119 VTermRect rect;
6120 int len;
6121 char_u *p;
6122
6123 if (row < 0 || row >= term->tl_rows)
6124 return;
6125 len = term->tl_cols * MB_MAXBYTES + 1;
6126 p = alloc(len);
6127 if (p == NULL)
6128 return;
6129 rettv->vval.v_string = p;
6130
6131 rect.start_col = 0;
6132 rect.end_col = term->tl_cols;
6133 rect.start_row = row;
6134 rect.end_row = row + 1;
6135 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6136 }
6137}
6138
6139/*
6140 * "term_getscrolled(buf)" function
6141 */
6142 void
6143f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6144{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006145 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006146
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006147 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6148 return;
6149
6150 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006151 if (buf == NULL)
6152 return;
6153 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6154}
6155
6156/*
6157 * "term_getsize(buf)" function
6158 */
6159 void
6160f_term_getsize(typval_T *argvars, typval_T *rettv)
6161{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006162 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006163 list_T *l;
6164
6165 if (rettv_list_alloc(rettv) == FAIL)
6166 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006167
6168 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6169 return;
6170
6171 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006172 if (buf == NULL)
6173 return;
6174
6175 l = rettv->vval.v_list;
6176 list_append_number(l, buf->b_term->tl_rows);
6177 list_append_number(l, buf->b_term->tl_cols);
6178}
6179
6180/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006181 * "term_setsize(buf, rows, cols)" function
6182 */
6183 void
6184f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6185{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006186 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006187 term_T *term;
6188 varnumber_T rows, cols;
6189
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006190 if (in_vim9script()
6191 && (check_for_buffer_arg(argvars, 0) == FAIL
6192 || check_for_number_arg(argvars, 1) == FAIL
6193 || check_for_number_arg(argvars, 2) == FAIL))
6194 return;
6195
6196 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006197 if (buf == NULL)
6198 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006199 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006200 return;
6201 }
6202 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006203 return;
6204 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006205 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006206 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006207 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006208 cols = cols <= 0 ? term->tl_cols : cols;
6209 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006210 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006211
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006212 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006213 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6214 term_report_winsize(term, term->tl_rows, term->tl_cols);
6215}
6216
6217/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006218 * "term_getstatus(buf)" function
6219 */
6220 void
6221f_term_getstatus(typval_T *argvars, typval_T *rettv)
6222{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006223 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006224 term_T *term;
6225 char_u val[100];
6226
6227 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006228
6229 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6230 return;
6231
6232 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006233 if (buf == NULL)
6234 return;
6235 term = buf->b_term;
6236
6237 if (term_job_running(term))
6238 STRCPY(val, "running");
6239 else
6240 STRCPY(val, "finished");
6241 if (term->tl_normal_mode)
6242 STRCAT(val, ",normal");
6243 rettv->vval.v_string = vim_strsave(val);
6244}
6245
6246/*
6247 * "term_gettitle(buf)" function
6248 */
6249 void
6250f_term_gettitle(typval_T *argvars, typval_T *rettv)
6251{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006252 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006253
6254 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006255
6256 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6257 return;
6258
6259 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006260 if (buf == NULL)
6261 return;
6262
6263 if (buf->b_term->tl_title != NULL)
6264 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6265}
6266
6267/*
6268 * "term_gettty(buf)" function
6269 */
6270 void
6271f_term_gettty(typval_T *argvars, typval_T *rettv)
6272{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006273 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006274 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006275 int num = 0;
6276
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006277 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006278 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006279 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6280 return;
6281
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006282 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006283 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006284 if (buf == NULL)
6285 return;
6286 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006287 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006288
6289 switch (num)
6290 {
6291 case 0:
6292 if (buf->b_term->tl_job != NULL)
6293 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006294 break;
6295 case 1:
6296 if (buf->b_term->tl_job != NULL)
6297 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006298 break;
6299 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006300 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006301 return;
6302 }
6303 if (p != NULL)
6304 rettv->vval.v_string = vim_strsave(p);
6305}
6306
6307/*
6308 * "term_list()" function
6309 */
6310 void
6311f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6312{
6313 term_T *tp;
6314 list_T *l;
6315
6316 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6317 return;
6318
6319 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006320 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006321 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006322 if (list_append_number(l,
6323 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6324 return;
6325}
6326
6327/*
6328 * "term_scrape(buf, row)" function
6329 */
6330 void
6331f_term_scrape(typval_T *argvars, typval_T *rettv)
6332{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006333 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006334 VTermScreen *screen = NULL;
6335 VTermPos pos;
6336 list_T *l;
6337 term_T *term;
6338 char_u *p;
6339 sb_line_T *line;
6340
6341 if (rettv_list_alloc(rettv) == FAIL)
6342 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006343
6344 if (in_vim9script()
6345 && (check_for_buffer_arg(argvars, 0) == FAIL
6346 || check_for_lnum_arg(argvars, 1) == FAIL))
6347 return;
6348
6349 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006350 if (buf == NULL)
6351 return;
6352 term = buf->b_term;
6353
6354 l = rettv->vval.v_list;
6355 pos.row = get_row_number(&argvars[1], term);
6356
6357 if (term->tl_vterm != NULL)
6358 {
6359 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006360 if (screen == NULL) // can't really happen
6361 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006362 p = NULL;
6363 line = NULL;
6364 }
6365 else
6366 {
6367 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6368
6369 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6370 return;
6371 p = ml_get_buf(buf, lnum + 1, FALSE);
6372 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6373 }
6374
6375 for (pos.col = 0; pos.col < term->tl_cols; )
6376 {
6377 dict_T *dcell;
6378 int width;
6379 VTermScreenCellAttrs attrs;
6380 VTermColor fg, bg;
6381 char_u rgb[8];
6382 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6383 int off = 0;
6384 int i;
6385
6386 if (screen == NULL)
6387 {
6388 cellattr_T *cellattr;
6389 int len;
6390
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006391 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006392 if (pos.col >= line->sb_cols)
6393 break;
6394 cellattr = line->sb_cells + pos.col;
6395 width = cellattr->width;
6396 attrs = cellattr->attrs;
6397 fg = cellattr->fg;
6398 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006399 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006400 mch_memmove(mbs, p, len);
6401 mbs[len] = NUL;
6402 p += len;
6403 }
6404 else
6405 {
6406 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006407
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006408 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6409 break;
6410 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6411 {
6412 if (cell.chars[i] == 0)
6413 break;
6414 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6415 }
6416 mbs[off] = NUL;
6417 width = cell.width;
6418 attrs = cell.attrs;
6419 fg = cell.fg;
6420 bg = cell.bg;
6421 }
6422 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006423 if (dcell == NULL)
6424 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006425 list_append_dict(l, dcell);
6426
Bram Moolenaare0be1672018-07-08 16:50:37 +02006427 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006428
6429 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6430 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006431 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006432 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6433 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006434 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006435
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006436 dict_add_number(dcell, "attr",
6437 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006438 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006439
6440 ++pos.col;
6441 if (width == 2)
6442 ++pos.col;
6443 }
6444}
6445
6446/*
6447 * "term_sendkeys(buf, keys)" function
6448 */
6449 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006450f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006451{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006452 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006453 char_u *msg;
6454 term_T *term;
6455
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006456 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006457 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006458 || check_for_string_arg(argvars, 1) == FAIL))
6459 return;
6460
6461 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006462 if (buf == NULL)
6463 return;
6464
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006465 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006466 if (msg == NULL)
6467 return;
6468 term = buf->b_term;
6469 if (term->tl_vterm == NULL)
6470 return;
6471
6472 while (*msg != NUL)
6473 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006474 int c;
6475
6476 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6477 {
6478 c = TO_SPECIAL(msg[1], msg[2]);
6479 msg += 3;
6480 }
6481 else
6482 {
6483 c = PTR2CHAR(msg);
6484 msg += MB_CPTR2LEN(msg);
6485 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006486 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006487 }
6488}
6489
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006490#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6491/*
6492 * "term_getansicolors(buf)" function
6493 */
6494 void
6495f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6496{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006497 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006498 term_T *term;
6499 VTermState *state;
6500 VTermColor color;
6501 char_u hexbuf[10];
6502 int index;
6503 list_T *list;
6504
6505 if (rettv_list_alloc(rettv) == FAIL)
6506 return;
6507
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006508 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6509 return;
6510
6511 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006512 if (buf == NULL)
6513 return;
6514 term = buf->b_term;
6515 if (term->tl_vterm == NULL)
6516 return;
6517
6518 list = rettv->vval.v_list;
6519 state = vterm_obtain_state(term->tl_vterm);
6520 for (index = 0; index < 16; index++)
6521 {
6522 vterm_state_get_palette_color(state, index, &color);
6523 sprintf((char *)hexbuf, "#%02x%02x%02x",
6524 color.red, color.green, color.blue);
6525 if (list_append_string(list, hexbuf, 7) == FAIL)
6526 return;
6527 }
6528}
6529
6530/*
6531 * "term_setansicolors(buf, list)" function
6532 */
6533 void
6534f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6535{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006536 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006537 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006538 listitem_T *li;
6539 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006540
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006541 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006542 && (check_for_buffer_arg(argvars, 0) == FAIL
6543 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006544 return;
6545
6546 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006547 if (buf == NULL)
6548 return;
6549 term = buf->b_term;
6550 if (term->tl_vterm == NULL)
6551 return;
6552
Bram Moolenaard83392a2022-09-01 12:22:46 +01006553 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006554 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006555
LemonBoyb2b3acb2022-05-20 10:10:34 +01006556 if (argvars[1].vval.v_list->lv_first == &range_list_item
6557 || argvars[1].vval.v_list->lv_len != 16)
6558 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006559 emsg(_(e_invalid_argument));
LemonBoyb2b3acb2022-05-20 10:10:34 +01006560 return;
6561 }
6562
6563 if (term->tl_palette == NULL)
6564 term->tl_palette = ALLOC_MULT(long_u, 16);
6565 if (term->tl_palette == NULL)
6566 return;
6567
6568 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6569 {
6570 char_u *color_name;
6571 guicolor_T guicolor;
6572
6573 color_name = tv_get_string_chk(&li->li_tv);
6574 if (color_name == NULL)
6575 return;
6576
6577 guicolor = GUI_GET_COLOR(color_name);
6578 if (guicolor == INVALCOLOR)
6579 {
6580 semsg(_(e_cannot_allocate_color_str), color_name);
6581 return;
6582 }
6583
6584 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6585 }
6586
6587 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006588}
6589#endif
6590
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006591/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006592 * "term_setapi(buf, api)" function
6593 */
6594 void
6595f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6596{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006597 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006598 term_T *term;
6599 char_u *api;
6600
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006601 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006602 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006603 || check_for_string_arg(argvars, 1) == FAIL))
6604 return;
6605
6606 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006607 if (buf == NULL)
6608 return;
6609 term = buf->b_term;
6610 vim_free(term->tl_api);
6611 api = tv_get_string_chk(&argvars[1]);
6612 if (api != NULL)
6613 term->tl_api = vim_strsave(api);
6614 else
6615 term->tl_api = NULL;
6616}
6617
6618/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006619 * "term_setrestore(buf, command)" function
6620 */
6621 void
6622f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6623{
6624#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006625 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006626 term_T *term;
6627 char_u *cmd;
6628
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006629 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006630 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006631 || check_for_string_arg(argvars, 1) == FAIL))
6632 return;
6633
6634 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006635 if (buf == NULL)
6636 return;
6637 term = buf->b_term;
6638 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006639 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006640 if (cmd != NULL)
6641 term->tl_command = vim_strsave(cmd);
6642 else
6643 term->tl_command = NULL;
6644#endif
6645}
6646
6647/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006648 * "term_setkill(buf, how)" function
6649 */
6650 void
6651f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6652{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006653 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006654 term_T *term;
6655 char_u *how;
6656
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006657 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006658 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006659 || check_for_string_arg(argvars, 1) == FAIL))
6660 return;
6661
6662 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006663 if (buf == NULL)
6664 return;
6665 term = buf->b_term;
6666 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006667 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006668 if (how != NULL)
6669 term->tl_kill = vim_strsave(how);
6670 else
6671 term->tl_kill = NULL;
6672}
6673
6674/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006675 * "term_start(command, options)" function
6676 */
6677 void
6678f_term_start(typval_T *argvars, typval_T *rettv)
6679{
6680 jobopt_T opt;
6681 buf_T *buf;
6682
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006683 if (in_vim9script()
6684 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6685 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6686 return;
6687
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006688 init_job_options(&opt);
6689 if (argvars[1].v_type != VAR_UNKNOWN
6690 && get_job_options(&argvars[1], &opt,
6691 JO_TIMEOUT_ALL + JO_STOPONEXIT
6692 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6693 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6694 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6695 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006696 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006697 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006698 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006699 return;
6700
Bram Moolenaar13568252018-03-16 20:46:58 +01006701 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006702
6703 if (buf != NULL && buf->b_term != NULL)
6704 rettv->vval.v_number = buf->b_fnum;
6705}
6706
6707/*
6708 * "term_wait" function
6709 */
6710 void
6711f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6712{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006713 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006714
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006715 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006716 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006717 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006718 return;
6719
6720 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006721 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006722 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006723 if (buf->b_term->tl_job == NULL)
6724 {
6725 ch_log(NULL, "term_wait(): no job to wait for");
6726 return;
6727 }
6728 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006729 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006730 return;
6731
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006732 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006733 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006734 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6735 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006736 // The job is dead, keep reading channel I/O until the channel is
6737 // closed. buf->b_term may become NULL if the terminal was closed while
6738 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006739 ch_log(NULL, "term_wait(): waiting for channel to close");
6740 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6741 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006742 term_flush_messages();
6743
Bram Moolenaard45aa552018-05-21 22:50:29 +02006744 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006745 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006746 // If the terminal is closed when the channel is closed the
6747 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006748 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006749 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6750 // came here from a close callback, only wait one time
6751 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006752 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006753
6754 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006755 }
6756 else
6757 {
6758 long wait = 10L;
6759
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006760 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006761
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006762 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006763 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006764 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006765 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006766
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006767 // Flushing messages on channels is hopefully sufficient.
6768 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006769 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006770 }
6771}
6772
6773/*
6774 * Called when a channel has sent all the lines to a terminal.
6775 * Send a CTRL-D to mark the end of the text.
6776 */
6777 void
6778term_send_eof(channel_T *ch)
6779{
6780 term_T *term;
6781
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006782 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006783 if (term->tl_job == ch->ch_job)
6784 {
6785 if (term->tl_eof_chars != NULL)
6786 {
6787 channel_send(ch, PART_IN, term->tl_eof_chars,
6788 (int)STRLEN(term->tl_eof_chars), NULL);
6789 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6790 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006791# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006792 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006793 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006794 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6795# endif
6796 }
6797}
6798
Bram Moolenaar113e1072019-01-20 15:30:40 +01006799#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006800 job_T *
6801term_getjob(term_T *term)
6802{
6803 return term != NULL ? term->tl_job : NULL;
6804}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006805#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006806
Bram Moolenaar4f974752019-02-17 17:44:42 +01006807# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006808
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006809///////////////////////////////////////
6810// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006811#ifdef PROTO
6812typedef int COORD;
6813typedef int DWORD;
6814typedef int HANDLE;
6815typedef int *DWORD_PTR;
6816typedef int HPCON;
6817typedef int HRESULT;
6818typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006819typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006820typedef int PSIZE_T;
6821typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006822typedef int BOOL;
6823# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006824#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006825
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006826HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6827HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6828HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006829BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6830BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6831void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006832
6833 static int
6834dyn_conpty_init(int verbose)
6835{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006836 static HMODULE hKerneldll = NULL;
6837 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006838 static struct
6839 {
6840 char *name;
6841 FARPROC *ptr;
6842 } conpty_entry[] =
6843 {
6844 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6845 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6846 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6847 {"InitializeProcThreadAttributeList",
6848 (FARPROC*)&pInitializeProcThreadAttributeList},
6849 {"UpdateProcThreadAttribute",
6850 (FARPROC*)&pUpdateProcThreadAttribute},
6851 {"DeleteProcThreadAttributeList",
6852 (FARPROC*)&pDeleteProcThreadAttributeList},
6853 {NULL, NULL}
6854 };
6855
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006856 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006857 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006858 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006859 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006860 return FAIL;
6861 }
6862
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006863 // No need to initialize twice.
6864 if (hKerneldll)
6865 return OK;
6866
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006867 hKerneldll = vimLoadLib("kernel32.dll");
6868 for (i = 0; conpty_entry[i].name != NULL
6869 && conpty_entry[i].ptr != NULL; ++i)
6870 {
6871 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6872 conpty_entry[i].name)) == NULL)
6873 {
6874 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006875 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006876 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006877 return FAIL;
6878 }
6879 }
6880
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006881 return OK;
6882}
6883
6884 static int
6885conpty_term_and_job_init(
6886 term_T *term,
6887 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006888 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006889 jobopt_T *opt,
6890 jobopt_T *orig_opt)
6891{
6892 WCHAR *cmd_wchar = NULL;
6893 WCHAR *cmd_wchar_copy = NULL;
6894 WCHAR *cwd_wchar = NULL;
6895 WCHAR *env_wchar = NULL;
6896 channel_T *channel = NULL;
6897 job_T *job = NULL;
6898 HANDLE jo = NULL;
6899 garray_T ga_cmd, ga_env;
6900 char_u *cmd = NULL;
6901 HRESULT hr;
6902 COORD consize;
6903 SIZE_T breq;
6904 PROCESS_INFORMATION proc_info;
6905 HANDLE i_theirs = NULL;
6906 HANDLE o_theirs = NULL;
6907 HANDLE i_ours = NULL;
6908 HANDLE o_ours = NULL;
6909
Bram Moolenaar04935fb2022-01-08 16:19:22 +00006910 ga_init2(&ga_cmd, sizeof(char*), 20);
6911 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006912
6913 if (argvar->v_type == VAR_STRING)
6914 {
6915 cmd = argvar->vval.v_string;
6916 }
6917 else if (argvar->v_type == VAR_LIST)
6918 {
6919 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6920 goto failed;
6921 cmd = ga_cmd.ga_data;
6922 }
6923 if (cmd == NULL || *cmd == NUL)
6924 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006925 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006926 goto failed;
6927 }
6928
6929 term->tl_arg0_cmd = vim_strsave(cmd);
6930
6931 cmd_wchar = enc_to_utf16(cmd, NULL);
6932
6933 if (cmd_wchar != NULL)
6934 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006935 // Request by CreateProcessW
6936 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006937 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006938 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6939 }
6940
6941 ga_clear(&ga_cmd);
6942 if (cmd_wchar == NULL)
6943 goto failed;
6944 if (opt->jo_cwd != NULL)
6945 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6946
6947 win32_build_env(opt->jo_env, &ga_env, TRUE);
6948 env_wchar = ga_env.ga_data;
6949
6950 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6951 goto failed;
6952 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6953 goto failed;
6954
6955 consize.X = term->tl_cols;
6956 consize.Y = term->tl_rows;
6957 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6958 &term->tl_conpty);
6959 if (FAILED(hr))
6960 goto failed;
6961
6962 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6963
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006964 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006965 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006966 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006967 if (!term->tl_siex.lpAttributeList)
6968 goto failed;
6969 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6970 0, &breq))
6971 goto failed;
6972 if (!pUpdateProcThreadAttribute(
6973 term->tl_siex.lpAttributeList, 0,
6974 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6975 sizeof(HPCON), NULL, NULL))
6976 goto failed;
6977
6978 channel = add_channel();
6979 if (channel == NULL)
6980 goto failed;
6981
6982 job = job_alloc();
6983 if (job == NULL)
6984 goto failed;
6985 if (argvar->v_type == VAR_STRING)
6986 {
6987 int argc;
6988
6989 build_argv_from_string(cmd, &job->jv_argv, &argc);
6990 }
6991 else
6992 {
6993 int argc;
6994
6995 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6996 }
6997
6998 if (opt->jo_set & JO_IN_BUF)
6999 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7000
7001 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
7002 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02007003 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007004 env_wchar, cwd_wchar,
7005 &term->tl_siex.StartupInfo, &proc_info))
7006 goto failed;
7007
7008 CloseHandle(i_theirs);
7009 CloseHandle(o_theirs);
7010
7011 channel_set_pipes(channel,
7012 (sock_T)i_ours,
7013 (sock_T)o_ours,
7014 (sock_T)o_ours);
7015
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007016 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007017 channel->ch_write_text_mode = TRUE;
7018
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007019 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007020 channel->ch_anonymous_pipe = TRUE;
7021
7022 jo = CreateJobObject(NULL, NULL);
7023 if (jo == NULL)
7024 goto failed;
7025
7026 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7027 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007028 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007029 CloseHandle(jo);
7030 jo = NULL;
7031 }
7032
7033 ResumeThread(proc_info.hThread);
7034 CloseHandle(proc_info.hThread);
7035
7036 vim_free(cmd_wchar);
7037 vim_free(cmd_wchar_copy);
7038 vim_free(cwd_wchar);
7039 vim_free(env_wchar);
7040
7041 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7042 goto failed;
7043
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007044#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007045 if (term_use_palette())
7046 {
7047 if (term->tl_palette != NULL)
7048 set_vterm_palette(term->tl_vterm, term->tl_palette);
7049 else
7050 init_vterm_ansi_colors(term->tl_vterm);
7051 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007052#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007053
7054 channel_set_job(channel, job, opt);
7055 job_set_options(job, opt);
7056
7057 job->jv_channel = channel;
7058 job->jv_proc_info = proc_info;
7059 job->jv_job_object = jo;
7060 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007061 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007062 ++job->jv_refcount;
7063 term->tl_job = job;
7064
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007065 // Redirecting stdout and stderr doesn't work at the job level. Instead
7066 // open the file here and handle it in. opt->jo_io was changed in
7067 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007068 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7069 {
7070 char_u *fname = opt->jo_io_name[PART_OUT];
7071
7072 ch_log(channel, "Opening output file %s", fname);
7073 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7074 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007075 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007076 }
7077
7078 return OK;
7079
7080failed:
7081 ga_clear(&ga_cmd);
7082 ga_clear(&ga_env);
7083 vim_free(cmd_wchar);
7084 vim_free(cmd_wchar_copy);
7085 vim_free(cwd_wchar);
7086 if (channel != NULL)
7087 channel_clear(channel);
7088 if (job != NULL)
7089 {
7090 job->jv_channel = NULL;
7091 job_cleanup(job);
7092 }
7093 term->tl_job = NULL;
7094 if (jo != NULL)
7095 CloseHandle(jo);
7096
7097 if (term->tl_siex.lpAttributeList != NULL)
7098 {
7099 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7100 vim_free(term->tl_siex.lpAttributeList);
7101 }
7102 term->tl_siex.lpAttributeList = NULL;
7103 if (o_theirs != NULL)
7104 CloseHandle(o_theirs);
7105 if (o_ours != NULL)
7106 CloseHandle(o_ours);
7107 if (i_ours != NULL)
7108 CloseHandle(i_ours);
7109 if (i_theirs != NULL)
7110 CloseHandle(i_theirs);
7111 if (term->tl_conpty != NULL)
7112 pClosePseudoConsole(term->tl_conpty);
7113 term->tl_conpty = NULL;
7114 return FAIL;
7115}
7116
7117 static void
7118conpty_term_report_winsize(term_T *term, int rows, int cols)
7119{
7120 COORD consize;
7121
7122 consize.X = cols;
7123 consize.Y = rows;
7124 pResizePseudoConsole(term->tl_conpty, consize);
7125}
7126
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007127 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007128term_free_conpty(term_T *term)
7129{
7130 if (term->tl_siex.lpAttributeList != NULL)
7131 {
7132 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7133 vim_free(term->tl_siex.lpAttributeList);
7134 }
7135 term->tl_siex.lpAttributeList = NULL;
7136 if (term->tl_conpty != NULL)
7137 pClosePseudoConsole(term->tl_conpty);
7138 term->tl_conpty = NULL;
7139}
7140
7141 int
7142use_conpty(void)
7143{
7144 return has_conpty;
7145}
7146
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007147# ifndef PROTO
7148
7149#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7150#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007151#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007152
7153void* (*winpty_config_new)(UINT64, void*);
7154void* (*winpty_open)(void*, void*);
7155void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7156BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7157void (*winpty_config_set_mouse_mode)(void*, int);
7158void (*winpty_config_set_initial_size)(void*, int, int);
7159LPCWSTR (*winpty_conin_name)(void*);
7160LPCWSTR (*winpty_conout_name)(void*);
7161LPCWSTR (*winpty_conerr_name)(void*);
7162void (*winpty_free)(void*);
7163void (*winpty_config_free)(void*);
7164void (*winpty_spawn_config_free)(void*);
7165void (*winpty_error_free)(void*);
7166LPCWSTR (*winpty_error_msg)(void*);
7167BOOL (*winpty_set_size)(void*, int, int, void*);
7168HANDLE (*winpty_agent_process)(void*);
7169
7170#define WINPTY_DLL "winpty.dll"
7171
7172static HINSTANCE hWinPtyDLL = NULL;
7173# endif
7174
7175 static int
7176dyn_winpty_init(int verbose)
7177{
7178 int i;
7179 static struct
7180 {
7181 char *name;
7182 FARPROC *ptr;
7183 } winpty_entry[] =
7184 {
7185 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7186 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7187 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7188 {"winpty_config_set_mouse_mode",
7189 (FARPROC*)&winpty_config_set_mouse_mode},
7190 {"winpty_config_set_initial_size",
7191 (FARPROC*)&winpty_config_set_initial_size},
7192 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7193 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7194 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7195 {"winpty_free", (FARPROC*)&winpty_free},
7196 {"winpty_open", (FARPROC*)&winpty_open},
7197 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7198 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7199 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7200 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7201 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7202 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7203 {NULL, NULL}
7204 };
7205
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007206 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007207 if (hWinPtyDLL)
7208 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007209 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7210 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007211 if (*p_winptydll != NUL)
7212 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7213 if (!hWinPtyDLL)
7214 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7215 if (!hWinPtyDLL)
7216 {
7217 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007218 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007219 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7220 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007221 return FAIL;
7222 }
7223 for (i = 0; winpty_entry[i].name != NULL
7224 && winpty_entry[i].ptr != NULL; ++i)
7225 {
7226 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7227 winpty_entry[i].name)) == NULL)
7228 {
7229 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007230 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007231 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007232 return FAIL;
7233 }
7234 }
7235
7236 return OK;
7237}
7238
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007239 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007240winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007241 term_T *term,
7242 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007243 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007244 jobopt_T *opt,
7245 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007246{
7247 WCHAR *cmd_wchar = NULL;
7248 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007249 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007250 channel_T *channel = NULL;
7251 job_T *job = NULL;
7252 DWORD error;
7253 HANDLE jo = NULL;
7254 HANDLE child_process_handle;
7255 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007256 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007257 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007258 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007259 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007260
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007261 ga_init2(&ga_cmd, sizeof(char*), 20);
7262 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007263
7264 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007265 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007266 cmd = argvar->vval.v_string;
7267 }
7268 else if (argvar->v_type == VAR_LIST)
7269 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007270 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007271 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007272 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007273 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007274 if (cmd == NULL || *cmd == NUL)
7275 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007276 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007277 goto failed;
7278 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007279
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007280 term->tl_arg0_cmd = vim_strsave(cmd);
7281
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007282 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007283 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007284 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007285 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007286 if (opt->jo_cwd != NULL)
7287 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007288
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007289 win32_build_env(opt->jo_env, &ga_env, TRUE);
7290 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007291
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007292 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7293 if (term->tl_winpty_config == NULL)
7294 goto failed;
7295
7296 winpty_config_set_mouse_mode(term->tl_winpty_config,
7297 WINPTY_MOUSE_MODE_FORCE);
7298 winpty_config_set_initial_size(term->tl_winpty_config,
7299 term->tl_cols, term->tl_rows);
7300 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7301 if (term->tl_winpty == NULL)
7302 goto failed;
7303
7304 spawn_config = winpty_spawn_config_new(
7305 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7306 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7307 NULL,
7308 cmd_wchar,
7309 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007310 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007311 &winpty_err);
7312 if (spawn_config == NULL)
7313 goto failed;
7314
7315 channel = add_channel();
7316 if (channel == NULL)
7317 goto failed;
7318
7319 job = job_alloc();
7320 if (job == NULL)
7321 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007322 if (argvar->v_type == VAR_STRING)
7323 {
7324 int argc;
7325
7326 build_argv_from_string(cmd, &job->jv_argv, &argc);
7327 }
7328 else
7329 {
7330 int argc;
7331
7332 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7333 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007334
7335 if (opt->jo_set & JO_IN_BUF)
7336 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7337
7338 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7339 &child_thread_handle, &error, &winpty_err))
7340 goto failed;
7341
7342 channel_set_pipes(channel,
7343 (sock_T)CreateFileW(
7344 winpty_conin_name(term->tl_winpty),
7345 GENERIC_WRITE, 0, NULL,
7346 OPEN_EXISTING, 0, NULL),
7347 (sock_T)CreateFileW(
7348 winpty_conout_name(term->tl_winpty),
7349 GENERIC_READ, 0, NULL,
7350 OPEN_EXISTING, 0, NULL),
7351 (sock_T)CreateFileW(
7352 winpty_conerr_name(term->tl_winpty),
7353 GENERIC_READ, 0, NULL,
7354 OPEN_EXISTING, 0, NULL));
7355
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007356 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007357 channel->ch_write_text_mode = TRUE;
7358
7359 jo = CreateJobObject(NULL, NULL);
7360 if (jo == NULL)
7361 goto failed;
7362
7363 if (!AssignProcessToJobObject(jo, child_process_handle))
7364 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007365 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007366 CloseHandle(jo);
7367 jo = NULL;
7368 }
7369
7370 winpty_spawn_config_free(spawn_config);
7371 vim_free(cmd_wchar);
7372 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007373 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007374
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007375 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7376 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007377
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007378#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007379 if (term_use_palette())
7380 {
7381 if (term->tl_palette != NULL)
7382 set_vterm_palette(term->tl_vterm, term->tl_palette);
7383 else
7384 init_vterm_ansi_colors(term->tl_vterm);
7385 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007386#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007387
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007388 channel_set_job(channel, job, opt);
7389 job_set_options(job, opt);
7390
7391 job->jv_channel = channel;
7392 job->jv_proc_info.hProcess = child_process_handle;
7393 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7394 job->jv_job_object = jo;
7395 job->jv_status = JOB_STARTED;
7396 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007397 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007398 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007399 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007400 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007401 ++job->jv_refcount;
7402 term->tl_job = job;
7403
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007404 // Redirecting stdout and stderr doesn't work at the job level. Instead
7405 // open the file here and handle it in. opt->jo_io was changed in
7406 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007407 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7408 {
7409 char_u *fname = opt->jo_io_name[PART_OUT];
7410
7411 ch_log(channel, "Opening output file %s", fname);
7412 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7413 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007414 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007415 }
7416
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007417 return OK;
7418
7419failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007420 ga_clear(&ga_cmd);
7421 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007422 vim_free(cmd_wchar);
7423 vim_free(cwd_wchar);
7424 if (spawn_config != NULL)
7425 winpty_spawn_config_free(spawn_config);
7426 if (channel != NULL)
7427 channel_clear(channel);
7428 if (job != NULL)
7429 {
7430 job->jv_channel = NULL;
7431 job_cleanup(job);
7432 }
7433 term->tl_job = NULL;
7434 if (jo != NULL)
7435 CloseHandle(jo);
7436 if (term->tl_winpty != NULL)
7437 winpty_free(term->tl_winpty);
7438 term->tl_winpty = NULL;
7439 if (term->tl_winpty_config != NULL)
7440 winpty_config_free(term->tl_winpty_config);
7441 term->tl_winpty_config = NULL;
7442 if (winpty_err != NULL)
7443 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007444 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007445 (short_u *)winpty_error_msg(winpty_err), NULL);
7446
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007447 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007448 winpty_error_free(winpty_err);
7449 }
7450 return FAIL;
7451}
7452
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007453/*
7454 * Create a new terminal of "rows" by "cols" cells.
7455 * Store a reference in "term".
7456 * Return OK or FAIL.
7457 */
7458 static int
7459term_and_job_init(
7460 term_T *term,
7461 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007462 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007463 jobopt_T *opt,
7464 jobopt_T *orig_opt)
7465{
7466 int use_winpty = FALSE;
7467 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007468 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007469
7470 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7471 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7472
7473 if (!has_winpty && !has_conpty)
7474 // If neither is available give the errors for winpty, since when
7475 // conpty is not available it can't be installed either.
7476 return dyn_winpty_init(TRUE);
7477
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007478 if (opt->jo_tty_type != NUL)
7479 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007480
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007481 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007482 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007483 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007484 use_conpty = TRUE;
7485 else if (has_winpty)
7486 use_winpty = TRUE;
7487 // else: error
7488 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007489 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007490 {
7491 if (has_winpty)
7492 use_winpty = TRUE;
7493 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007494 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007495 {
7496 if (has_conpty)
7497 use_conpty = TRUE;
7498 else
7499 return dyn_conpty_init(TRUE);
7500 }
7501
7502 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007503 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007504
7505 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007506 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007507
7508 // error
7509 return dyn_winpty_init(TRUE);
7510}
7511
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007512 static int
7513create_pty_only(term_T *term, jobopt_T *options)
7514{
7515 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7516 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7517 char in_name[80], out_name[80];
7518 channel_T *channel = NULL;
7519
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007520 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7521 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007522
7523 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7524 GetCurrentProcessId(),
7525 curbuf->b_fnum);
7526 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7527 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7528 PIPE_UNLIMITED_INSTANCES,
7529 0, 0, NMPWAIT_NOWAIT, NULL);
7530 if (hPipeIn == INVALID_HANDLE_VALUE)
7531 goto failed;
7532
7533 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7534 GetCurrentProcessId(),
7535 curbuf->b_fnum);
7536 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7537 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7538 PIPE_UNLIMITED_INSTANCES,
7539 0, 0, 0, NULL);
7540 if (hPipeOut == INVALID_HANDLE_VALUE)
7541 goto failed;
7542
7543 ConnectNamedPipe(hPipeIn, NULL);
7544 ConnectNamedPipe(hPipeOut, NULL);
7545
7546 term->tl_job = job_alloc();
7547 if (term->tl_job == NULL)
7548 goto failed;
7549 ++term->tl_job->jv_refcount;
7550
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007551 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007552 term->tl_job->jv_status = JOB_FINISHED;
7553
7554 channel = add_channel();
7555 if (channel == NULL)
7556 goto failed;
7557 term->tl_job->jv_channel = channel;
7558 channel->ch_keep_open = TRUE;
7559 channel->ch_named_pipe = TRUE;
7560
7561 channel_set_pipes(channel,
7562 (sock_T)hPipeIn,
7563 (sock_T)hPipeOut,
7564 (sock_T)hPipeOut);
7565 channel_set_job(channel, term->tl_job, options);
7566 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7567 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7568
7569 return OK;
7570
7571failed:
7572 if (hPipeIn != NULL)
7573 CloseHandle(hPipeIn);
7574 if (hPipeOut != NULL)
7575 CloseHandle(hPipeOut);
7576 return FAIL;
7577}
7578
7579/*
7580 * Free the terminal emulator part of "term".
7581 */
7582 static void
7583term_free_vterm(term_T *term)
7584{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007585 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007586 if (term->tl_winpty != NULL)
7587 winpty_free(term->tl_winpty);
7588 term->tl_winpty = NULL;
7589 if (term->tl_winpty_config != NULL)
7590 winpty_config_free(term->tl_winpty_config);
7591 term->tl_winpty_config = NULL;
7592 if (term->tl_vterm != NULL)
7593 vterm_free(term->tl_vterm);
7594 term->tl_vterm = NULL;
7595}
7596
7597/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007598 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007599 */
7600 static void
7601term_report_winsize(term_T *term, int rows, int cols)
7602{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007603 if (term->tl_conpty)
7604 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007605 if (term->tl_winpty)
7606 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7607}
7608
7609 int
7610terminal_enabled(void)
7611{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007612 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007613}
7614
7615# else
7616
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007617///////////////////////////////////////
7618// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007619
7620/*
7621 * Create a new terminal of "rows" by "cols" cells.
7622 * Start job for "cmd".
7623 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007624 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007625 * Return OK or FAIL.
7626 */
7627 static int
7628term_and_job_init(
7629 term_T *term,
7630 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007631 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007632 jobopt_T *opt,
7633 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007634{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007635 term->tl_arg0_cmd = NULL;
7636
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007637 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7638 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007639
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007640#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007641 if (term_use_palette())
7642 {
7643 if (term->tl_palette != NULL)
7644 set_vterm_palette(term->tl_vterm, term->tl_palette);
7645 else
7646 init_vterm_ansi_colors(term->tl_vterm);
7647 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007648#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007649
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007650 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007651 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007652 if (term->tl_job != NULL)
7653 ++term->tl_job->jv_refcount;
7654
7655 return term->tl_job != NULL
7656 && term->tl_job->jv_channel != NULL
7657 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7658}
7659
7660 static int
7661create_pty_only(term_T *term, jobopt_T *opt)
7662{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007663 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7664 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007665
7666 term->tl_job = job_alloc();
7667 if (term->tl_job == NULL)
7668 return FAIL;
7669 ++term->tl_job->jv_refcount;
7670
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007671 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007672 term->tl_job->jv_status = JOB_FINISHED;
7673
7674 return mch_create_pty_channel(term->tl_job, opt);
7675}
7676
7677/*
7678 * Free the terminal emulator part of "term".
7679 */
7680 static void
7681term_free_vterm(term_T *term)
7682{
7683 if (term->tl_vterm != NULL)
7684 vterm_free(term->tl_vterm);
7685 term->tl_vterm = NULL;
7686}
7687
7688/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007689 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007690 */
7691 static void
7692term_report_winsize(term_T *term, int rows, int cols)
7693{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007694 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007695 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
7696 {
7697 int fd = -1;
7698 int part;
7699
7700 for (part = PART_OUT; part < PART_COUNT; ++part)
7701 {
7702 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01007703 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007704 break;
7705 }
7706 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7707 mch_signal_job(term->tl_job, (char_u *)"winch");
7708 }
7709}
7710
7711# endif
7712
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007713#endif // FEAT_TERMINAL