blob: 64e6ad45dc63e21cf2593f0db4c8b2b9abed19ad [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);
1023 hash_add(terminal_bufs, (char_u *)hash_key);
1024 }
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
Shougo Matsushita4ccaedf2022-10-15 11:48:00 +01001237 // Make sure an invoked autocmd doesn't delete the buffer (and the
1238 // terminal) under our fingers.
1239 ++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 Moolenaar2e6ab182017-09-20 10:03:07 +02001590 /*
1591 * Convert special keys to vterm keys:
1592 * - Write keys to vterm: vterm_keyboard_key()
1593 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001594 */
1595 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001596 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001597 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001598 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001599 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001600 vterm_keyboard_unichar(vterm, c, mod);
1601
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001602 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001603 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1604}
1605
1606/*
1607 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001608 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001609 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001610 */
1611 static int
1612term_job_running_check(term_T *term, int check_job_status)
1613{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001614 // Also consider the job finished when the channel is closed, to avoid a
1615 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001616 if (term != NULL
1617 && term->tl_job != NULL
1618 && channel_is_open(term->tl_job->jv_channel))
1619 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001620 job_T *job = term->tl_job;
1621
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00001622 // Careful: Checking the job status may invoke callbacks, which close
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001623 // the buffer and terminate "term". However, "job" will not be freed
1624 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001625 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001626 job_status(job);
1627 return (job->jv_status == JOB_STARTED
1628 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001629 }
1630 return FALSE;
1631}
1632
1633/*
1634 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001635 */
1636 int
1637term_job_running(term_T *term)
1638{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001639 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001640}
1641
1642/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001643 * Return TRUE if the job for "term" is still running, ignoring the job was
1644 * "NONE".
1645 */
1646 int
1647term_job_running_not_none(term_T *term)
1648{
1649 return term_job_running(term) && !term_none_open(term);
1650}
1651
1652/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001653 * Return TRUE if "term" has an active channel and used ":term NONE".
1654 */
1655 int
1656term_none_open(term_T *term)
1657{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001658 // Also consider the job finished when the channel is closed, to avoid a
1659 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001660 return term != NULL
1661 && term->tl_job != NULL
1662 && channel_is_open(term->tl_job->jv_channel)
1663 && term->tl_job->jv_channel->ch_keep_open;
1664}
1665
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001666//
1667// Used to confirm whether we would like to kill a terminal.
1668// Return OK when the user confirms to kill it.
1669// Return FAIL if the user selects otherwise.
1670//
1671 int
1672term_confirm_stop(buf_T *buf)
1673{
1674 char_u buff[DIALOG_MSG_SIZE];
1675 int ret;
1676
1677 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
1678 ret = vim_dialog_yesno(VIM_QUESTION, NULL, buff, 1);
1679 if (ret == VIM_YES)
1680 return OK;
1681 else
1682 return FAIL;
1683}
1684
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001685/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001686 * Used when exiting: kill the job in "buf" if so desired.
1687 * Return OK when the job finished.
1688 * Return FAIL when the job is still running.
1689 */
1690 int
1691term_try_stop_job(buf_T *buf)
1692{
1693 int count;
1694 char *how = (char *)buf->b_term->tl_kill;
1695
1696#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001697 if ((how == NULL || *how == NUL)
1698 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001699 {
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001700 if (term_confirm_stop(buf) == OK)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001701 how = "kill";
Yee Cheng Chin15b314f2022-10-09 18:53:32 +01001702 else
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001703 return FAIL;
1704 }
1705#endif
1706 if (how == NULL || *how == NUL)
1707 return FAIL;
1708
1709 job_stop(buf->b_term->tl_job, NULL, how);
1710
Bram Moolenaar9172d232019-01-29 23:06:54 +01001711 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001712 for (count = 0; count < 100; ++count)
1713 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001714 job_T *job;
1715
1716 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001717 if (!buf_valid(buf)
1718 || buf->b_term == NULL
1719 || buf->b_term->tl_job == NULL)
1720 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001721 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001722
Bram Moolenaar9172d232019-01-29 23:06:54 +01001723 // Call job_status() to update jv_status. It may cause the job to be
1724 // cleaned up but it won't be freed.
1725 job_status(job);
1726 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001727 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001728
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001729 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001730 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001731 }
1732 return FAIL;
1733}
1734
1735/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001736 * Add the last line of the scrollback buffer to the buffer in the window.
1737 */
1738 static void
1739add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1740{
1741 buf_T *buf = term->tl_buffer;
1742 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1743 linenr_T lnum = buf->b_ml.ml_line_count;
1744
Bram Moolenaar4f974752019-02-17 17:44:42 +01001745#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001746 if (!enc_utf8 && enc_codepage > 0)
1747 {
1748 WCHAR *ret = NULL;
1749 int length = 0;
1750
1751 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1752 &ret, &length);
1753 if (ret != NULL)
1754 {
1755 WideCharToMultiByte_alloc(enc_codepage, 0,
1756 ret, length, (char **)&text, &len, 0, 0);
1757 vim_free(ret);
1758 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1759 vim_free(text);
1760 }
1761 }
1762 else
1763#endif
1764 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1765 if (empty)
1766 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001767 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001768 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001769 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001770 curbuf = curwin->w_buffer;
1771 }
1772}
1773
1774 static void
1775cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1776{
1777 attr->width = cell->width;
1778 attr->attrs = cell->attrs;
1779 attr->fg = cell->fg;
1780 attr->bg = cell->bg;
1781}
1782
1783 static int
1784equal_celattr(cellattr_T *a, cellattr_T *b)
1785{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001786 // We only compare the RGB colors, ignoring the ANSI index and type.
1787 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001788 return a->fg.red == b->fg.red
1789 && a->fg.green == b->fg.green
1790 && a->fg.blue == b->fg.blue
1791 && a->bg.red == b->bg.red
1792 && a->bg.green == b->bg.green
1793 && a->bg.blue == b->bg.blue;
1794}
1795
Bram Moolenaard96ff162018-02-18 22:13:29 +01001796/*
1797 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1798 * line at this position. Otherwise at the end.
1799 */
1800 static int
1801add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1802{
1803 if (ga_grow(&term->tl_scrollback, 1) == OK)
1804 {
1805 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1806 + term->tl_scrollback.ga_len;
1807
1808 if (lnum > 0)
1809 {
1810 int i;
1811
1812 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1813 {
1814 *line = *(line - 1);
1815 --line;
1816 }
1817 }
1818 line->sb_cols = 0;
1819 line->sb_cells = NULL;
1820 line->sb_fill_attr = *fill_attr;
1821 ++term->tl_scrollback.ga_len;
1822 return OK;
1823 }
1824 return FALSE;
1825}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001826
1827/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001828 * Remove the terminal contents from the scrollback and the buffer.
1829 * Used before adding a new scrollback line or updating the buffer for lines
1830 * displayed in the terminal.
1831 */
1832 static void
1833cleanup_scrollback(term_T *term)
1834{
1835 sb_line_T *line;
1836 garray_T *gap;
1837
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001838 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001839 gap = &term->tl_scrollback;
1840 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1841 && gap->ga_len > 0)
1842 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001843 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001844 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1845 vim_free(line->sb_cells);
1846 --gap->ga_len;
1847 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001848 curbuf = curwin->w_buffer;
1849 if (curbuf == term->tl_buffer)
1850 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001851}
1852
1853/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001854 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001855 */
1856 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001857update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001858{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001859 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001860 int len;
1861 int lines_skipped = 0;
1862 VTermPos pos;
1863 VTermScreenCell cell;
1864 cellattr_T fill_attr, new_fill_attr;
1865 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001866
1867 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1868 "Adding terminal window snapshot to buffer");
1869
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001870 // First remove the lines that were appended before, they might be
1871 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001872 cleanup_scrollback(term);
1873
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001874 screen = vterm_obtain_screen(term->tl_vterm);
1875 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001876 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1877 {
1878 len = 0;
1879 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1880 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1881 && cell.chars[0] != NUL)
1882 {
1883 len = pos.col + 1;
1884 new_fill_attr = term->tl_default_color;
1885 }
1886 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001887 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001888 cell2cellattr(&cell, &new_fill_attr);
1889
1890 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1891 ++lines_skipped;
1892 else
1893 {
1894 while (lines_skipped > 0)
1895 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001896 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001898 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001899 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001900 }
1901
1902 if (len == 0)
1903 p = NULL;
1904 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001905 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001906 if ((p != NULL || len == 0)
1907 && ga_grow(&term->tl_scrollback, 1) == OK)
1908 {
1909 garray_T ga;
1910 int width;
1911 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1912 + term->tl_scrollback.ga_len;
1913
1914 ga_init2(&ga, 1, 100);
1915 for (pos.col = 0; pos.col < len; pos.col += width)
1916 {
1917 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1918 {
1919 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02001920 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001921 if (ga_grow(&ga, 1) == OK)
1922 ga.ga_len += utf_char2bytes(' ',
1923 (char_u *)ga.ga_data + ga.ga_len);
1924 }
1925 else
1926 {
1927 width = cell.width;
1928
1929 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01001930 if (width == 2)
1931 // second cell of double-width character has the
1932 // same attributes.
1933 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001934
Bram Moolenaara79fd562018-12-20 20:47:32 +01001935 // Each character can be up to 6 bytes.
1936 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001937 {
1938 int i;
1939 int c;
1940
1941 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1942 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1943 (char_u *)ga.ga_data + ga.ga_len);
1944 }
1945 }
1946 }
1947 line->sb_cols = len;
1948 line->sb_cells = p;
1949 line->sb_fill_attr = new_fill_attr;
1950 fill_attr = new_fill_attr;
1951 ++term->tl_scrollback.ga_len;
1952
1953 if (ga_grow(&ga, 1) == FAIL)
1954 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1955 else
1956 {
1957 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1958 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1959 }
1960 ga_clear(&ga);
1961 }
1962 else
1963 vim_free(p);
1964 }
1965 }
1966
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001967 // Add trailing empty lines.
1968 for (pos.row = term->tl_scrollback.ga_len;
1969 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1970 ++pos.row)
1971 {
1972 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1973 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1974 }
1975
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001976 term->tl_dirty_snapshot = FALSE;
1977#ifdef FEAT_TIMERS
1978 term->tl_timer_set = FALSE;
1979#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001980}
1981
1982/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001983 * Loop over all windows in the current tab, and also curwin, which is not
1984 * encountered when using a terminal in a popup window.
1985 * Return TRUE if "*wp" was set to the next window.
1986 */
1987 static int
1988for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1989{
1990 if (*wp == NULL)
1991 *wp = firstwin;
1992 else if ((*wp)->w_next != NULL)
1993 *wp = (*wp)->w_next;
1994 else if (!*did_curwin)
1995 *wp = curwin;
1996 else
1997 return FALSE;
1998 if (*wp == curwin)
1999 *did_curwin = TRUE;
2000 return TRUE;
2001}
2002
2003/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002004 * If needed, add the current lines of the terminal to scrollback and to the
2005 * buffer. Called after the job has ended and when switching to
2006 * Terminal-Normal mode.
2007 * When "redraw" is TRUE redraw the windows that show the terminal.
2008 */
2009 static void
2010may_move_terminal_to_buffer(term_T *term, int redraw)
2011{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002012 if (term->tl_vterm == NULL)
2013 return;
2014
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002015 // Update the snapshot only if something changes or the buffer does not
2016 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002017 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
2018 <= term->tl_scrollback_scrolled)
2019 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002020
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002021 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2023 &term->tl_default_color.fg, &term->tl_default_color.bg);
2024
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002025 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002026 {
2027 win_T *wp = NULL;
2028 int did_curwin = FALSE;
2029
2030 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002031 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002032 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002033 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002034 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2035 wp->w_cursor.col = 0;
2036 wp->w_valid = 0;
2037 if (wp->w_cursor.lnum >= wp->w_height)
2038 {
2039 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002040
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002041 if (wp->w_topline < min_topline)
2042 wp->w_topline = min_topline;
2043 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002044 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002045 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002046 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002047 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002048}
2049
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002050#if defined(FEAT_TIMERS) || defined(PROTO)
2051/*
2052 * Check if any terminal timer expired. If so, copy text from the terminal to
2053 * the buffer.
2054 * Return the time until the next timer will expire.
2055 */
2056 int
2057term_check_timers(int next_due_arg, proftime_T *now)
2058{
2059 term_T *term;
2060 int next_due = next_due_arg;
2061
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002062 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002063 {
2064 if (term->tl_timer_set && !term->tl_normal_mode)
2065 {
2066 long this_due = proftime_time_left(&term->tl_timer_due, now);
2067
2068 if (this_due <= 1)
2069 {
2070 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002071 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002072 }
2073 else if (next_due == -1 || next_due > this_due)
2074 next_due = this_due;
2075 }
2076 }
2077
2078 return next_due;
2079}
2080#endif
2081
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002082/*
2083 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2084 * otherwise end it.
2085 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002086 static void
2087set_terminal_mode(term_T *term, int normal_mode)
2088{
2089 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002090 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002091 if (!normal_mode)
2092 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002093 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002094 if (term->tl_buffer == curbuf)
2095 maketitle();
2096}
2097
2098/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002099 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002100 * Move the vterm contents into the scrollback buffer and free the vterm.
2101 */
2102 static void
2103cleanup_vterm(term_T *term)
2104{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002105 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002106 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002107 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002108 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002109}
2110
2111/*
2112 * Switch from Terminal-Job mode to Terminal-Normal mode.
2113 * Suspends updating the terminal window.
2114 */
2115 static void
2116term_enter_normal_mode(void)
2117{
2118 term_T *term = curbuf->b_term;
2119
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002120 set_terminal_mode(term, TRUE);
2121
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002122 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002123 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002124
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002125 // Move the window cursor to the position of the cursor in the
2126 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002127 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2128 + term->tl_cursor_pos.row + 1;
2129 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002130 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2131 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002132 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002133
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002134 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002135 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2136}
2137
2138/*
2139 * Returns TRUE if the current window contains a terminal and we are in
2140 * Terminal-Normal mode.
2141 */
2142 int
2143term_in_normal_mode(void)
2144{
2145 term_T *term = curbuf->b_term;
2146
2147 return term != NULL && term->tl_normal_mode;
2148}
2149
2150/*
2151 * Switch from Terminal-Normal mode to Terminal-Job mode.
2152 * Restores updating the terminal window.
2153 */
2154 void
2155term_enter_job_mode()
2156{
2157 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002158
2159 set_terminal_mode(term, FALSE);
2160
2161 if (term->tl_channel_closed)
2162 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002163 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002164#ifdef FEAT_PROP_POPUP
2165 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002166 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002167#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002168}
2169
2170/*
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002171 * When "modify_other_keys" is set then vgetc() should not reduce a key with
2172 * modifiers into a basic key. However, we may only find out after calling
2173 * vgetc(). Therefore vgetorpeek() will call check_no_reduce_keys() to update
2174 * "no_reduce_keys" before using it.
2175 */
2176typedef enum {
2177 NRKS_NONE, // initial value
2178 NRKS_CHECK, // modify_other_keys was off before calling vgetc()
2179 NRKS_SET, // no_reduce_keys was incremented in term_vgetc() or
2180 // check_no_reduce_keys(), must be decremented.
2181} reduce_key_state_T;
2182
2183static reduce_key_state_T no_reduce_key_state = NRKS_NONE;
2184
2185 void
2186check_no_reduce_keys(void)
2187{
2188 if (no_reduce_key_state != NRKS_CHECK
2189 || no_reduce_keys >= 1
2190 || curbuf->b_term == NULL
2191 || curbuf->b_term->tl_vterm == NULL)
2192 return;
2193
2194 if (vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2195 {
2196 // "modify_other_keys" was enabled while waiting.
2197 no_reduce_key_state = NRKS_SET;
2198 ++no_reduce_keys;
2199 }
2200}
2201
2202/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002203 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002204 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002205 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002206 */
2207 static int
2208term_vgetc()
2209{
2210 int c;
2211 int save_State = State;
2212
Bram Moolenaar24959102022-05-07 20:01:16 +01002213 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002214 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002215#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002216 ctrl_break_was_pressed = FALSE;
2217#endif
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002218
2219 if (curbuf->b_term->tl_vterm != NULL
2220 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2221 {
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002222 ++no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002223 no_reduce_key_state = NRKS_SET;
2224 }
2225 else
2226 {
2227 no_reduce_key_state = NRKS_CHECK;
2228 }
2229
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002230 c = vgetc();
2231 got_int = FALSE;
2232 State = save_State;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002233
2234 if (no_reduce_key_state == NRKS_SET)
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002235 --no_reduce_keys;
Bram Moolenaarc896adb2022-11-19 19:02:40 +00002236 no_reduce_key_state = NRKS_NONE;
2237
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002238 return c;
2239}
2240
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002241static int mouse_was_outside = FALSE;
2242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002243/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002244 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002245 * Return FAIL when the key needs to be handled in Normal mode.
2246 * Return OK when the key was dropped or sent to the terminal.
2247 */
2248 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002249send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002250{
2251 char msg[KEY_BUF_LEN];
2252 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002253 int dragging_outside = FALSE;
2254
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002255 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002256 switch (c)
2257 {
2258 case NUL:
2259 case K_ZERO:
2260 if (typed)
2261 stuffcharReadbuff(c);
2262 return FAIL;
2263
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002264 case K_TABLINE:
2265 stuffcharReadbuff(c);
2266 return FAIL;
2267
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002268 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002269 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002270 return FAIL;
2271
2272 case K_LEFTDRAG:
2273 case K_MIDDLEDRAG:
2274 case K_RIGHTDRAG:
2275 case K_X1DRAG:
2276 case K_X2DRAG:
2277 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002278 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002279 case K_LEFTMOUSE:
2280 case K_LEFTMOUSE_NM:
2281 case K_LEFTRELEASE:
2282 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002283 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002284 case K_MIDDLEMOUSE:
2285 case K_MIDDLERELEASE:
2286 case K_RIGHTMOUSE:
2287 case K_RIGHTRELEASE:
2288 case K_X1MOUSE:
2289 case K_X1RELEASE:
2290 case K_X2MOUSE:
2291 case K_X2RELEASE:
2292
2293 case K_MOUSEUP:
2294 case K_MOUSEDOWN:
2295 case K_MOUSELEFT:
2296 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002297 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002298 int row = mouse_row;
2299 int col = mouse_col;
2300
2301#ifdef FEAT_PROP_POPUP
2302 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002303 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002304 row -= popup_top_extra(curwin);
2305 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002306 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002307#endif
2308 if (row < W_WINROW(curwin)
2309 || row >= (W_WINROW(curwin) + curwin->w_height)
2310 || col < curwin->w_wincol
2311 || col >= W_ENDCOL(curwin)
2312 || dragging_outside)
2313 {
2314 // click or scroll outside the current window or on status
2315 // line or vertical separator
2316 if (typed)
2317 {
2318 stuffcharReadbuff(c);
2319 mouse_was_outside = TRUE;
2320 }
2321 return FAIL;
2322 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002323 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002324 break;
2325
2326 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002327 case K_SCRIPT_COMMAND:
2328 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002329 }
2330 if (typed)
2331 mouse_was_outside = FALSE;
2332
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002333 // Convert the typed key to a sequence of bytes for the job.
2334 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002335 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002336 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002337 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2338 (char_u *)msg, (int)len, NULL);
2339
2340 return OK;
2341}
2342
2343 static void
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002344position_cursor(win_T *wp, VTermPos *pos)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002345{
2346 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2347 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002348#ifdef FEAT_PROP_POPUP
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002349 if (popup_is_popup(wp))
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002350 {
Bram Moolenaarf5452692020-11-28 21:56:06 +01002351 wp->w_wrow += popup_top_extra(wp);
2352 wp->w_wcol += popup_left_extra(wp);
Bram Moolenaar6a076442020-11-15 20:32:58 +01002353 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002354 }
Bram Moolenaar6a076442020-11-15 20:32:58 +01002355 else
2356 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002357#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2359}
2360
2361/*
2362 * Handle CTRL-W "": send register contents to the job.
2363 */
2364 static void
2365term_paste_register(int prev_c UNUSED)
2366{
2367 int c;
2368 list_T *l;
2369 listitem_T *item;
2370 long reglen = 0;
2371 int type;
2372
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002373 if (add_to_showcmd(prev_c))
2374 if (add_to_showcmd('"'))
2375 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002376
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002377 c = term_vgetc();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002378 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002379
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002380 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002381 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002382 return;
2383
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002384 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002385 if (c == '=' && get_expr_register() != '=')
2386 return;
2387 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002388 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002389 return;
2390
2391 l = (list_T *)get_reg_contents(c, GREG_LIST);
2392 if (l != NULL)
2393 {
2394 type = get_reg_type(c, &reglen);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002395 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002396 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002397 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002398#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002399 char_u *tmp = s;
2400
2401 if (!enc_utf8 && enc_codepage > 0)
2402 {
2403 WCHAR *ret = NULL;
2404 int length = 0;
2405
2406 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2407 (int)STRLEN(s), &ret, &length);
2408 if (ret != NULL)
2409 {
2410 WideCharToMultiByte_alloc(CP_UTF8, 0,
2411 ret, length, (char **)&s, &length, 0, 0);
2412 vim_free(ret);
2413 }
2414 }
2415#endif
2416 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2417 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002418#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002419 if (tmp != s)
2420 vim_free(s);
2421#endif
2422
2423 if (item->li_next != NULL || type == MLINE)
2424 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2425 (char_u *)"\r", 1, NULL);
2426 }
2427 list_free(l);
2428 }
2429}
2430
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002431/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002432 * Return TRUE when waiting for a character in the terminal, the cursor of the
2433 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002434 */
2435 int
2436terminal_is_active()
2437{
2438 return in_terminal_loop != NULL;
2439}
2440
Bram Moolenaar83d47902020-03-26 20:34:00 +01002441/*
dundargocc57b5bc2022-11-02 13:30:51 +00002442 * Return the highlight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002443 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002444 static int
2445term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002446{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002447 char_u *name;
2448
2449 if (wp != NULL && *wp->w_p_wcr != NUL)
2450 name = wp->w_p_wcr;
2451 else if (term->tl_highlight_name != NULL)
2452 name = term->tl_highlight_name;
2453 else
2454 name = (char_u*)"Terminal";
2455
2456 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002457}
2458
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002459#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002460 cursorentry_T *
2461term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2462{
2463 term_T *term = in_terminal_loop;
2464 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002465 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002466 guicolor_T term_fg = INVALCOLOR;
2467 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002468
Bram Moolenaara80faa82020-04-12 19:37:17 +02002469 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002470 entry.shape = entry.mshape =
2471 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2472 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2473 SHAPE_BLOCK;
2474 entry.percentage = 20;
2475 if (term->tl_cursor_blink)
2476 {
2477 entry.blinkwait = 700;
2478 entry.blinkon = 400;
2479 entry.blinkoff = 250;
2480 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002481
Bram Moolenaar83d47902020-03-26 20:34:00 +01002482 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002483 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002484 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002485 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002486 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002487 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002488 else
2489 *fg = gui.back_pixel;
2490
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002491 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002492 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002493 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002494 *bg = term_fg;
2495 else
2496 *bg = gui.norm_pixel;
2497 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002498 else
2499 *bg = color_name2handle(term->tl_cursor_color);
2500 entry.name = "n";
2501 entry.used_for = SHAPE_CURSOR;
2502
2503 return &entry;
2504}
2505#endif
2506
Bram Moolenaard317b382018-02-08 22:33:31 +01002507 static void
2508may_output_cursor_props(void)
2509{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002510 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002511 || last_set_cursor_shape != desired_cursor_shape
2512 || last_set_cursor_blink != desired_cursor_blink)
2513 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002514 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002515 last_set_cursor_shape = desired_cursor_shape;
2516 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002517 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002518 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002519 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002520 ui_cursor_shape_forced(TRUE);
2521 else
2522 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2523 }
2524}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002525
Bram Moolenaard317b382018-02-08 22:33:31 +01002526/*
2527 * Set the cursor color and shape, if not last set to these.
2528 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002529 static void
2530may_set_cursor_props(term_T *term)
2531{
2532#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002533 // For the GUI the cursor properties are obtained with
2534 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002535 if (gui.in_use)
2536 return;
2537#endif
2538 if (in_terminal_loop == term)
2539 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002540 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002541 desired_cursor_shape = term->tl_cursor_shape;
2542 desired_cursor_blink = term->tl_cursor_blink;
2543 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002544 }
2545}
2546
Bram Moolenaard317b382018-02-08 22:33:31 +01002547/*
2548 * Reset the desired cursor properties and restore them when needed.
2549 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002550 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002551prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002552{
2553#ifdef FEAT_GUI
2554 if (gui.in_use)
2555 return;
2556#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002557 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002558 desired_cursor_shape = -1;
2559 desired_cursor_blink = -1;
2560 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002561}
2562
2563/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002564 * Returns TRUE if the current window contains a terminal and we are sending
2565 * keys to the job.
2566 * If "check_job_status" is TRUE update the job status.
2567 */
2568 static int
2569term_use_loop_check(int check_job_status)
2570{
2571 term_T *term = curbuf->b_term;
2572
2573 return term != NULL
2574 && !term->tl_normal_mode
2575 && term->tl_vterm != NULL
2576 && term_job_running_check(term, check_job_status);
2577}
2578
2579/*
2580 * Returns TRUE if the current window contains a terminal and we are sending
2581 * keys to the job.
2582 */
2583 int
2584term_use_loop(void)
2585{
2586 return term_use_loop_check(FALSE);
2587}
2588
2589/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002590 * Called when entering a window with the mouse. If this is a terminal window
2591 * we may want to change state.
2592 */
2593 void
2594term_win_entered()
2595{
2596 term_T *term = curbuf->b_term;
2597
2598 if (term != NULL)
2599 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002600 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002601 {
2602 reset_VIsual_and_resel();
Bram Moolenaar24959102022-05-07 20:01:16 +01002603 if (State & MODE_INSERT)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002604 stop_insert_mode = TRUE;
2605 }
2606 mouse_was_outside = FALSE;
2607 enter_mouse_col = mouse_col;
2608 enter_mouse_row = mouse_row;
2609 }
2610}
2611
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002612 void
2613term_focus_change(int in_focus)
2614{
2615 term_T *term = curbuf->b_term;
2616
2617 if (term != NULL && term->tl_vterm != NULL)
2618 {
2619 VTermState *state = vterm_obtain_state(term->tl_vterm);
2620
2621 if (in_focus)
2622 vterm_state_focus_in(state);
2623 else
2624 vterm_state_focus_out(state);
2625 term_forward_output(term);
2626 }
2627}
2628
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002629/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002630 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2631 * Return the Ctrl-key value in that case.
2632 */
2633 static int
2634raw_c_to_ctrl(int c)
2635{
2636 if ((mod_mask & MOD_MASK_CTRL)
2637 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2638 return c & 0x1f;
2639 return c;
2640}
2641
2642/*
2643 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2644 * May set "mod_mask".
2645 */
2646 static int
2647ctrl_to_raw_c(int c)
2648{
2649 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2650 {
2651 mod_mask |= MOD_MASK_CTRL;
2652 return c + '@';
2653 }
2654 return c;
2655}
2656
2657/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002658 * Wait for input and send it to the job.
2659 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2660 * when there is no more typahead.
2661 * Return when the start of a CTRL-W command is typed or anything else that
2662 * should be handled as a Normal mode command.
2663 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2664 * the terminal was closed.
2665 */
2666 int
2667terminal_loop(int blocking)
2668{
2669 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002670 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002671 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002672 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002673#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002674 int tty_fd = curbuf->b_term->tl_job->jv_channel
2675 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002676#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002677 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002678
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002679 // Remember the terminal we are sending keys to. However, the terminal
2680 // might be closed while waiting for a character, e.g. typing "exit" in a
2681 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2682 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002683 in_terminal_loop = curbuf->b_term;
2684
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002685 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002686 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002687 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002688 if (termwinkey == Ctrl_W)
2689 termwinkey = 0;
2690 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002691 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002692 may_set_cursor_props(curbuf->b_term);
2693
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002694 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002695 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002696#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002697 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002698#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002699 // TODO: skip screen update when handling a sequence of keys.
2700 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002701 while (must_redraw != 0)
2702 if (update_screen(0) == FAIL)
2703 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002704 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002705 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002706 break;
2707
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002708 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002709 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002710
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002711 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002712 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002713 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002714 // Job finished while waiting for a character. Push back the
2715 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002716 if (raw_c != K_IGNORE)
2717 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002718 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002719 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002720 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002721 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002722 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002723
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002724#ifdef UNIX
2725 /*
2726 * The shell or another program may change the tty settings. Getting
2727 * them for every typed character is a bit of overhead, but it's needed
2728 * for the first character typed, e.g. when Vim starts in a shell.
2729 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002730 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002731 {
2732 ttyinfo_T info;
2733
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002734 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002735 if (get_tty_info(tty_fd, &info) == OK)
2736 term_backspace_char = info.backspace;
2737 }
2738#endif
2739
Bram Moolenaar4f974752019-02-17 17:44:42 +01002740#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002741 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2742 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002743 if (ctrl_break_was_pressed)
2744 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2745#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002746 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2747 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002748 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002749#ifdef FEAT_GUI
2750 && !curbuf->b_term->tl_system
2751#endif
2752 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002753 {
2754 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002755 int prev_raw_c = raw_c;
2756 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002757
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002758 if (add_to_showcmd(c))
2759 out_flush();
Martin Tournoijba43e762022-10-13 22:12:15 +01002760
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002761 raw_c = term_vgetc();
2762 c = raw_c_to_ctrl(raw_c);
2763
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002764 clear_showcmd();
Martin Tournoijba43e762022-10-13 22:12:15 +01002765
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002766 if (!term_use_loop_check(TRUE)
2767 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002768 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002769 break;
2770
2771 if (prev_c == Ctrl_BSL)
2772 {
2773 if (c == Ctrl_N)
2774 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002775 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002776 term_enter_normal_mode();
2777 ret = FAIL;
2778 goto theend;
2779 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002780 // Send both keys to the terminal, first one here, second one
2781 // below.
2782 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2783 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002784 }
2785 else if (c == Ctrl_C)
2786 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002787 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002788 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2789 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002790 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002791 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002792 // "CTRL-W .": send CTRL-W to the job
2793 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002794 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002795 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002796 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002797 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002798 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002799 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002800 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002801 else if (c == 'N')
2802 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002803 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002804 term_enter_normal_mode();
2805 ret = FAIL;
2806 goto theend;
2807 }
2808 else if (c == '"')
2809 {
2810 term_paste_register(prev_c);
2811 continue;
2812 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002813 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002814 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002815 // space for CTRL-W, modifier, multi-byte char and NUL
2816 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002817
2818 // Put the command into the typeahead buffer, when using the
2819 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2820 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002821 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002822 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002823 ret = OK;
2824 goto theend;
2825 }
2826 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002827# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002828 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002829 {
2830 WCHAR wc;
2831 char_u mb[3];
2832
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002833 mb[0] = (unsigned)raw_c >> 8;
2834 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002835 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002836 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002837 }
2838# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002839 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002840 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002841 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002842 // We are sure to come back here, don't reset the cursor color
2843 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002844 restore_cursor = FALSE;
2845
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002846 ret = OK;
2847 goto theend;
2848 }
2849 }
2850 ret = FAIL;
2851
2852theend:
2853 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002854 if (restore_cursor)
2855 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002856
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002857 // Move a snapshot of the screen contents to the buffer, so that completion
2858 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002859 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2860 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002861
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002862 return ret;
2863}
2864
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002865 static void
2866may_toggle_cursor(term_T *term)
2867{
2868 if (in_terminal_loop == term)
2869 {
2870 if (term->tl_cursor_visible)
2871 cursor_on();
2872 else
2873 cursor_off();
2874 }
2875}
2876
2877/*
2878 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002879 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880 */
2881 static int
2882color2index(VTermColor *color, int fg, int *boldp)
2883{
2884 int red = color->red;
2885 int blue = color->blue;
2886 int green = color->green;
2887
LemonBoyb2b3acb2022-05-20 10:10:34 +01002888 *boldp = FALSE;
2889
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002890 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002891 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01002892
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002893 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002894 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01002895 // Use the color as-is if possible, give up otherwise.
2896 if (color->index < t_colors)
2897 return color->index + 1;
2898 // 8-color terminals can actually display twice as many colors by
2899 // setting the high-intensity/bold bit.
2900 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002901 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01002902 *boldp = TRUE;
2903 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002904 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01002905 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002906 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002907
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002908 if (t_colors >= 256)
2909 {
2910 if (red == blue && red == green)
2911 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002912 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002913 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002914 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2915 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2916 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002917 int i;
2918
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002919 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002920 return 17; // 00/00/00
2921 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002922 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002923 for (i = 0; i < 23; ++i)
2924 if (red < cutoff[i])
2925 return i + 233;
2926 return 256;
2927 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002928 {
2929 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2930 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002931
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002932 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002933 for (ri = 0; ri < 5; ++ri)
2934 if (red < cutoff[ri])
2935 break;
2936 for (gi = 0; gi < 5; ++gi)
2937 if (green < cutoff[gi])
2938 break;
2939 for (bi = 0; bi < 5; ++bi)
2940 if (blue < cutoff[bi])
2941 break;
2942 return 17 + ri * 36 + gi * 6 + bi;
2943 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002944 }
2945 return 0;
2946}
2947
2948/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002949 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002950 */
2951 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002952vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002953{
2954 int attr = 0;
2955
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002956 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002957 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002958 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002959 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002960 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002961 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002962 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002963 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002964 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002965 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002966 return attr;
2967}
2968
2969/*
2970 * Store Vterm attributes in "cell" from highlight flags.
2971 */
2972 static void
2973hl2vtermAttr(int attr, cellattr_T *cell)
2974{
Bram Moolenaara80faa82020-04-12 19:37:17 +02002975 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002976 if (attr & HL_BOLD)
2977 cell->attrs.bold = 1;
2978 if (attr & HL_UNDERLINE)
2979 cell->attrs.underline = 1;
2980 if (attr & HL_ITALIC)
2981 cell->attrs.italic = 1;
2982 if (attr & HL_STRIKETHROUGH)
2983 cell->attrs.strike = 1;
2984 if (attr & HL_INVERSE)
2985 cell->attrs.reverse = 1;
2986}
2987
2988/*
2989 * Convert the attributes of a vterm cell into an attribute index.
2990 */
2991 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002992cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01002993 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002994 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002995 VTermScreenCellAttrs *cellattrs,
2996 VTermColor *cellfg,
2997 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002998{
2999 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003000 VTermColor *fg = cellfg;
3001 VTermColor *bg = cellbg;
3002 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
3003 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
3004
3005 if (is_default_fg || is_default_bg)
3006 {
3007 if (wp != NULL && *wp->w_p_wcr != NUL)
3008 {
3009 if (is_default_fg)
3010 fg = &wp->w_term_wincolor.fg;
3011 if (is_default_bg)
3012 bg = &wp->w_term_wincolor.bg;
3013 }
3014 else
3015 {
3016 if (is_default_fg)
3017 fg = &term->tl_default_color.fg;
3018 if (is_default_bg)
3019 bg = &term->tl_default_color.bg;
3020 }
3021 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003022
3023#ifdef FEAT_GUI
3024 if (gui.in_use)
3025 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003026 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
3027 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
3028 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003029 }
3030 else
3031#endif
3032#ifdef FEAT_TERMGUICOLORS
3033 if (p_tgc)
3034 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003035 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
3036 ? INVALCOLOR
3037 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
3038 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
3039 ? INVALCOLOR
3040 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
3041 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003042 }
3043 else
3044#endif
3045 {
3046 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003047 int ctermfg = color2index(fg, TRUE, &bold);
3048 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01003049
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003050 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003051 if (bold == TRUE)
3052 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003053
3054 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003055 }
3056 return 0;
3057}
3058
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003059 static void
3060set_dirty_snapshot(term_T *term)
3061{
3062 term->tl_dirty_snapshot = TRUE;
3063#ifdef FEAT_TIMERS
3064 if (!term->tl_normal_mode)
3065 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003066 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003067 profile_setlimit(100L, &term->tl_timer_due);
3068 term->tl_timer_set = TRUE;
3069 }
3070#endif
3071}
3072
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003073 static int
3074handle_damage(VTermRect rect, void *user)
3075{
3076 term_T *term = (term_T *)user;
3077
3078 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3079 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003080 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003081 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003082 return 1;
3083}
3084
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003085 static void
3086term_scroll_up(term_T *term, int start_row, int count)
3087{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003088 win_T *wp = NULL;
3089 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003090 VTermColor fg, bg;
3091 VTermScreenCellAttrs attr;
3092 int clear_attr;
3093
Bram Moolenaara80faa82020-04-12 19:37:17 +02003094 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003095
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003096 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003097 {
3098 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003099 {
3100 // Set the color to clear lines with.
3101 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3102 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003103 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003104 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003105 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003106 }
3107}
3108
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003109 static int
3110handle_moverect(VTermRect dest, VTermRect src, void *user)
3111{
3112 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003113 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003114
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003115 // Scrolling up is done much more efficiently by deleting lines instead of
3116 // redrawing the text. But avoid doing this multiple times, postpone until
3117 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003118 if (dest.start_col == src.start_col
3119 && dest.end_col == src.end_col
3120 && dest.start_row < src.start_row)
3121 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003122 if (dest.start_row == 0)
3123 term->tl_postponed_scroll += count;
3124 else
3125 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003126 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003127
3128 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3129 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003130 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003131
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003132 // Note sure if the scrolling will work correctly, let's do a complete
3133 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003134 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003135 return 1;
3136}
3137
3138 static int
3139handle_movecursor(
3140 VTermPos pos,
3141 VTermPos oldpos UNUSED,
3142 int visible,
3143 void *user)
3144{
3145 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003146 win_T *wp = NULL;
3147 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003148
3149 term->tl_cursor_pos = pos;
3150 term->tl_cursor_visible = visible;
3151
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003152 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153 {
3154 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003155 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156 }
3157 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003158 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003159
3160 return 1;
3161}
3162
3163 static int
3164handle_settermprop(
3165 VTermProp prop,
3166 VTermValue *value,
3167 void *user)
3168{
3169 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003170 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003171
3172 switch (prop)
3173 {
3174 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003175 if (disable_vterm_title_for_testing)
3176 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003177 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003178 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003179 if (strval == NULL)
3180 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003181 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003182 // a blank title isn't useful, make it empty, so that "running" is
3183 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003184 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003185 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003186 // Same as blank
3187 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003188 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003189 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3190 term->tl_title = NULL;
3191 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003192 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003193 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003194#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003195 else if (!enc_utf8 && enc_codepage > 0)
3196 {
3197 WCHAR *ret = NULL;
3198 int length = 0;
3199
3200 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003201 (char*)value->string.str,
3202 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003203 if (ret != NULL)
3204 {
3205 WideCharToMultiByte_alloc(enc_codepage, 0,
3206 ret, length, (char**)&term->tl_title,
3207 &length, 0, 0);
3208 vim_free(ret);
3209 }
3210 }
3211#endif
3212 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003213 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003214 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003215 strval = NULL;
3216 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003217 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003218 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003219 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003220 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003221 curwin->w_redr_status = TRUE;
3222 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003223 break;
3224
3225 case VTERM_PROP_CURSORVISIBLE:
3226 term->tl_cursor_visible = value->boolean;
3227 may_toggle_cursor(term);
3228 out_flush();
3229 break;
3230
3231 case VTERM_PROP_CURSORBLINK:
3232 term->tl_cursor_blink = value->boolean;
3233 may_set_cursor_props(term);
3234 break;
3235
3236 case VTERM_PROP_CURSORSHAPE:
3237 term->tl_cursor_shape = value->number;
3238 may_set_cursor_props(term);
3239 break;
3240
3241 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003242 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003243 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003244 if (strval == NULL)
3245 break;
3246 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003247 may_set_cursor_props(term);
3248 break;
3249
3250 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003251 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003252 term->tl_using_altscreen = value->boolean;
3253 break;
3254
3255 default:
3256 break;
3257 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003258 vim_free(strval);
3259
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003260 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003261 return 1;
3262}
3263
3264/*
3265 * The job running in the terminal resized the terminal.
3266 */
3267 static int
3268handle_resize(int rows, int cols, void *user)
3269{
3270 term_T *term = (term_T *)user;
3271 win_T *wp;
3272
3273 term->tl_rows = rows;
3274 term->tl_cols = cols;
3275 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003276 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003277 term->tl_vterm_size_changed = FALSE;
3278 else
3279 {
3280 FOR_ALL_WINDOWS(wp)
3281 {
3282 if (wp->w_buffer == term->tl_buffer)
3283 {
3284 win_setheight_win(rows, wp);
3285 win_setwidth_win(cols, wp);
3286 }
3287 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003288 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003289 }
3290 return 1;
3291}
3292
3293/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003294 * If the number of lines that are stored goes over 'termscrollback' then
3295 * delete the first 10%.
3296 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3297 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003298 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003299 static void
3300limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003301{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003302 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003303 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003304 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003305 int i;
3306
3307 curbuf = term->tl_buffer;
3308 for (i = 0; i < todo; ++i)
3309 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003310 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3311 if (update_buffer)
Bram Moolenaarca70c072020-05-30 20:30:46 +02003312 ml_delete(1);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003313 }
3314 curbuf = curwin->w_buffer;
3315
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003316 gap->ga_len -= todo;
3317 mch_memmove(gap->ga_data,
3318 (sb_line_T *)gap->ga_data + todo,
3319 sizeof(sb_line_T) * gap->ga_len);
3320 if (update_buffer)
3321 term->tl_scrollback_scrolled -= todo;
3322 }
3323}
3324
3325/*
3326 * Handle a line that is pushed off the top of the screen.
3327 */
3328 static int
3329handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3330{
3331 term_T *term = (term_T *)user;
3332 garray_T *gap;
3333 int update_buffer;
3334
3335 if (term->tl_normal_mode)
3336 {
3337 // In Terminal-Normal mode the user interacts with the buffer, thus we
3338 // must not change it. Postpone adding the scrollback lines.
3339 gap = &term->tl_scrollback_postponed;
3340 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003341 }
3342 else
3343 {
3344 // First remove the lines that were appended before, the pushed line
3345 // goes above it.
3346 cleanup_scrollback(term);
3347 gap = &term->tl_scrollback;
3348 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003349 }
3350
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003351 limit_scrollback(term, gap, update_buffer);
3352
3353 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003354 {
3355 cellattr_T *p = NULL;
3356 int len = 0;
3357 int i;
3358 int c;
3359 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003360 int text_len;
3361 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003362 sb_line_T *line;
3363 garray_T ga;
3364 cellattr_T fill_attr = term->tl_default_color;
3365
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003366 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003367 for (i = 0; i < cols; ++i)
3368 if (cells[i].chars[0] != 0)
3369 len = i + 1;
3370 else
3371 cell2cellattr(&cells[i], &fill_attr);
3372
3373 ga_init2(&ga, 1, 100);
3374 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003375 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003376 if (p != NULL)
3377 {
3378 for (col = 0; col < len; col += cells[col].width)
3379 {
3380 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3381 {
3382 ga.ga_len = 0;
3383 break;
3384 }
3385 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3386 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3387 (char_u *)ga.ga_data + ga.ga_len);
3388 cell2cellattr(&cells[col], &p[col]);
3389 }
3390 }
3391 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003392 {
3393 if (update_buffer)
3394 text = (char_u *)"";
3395 else
3396 text = vim_strsave((char_u *)"");
3397 text_len = 0;
3398 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003399 else
3400 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003401 text = ga.ga_data;
3402 text_len = ga.ga_len;
3403 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003404 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003405 if (update_buffer)
3406 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003407
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003408 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003409 line->sb_cols = len;
3410 line->sb_cells = p;
3411 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003412 if (update_buffer)
3413 {
3414 line->sb_text = NULL;
3415 ++term->tl_scrollback_scrolled;
3416 ga_clear(&ga); // free the text
3417 }
3418 else
3419 {
3420 line->sb_text = text;
3421 ga_init(&ga); // text is kept in tl_scrollback_postponed
3422 }
3423 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003424 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003425 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003426}
3427
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003428/*
3429 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3430 * received and stored in tl_scrollback_postponed.
3431 */
3432 static void
3433handle_postponed_scrollback(term_T *term)
3434{
3435 int i;
3436
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003437 if (term->tl_scrollback_postponed.ga_len == 0)
3438 return;
3439 ch_log(NULL, "Moving postponed scrollback to scrollback");
3440
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003441 // First remove the lines that were appended before, the pushed lines go
3442 // above it.
3443 cleanup_scrollback(term);
3444
3445 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3446 {
3447 char_u *text;
3448 sb_line_T *pp_line;
3449 sb_line_T *line;
3450
3451 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3452 break;
3453 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3454
3455 text = pp_line->sb_text;
3456 if (text == NULL)
3457 text = (char_u *)"";
3458 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3459 vim_free(pp_line->sb_text);
3460
3461 line = (sb_line_T *)term->tl_scrollback.ga_data
3462 + term->tl_scrollback.ga_len;
3463 line->sb_cols = pp_line->sb_cols;
3464 line->sb_cells = pp_line->sb_cells;
3465 line->sb_fill_attr = pp_line->sb_fill_attr;
3466 line->sb_text = NULL;
3467 ++term->tl_scrollback_scrolled;
3468 ++term->tl_scrollback.ga_len;
3469 }
3470
3471 ga_clear(&term->tl_scrollback_postponed);
3472 limit_scrollback(term, &term->tl_scrollback, TRUE);
3473}
3474
LemonBoy77771d32022-04-13 11:47:25 +01003475/*
3476 * Called when the terminal wants to ring the system bell.
3477 */
3478 static int
3479handle_bell(void *user UNUSED)
3480{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003481 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003482 return 0;
3483}
3484
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003485static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003486 handle_damage, // damage
3487 handle_moverect, // moverect
3488 handle_movecursor, // movecursor
3489 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003490 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003491 handle_resize, // resize
3492 handle_pushline, // sb_pushline
Bram Moolenaar6a12d262022-10-16 19:26:52 +01003493 NULL, // sb_popline
3494 NULL // sb_clear
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003495};
3496
3497/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003498 * Do the work after the channel of a terminal was closed.
3499 * Must be called only when updating_screen is FALSE.
3500 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3501 */
3502 static int
3503term_after_channel_closed(term_T *term)
3504{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003505 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003506 if (!term->tl_normal_mode)
3507 {
3508 int fnum = term->tl_buffer->b_fnum;
3509
3510 cleanup_vterm(term);
3511
3512 if (term->tl_finish == TL_FINISH_CLOSE)
3513 {
3514 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003515 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003516#ifdef FEAT_PROP_POPUP
3517 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003518
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003519 // If this was a terminal in a popup window, go back to the
3520 // previous window.
3521 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3522 {
3523 pwin = curwin;
3524 if (win_valid(prevwin))
3525 win_enter(prevwin, FALSE);
3526 }
3527 else
3528#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003529 // If this is the last normal window: exit Vim.
3530 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3531 {
3532 exarg_T ea;
3533
Bram Moolenaara80faa82020-04-12 19:37:17 +02003534 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003535 ex_quit(&ea);
3536 return TRUE;
3537 }
3538
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003539 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003540 ch_log(NULL, "terminal job finished, closing window");
3541 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003542 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003543 if (curwin == aucmd_win)
3544 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003545 if (do_set_w_closing)
3546 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003547 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003548 if (do_set_w_closing)
3549 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003550 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003551#ifdef FEAT_PROP_POPUP
3552 if (pwin != NULL)
3553 popup_close_with_retval(pwin, 0);
3554#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003555 return TRUE;
3556 }
3557 if (term->tl_finish == TL_FINISH_OPEN
3558 && term->tl_buffer->b_nwindows == 0)
3559 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003560 char *cmd = term->tl_opencmd == NULL
3561 ? "botright sbuf %d"
3562 : (char *)term->tl_opencmd;
3563 size_t len = strlen(cmd) + 50;
3564 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003565
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003566 if (buf != NULL)
3567 {
3568 ch_log(NULL, "terminal job finished, opening window");
3569 vim_snprintf(buf, len, cmd, fnum);
3570 do_cmdline_cmd((char_u *)buf);
3571 vim_free(buf);
3572 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003573 }
3574 else
3575 ch_log(NULL, "terminal job finished");
3576 }
3577
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003578 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003579 return FALSE;
3580}
3581
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003582#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3583/*
3584 * If the current window is a terminal in a popup window and the job has
3585 * finished, close the popup window and to back to the previous window.
3586 * Otherwise return FAIL.
3587 */
3588 int
3589may_close_term_popup(void)
3590{
3591 if (popup_is_popup(curwin) && curbuf->b_term != NULL
Bram Moolenaar9e636b92022-05-29 22:37:05 +01003592 && !term_job_running_not_none(curbuf->b_term))
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003593 {
3594 win_T *pwin = curwin;
3595
3596 if (win_valid(prevwin))
3597 win_enter(prevwin, FALSE);
3598 popup_close_with_retval(pwin, 0);
3599 return OK;
3600 }
3601 return FAIL;
3602}
3603#endif
3604
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003605/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003606 * Called when a channel is going to be closed, before invoking the close
3607 * callback.
3608 */
3609 void
3610term_channel_closing(channel_T *ch)
3611{
3612 term_T *term;
3613
3614 for (term = first_term; term != NULL; term = term->tl_next)
3615 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3616 term->tl_channel_closing = TRUE;
3617}
3618
3619/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003620 * Called when a channel has been closed.
3621 * If this was a channel for a terminal window then finish it up.
3622 */
3623 void
3624term_channel_closed(channel_T *ch)
3625{
3626 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003627 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003628 int did_one = FALSE;
3629
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003630 for (term = first_term; term != NULL; term = next_term)
3631 {
3632 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003633 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003634 {
3635 term->tl_channel_closed = TRUE;
3636 did_one = TRUE;
3637
Bram Moolenaard23a8232018-02-10 18:45:26 +01003638 VIM_CLEAR(term->tl_title);
3639 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003640#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003641 if (term->tl_out_fd != NULL)
3642 {
3643 fclose(term->tl_out_fd);
3644 term->tl_out_fd = NULL;
3645 }
3646#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003647
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003648 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003649 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003650 // Cannot open or close windows now. Can happen when
3651 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003652 term->tl_channel_recently_closed = TRUE;
3653 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003654 }
3655
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003656 if (term_after_channel_closed(term))
3657 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003658 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003659 }
3660
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003661 if (did_one)
3662 {
3663 redraw_statuslines();
3664
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003665 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003666 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003667 typebuf_was_filled = TRUE;
3668
3669 term = curbuf->b_term;
3670 if (term != NULL)
3671 {
3672 if (term->tl_job == ch->ch_job)
3673 maketitle();
3674 update_cursor(term, term->tl_cursor_visible);
3675 }
3676 }
3677}
3678
3679/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003680 * To be called after resetting updating_screen: handle any terminal where the
3681 * channel was closed.
3682 */
3683 void
3684term_check_channel_closed_recently()
3685{
3686 term_T *term;
3687 term_T *next_term;
3688
3689 for (term = first_term; term != NULL; term = next_term)
3690 {
3691 next_term = term->tl_next;
3692 if (term->tl_channel_recently_closed)
3693 {
3694 term->tl_channel_recently_closed = FALSE;
3695 if (term_after_channel_closed(term))
3696 // start over, the list may have changed
3697 next_term = first_term;
3698 }
3699 }
3700}
3701
3702/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003703 * Fill one screen line from a line of the terminal.
3704 * Advances "pos" to past the last column.
3705 */
3706 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003707term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003708 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003709 win_T *wp,
3710 VTermScreen *screen,
3711 VTermPos *pos,
3712 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003713{
3714 int off = screen_get_current_line_off();
3715
3716 for (pos->col = 0; pos->col < max_col; )
3717 {
3718 VTermScreenCell cell;
3719 int c;
3720
3721 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003722 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003723
3724 c = cell.chars[0];
3725 if (c == NUL)
3726 {
3727 ScreenLines[off] = ' ';
3728 if (enc_utf8)
3729 ScreenLinesUC[off] = NUL;
3730 }
3731 else
3732 {
3733 if (enc_utf8)
3734 {
3735 int i;
3736
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003737 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003738 for (i = 0; i < Screen_mco
3739 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3740 {
3741 ScreenLinesC[i][off] = cell.chars[i + 1];
3742 if (cell.chars[i + 1] == 0)
3743 break;
3744 }
3745 if (c >= 0x80 || (Screen_mco > 0
3746 && ScreenLinesC[0][off] != 0))
3747 {
3748 ScreenLines[off] = ' ';
3749 ScreenLinesUC[off] = c;
3750 }
3751 else
3752 {
3753 ScreenLines[off] = c;
3754 ScreenLinesUC[off] = NUL;
3755 }
3756 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003757#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003758 else if (has_mbyte && c >= 0x80)
3759 {
3760 char_u mb[MB_MAXBYTES+1];
3761 WCHAR wc = c;
3762
3763 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3764 (char*)mb, 2, 0, 0) > 1)
3765 {
3766 ScreenLines[off] = mb[0];
3767 ScreenLines[off + 1] = mb[1];
3768 cell.width = mb_ptr2cells(mb);
3769 }
3770 else
3771 ScreenLines[off] = c;
3772 }
3773#endif
3774 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003775 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003776 ScreenLines[off] = c;
3777 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003778 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3779 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003780
3781 ++pos->col;
3782 ++off;
3783 if (cell.width == 2)
3784 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003785 // don't set the second byte to NUL for a DBCS encoding, it
3786 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003787 if (enc_utf8)
3788 {
3789 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003790 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003791 }
3792 else if (!has_mbyte)
3793 {
3794 // Can't show a double-width character with a single-byte
3795 // 'encoding', just use a space.
3796 ScreenLines[off] = ' ';
3797 ScreenAttrs[off] = ScreenAttrs[off - 1];
3798 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003799
3800 ++pos->col;
3801 ++off;
3802 }
3803 }
3804}
3805
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003806#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003807 static void
3808update_system_term(term_T *term)
3809{
3810 VTermPos pos;
3811 VTermScreen *screen;
3812
3813 if (term->tl_vterm == NULL)
3814 return;
3815 screen = vterm_obtain_screen(term->tl_vterm);
3816
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003817 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003818 while (term->tl_toprow > 0
3819 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3820 {
3821 int save_p_more = p_more;
3822
3823 p_more = FALSE;
3824 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003825 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003826 p_more = save_p_more;
3827 --term->tl_toprow;
3828 }
3829
3830 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3831 && pos.row < Rows; ++pos.row)
3832 {
3833 if (pos.row < term->tl_rows)
3834 {
3835 int max_col = MIN(Columns, term->tl_cols);
3836
Bram Moolenaar83d47902020-03-26 20:34:00 +01003837 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003838 }
3839 else
3840 pos.col = 0;
3841
Bram Moolenaar510f0372022-07-04 17:46:22 +01003842 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003843 }
3844
3845 term->tl_dirty_row_start = MAX_ROW;
3846 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003847}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003848#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003849
3850/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003851 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3852 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003853 * Terminal-Normal mode.
3854 */
3855 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003856term_do_update_window(win_T *wp)
3857{
3858 term_T *term = wp->w_buffer->b_term;
3859
3860 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3861}
3862
3863/*
3864 * Called to update a window that contains an active terminal.
3865 */
3866 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003867term_update_window(win_T *wp)
3868{
3869 term_T *term = wp->w_buffer->b_term;
3870 VTerm *vterm;
3871 VTermScreen *screen;
3872 VTermState *state;
3873 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003874 int rows, cols;
3875 int newrows, newcols;
3876 int minsize;
3877 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003878
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003879 vterm = term->tl_vterm;
3880 screen = vterm_obtain_screen(vterm);
3881 state = vterm_obtain_state(vterm);
3882
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003883 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
3884 // With UPD_SOME_VALID only redraw what was marked dirty.
3885 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003886 {
3887 term->tl_dirty_row_start = 0;
3888 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003889
3890 if (term->tl_postponed_scroll > 0
3891 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003892 // Scrolling is usually faster than redrawing, when there are only
3893 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003894 term_scroll_up(term, 0, term->tl_postponed_scroll);
3895 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003896 }
3897
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003898 /*
3899 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003900 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003901 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003902 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003903
Bram Moolenaar498c2562018-04-15 23:45:15 +02003904 newrows = 99999;
3905 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003906 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003907 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003908 // Always use curwin, it may be a popup window.
3909 win_T *wwp = twp == NULL ? curwin : twp;
3910
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003911 // When more than one window shows the same terminal, use the
3912 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003913 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003914 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003915 newrows = MIN(newrows, wwp->w_height);
3916 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003917 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003918 if (twp == NULL)
3919 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003920 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003921 if (newrows == 99999 || newcols == 99999)
3922 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003923 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3924 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3925
Bram Moolenaareba13e42021-02-23 17:47:23 +01003926 // If no cell is visible there is no point in resizing. Also, vterm can't
3927 // handle a zero height.
3928 if (newrows == 0 || newcols == 0)
3929 return;
3930
Bram Moolenaar498c2562018-04-15 23:45:15 +02003931 if (term->tl_rows != newrows || term->tl_cols != newcols)
3932 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003933 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003934 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003935 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003936 newrows);
3937 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003938
3939 // Updating the terminal size will cause the snapshot to be cleared.
3940 // When not in terminal_loop() we need to restore it.
3941 if (term != in_terminal_loop)
3942 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003943 }
3944
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003945 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003946 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003947 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003948
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003949 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3950 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003951 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003952 if (pos.row < term->tl_rows)
3953 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003954 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003955
Bram Moolenaar83d47902020-03-26 20:34:00 +01003956 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003957 }
3958 else
3959 pos.col = 0;
3960
Bram Moolenaar510f0372022-07-04 17:46:22 +01003961 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01003962#ifdef FEAT_MENU
3963 + winbar_height(wp)
3964#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003965 , wp->w_wincol, pos.col, wp->w_width,
3966#ifdef FEAT_PROP_POPUP
3967 popup_is_popup(wp) ? SLF_POPUP :
3968#endif
3969 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003970 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00003971}
3972
3973/*
3974 * Called after updating all windows: may reset dirty rows.
3975 */
3976 void
3977term_did_update_window(win_T *wp)
3978{
3979 term_T *term = wp->w_buffer->b_term;
3980
3981 if (term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode
3982 && wp->w_redr_type == 0)
3983 {
3984 term->tl_dirty_row_start = MAX_ROW;
3985 term->tl_dirty_row_end = 0;
3986 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003987}
3988
3989/*
3990 * Return TRUE if "wp" is a terminal window where the job has finished.
3991 */
3992 int
3993term_is_finished(buf_T *buf)
3994{
3995 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3996}
3997
3998/*
3999 * Return TRUE if "wp" is a terminal window where the job has finished or we
4000 * are in Terminal-Normal mode, thus we show the buffer contents.
4001 */
4002 int
4003term_show_buffer(buf_T *buf)
4004{
4005 term_T *term = buf->b_term;
4006
4007 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
4008}
4009
4010/*
4011 * The current buffer is going to be changed. If there is terminal
4012 * highlighting remove it now.
4013 */
4014 void
4015term_change_in_curbuf(void)
4016{
4017 term_T *term = curbuf->b_term;
4018
4019 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
4020 {
4021 free_scrollback(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01004022 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004023
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004024 // The buffer is now like a normal buffer, it cannot be easily
4025 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004026 set_string_option_direct((char_u *)"buftype", -1,
4027 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
4028 }
4029}
4030
4031/*
4032 * Get the screen attribute for a position in the buffer.
4033 * Use a negative "col" to get the filler background color.
4034 */
4035 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004036term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004037{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004038 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004039 term_T *term = buf->b_term;
4040 sb_line_T *line;
4041 cellattr_T *cellattr;
4042
4043 if (lnum > term->tl_scrollback.ga_len)
4044 cellattr = &term->tl_default_color;
4045 else
4046 {
4047 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
4048 if (col < 0 || col >= line->sb_cols)
4049 cellattr = &line->sb_fill_attr;
4050 else
4051 cellattr = line->sb_cells + col;
4052 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004053 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004054}
4055
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004056/*
4057 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02004058 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004059 */
4060 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004061cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004062{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004063 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4064 if (rgb->index == 0)
4065 rgb->type = VTERM_COLOR_RGB;
4066 else
4067 {
4068 rgb->type = VTERM_COLOR_INDEXED;
4069 --rgb->index;
4070 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004071}
4072
4073/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004074 * Initialize vterm color from the synID.
4075 * Returns TRUE if color is set to "fg" and "bg".
4076 * Otherwise returns FALSE.
4077 */
4078 static int
4079get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4080{
4081#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4082 // Use the actual color for the GUI and when 'termguicolors' is set.
4083 if (0
4084# ifdef FEAT_GUI
4085 || gui.in_use
4086# endif
4087# ifdef FEAT_TERMGUICOLORS
4088 || p_tgc
4089# ifdef FEAT_VTP
4090 // Finally get INVALCOLOR on this execution path
4091 || (!p_tgc && t_colors >= 256)
4092# endif
4093# endif
4094 )
4095 {
4096 guicolor_T fg_rgb = INVALCOLOR;
4097 guicolor_T bg_rgb = INVALCOLOR;
4098
4099 if (id > 0)
4100 syn_id2colors(id, &fg_rgb, &bg_rgb);
4101
4102 if (fg_rgb != INVALCOLOR)
4103 {
4104 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4105 fg->red = (unsigned)(rgb >> 16);
4106 fg->green = (unsigned)(rgb >> 8) & 255;
4107 fg->blue = (unsigned)rgb & 255;
4108 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4109 }
4110 else
4111 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4112
4113 if (bg_rgb != INVALCOLOR)
4114 {
4115 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4116 bg->red = (unsigned)(rgb >> 16);
4117 bg->green = (unsigned)(rgb >> 8) & 255;
4118 bg->blue = (unsigned)rgb & 255;
4119 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4120 }
4121 else
4122 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4123
4124 return TRUE;
4125 }
4126 else
4127#endif
4128 if (t_colors >= 16)
4129 {
4130 int cterm_fg = -1;
4131 int cterm_bg = -1;
4132
4133 if (id > 0)
4134 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4135
4136 if (cterm_fg >= 0)
4137 {
4138 cterm_color2vterm(cterm_fg, fg);
4139 fg->type |= VTERM_COLOR_DEFAULT_FG;
4140 }
4141 else
4142 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4143
4144 if (cterm_bg >= 0)
4145 {
4146 cterm_color2vterm(cterm_bg, bg);
4147 bg->type |= VTERM_COLOR_DEFAULT_BG;
4148 }
4149 else
4150 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4151
4152 return TRUE;
4153 }
4154
4155 return FALSE;
4156}
4157
4158 void
4159term_reset_wincolor(win_T *wp)
4160{
4161 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4162 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4163}
4164
4165/*
4166 * Cache the color of 'wincolor'.
4167 */
4168 void
4169term_update_wincolor(win_T *wp)
4170{
4171 int id = 0;
4172
4173 if (*wp->w_p_wcr != NUL)
4174 id = syn_name2id(wp->w_p_wcr);
4175 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4176 &wp->w_term_wincolor.bg))
4177 term_reset_wincolor(wp);
4178}
4179
4180/*
4181 * Called when option 'termguicolors' was set,
4182 * or when any highlight is changed.
4183 */
4184 void
4185term_update_wincolor_all()
4186{
4187 win_T *wp = NULL;
4188 int did_curwin = FALSE;
4189
4190 while (for_all_windows_and_curwin(&wp, &did_curwin))
4191 term_update_wincolor(wp);
4192}
4193
4194/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004195 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004196 */
4197 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004198init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004199{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004200 VTermColor *fg, *bg;
4201 int fgval, bgval;
4202 int id;
4203
Bram Moolenaara80faa82020-04-12 19:37:17 +02004204 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004205 term->tl_default_color.width = 1;
4206 fg = &term->tl_default_color.fg;
4207 bg = &term->tl_default_color.bg;
4208
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004209 // Vterm uses a default black background. Set it to white when
4210 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004211 if (*p_bg == 'l')
4212 {
4213 fgval = 0;
4214 bgval = 255;
4215 }
4216 else
4217 {
4218 fgval = 255;
4219 bgval = 0;
4220 }
4221 fg->red = fg->green = fg->blue = fgval;
4222 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004223 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4224 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004225
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004226 // The highlight group overrules the defaults.
4227 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004228
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004229 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004230 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004231#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004232 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004233#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004234
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004235 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004236 if (cterm_normal_fg_color > 0)
4237 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004238 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004239# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4240# ifdef VIMDLL
4241 if (!gui.in_use)
4242# endif
4243 {
4244 tmp = fg->red;
4245 fg->red = fg->blue;
4246 fg->blue = tmp;
4247 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004248# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004249 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004250# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004251 else
4252 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004253# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004254
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004255 if (cterm_normal_bg_color > 0)
4256 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004257 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004258# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4259# ifdef VIMDLL
4260 if (!gui.in_use)
4261# endif
4262 {
4263 tmp = fg->red;
4264 fg->red = fg->blue;
4265 fg->blue = tmp;
4266 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004267# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004268 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004269# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004270 else
4271 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004272# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004273 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004274}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004275
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004276#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4277/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004278 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4279 * "ansi_colors" argument in term_start()) shall be applied.
4280 */
4281 static int
4282term_use_palette()
4283{
4284 if (0
4285#ifdef FEAT_GUI
4286 || gui.in_use
4287#endif
4288#ifdef FEAT_TERMGUICOLORS
4289 || p_tgc
4290#endif
4291 )
4292 return TRUE;
4293 return FALSE;
4294}
4295
4296/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004297 * Set the 16 ANSI colors from array of RGB values
4298 */
4299 static void
4300set_vterm_palette(VTerm *vterm, long_u *rgb)
4301{
4302 int index = 0;
4303 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004304
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004305 for (; index < 16; index++)
4306 {
4307 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004308
Millyb771b6b2021-11-23 12:07:25 +00004309 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004310 color.red = (unsigned)(rgb[index] >> 16);
4311 color.green = (unsigned)(rgb[index] >> 8) & 255;
4312 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004313 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004314 vterm_state_set_palette_color(state, index, &color);
4315 }
4316}
4317
4318/*
4319 * Set the ANSI color palette from a list of colors
4320 */
4321 static int
4322set_ansi_colors_list(VTerm *vterm, list_T *list)
4323{
4324 int n = 0;
4325 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004326 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004327
Bram Moolenaarb0992022020-01-30 14:55:42 +01004328 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004329 {
4330 char_u *color_name;
4331 guicolor_T guicolor;
4332
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004333 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004334 if (color_name == NULL)
4335 return FAIL;
4336
4337 guicolor = GUI_GET_COLOR(color_name);
4338 if (guicolor == INVALCOLOR)
4339 return FAIL;
4340
4341 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4342 }
4343
4344 if (n != 16 || li != NULL)
4345 return FAIL;
4346
4347 set_vterm_palette(vterm, rgb);
4348
4349 return OK;
4350}
4351
4352/*
4353 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4354 */
4355 static void
4356init_vterm_ansi_colors(VTerm *vterm)
4357{
4358 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4359
LemonBoyb2b3acb2022-05-20 10:10:34 +01004360 if (var == NULL)
4361 return;
4362
4363 if (var->di_tv.v_type != VAR_LIST
4364 || var->di_tv.vval.v_list == NULL
4365 || var->di_tv.vval.v_list->lv_first == &range_list_item
4366 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004367 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004368}
4369#endif
4370
Bram Moolenaar52acb112018-03-18 19:20:22 +01004371/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004372 * Handles a "drop" command from the job in the terminal.
4373 * "item" is the file name, "item->li_next" may have options.
4374 */
4375 static void
4376handle_drop_command(listitem_T *item)
4377{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004378 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004379 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004380 int bufnr;
4381 win_T *wp;
4382 tabpage_T *tp;
4383 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004384 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004385
4386 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4387 FOR_ALL_TAB_WINDOWS(tp, wp)
4388 {
4389 if (wp->w_buffer->b_fnum == bufnr)
4390 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004391 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004392 goto_tabpage_win(tp, wp);
4393 return;
4394 }
4395 }
4396
Bram Moolenaara80faa82020-04-12 19:37:17 +02004397 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004398
4399 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4400 && opt_item->li_tv.vval.v_dict != NULL)
4401 {
4402 dict_T *dict = opt_item->li_tv.vval.v_dict;
4403 char_u *p;
4404
Bram Moolenaard61efa52022-07-23 09:52:04 +01004405 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004406 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004407 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004408 if (p != NULL)
4409 {
4410 if (check_ff_value(p) == FAIL)
4411 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4412 else
4413 ea.force_ff = *p;
4414 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004415 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004416 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004417 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004418 if (p != NULL)
4419 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004420 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004421 if (ea.cmd != NULL)
4422 {
4423 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4424 ea.force_enc = 11;
4425 tofree = ea.cmd;
4426 }
4427 }
4428
Bram Moolenaard61efa52022-07-23 09:52:04 +01004429 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004430 if (p != NULL)
4431 get_bad_opt(p, &ea);
4432
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004433 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004434 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004435 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004436 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004437 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004438 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004439 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004440 ea.force_bin = FORCE_NOBIN;
4441 }
4442
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004443 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004444 if (ea.cmd == NULL)
4445 ea.cmd = (char_u *)"split";
4446 ea.arg = fname;
4447 ea.cmdidx = CMD_split;
4448 ex_splitview(&ea);
4449
4450 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004451}
4452
4453/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004454 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4455 */
4456 static int
4457is_permitted_term_api(char_u *func, char_u *pat)
4458{
4459 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4460}
4461
4462/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004463 * Handles a function call from the job running in a terminal.
4464 * "item" is the function name, "item->li_next" has the arguments.
4465 */
4466 static void
4467handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4468{
4469 char_u *func;
4470 typval_T argvars[2];
4471 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004472 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004473
4474 if (item->li_next == NULL)
4475 {
4476 ch_log(channel, "Missing function arguments for call");
4477 return;
4478 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004479 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004480
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004481 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004482 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004483 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004484 return;
4485 }
4486
4487 argvars[0].v_type = VAR_NUMBER;
4488 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4489 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004490 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004491 funcexe.fe_firstline = 1L;
4492 funcexe.fe_lastline = 1L;
4493 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004494 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004495 {
4496 clear_tv(&rettv);
4497 ch_log(channel, "Function %s called", func);
4498 }
4499 else
4500 ch_log(channel, "Calling function %s failed", func);
4501}
4502
4503/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004504 * URL decoding (also know as Percent-encoding).
4505 *
4506 * Note this function currently is only used for decoding shell's
4507 * OSC 7 escape sequence which we can assume all bytes are valid
4508 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4509 * encoding bytes like 0xfe, 0xff.
4510 */
4511 static size_t
4512url_decode(const char *src, const size_t len, char_u *dst)
4513{
4514 size_t i = 0, j = 0;
4515
4516 while (i < len)
4517 {
4518 if (src[i] == '%' && i + 2 < len)
4519 {
4520 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4521 j++;
4522 i += 3;
4523 }
4524 else
4525 {
4526 dst[j] = src[i];
4527 i++;
4528 j++;
4529 }
4530 }
4531 dst[j] = '\0';
4532 return j;
4533}
4534
4535/*
4536 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4537 *
4538 * The OSC 7 sequence has the format of
4539 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4540 * and what VTerm provides via VTermStringFragment is
4541 * "file://HOSTNAME/CURRENT/DIR"
4542 */
4543 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004544sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004545{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004546 int offset = 7; // len of "file://" is 7
4547 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004548 char_u *new_dir;
4549
4550 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004551 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004552 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004553 ++offset;
4554 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004555 }
4556
Bram Moolenaar474ad392022-08-21 11:37:17 +01004557 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004558 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004559 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004560 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004561 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004562 }
4563
Bram Moolenaar474ad392022-08-21 11:37:17 +01004564 new_dir = alloc(gap->ga_len - offset + 1);
4565 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004566 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4567 vim_free(new_dir);
4568}
4569
4570/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004571 * Called by libvterm when it cannot recognize an OSC sequence.
4572 * We recognize a terminal API command.
4573 */
4574 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004575parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004576{
4577 term_T *term = (term_T *)user;
4578 js_read_T reader;
4579 typval_T tv;
4580 channel_T *channel = term->tl_job == NULL ? NULL
4581 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004582 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004583
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004584 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004585 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004586 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004587
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004588 // Concatenate what was received until the final piece is found.
4589 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4590 {
4591 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004592 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004593 }
4594 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004595 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004596 if (!frag.final)
4597 return 1;
4598
4599 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004600
4601 if (command == 7)
4602 {
4603 sync_shell_dir(gap);
4604 ga_clear(gap);
4605 return 1;
4606 }
4607
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004608 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004609 reader.js_fill = NULL;
4610 reader.js_used = 0;
4611 if (json_decode(&reader, &tv, 0) == OK
4612 && tv.v_type == VAR_LIST
4613 && tv.vval.v_list != NULL)
4614 {
4615 listitem_T *item = tv.vval.v_list->lv_first;
4616
4617 if (item == NULL)
4618 ch_log(channel, "Missing command");
4619 else
4620 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004621 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004622
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004623 // Make sure an invoked command doesn't delete the buffer (and the
4624 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004625 ++term->tl_buffer->b_locked;
4626
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004627 item = item->li_next;
4628 if (item == NULL)
4629 ch_log(channel, "Missing argument for %s", cmd);
4630 else if (STRCMP(cmd, "drop") == 0)
4631 handle_drop_command(item);
4632 else if (STRCMP(cmd, "call") == 0)
4633 handle_call_command(term, channel, item);
4634 else
4635 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004636 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004637 }
4638 }
4639 else
4640 ch_log(channel, "Invalid JSON received");
4641
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004642 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004643 clear_tv(&tv);
4644 return 1;
4645}
4646
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004647/*
4648 * Called by libvterm when it cannot recognize a CSI sequence.
4649 * We recognize the window position report.
4650 */
4651 static int
4652parse_csi(
4653 const char *leader UNUSED,
4654 const long args[],
4655 int argcount,
4656 const char *intermed UNUSED,
4657 char command,
4658 void *user)
4659{
4660 term_T *term = (term_T *)user;
4661 char buf[100];
4662 int len;
4663 int x = 0;
4664 int y = 0;
4665 win_T *wp;
4666
4667 // We recognize only CSI 13 t
4668 if (command != 't' || argcount != 1 || args[0] != 13)
4669 return 0; // not handled
4670
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004671 // When getting the window position is not possible or it fails it results
4672 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004673#if defined(FEAT_GUI) \
4674 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4675 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004676 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004677#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004678
4679 FOR_ALL_WINDOWS(wp)
4680 if (wp->w_buffer == term->tl_buffer)
4681 break;
4682 if (wp != NULL)
4683 {
4684#ifdef FEAT_GUI
4685 if (gui.in_use)
4686 {
4687 x += wp->w_wincol * gui.char_width;
4688 y += W_WINROW(wp) * gui.char_height;
4689 }
4690 else
4691#endif
4692 {
4693 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004694 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004695 x += wp->w_wincol * 7;
4696 y += W_WINROW(wp) * 10;
4697 }
4698 }
4699
4700 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4701 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4702 (char_u *)buf, len, NULL);
4703 return 1;
4704}
4705
Bram Moolenaard8637282020-05-20 18:41:41 +02004706static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004707 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004708 parse_csi, // csi
4709 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004710 NULL, // dcs
4711 NULL, // apc
4712 NULL, // pm
4713 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004714};
4715
4716/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004717 * Use Vim's allocation functions for vterm so profiling works.
4718 */
4719 static void *
4720vterm_malloc(size_t size, void *data UNUSED)
4721{
Bram Moolenaar88137392021-11-12 16:01:15 +00004722 // make sure that the length is not zero
4723 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004724}
4725
4726 static void
4727vterm_memfree(void *ptr, void *data UNUSED)
4728{
4729 vim_free(ptr);
4730}
4731
4732static VTermAllocatorFunctions vterm_allocator = {
4733 &vterm_malloc,
4734 &vterm_memfree
4735};
4736
4737/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004738 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004739 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004740 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004741 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004742create_vterm(term_T *term, int rows, int cols)
4743{
4744 VTerm *vterm;
4745 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004746 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004747 VTermValue value;
4748
Bram Moolenaar756ef112018-04-10 12:04:27 +02004749 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004750 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004751 if (vterm == NULL)
4752 return FAIL;
4753
4754 // Allocate screen and state here, so we can bail out if that fails.
4755 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004756 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004757 if (state == NULL || screen == NULL)
4758 {
4759 vterm_free(vterm);
4760 return FAIL;
4761 }
4762
Bram Moolenaar52acb112018-03-18 19:20:22 +01004763 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004764 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004765 vterm_set_utf8(vterm, 1);
4766
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004767 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004768
4769 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004770 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004771 &term->tl_default_color.fg,
4772 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004773
Bram Moolenaar9e587872019-05-13 20:27:23 +02004774 if (t_colors < 16)
4775 // Less than 16 colors: assume that bold means using a bright color for
4776 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004777 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4778
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004779 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004780 vterm_screen_reset(screen, 1 /* hard */);
4781
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004782 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004783 vterm_screen_enable_altscreen(screen, 1);
4784
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004785 // For unix do not use a blinking cursor. In an xterm this causes the
4786 // cursor to blink if it's blinking in the xterm.
4787 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004788#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004789 if (GetCaretBlinkTime() == INFINITE)
4790 value.boolean = 0;
4791 else
4792 value.boolean = 1;
4793#else
4794 value.boolean = 0;
4795#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004796 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004797 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004798
4799 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004800}
4801
4802/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004803 * Reset the terminal palette to its default value.
4804 */
4805 static void
4806term_reset_palette(VTerm *vterm)
4807{
4808 VTermState *state = vterm_obtain_state(vterm);
4809 int index;
4810
4811 for (index = 0; index < 16; index++)
4812 {
4813 VTermColor color;
4814
4815 color.type = VTERM_COLOR_INDEXED;
4816 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4817 &color.index);
4818 // The first valid index starts at 1.
4819 color.index -= 1;
4820
4821 vterm_state_set_palette_color(state, index, &color);
4822 }
4823}
4824
4825 static void
4826term_update_palette(term_T *term)
4827{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004828#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004829 if (term_use_palette()
4830 && (term->tl_palette != NULL
4831 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004832 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004833 {
4834 if (term->tl_palette != NULL)
4835 set_vterm_palette(term->tl_vterm, term->tl_palette);
4836 else
4837 init_vterm_ansi_colors(term->tl_vterm);
4838 }
4839 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004840#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004841 term_reset_palette(term->tl_vterm);
4842}
4843
4844/*
4845 * Called when option 'termguicolors' is changed.
4846 */
4847 void
4848term_update_palette_all()
4849{
4850 term_T *term;
4851
4852 FOR_ALL_TERMS(term)
4853 {
4854 if (term->tl_vterm == NULL)
4855 continue;
4856 term_update_palette(term);
4857 }
4858}
4859
4860/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004861 * Called when option 'background' or 'termguicolors' was set,
4862 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02004863 */
4864 void
4865term_update_colors_all(void)
4866{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004867 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02004868
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004869 FOR_ALL_TERMS(term)
4870 {
4871 if (term->tl_vterm == NULL)
4872 continue;
4873 init_default_colors(term);
4874 vterm_state_set_default_colors(
4875 vterm_obtain_state(term->tl_vterm),
4876 &term->tl_default_color.fg,
4877 &term->tl_default_color.bg);
4878 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004879}
4880
4881/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004882 * Return the text to show for the buffer name and status.
4883 */
4884 char_u *
4885term_get_status_text(term_T *term)
4886{
4887 if (term->tl_status_text == NULL)
4888 {
4889 char_u *txt;
4890 size_t len;
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004891 char_u *fname;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004892
4893 if (term->tl_normal_mode)
4894 {
4895 if (term_job_running(term))
4896 txt = (char_u *)_("Terminal");
4897 else
4898 txt = (char_u *)_("Terminal-finished");
4899 }
4900 else if (term->tl_title != NULL)
4901 txt = term->tl_title;
4902 else if (term_none_open(term))
4903 txt = (char_u *)_("active");
4904 else if (term_job_running(term))
4905 txt = (char_u *)_("running");
4906 else
4907 txt = (char_u *)_("finished");
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004908 fname = buf_get_fname(term->tl_buffer);
4909 len = 9 + STRLEN(fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004910 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004911 if (term->tl_status_text != NULL)
4912 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004913 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004914 }
4915 return term->tl_status_text;
4916}
4917
4918/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00004919 * Clear the cached value of the status text.
4920 */
4921 void
4922term_clear_status_text(term_T *term)
4923{
4924 VIM_CLEAR(term->tl_status_text);
4925}
4926
4927/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004928 * Mark references in jobs of terminals.
4929 */
4930 int
4931set_ref_in_term(int copyID)
4932{
4933 int abort = FALSE;
4934 term_T *term;
4935 typval_T tv;
4936
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004937 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004938 if (term->tl_job != NULL)
4939 {
4940 tv.v_type = VAR_JOB;
4941 tv.vval.v_job = term->tl_job;
4942 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4943 }
4944 return abort;
4945}
4946
4947/*
4948 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004949 * Returns NULL when the buffer is not for a terminal window and logs a message
4950 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004951 */
4952 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004953term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004954{
4955 buf_T *buf;
4956
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004957 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004958 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004959 --emsg_off;
4960 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004961 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01004962 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004963 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004964 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004965 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004966 return buf;
4967}
4968
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004969 static void
4970clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004971{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004972 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004973 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4974 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004975}
4976
4977 static void
4978dump_term_color(FILE *fd, VTermColor *color)
4979{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004980 int index;
4981
4982 if (VTERM_COLOR_IS_INDEXED(color))
4983 index = color->index + 1;
4984 else if (color->type == 0)
4985 // use RGB values
4986 index = 255;
4987 else
4988 // default color
4989 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004990 fprintf(fd, "%02x%02x%02x%d",
4991 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004992 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004993}
4994
4995/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004996 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004997 *
4998 * Each screen cell in full is:
4999 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
5000 * {characters} is a space for an empty cell
5001 * For a double-width character "+" is changed to "*" and the next cell is
5002 * skipped.
5003 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
5004 * when "&" use the same as the previous cell.
5005 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
5006 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
5007 * {color-idx} is a number from 0 to 255
5008 *
5009 * Screen cell with same width, attributes and color as the previous one:
5010 * |{characters}
5011 *
5012 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
5013 *
5014 * Repeating the previous screen cell:
5015 * @{count}
5016 */
5017 void
5018f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
5019{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005020 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005021 term_T *term;
5022 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005023 int max_height = 0;
5024 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005025 stat_T st;
5026 FILE *fd;
5027 VTermPos pos;
5028 VTermScreen *screen;
5029 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005030 VTermState *state;
5031 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005032
5033 if (check_restricted() || check_secure())
5034 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005035
5036 if (in_vim9script()
5037 && (check_for_buffer_arg(argvars, 0) == FAIL
5038 || check_for_string_arg(argvars, 1) == FAIL
5039 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5040 return;
5041
5042 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01005043 if (buf == NULL)
5044 return;
5045 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005046 if (term->tl_vterm == NULL)
5047 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005048 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02005049 return;
5050 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005051
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005052 if (argvars[2].v_type != VAR_UNKNOWN)
5053 {
5054 dict_T *d;
5055
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01005056 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005057 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005058 d = argvars[2].vval.v_dict;
5059 if (d != NULL)
5060 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005061 max_height = dict_get_number(d, "rows");
5062 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005063 }
5064 }
5065
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005066 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005067 if (fname == NULL)
5068 return;
5069 if (mch_stat((char *)fname, &st) >= 0)
5070 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005071 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005072 return;
5073 }
5074
Bram Moolenaard96ff162018-02-18 22:13:29 +01005075 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5076 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005077 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005078 return;
5079 }
5080
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005081 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005082
5083 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005084 state = vterm_obtain_state(term->tl_vterm);
5085 vterm_state_get_cursorpos(state, &cursor_pos);
5086
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005087 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5088 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005089 {
5090 int repeat = 0;
5091
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005092 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5093 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005094 {
5095 VTermScreenCell cell;
5096 int same_attr;
5097 int same_chars = TRUE;
5098 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005099 int is_cursor_pos = (pos.col == cursor_pos.col
5100 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005101
5102 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005103 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005104
5105 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5106 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005107 int c = cell.chars[i];
5108 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005109 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005110
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005111 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005112 if (i == 0)
5113 {
5114 c = (c == NUL) ? ' ' : c;
5115 pc = (pc == NUL) ? ' ' : pc;
5116 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005117 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005118 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005119 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005120 break;
5121 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005122 same_attr = vtermAttr2hl(&cell.attrs)
5123 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005124 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5125 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005126 if (same_chars && cell.width == prev_cell.width && same_attr
5127 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005128 {
5129 ++repeat;
5130 }
5131 else
5132 {
5133 if (repeat > 0)
5134 {
5135 fprintf(fd, "@%d", repeat);
5136 repeat = 0;
5137 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005138 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005139
5140 if (cell.chars[0] == NUL)
5141 fputs(" ", fd);
5142 else
5143 {
5144 char_u charbuf[10];
5145 int len;
5146
5147 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5148 && cell.chars[i] != NUL; ++i)
5149 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005150 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005151 fwrite(charbuf, len, 1, fd);
5152 }
5153 }
5154
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005155 // When only the characters differ we don't write anything, the
5156 // following "|", "@" or NL will indicate using the same
5157 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005158 if (cell.width != prev_cell.width || !same_attr)
5159 {
5160 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005161 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005162 else
5163 fputs("+", fd);
5164
5165 if (same_attr)
5166 {
5167 fputs("&", fd);
5168 }
5169 else
5170 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005171 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005172 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005173 fputs("&", fd);
5174 else
5175 {
5176 fputs("#", fd);
5177 dump_term_color(fd, &cell.fg);
5178 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005179 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005180 fputs("&", fd);
5181 else
5182 {
5183 fputs("#", fd);
5184 dump_term_color(fd, &cell.bg);
5185 }
5186 }
5187 }
5188
5189 prev_cell = cell;
5190 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005191
5192 if (cell.width == 2)
5193 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005194 }
5195 if (repeat > 0)
5196 fprintf(fd, "@%d", repeat);
5197 fputs("\n", fd);
5198 }
5199
5200 fclose(fd);
5201}
5202
5203/*
5204 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5205 */
5206 static void
5207dump_is_corrupt(garray_T *gap)
5208{
5209 ga_concat(gap, (char_u *)"CORRUPT");
5210}
5211
5212 static void
5213append_cell(garray_T *gap, cellattr_T *cell)
5214{
5215 if (ga_grow(gap, 1) == OK)
5216 {
5217 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5218 ++gap->ga_len;
5219 }
5220}
5221
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005222 static void
5223clear_cellattr(cellattr_T *cell)
5224{
5225 CLEAR_FIELD(*cell);
5226 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5227 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5228}
5229
Bram Moolenaard96ff162018-02-18 22:13:29 +01005230/*
5231 * Read the dump file from "fd" and append lines to the current buffer.
5232 * Return the cell width of the longest line.
5233 */
5234 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005235read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005236{
5237 int c;
5238 garray_T ga_text;
5239 garray_T ga_cell;
5240 char_u *prev_char = NULL;
5241 int attr = 0;
5242 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005243 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005244 term_T *term = curbuf->b_term;
5245 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005246 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005247
5248 ga_init2(&ga_text, 1, 90);
5249 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005250 clear_cellattr(&cell);
5251 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005252 cursor_pos->row = -1;
5253 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005254
5255 c = fgetc(fd);
5256 for (;;)
5257 {
5258 if (c == EOF)
5259 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005260 if (c == '\r')
5261 {
5262 // DOS line endings? Ignore.
5263 c = fgetc(fd);
5264 }
5265 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005266 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005267 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005268 if (ga_text.ga_data == NULL)
5269 dump_is_corrupt(&ga_text);
5270 if (ga_grow(&term->tl_scrollback, 1) == OK)
5271 {
5272 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5273 + term->tl_scrollback.ga_len;
5274
5275 if (max_cells < ga_cell.ga_len)
5276 max_cells = ga_cell.ga_len;
5277 line->sb_cols = ga_cell.ga_len;
5278 line->sb_cells = ga_cell.ga_data;
5279 line->sb_fill_attr = term->tl_default_color;
5280 ++term->tl_scrollback.ga_len;
5281 ga_init(&ga_cell);
5282
5283 ga_append(&ga_text, NUL);
5284 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5285 ga_text.ga_len, FALSE);
5286 }
5287 else
5288 ga_clear(&ga_cell);
5289 ga_text.ga_len = 0;
5290
5291 c = fgetc(fd);
5292 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005293 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005294 {
5295 int prev_len = ga_text.ga_len;
5296
Bram Moolenaar9271d052018-02-25 21:39:46 +01005297 if (c == '>')
5298 {
5299 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005300 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005301 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5302 cursor_pos->col = ga_cell.ga_len;
5303 }
5304
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005305 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005306 c = fgetc(fd);
5307 if (c != EOF)
5308 ga_append(&ga_text, c);
5309 for (;;)
5310 {
5311 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005312 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005313 || c == EOF || c == '\n')
5314 break;
5315 ga_append(&ga_text, c);
5316 }
5317
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005318 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005319 vim_free(prev_char);
5320 if (ga_text.ga_data != NULL)
5321 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5322 ga_text.ga_len - prev_len);
5323
Bram Moolenaar9271d052018-02-25 21:39:46 +01005324 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005325 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005326 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005327 }
5328 else if (c == '+' || c == '*')
5329 {
5330 int is_bg;
5331
5332 cell.width = c == '+' ? 1 : 2;
5333
5334 c = fgetc(fd);
5335 if (c == '&')
5336 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005337 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005338 c = fgetc(fd);
5339 }
5340 else if (isdigit(c))
5341 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005342 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005343 attr = 0;
5344 while (isdigit(c))
5345 {
5346 attr = attr * 10 + (c - '0');
5347 c = fgetc(fd);
5348 }
5349 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005350
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005351 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005352 for (is_bg = 0; is_bg <= 1; ++is_bg)
5353 {
5354 if (c == '&')
5355 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005356 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005357 c = fgetc(fd);
5358 }
5359 else if (c == '#')
5360 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005361 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005362
5363 c = fgetc(fd);
5364 red = hex2nr(c);
5365 c = fgetc(fd);
5366 red = (red << 4) + hex2nr(c);
5367 c = fgetc(fd);
5368 green = hex2nr(c);
5369 c = fgetc(fd);
5370 green = (green << 4) + hex2nr(c);
5371 c = fgetc(fd);
5372 blue = hex2nr(c);
5373 c = fgetc(fd);
5374 blue = (blue << 4) + hex2nr(c);
5375 c = fgetc(fd);
5376 if (!isdigit(c))
5377 dump_is_corrupt(&ga_text);
5378 while (isdigit(c))
5379 {
5380 index = index * 10 + (c - '0');
5381 c = fgetc(fd);
5382 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005383 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005384 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005385 type = VTERM_COLOR_RGB;
5386 if (index == 0)
5387 {
5388 if (is_bg)
5389 type |= VTERM_COLOR_DEFAULT_BG;
5390 else
5391 type |= VTERM_COLOR_DEFAULT_FG;
5392 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005393 }
5394 else
5395 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005396 type = VTERM_COLOR_INDEXED;
5397 index -= 1;
5398 }
5399 if (is_bg)
5400 {
5401 cell.bg.type = type;
5402 cell.bg.red = red;
5403 cell.bg.green = green;
5404 cell.bg.blue = blue;
5405 cell.bg.index = index;
5406 }
5407 else
5408 {
5409 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005410 cell.fg.red = red;
5411 cell.fg.green = green;
5412 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005413 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005414 }
5415 }
5416 else
5417 dump_is_corrupt(&ga_text);
5418 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005419 }
5420 else
5421 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005422 }
5423 else
5424 dump_is_corrupt(&ga_text);
5425
5426 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005427 if (cell.width == 2)
5428 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005429 }
5430 else if (c == '@')
5431 {
5432 if (prev_char == NULL)
5433 dump_is_corrupt(&ga_text);
5434 else
5435 {
5436 int count = 0;
5437
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005438 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005439 for (;;)
5440 {
5441 c = fgetc(fd);
5442 if (!isdigit(c))
5443 break;
5444 count = count * 10 + (c - '0');
5445 }
5446
5447 while (count-- > 0)
5448 {
5449 ga_concat(&ga_text, prev_char);
5450 append_cell(&ga_cell, &cell);
5451 }
5452 }
5453 }
5454 else
5455 {
5456 dump_is_corrupt(&ga_text);
5457 c = fgetc(fd);
5458 }
5459 }
5460
5461 if (ga_text.ga_len > 0)
5462 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005463 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005464 dump_is_corrupt(&ga_text);
5465 ga_append(&ga_text, NUL);
5466 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5467 ga_text.ga_len, FALSE);
5468 }
5469
5470 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005471 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005472 vim_free(prev_char);
5473
5474 return max_cells;
5475}
5476
5477/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005478 * Return an allocated string with at least "text_width" "=" characters and
5479 * "fname" inserted in the middle.
5480 */
5481 static char_u *
5482get_separator(int text_width, char_u *fname)
5483{
5484 int width = MAX(text_width, curwin->w_width);
5485 char_u *textline;
5486 int fname_size;
5487 char_u *p = fname;
5488 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005489 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005490
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005491 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005492 if (textline == NULL)
5493 return NULL;
5494
5495 fname_size = vim_strsize(fname);
5496 if (fname_size < width - 8)
5497 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005498 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005499 width = MAX(text_width, fname_size + 8);
5500 }
5501 else if (fname_size > width - 8)
5502 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005503 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005504 p = gettail(fname);
5505 fname_size = vim_strsize(p);
5506 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005507 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005508 while (fname_size > width - 8)
5509 {
5510 p += (*mb_ptr2len)(p);
5511 fname_size = vim_strsize(p);
5512 }
5513
5514 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5515 textline[i] = '=';
5516 textline[i++] = ' ';
5517
5518 STRCPY(textline + i, p);
5519 off = STRLEN(textline);
5520 textline[off] = ' ';
5521 for (i = 1; i < (width - fname_size) / 2; ++i)
5522 textline[off + i] = '=';
5523 textline[off + i] = NUL;
5524
5525 return textline;
5526}
5527
5528/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005529 * Common for "term_dumpdiff()" and "term_dumpload()".
5530 */
5531 static void
5532term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5533{
5534 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005535 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005536 char_u buf1[NUMBUFLEN];
5537 char_u buf2[NUMBUFLEN];
5538 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005539 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005540 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005541 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005542 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005543 char_u *textline = NULL;
5544
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005545 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005546 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005547 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005548 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005549 if (fname1 == NULL || (do_diff && fname2 == NULL))
5550 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005551 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005552 return;
5553 }
5554 fd1 = mch_fopen((char *)fname1, READBIN);
5555 if (fd1 == NULL)
5556 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005557 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005558 return;
5559 }
5560 if (do_diff)
5561 {
5562 fd2 = mch_fopen((char *)fname2, READBIN);
5563 if (fd2 == NULL)
5564 {
5565 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005566 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005567 return;
5568 }
5569 }
5570
5571 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005572 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5573 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5574 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5575 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5576 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005577
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005578 if (opt.jo_term_name == NULL)
5579 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005580 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005581
Bram Moolenaar51e14382019-05-25 20:21:28 +02005582 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005583 if (fname_tofree != NULL)
5584 {
5585 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5586 opt.jo_term_name = fname_tofree;
5587 }
5588 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005589
Bram Moolenaar87abab92019-06-03 21:14:59 +02005590 if (opt.jo_bufnr_buf != NULL)
5591 {
5592 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5593
5594 // With "bufnr" argument: enter the window with this buffer and make it
5595 // empty.
5596 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005597 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005598 else
5599 {
5600 buf = curbuf;
5601 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005602 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005603 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005604 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005605 }
5606 }
5607 else
5608 // Create a new terminal window.
5609 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5610
Bram Moolenaard96ff162018-02-18 22:13:29 +01005611 if (buf != NULL && buf->b_term != NULL)
5612 {
5613 int i;
5614 linenr_T bot_lnum;
5615 linenr_T lnum;
5616 term_T *term = buf->b_term;
5617 int width;
5618 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005619 VTermPos cursor_pos1;
5620 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005621
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005622 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005623
Bram Moolenaard96ff162018-02-18 22:13:29 +01005624 rettv->vval.v_number = buf->b_fnum;
5625
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005626 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005627 width = read_dump_file(fd1, &cursor_pos1);
5628
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005629 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005630 if (cursor_pos1.row >= 0)
5631 {
5632 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5633 coladvance(cursor_pos1.col);
5634 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005635
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005636 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005637 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005638
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005639 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005640 if (!do_diff)
5641 goto theend;
5642
5643 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5644
Bram Moolenaar4a696342018-04-05 18:45:26 +02005645 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005646 if (textline == NULL)
5647 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005648 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5649 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5650 vim_free(textline);
5651
5652 textline = get_separator(width, fname2);
5653 if (textline == NULL)
5654 goto theend;
5655 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5656 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005657 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005658
5659 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005660 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005661 if (width2 > width)
5662 {
5663 vim_free(textline);
5664 textline = alloc(width2 + 1);
5665 if (textline == NULL)
5666 goto theend;
5667 width = width2;
5668 textline[width] = NUL;
5669 }
5670 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5671
5672 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5673 {
5674 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5675 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005676 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005677 for (i = 0; i < width; ++i)
5678 textline[i] = '-';
5679 }
5680 else
5681 {
5682 char_u *line1;
5683 char_u *line2;
5684 char_u *p1;
5685 char_u *p2;
5686 int col;
5687 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5688 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5689 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5690 ->sb_cells;
5691
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005692 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005693 line1 = vim_strsave(ml_get(lnum));
5694 if (line1 == NULL)
5695 break;
5696 p1 = line1;
5697
5698 line2 = ml_get(lnum + bot_lnum);
5699 p2 = line2;
5700 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5701 {
5702 int len1 = utfc_ptr2len(p1);
5703 int len2 = utfc_ptr2len(p2);
5704
5705 textline[col] = ' ';
5706 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005707 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005708 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005709 else if (lnum == cursor_pos1.row + 1
5710 && col == cursor_pos1.col
5711 && (cursor_pos1.row != cursor_pos2.row
5712 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005713 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005714 textline[col] = '>';
5715 else if (lnum == cursor_pos2.row + 1
5716 && col == cursor_pos2.col
5717 && (cursor_pos1.row != cursor_pos2.row
5718 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005719 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005720 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005721 else if (cellattr1 != NULL && cellattr2 != NULL)
5722 {
5723 if ((cellattr1 + col)->width
5724 != (cellattr2 + col)->width)
5725 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005726 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005727 &(cellattr2 + col)->fg))
5728 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005729 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005730 &(cellattr2 + col)->bg))
5731 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005732 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5733 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005734 textline[col] = 'a';
5735 }
5736 p1 += len1;
5737 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005738 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005739 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005740
5741 while (col < width)
5742 {
5743 if (*p1 == NUL && *p2 == NUL)
5744 textline[col] = '?';
5745 else if (*p1 == NUL)
5746 {
5747 textline[col] = '+';
5748 p2 += utfc_ptr2len(p2);
5749 }
5750 else
5751 {
5752 textline[col] = '-';
5753 p1 += utfc_ptr2len(p1);
5754 }
5755 ++col;
5756 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005757
5758 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005759 }
5760 if (add_empty_scrollback(term, &term->tl_default_color,
5761 term->tl_top_diff_rows) == OK)
5762 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5763 ++bot_lnum;
5764 }
5765
5766 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5767 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005768 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005769 for (i = 0; i < width; ++i)
5770 textline[i] = '+';
5771 if (add_empty_scrollback(term, &term->tl_default_color,
5772 term->tl_top_diff_rows) == OK)
5773 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5774 ++lnum;
5775 ++bot_lnum;
5776 }
5777
5778 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005779
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005780 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005781 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005782 }
5783
5784theend:
5785 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005786 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005787 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005788 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005789 fclose(fd2);
5790}
5791
5792/*
5793 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5794 * bottom files.
5795 * Return FAIL when this is not possible.
5796 */
5797 int
5798term_swap_diff()
5799{
5800 term_T *term = curbuf->b_term;
5801 linenr_T line_count;
5802 linenr_T top_rows;
5803 linenr_T bot_rows;
5804 linenr_T bot_start;
5805 linenr_T lnum;
5806 char_u *p;
5807 sb_line_T *sb_line;
5808
5809 if (term == NULL
5810 || !term_is_finished(curbuf)
5811 || term->tl_top_diff_rows == 0
5812 || term->tl_scrollback.ga_len == 0)
5813 return FAIL;
5814
5815 line_count = curbuf->b_ml.ml_line_count;
5816 top_rows = term->tl_top_diff_rows;
5817 bot_rows = term->tl_bot_diff_rows;
5818 bot_start = line_count - bot_rows;
5819 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5820
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005821 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005822 for (lnum = 1; lnum <= top_rows; ++lnum)
5823 {
5824 p = vim_strsave(ml_get(1));
5825 if (p == NULL)
5826 return OK;
5827 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005828 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005829 vim_free(p);
5830 }
5831
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005832 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005833 for (lnum = 1; lnum <= bot_rows; ++lnum)
5834 {
5835 p = vim_strsave(ml_get(bot_start + lnum));
5836 if (p == NULL)
5837 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005838 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005839 ml_append(lnum - 1, p, 0, FALSE);
5840 vim_free(p);
5841 }
5842
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005843 // move top title to bottom
5844 p = vim_strsave(ml_get(bot_rows + 1));
5845 if (p == NULL)
5846 return OK;
5847 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005848 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005849 vim_free(p);
5850
5851 // move bottom title to top
5852 p = vim_strsave(ml_get(line_count - top_rows));
5853 if (p == NULL)
5854 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005855 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005856 ml_append(bot_rows, p, 0, FALSE);
5857 vim_free(p);
5858
Bram Moolenaard96ff162018-02-18 22:13:29 +01005859 if (top_rows == bot_rows)
5860 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005861 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005862 for (lnum = 0; lnum < top_rows; ++lnum)
5863 {
5864 sb_line_T temp;
5865
5866 temp = *(sb_line + lnum);
5867 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5868 *(sb_line + bot_start + lnum) = temp;
5869 }
5870 }
5871 else
5872 {
5873 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005874 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005875
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005876 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005877 if (temp != NULL)
5878 {
5879 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5880 mch_memmove(term->tl_scrollback.ga_data,
5881 temp + bot_start,
5882 sizeof(sb_line_T) * bot_rows);
5883 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5884 temp + top_rows,
5885 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5886 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5887 + line_count - top_rows,
5888 temp,
5889 sizeof(sb_line_T) * top_rows);
5890 vim_free(temp);
5891 }
5892 }
5893
5894 term->tl_top_diff_rows = bot_rows;
5895 term->tl_bot_diff_rows = top_rows;
5896
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005897 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005898 return OK;
5899}
5900
5901/*
5902 * "term_dumpdiff(filename, filename, options)" function
5903 */
5904 void
5905f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5906{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005907 if (in_vim9script()
5908 && (check_for_string_arg(argvars, 0) == FAIL
5909 || check_for_string_arg(argvars, 1) == FAIL
5910 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5911 return;
5912
Bram Moolenaard96ff162018-02-18 22:13:29 +01005913 term_load_dump(argvars, rettv, TRUE);
5914}
5915
5916/*
5917 * "term_dumpload(filename, options)" function
5918 */
5919 void
5920f_term_dumpload(typval_T *argvars, typval_T *rettv)
5921{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005922 if (in_vim9script()
5923 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02005924 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005925 return;
5926
Bram Moolenaard96ff162018-02-18 22:13:29 +01005927 term_load_dump(argvars, rettv, FALSE);
5928}
5929
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005930/*
5931 * "term_getaltscreen(buf)" function
5932 */
5933 void
5934f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5935{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005936 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005937
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005938 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5939 return;
5940
5941 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005942 if (buf == NULL)
5943 return;
5944 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5945}
5946
5947/*
5948 * "term_getattr(attr, name)" function
5949 */
5950 void
5951f_term_getattr(typval_T *argvars, typval_T *rettv)
5952{
5953 int attr;
5954 size_t i;
5955 char_u *name;
5956
5957 static struct {
5958 char *name;
5959 int attr;
5960 } attrs[] = {
5961 {"bold", HL_BOLD},
5962 {"italic", HL_ITALIC},
5963 {"underline", HL_UNDERLINE},
5964 {"strike", HL_STRIKETHROUGH},
5965 {"reverse", HL_INVERSE},
5966 };
5967
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02005968 if (in_vim9script()
5969 && (check_for_number_arg(argvars, 0) == FAIL
5970 || check_for_string_arg(argvars, 1) == FAIL))
5971 return;
5972
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005973 attr = tv_get_number(&argvars[0]);
5974 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005975 if (name == NULL)
5976 return;
5977
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005978 if (attr > HL_ALL)
5979 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02005980 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005981 if (STRCMP(name, attrs[i].name) == 0)
5982 {
5983 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5984 break;
5985 }
5986}
5987
5988/*
5989 * "term_getcursor(buf)" function
5990 */
5991 void
5992f_term_getcursor(typval_T *argvars, typval_T *rettv)
5993{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005994 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005995 term_T *term;
5996 list_T *l;
5997 dict_T *d;
5998
5999 if (rettv_list_alloc(rettv) == FAIL)
6000 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006001
6002 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6003 return;
6004
6005 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006006 if (buf == NULL)
6007 return;
6008 term = buf->b_term;
6009
6010 l = rettv->vval.v_list;
6011 list_append_number(l, term->tl_cursor_pos.row + 1);
6012 list_append_number(l, term->tl_cursor_pos.col + 1);
6013
6014 d = dict_alloc();
6015 if (d != NULL)
6016 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02006017 dict_add_number(d, "visible", term->tl_cursor_visible);
6018 dict_add_number(d, "blink", blink_state_is_inverted()
6019 ? !term->tl_cursor_blink : term->tl_cursor_blink);
6020 dict_add_number(d, "shape", term->tl_cursor_shape);
6021 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006022 list_append_dict(l, d);
6023 }
6024}
6025
6026/*
6027 * "term_getjob(buf)" function
6028 */
6029 void
6030f_term_getjob(typval_T *argvars, typval_T *rettv)
6031{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006032 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006033
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006034 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6035 return;
6036
6037 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006038 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006039 {
6040 rettv->v_type = VAR_SPECIAL;
6041 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006042 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006043 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006044
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01006045 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006046 rettv->vval.v_job = buf->b_term->tl_job;
6047 if (rettv->vval.v_job != NULL)
6048 ++rettv->vval.v_job->jv_refcount;
6049}
6050
6051 static int
6052get_row_number(typval_T *tv, term_T *term)
6053{
6054 if (tv->v_type == VAR_STRING
6055 && tv->vval.v_string != NULL
6056 && STRCMP(tv->vval.v_string, ".") == 0)
6057 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006058 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006059}
6060
6061/*
6062 * "term_getline(buf, row)" function
6063 */
6064 void
6065f_term_getline(typval_T *argvars, typval_T *rettv)
6066{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006067 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006068 term_T *term;
6069 int row;
6070
6071 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006072
6073 if (in_vim9script()
6074 && (check_for_buffer_arg(argvars, 0) == FAIL
6075 || check_for_lnum_arg(argvars, 1) == FAIL))
6076 return;
6077
6078 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006079 if (buf == NULL)
6080 return;
6081 term = buf->b_term;
6082 row = get_row_number(&argvars[1], term);
6083
6084 if (term->tl_vterm == NULL)
6085 {
6086 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6087
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006088 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006089 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6090 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6091 }
6092 else
6093 {
6094 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6095 VTermRect rect;
6096 int len;
6097 char_u *p;
6098
6099 if (row < 0 || row >= term->tl_rows)
6100 return;
6101 len = term->tl_cols * MB_MAXBYTES + 1;
6102 p = alloc(len);
6103 if (p == NULL)
6104 return;
6105 rettv->vval.v_string = p;
6106
6107 rect.start_col = 0;
6108 rect.end_col = term->tl_cols;
6109 rect.start_row = row;
6110 rect.end_row = row + 1;
6111 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6112 }
6113}
6114
6115/*
6116 * "term_getscrolled(buf)" function
6117 */
6118 void
6119f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6120{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006121 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006122
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006123 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6124 return;
6125
6126 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006127 if (buf == NULL)
6128 return;
6129 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6130}
6131
6132/*
6133 * "term_getsize(buf)" function
6134 */
6135 void
6136f_term_getsize(typval_T *argvars, typval_T *rettv)
6137{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006138 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006139 list_T *l;
6140
6141 if (rettv_list_alloc(rettv) == FAIL)
6142 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006143
6144 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6145 return;
6146
6147 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006148 if (buf == NULL)
6149 return;
6150
6151 l = rettv->vval.v_list;
6152 list_append_number(l, buf->b_term->tl_rows);
6153 list_append_number(l, buf->b_term->tl_cols);
6154}
6155
6156/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006157 * "term_setsize(buf, rows, cols)" function
6158 */
6159 void
6160f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6161{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006162 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006163 term_T *term;
6164 varnumber_T rows, cols;
6165
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006166 if (in_vim9script()
6167 && (check_for_buffer_arg(argvars, 0) == FAIL
6168 || check_for_number_arg(argvars, 1) == FAIL
6169 || check_for_number_arg(argvars, 2) == FAIL))
6170 return;
6171
6172 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006173 if (buf == NULL)
6174 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006175 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006176 return;
6177 }
6178 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006179 return;
6180 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006181 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006182 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006183 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006184 cols = cols <= 0 ? term->tl_cols : cols;
6185 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006186 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006187
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006188 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006189 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6190 term_report_winsize(term, term->tl_rows, term->tl_cols);
6191}
6192
6193/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006194 * "term_getstatus(buf)" function
6195 */
6196 void
6197f_term_getstatus(typval_T *argvars, typval_T *rettv)
6198{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006199 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006200 term_T *term;
6201 char_u val[100];
6202
6203 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006204
6205 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6206 return;
6207
6208 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006209 if (buf == NULL)
6210 return;
6211 term = buf->b_term;
6212
6213 if (term_job_running(term))
6214 STRCPY(val, "running");
6215 else
6216 STRCPY(val, "finished");
6217 if (term->tl_normal_mode)
6218 STRCAT(val, ",normal");
6219 rettv->vval.v_string = vim_strsave(val);
6220}
6221
6222/*
6223 * "term_gettitle(buf)" function
6224 */
6225 void
6226f_term_gettitle(typval_T *argvars, typval_T *rettv)
6227{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006228 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006229
6230 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006231
6232 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6233 return;
6234
6235 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006236 if (buf == NULL)
6237 return;
6238
6239 if (buf->b_term->tl_title != NULL)
6240 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6241}
6242
6243/*
6244 * "term_gettty(buf)" function
6245 */
6246 void
6247f_term_gettty(typval_T *argvars, typval_T *rettv)
6248{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006249 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006250 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006251 int num = 0;
6252
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006253 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006254 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006255 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6256 return;
6257
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006258 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006259 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006260 if (buf == NULL)
6261 return;
6262 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006263 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006264
6265 switch (num)
6266 {
6267 case 0:
6268 if (buf->b_term->tl_job != NULL)
6269 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006270 break;
6271 case 1:
6272 if (buf->b_term->tl_job != NULL)
6273 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006274 break;
6275 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006276 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006277 return;
6278 }
6279 if (p != NULL)
6280 rettv->vval.v_string = vim_strsave(p);
6281}
6282
6283/*
6284 * "term_list()" function
6285 */
6286 void
6287f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6288{
6289 term_T *tp;
6290 list_T *l;
6291
6292 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6293 return;
6294
6295 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006296 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006297 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006298 if (list_append_number(l,
6299 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6300 return;
6301}
6302
6303/*
6304 * "term_scrape(buf, row)" function
6305 */
6306 void
6307f_term_scrape(typval_T *argvars, typval_T *rettv)
6308{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006309 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006310 VTermScreen *screen = NULL;
6311 VTermPos pos;
6312 list_T *l;
6313 term_T *term;
6314 char_u *p;
6315 sb_line_T *line;
6316
6317 if (rettv_list_alloc(rettv) == FAIL)
6318 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006319
6320 if (in_vim9script()
6321 && (check_for_buffer_arg(argvars, 0) == FAIL
6322 || check_for_lnum_arg(argvars, 1) == FAIL))
6323 return;
6324
6325 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006326 if (buf == NULL)
6327 return;
6328 term = buf->b_term;
6329
6330 l = rettv->vval.v_list;
6331 pos.row = get_row_number(&argvars[1], term);
6332
6333 if (term->tl_vterm != NULL)
6334 {
6335 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006336 if (screen == NULL) // can't really happen
6337 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006338 p = NULL;
6339 line = NULL;
6340 }
6341 else
6342 {
6343 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6344
6345 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6346 return;
6347 p = ml_get_buf(buf, lnum + 1, FALSE);
6348 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6349 }
6350
6351 for (pos.col = 0; pos.col < term->tl_cols; )
6352 {
6353 dict_T *dcell;
6354 int width;
6355 VTermScreenCellAttrs attrs;
6356 VTermColor fg, bg;
6357 char_u rgb[8];
6358 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6359 int off = 0;
6360 int i;
6361
6362 if (screen == NULL)
6363 {
6364 cellattr_T *cellattr;
6365 int len;
6366
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006367 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006368 if (pos.col >= line->sb_cols)
6369 break;
6370 cellattr = line->sb_cells + pos.col;
6371 width = cellattr->width;
6372 attrs = cellattr->attrs;
6373 fg = cellattr->fg;
6374 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006375 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006376 mch_memmove(mbs, p, len);
6377 mbs[len] = NUL;
6378 p += len;
6379 }
6380 else
6381 {
6382 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006383
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006384 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6385 break;
6386 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6387 {
6388 if (cell.chars[i] == 0)
6389 break;
6390 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6391 }
6392 mbs[off] = NUL;
6393 width = cell.width;
6394 attrs = cell.attrs;
6395 fg = cell.fg;
6396 bg = cell.bg;
6397 }
6398 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006399 if (dcell == NULL)
6400 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006401 list_append_dict(l, dcell);
6402
Bram Moolenaare0be1672018-07-08 16:50:37 +02006403 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006404
6405 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6406 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006407 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006408 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6409 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006410 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006411
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006412 dict_add_number(dcell, "attr",
6413 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006414 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006415
6416 ++pos.col;
6417 if (width == 2)
6418 ++pos.col;
6419 }
6420}
6421
6422/*
6423 * "term_sendkeys(buf, keys)" function
6424 */
6425 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006426f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006427{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006428 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006429 char_u *msg;
6430 term_T *term;
6431
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006432 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006433 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006434 || check_for_string_arg(argvars, 1) == FAIL))
6435 return;
6436
6437 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006438 if (buf == NULL)
6439 return;
6440
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006441 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006442 if (msg == NULL)
6443 return;
6444 term = buf->b_term;
6445 if (term->tl_vterm == NULL)
6446 return;
6447
6448 while (*msg != NUL)
6449 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006450 int c;
6451
6452 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6453 {
6454 c = TO_SPECIAL(msg[1], msg[2]);
6455 msg += 3;
6456 }
6457 else
6458 {
6459 c = PTR2CHAR(msg);
6460 msg += MB_CPTR2LEN(msg);
6461 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006462 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006463 }
6464}
6465
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006466#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6467/*
6468 * "term_getansicolors(buf)" function
6469 */
6470 void
6471f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6472{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006473 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006474 term_T *term;
6475 VTermState *state;
6476 VTermColor color;
6477 char_u hexbuf[10];
6478 int index;
6479 list_T *list;
6480
6481 if (rettv_list_alloc(rettv) == FAIL)
6482 return;
6483
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006484 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6485 return;
6486
6487 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006488 if (buf == NULL)
6489 return;
6490 term = buf->b_term;
6491 if (term->tl_vterm == NULL)
6492 return;
6493
6494 list = rettv->vval.v_list;
6495 state = vterm_obtain_state(term->tl_vterm);
6496 for (index = 0; index < 16; index++)
6497 {
6498 vterm_state_get_palette_color(state, index, &color);
6499 sprintf((char *)hexbuf, "#%02x%02x%02x",
6500 color.red, color.green, color.blue);
6501 if (list_append_string(list, hexbuf, 7) == FAIL)
6502 return;
6503 }
6504}
6505
6506/*
6507 * "term_setansicolors(buf, list)" function
6508 */
6509 void
6510f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6511{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006512 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006513 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006514 listitem_T *li;
6515 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006516
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006517 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006518 && (check_for_buffer_arg(argvars, 0) == FAIL
6519 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006520 return;
6521
6522 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006523 if (buf == NULL)
6524 return;
6525 term = buf->b_term;
6526 if (term->tl_vterm == NULL)
6527 return;
6528
Bram Moolenaard83392a2022-09-01 12:22:46 +01006529 if (check_for_nonnull_list_arg(argvars, 1) == FAIL)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006530 return;
Bram Moolenaard83392a2022-09-01 12:22:46 +01006531
LemonBoyb2b3acb2022-05-20 10:10:34 +01006532 if (argvars[1].vval.v_list->lv_first == &range_list_item
6533 || argvars[1].vval.v_list->lv_len != 16)
6534 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006535 emsg(_(e_invalid_argument));
LemonBoyb2b3acb2022-05-20 10:10:34 +01006536 return;
6537 }
6538
6539 if (term->tl_palette == NULL)
6540 term->tl_palette = ALLOC_MULT(long_u, 16);
6541 if (term->tl_palette == NULL)
6542 return;
6543
6544 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6545 {
6546 char_u *color_name;
6547 guicolor_T guicolor;
6548
6549 color_name = tv_get_string_chk(&li->li_tv);
6550 if (color_name == NULL)
6551 return;
6552
6553 guicolor = GUI_GET_COLOR(color_name);
6554 if (guicolor == INVALCOLOR)
6555 {
6556 semsg(_(e_cannot_allocate_color_str), color_name);
6557 return;
6558 }
6559
6560 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6561 }
6562
6563 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006564}
6565#endif
6566
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006567/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006568 * "term_setapi(buf, api)" function
6569 */
6570 void
6571f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6572{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006573 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006574 term_T *term;
6575 char_u *api;
6576
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006577 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006578 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006579 || check_for_string_arg(argvars, 1) == FAIL))
6580 return;
6581
6582 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006583 if (buf == NULL)
6584 return;
6585 term = buf->b_term;
6586 vim_free(term->tl_api);
6587 api = tv_get_string_chk(&argvars[1]);
6588 if (api != NULL)
6589 term->tl_api = vim_strsave(api);
6590 else
6591 term->tl_api = NULL;
6592}
6593
6594/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006595 * "term_setrestore(buf, command)" function
6596 */
6597 void
6598f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6599{
6600#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006601 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006602 term_T *term;
6603 char_u *cmd;
6604
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006605 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006606 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006607 || check_for_string_arg(argvars, 1) == FAIL))
6608 return;
6609
6610 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006611 if (buf == NULL)
6612 return;
6613 term = buf->b_term;
6614 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006615 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006616 if (cmd != NULL)
6617 term->tl_command = vim_strsave(cmd);
6618 else
6619 term->tl_command = NULL;
6620#endif
6621}
6622
6623/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006624 * "term_setkill(buf, how)" function
6625 */
6626 void
6627f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6628{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006629 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006630 term_T *term;
6631 char_u *how;
6632
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006633 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006634 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006635 || check_for_string_arg(argvars, 1) == FAIL))
6636 return;
6637
6638 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006639 if (buf == NULL)
6640 return;
6641 term = buf->b_term;
6642 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006643 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006644 if (how != NULL)
6645 term->tl_kill = vim_strsave(how);
6646 else
6647 term->tl_kill = NULL;
6648}
6649
6650/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006651 * "term_start(command, options)" function
6652 */
6653 void
6654f_term_start(typval_T *argvars, typval_T *rettv)
6655{
6656 jobopt_T opt;
6657 buf_T *buf;
6658
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006659 if (in_vim9script()
6660 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6661 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6662 return;
6663
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006664 init_job_options(&opt);
6665 if (argvars[1].v_type != VAR_UNKNOWN
6666 && get_job_options(&argvars[1], &opt,
6667 JO_TIMEOUT_ALL + JO_STOPONEXIT
6668 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6669 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6670 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6671 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006672 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006673 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006674 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006675 return;
6676
Bram Moolenaar13568252018-03-16 20:46:58 +01006677 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006678
6679 if (buf != NULL && buf->b_term != NULL)
6680 rettv->vval.v_number = buf->b_fnum;
6681}
6682
6683/*
6684 * "term_wait" function
6685 */
6686 void
6687f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6688{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006689 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006690
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006691 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006692 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006693 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006694 return;
6695
6696 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006697 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006698 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006699 if (buf->b_term->tl_job == NULL)
6700 {
6701 ch_log(NULL, "term_wait(): no job to wait for");
6702 return;
6703 }
6704 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006705 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006706 return;
6707
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006708 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006709 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006710 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6711 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006712 // The job is dead, keep reading channel I/O until the channel is
6713 // closed. buf->b_term may become NULL if the terminal was closed while
6714 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006715 ch_log(NULL, "term_wait(): waiting for channel to close");
6716 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6717 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006718 term_flush_messages();
6719
Bram Moolenaard45aa552018-05-21 22:50:29 +02006720 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006721 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006722 // If the terminal is closed when the channel is closed the
6723 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006724 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006725 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6726 // came here from a close callback, only wait one time
6727 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006728 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006729
6730 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006731 }
6732 else
6733 {
6734 long wait = 10L;
6735
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006736 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006737
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006738 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006739 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006740 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006741 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006742
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006743 // Flushing messages on channels is hopefully sufficient.
6744 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006745 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006746 }
6747}
6748
6749/*
6750 * Called when a channel has sent all the lines to a terminal.
6751 * Send a CTRL-D to mark the end of the text.
6752 */
6753 void
6754term_send_eof(channel_T *ch)
6755{
6756 term_T *term;
6757
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006758 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006759 if (term->tl_job == ch->ch_job)
6760 {
6761 if (term->tl_eof_chars != NULL)
6762 {
6763 channel_send(ch, PART_IN, term->tl_eof_chars,
6764 (int)STRLEN(term->tl_eof_chars), NULL);
6765 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6766 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006767# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006768 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006769 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006770 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6771# endif
6772 }
6773}
6774
Bram Moolenaar113e1072019-01-20 15:30:40 +01006775#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006776 job_T *
6777term_getjob(term_T *term)
6778{
6779 return term != NULL ? term->tl_job : NULL;
6780}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006781#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006782
Bram Moolenaar4f974752019-02-17 17:44:42 +01006783# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006784
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006785///////////////////////////////////////
6786// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006787#ifdef PROTO
6788typedef int COORD;
6789typedef int DWORD;
6790typedef int HANDLE;
6791typedef int *DWORD_PTR;
6792typedef int HPCON;
6793typedef int HRESULT;
6794typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006795typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006796typedef int PSIZE_T;
6797typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006798typedef int BOOL;
6799# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006800#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006801
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006802HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6803HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6804HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006805BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6806BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6807void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006808
6809 static int
6810dyn_conpty_init(int verbose)
6811{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006812 static HMODULE hKerneldll = NULL;
6813 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006814 static struct
6815 {
6816 char *name;
6817 FARPROC *ptr;
6818 } conpty_entry[] =
6819 {
6820 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6821 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6822 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6823 {"InitializeProcThreadAttributeList",
6824 (FARPROC*)&pInitializeProcThreadAttributeList},
6825 {"UpdateProcThreadAttribute",
6826 (FARPROC*)&pUpdateProcThreadAttribute},
6827 {"DeleteProcThreadAttributeList",
6828 (FARPROC*)&pDeleteProcThreadAttributeList},
6829 {NULL, NULL}
6830 };
6831
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006832 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006833 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006834 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006835 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006836 return FAIL;
6837 }
6838
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006839 // No need to initialize twice.
6840 if (hKerneldll)
6841 return OK;
6842
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006843 hKerneldll = vimLoadLib("kernel32.dll");
6844 for (i = 0; conpty_entry[i].name != NULL
6845 && conpty_entry[i].ptr != NULL; ++i)
6846 {
6847 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6848 conpty_entry[i].name)) == NULL)
6849 {
6850 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006851 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006852 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006853 return FAIL;
6854 }
6855 }
6856
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006857 return OK;
6858}
6859
6860 static int
6861conpty_term_and_job_init(
6862 term_T *term,
6863 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006864 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006865 jobopt_T *opt,
6866 jobopt_T *orig_opt)
6867{
6868 WCHAR *cmd_wchar = NULL;
6869 WCHAR *cmd_wchar_copy = NULL;
6870 WCHAR *cwd_wchar = NULL;
6871 WCHAR *env_wchar = NULL;
6872 channel_T *channel = NULL;
6873 job_T *job = NULL;
6874 HANDLE jo = NULL;
6875 garray_T ga_cmd, ga_env;
6876 char_u *cmd = NULL;
6877 HRESULT hr;
6878 COORD consize;
6879 SIZE_T breq;
6880 PROCESS_INFORMATION proc_info;
6881 HANDLE i_theirs = NULL;
6882 HANDLE o_theirs = NULL;
6883 HANDLE i_ours = NULL;
6884 HANDLE o_ours = NULL;
6885
Bram Moolenaar04935fb2022-01-08 16:19:22 +00006886 ga_init2(&ga_cmd, sizeof(char*), 20);
6887 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006888
6889 if (argvar->v_type == VAR_STRING)
6890 {
6891 cmd = argvar->vval.v_string;
6892 }
6893 else if (argvar->v_type == VAR_LIST)
6894 {
6895 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6896 goto failed;
6897 cmd = ga_cmd.ga_data;
6898 }
6899 if (cmd == NULL || *cmd == NUL)
6900 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006901 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006902 goto failed;
6903 }
6904
6905 term->tl_arg0_cmd = vim_strsave(cmd);
6906
6907 cmd_wchar = enc_to_utf16(cmd, NULL);
6908
6909 if (cmd_wchar != NULL)
6910 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006911 // Request by CreateProcessW
6912 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006913 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006914 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6915 }
6916
6917 ga_clear(&ga_cmd);
6918 if (cmd_wchar == NULL)
6919 goto failed;
6920 if (opt->jo_cwd != NULL)
6921 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6922
6923 win32_build_env(opt->jo_env, &ga_env, TRUE);
6924 env_wchar = ga_env.ga_data;
6925
6926 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6927 goto failed;
6928 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6929 goto failed;
6930
6931 consize.X = term->tl_cols;
6932 consize.Y = term->tl_rows;
6933 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6934 &term->tl_conpty);
6935 if (FAILED(hr))
6936 goto failed;
6937
6938 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6939
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006940 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006941 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006942 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006943 if (!term->tl_siex.lpAttributeList)
6944 goto failed;
6945 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6946 0, &breq))
6947 goto failed;
6948 if (!pUpdateProcThreadAttribute(
6949 term->tl_siex.lpAttributeList, 0,
6950 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6951 sizeof(HPCON), NULL, NULL))
6952 goto failed;
6953
6954 channel = add_channel();
6955 if (channel == NULL)
6956 goto failed;
6957
6958 job = job_alloc();
6959 if (job == NULL)
6960 goto failed;
6961 if (argvar->v_type == VAR_STRING)
6962 {
6963 int argc;
6964
6965 build_argv_from_string(cmd, &job->jv_argv, &argc);
6966 }
6967 else
6968 {
6969 int argc;
6970
6971 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6972 }
6973
6974 if (opt->jo_set & JO_IN_BUF)
6975 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6976
6977 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6978 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02006979 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006980 env_wchar, cwd_wchar,
6981 &term->tl_siex.StartupInfo, &proc_info))
6982 goto failed;
6983
6984 CloseHandle(i_theirs);
6985 CloseHandle(o_theirs);
6986
6987 channel_set_pipes(channel,
6988 (sock_T)i_ours,
6989 (sock_T)o_ours,
6990 (sock_T)o_ours);
6991
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006992 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006993 channel->ch_write_text_mode = TRUE;
6994
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006995 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006996 channel->ch_anonymous_pipe = TRUE;
6997
6998 jo = CreateJobObject(NULL, NULL);
6999 if (jo == NULL)
7000 goto failed;
7001
7002 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
7003 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007004 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007005 CloseHandle(jo);
7006 jo = NULL;
7007 }
7008
7009 ResumeThread(proc_info.hThread);
7010 CloseHandle(proc_info.hThread);
7011
7012 vim_free(cmd_wchar);
7013 vim_free(cmd_wchar_copy);
7014 vim_free(cwd_wchar);
7015 vim_free(env_wchar);
7016
7017 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7018 goto failed;
7019
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007020#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007021 if (term_use_palette())
7022 {
7023 if (term->tl_palette != NULL)
7024 set_vterm_palette(term->tl_vterm, term->tl_palette);
7025 else
7026 init_vterm_ansi_colors(term->tl_vterm);
7027 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007028#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007029
7030 channel_set_job(channel, job, opt);
7031 job_set_options(job, opt);
7032
7033 job->jv_channel = channel;
7034 job->jv_proc_info = proc_info;
7035 job->jv_job_object = jo;
7036 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007037 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007038 ++job->jv_refcount;
7039 term->tl_job = job;
7040
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007041 // Redirecting stdout and stderr doesn't work at the job level. Instead
7042 // open the file here and handle it in. opt->jo_io was changed in
7043 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007044 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7045 {
7046 char_u *fname = opt->jo_io_name[PART_OUT];
7047
7048 ch_log(channel, "Opening output file %s", fname);
7049 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7050 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007051 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007052 }
7053
7054 return OK;
7055
7056failed:
7057 ga_clear(&ga_cmd);
7058 ga_clear(&ga_env);
7059 vim_free(cmd_wchar);
7060 vim_free(cmd_wchar_copy);
7061 vim_free(cwd_wchar);
7062 if (channel != NULL)
7063 channel_clear(channel);
7064 if (job != NULL)
7065 {
7066 job->jv_channel = NULL;
7067 job_cleanup(job);
7068 }
7069 term->tl_job = NULL;
7070 if (jo != NULL)
7071 CloseHandle(jo);
7072
7073 if (term->tl_siex.lpAttributeList != NULL)
7074 {
7075 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7076 vim_free(term->tl_siex.lpAttributeList);
7077 }
7078 term->tl_siex.lpAttributeList = NULL;
7079 if (o_theirs != NULL)
7080 CloseHandle(o_theirs);
7081 if (o_ours != NULL)
7082 CloseHandle(o_ours);
7083 if (i_ours != NULL)
7084 CloseHandle(i_ours);
7085 if (i_theirs != NULL)
7086 CloseHandle(i_theirs);
7087 if (term->tl_conpty != NULL)
7088 pClosePseudoConsole(term->tl_conpty);
7089 term->tl_conpty = NULL;
7090 return FAIL;
7091}
7092
7093 static void
7094conpty_term_report_winsize(term_T *term, int rows, int cols)
7095{
7096 COORD consize;
7097
7098 consize.X = cols;
7099 consize.Y = rows;
7100 pResizePseudoConsole(term->tl_conpty, consize);
7101}
7102
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007103 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007104term_free_conpty(term_T *term)
7105{
7106 if (term->tl_siex.lpAttributeList != NULL)
7107 {
7108 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7109 vim_free(term->tl_siex.lpAttributeList);
7110 }
7111 term->tl_siex.lpAttributeList = NULL;
7112 if (term->tl_conpty != NULL)
7113 pClosePseudoConsole(term->tl_conpty);
7114 term->tl_conpty = NULL;
7115}
7116
7117 int
7118use_conpty(void)
7119{
7120 return has_conpty;
7121}
7122
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007123# ifndef PROTO
7124
7125#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7126#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007127#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007128
7129void* (*winpty_config_new)(UINT64, void*);
7130void* (*winpty_open)(void*, void*);
7131void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7132BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7133void (*winpty_config_set_mouse_mode)(void*, int);
7134void (*winpty_config_set_initial_size)(void*, int, int);
7135LPCWSTR (*winpty_conin_name)(void*);
7136LPCWSTR (*winpty_conout_name)(void*);
7137LPCWSTR (*winpty_conerr_name)(void*);
7138void (*winpty_free)(void*);
7139void (*winpty_config_free)(void*);
7140void (*winpty_spawn_config_free)(void*);
7141void (*winpty_error_free)(void*);
7142LPCWSTR (*winpty_error_msg)(void*);
7143BOOL (*winpty_set_size)(void*, int, int, void*);
7144HANDLE (*winpty_agent_process)(void*);
7145
7146#define WINPTY_DLL "winpty.dll"
7147
7148static HINSTANCE hWinPtyDLL = NULL;
7149# endif
7150
7151 static int
7152dyn_winpty_init(int verbose)
7153{
7154 int i;
7155 static struct
7156 {
7157 char *name;
7158 FARPROC *ptr;
7159 } winpty_entry[] =
7160 {
7161 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7162 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7163 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7164 {"winpty_config_set_mouse_mode",
7165 (FARPROC*)&winpty_config_set_mouse_mode},
7166 {"winpty_config_set_initial_size",
7167 (FARPROC*)&winpty_config_set_initial_size},
7168 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7169 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7170 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7171 {"winpty_free", (FARPROC*)&winpty_free},
7172 {"winpty_open", (FARPROC*)&winpty_open},
7173 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7174 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7175 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7176 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7177 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7178 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7179 {NULL, NULL}
7180 };
7181
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007182 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007183 if (hWinPtyDLL)
7184 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007185 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7186 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007187 if (*p_winptydll != NUL)
7188 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7189 if (!hWinPtyDLL)
7190 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7191 if (!hWinPtyDLL)
7192 {
7193 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007194 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007195 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7196 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007197 return FAIL;
7198 }
7199 for (i = 0; winpty_entry[i].name != NULL
7200 && winpty_entry[i].ptr != NULL; ++i)
7201 {
7202 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7203 winpty_entry[i].name)) == NULL)
7204 {
7205 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007206 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007207 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007208 return FAIL;
7209 }
7210 }
7211
7212 return OK;
7213}
7214
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007215 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007216winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007217 term_T *term,
7218 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007219 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007220 jobopt_T *opt,
7221 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007222{
7223 WCHAR *cmd_wchar = NULL;
7224 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007225 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007226 channel_T *channel = NULL;
7227 job_T *job = NULL;
7228 DWORD error;
7229 HANDLE jo = NULL;
7230 HANDLE child_process_handle;
7231 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007232 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007233 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007234 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007235 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007236
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007237 ga_init2(&ga_cmd, sizeof(char*), 20);
7238 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007239
7240 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007241 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007242 cmd = argvar->vval.v_string;
7243 }
7244 else if (argvar->v_type == VAR_LIST)
7245 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007246 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007247 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007248 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007249 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007250 if (cmd == NULL || *cmd == NUL)
7251 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007252 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007253 goto failed;
7254 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007255
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007256 term->tl_arg0_cmd = vim_strsave(cmd);
7257
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007258 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007259 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007260 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007261 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007262 if (opt->jo_cwd != NULL)
7263 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007264
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007265 win32_build_env(opt->jo_env, &ga_env, TRUE);
7266 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007267
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007268 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7269 if (term->tl_winpty_config == NULL)
7270 goto failed;
7271
7272 winpty_config_set_mouse_mode(term->tl_winpty_config,
7273 WINPTY_MOUSE_MODE_FORCE);
7274 winpty_config_set_initial_size(term->tl_winpty_config,
7275 term->tl_cols, term->tl_rows);
7276 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7277 if (term->tl_winpty == NULL)
7278 goto failed;
7279
7280 spawn_config = winpty_spawn_config_new(
7281 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7282 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7283 NULL,
7284 cmd_wchar,
7285 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007286 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007287 &winpty_err);
7288 if (spawn_config == NULL)
7289 goto failed;
7290
7291 channel = add_channel();
7292 if (channel == NULL)
7293 goto failed;
7294
7295 job = job_alloc();
7296 if (job == NULL)
7297 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007298 if (argvar->v_type == VAR_STRING)
7299 {
7300 int argc;
7301
7302 build_argv_from_string(cmd, &job->jv_argv, &argc);
7303 }
7304 else
7305 {
7306 int argc;
7307
7308 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7309 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007310
7311 if (opt->jo_set & JO_IN_BUF)
7312 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7313
7314 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7315 &child_thread_handle, &error, &winpty_err))
7316 goto failed;
7317
7318 channel_set_pipes(channel,
7319 (sock_T)CreateFileW(
7320 winpty_conin_name(term->tl_winpty),
7321 GENERIC_WRITE, 0, NULL,
7322 OPEN_EXISTING, 0, NULL),
7323 (sock_T)CreateFileW(
7324 winpty_conout_name(term->tl_winpty),
7325 GENERIC_READ, 0, NULL,
7326 OPEN_EXISTING, 0, NULL),
7327 (sock_T)CreateFileW(
7328 winpty_conerr_name(term->tl_winpty),
7329 GENERIC_READ, 0, NULL,
7330 OPEN_EXISTING, 0, NULL));
7331
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007332 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007333 channel->ch_write_text_mode = TRUE;
7334
7335 jo = CreateJobObject(NULL, NULL);
7336 if (jo == NULL)
7337 goto failed;
7338
7339 if (!AssignProcessToJobObject(jo, child_process_handle))
7340 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007341 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007342 CloseHandle(jo);
7343 jo = NULL;
7344 }
7345
7346 winpty_spawn_config_free(spawn_config);
7347 vim_free(cmd_wchar);
7348 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007349 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007350
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007351 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7352 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007353
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007354#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007355 if (term_use_palette())
7356 {
7357 if (term->tl_palette != NULL)
7358 set_vterm_palette(term->tl_vterm, term->tl_palette);
7359 else
7360 init_vterm_ansi_colors(term->tl_vterm);
7361 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007362#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007363
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007364 channel_set_job(channel, job, opt);
7365 job_set_options(job, opt);
7366
7367 job->jv_channel = channel;
7368 job->jv_proc_info.hProcess = child_process_handle;
7369 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7370 job->jv_job_object = jo;
7371 job->jv_status = JOB_STARTED;
7372 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007373 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007374 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007375 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007376 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007377 ++job->jv_refcount;
7378 term->tl_job = job;
7379
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007380 // Redirecting stdout and stderr doesn't work at the job level. Instead
7381 // open the file here and handle it in. opt->jo_io was changed in
7382 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007383 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7384 {
7385 char_u *fname = opt->jo_io_name[PART_OUT];
7386
7387 ch_log(channel, "Opening output file %s", fname);
7388 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7389 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007390 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007391 }
7392
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007393 return OK;
7394
7395failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007396 ga_clear(&ga_cmd);
7397 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007398 vim_free(cmd_wchar);
7399 vim_free(cwd_wchar);
7400 if (spawn_config != NULL)
7401 winpty_spawn_config_free(spawn_config);
7402 if (channel != NULL)
7403 channel_clear(channel);
7404 if (job != NULL)
7405 {
7406 job->jv_channel = NULL;
7407 job_cleanup(job);
7408 }
7409 term->tl_job = NULL;
7410 if (jo != NULL)
7411 CloseHandle(jo);
7412 if (term->tl_winpty != NULL)
7413 winpty_free(term->tl_winpty);
7414 term->tl_winpty = NULL;
7415 if (term->tl_winpty_config != NULL)
7416 winpty_config_free(term->tl_winpty_config);
7417 term->tl_winpty_config = NULL;
7418 if (winpty_err != NULL)
7419 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007420 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007421 (short_u *)winpty_error_msg(winpty_err), NULL);
7422
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007423 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007424 winpty_error_free(winpty_err);
7425 }
7426 return FAIL;
7427}
7428
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007429/*
7430 * Create a new terminal of "rows" by "cols" cells.
7431 * Store a reference in "term".
7432 * Return OK or FAIL.
7433 */
7434 static int
7435term_and_job_init(
7436 term_T *term,
7437 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007438 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007439 jobopt_T *opt,
7440 jobopt_T *orig_opt)
7441{
7442 int use_winpty = FALSE;
7443 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007444 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007445
7446 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7447 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7448
7449 if (!has_winpty && !has_conpty)
7450 // If neither is available give the errors for winpty, since when
7451 // conpty is not available it can't be installed either.
7452 return dyn_winpty_init(TRUE);
7453
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007454 if (opt->jo_tty_type != NUL)
7455 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007456
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007457 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007458 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007459 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007460 use_conpty = TRUE;
7461 else if (has_winpty)
7462 use_winpty = TRUE;
7463 // else: error
7464 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007465 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007466 {
7467 if (has_winpty)
7468 use_winpty = TRUE;
7469 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007470 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007471 {
7472 if (has_conpty)
7473 use_conpty = TRUE;
7474 else
7475 return dyn_conpty_init(TRUE);
7476 }
7477
7478 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007479 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007480
7481 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007482 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007483
7484 // error
7485 return dyn_winpty_init(TRUE);
7486}
7487
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007488 static int
7489create_pty_only(term_T *term, jobopt_T *options)
7490{
7491 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7492 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7493 char in_name[80], out_name[80];
7494 channel_T *channel = NULL;
7495
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007496 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7497 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007498
7499 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7500 GetCurrentProcessId(),
7501 curbuf->b_fnum);
7502 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7503 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7504 PIPE_UNLIMITED_INSTANCES,
7505 0, 0, NMPWAIT_NOWAIT, NULL);
7506 if (hPipeIn == INVALID_HANDLE_VALUE)
7507 goto failed;
7508
7509 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7510 GetCurrentProcessId(),
7511 curbuf->b_fnum);
7512 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7513 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7514 PIPE_UNLIMITED_INSTANCES,
7515 0, 0, 0, NULL);
7516 if (hPipeOut == INVALID_HANDLE_VALUE)
7517 goto failed;
7518
7519 ConnectNamedPipe(hPipeIn, NULL);
7520 ConnectNamedPipe(hPipeOut, NULL);
7521
7522 term->tl_job = job_alloc();
7523 if (term->tl_job == NULL)
7524 goto failed;
7525 ++term->tl_job->jv_refcount;
7526
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007527 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007528 term->tl_job->jv_status = JOB_FINISHED;
7529
7530 channel = add_channel();
7531 if (channel == NULL)
7532 goto failed;
7533 term->tl_job->jv_channel = channel;
7534 channel->ch_keep_open = TRUE;
7535 channel->ch_named_pipe = TRUE;
7536
7537 channel_set_pipes(channel,
7538 (sock_T)hPipeIn,
7539 (sock_T)hPipeOut,
7540 (sock_T)hPipeOut);
7541 channel_set_job(channel, term->tl_job, options);
7542 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7543 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7544
7545 return OK;
7546
7547failed:
7548 if (hPipeIn != NULL)
7549 CloseHandle(hPipeIn);
7550 if (hPipeOut != NULL)
7551 CloseHandle(hPipeOut);
7552 return FAIL;
7553}
7554
7555/*
7556 * Free the terminal emulator part of "term".
7557 */
7558 static void
7559term_free_vterm(term_T *term)
7560{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007561 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007562 if (term->tl_winpty != NULL)
7563 winpty_free(term->tl_winpty);
7564 term->tl_winpty = NULL;
7565 if (term->tl_winpty_config != NULL)
7566 winpty_config_free(term->tl_winpty_config);
7567 term->tl_winpty_config = NULL;
7568 if (term->tl_vterm != NULL)
7569 vterm_free(term->tl_vterm);
7570 term->tl_vterm = NULL;
7571}
7572
7573/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007574 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007575 */
7576 static void
7577term_report_winsize(term_T *term, int rows, int cols)
7578{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007579 if (term->tl_conpty)
7580 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007581 if (term->tl_winpty)
7582 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7583}
7584
7585 int
7586terminal_enabled(void)
7587{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007588 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007589}
7590
7591# else
7592
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007593///////////////////////////////////////
7594// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007595
7596/*
7597 * Create a new terminal of "rows" by "cols" cells.
7598 * Start job for "cmd".
7599 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007600 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007601 * Return OK or FAIL.
7602 */
7603 static int
7604term_and_job_init(
7605 term_T *term,
7606 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007607 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007608 jobopt_T *opt,
7609 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007610{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007611 term->tl_arg0_cmd = NULL;
7612
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007613 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7614 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007615
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007616#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007617 if (term_use_palette())
7618 {
7619 if (term->tl_palette != NULL)
7620 set_vterm_palette(term->tl_vterm, term->tl_palette);
7621 else
7622 init_vterm_ansi_colors(term->tl_vterm);
7623 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007624#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007625
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007626 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007627 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007628 if (term->tl_job != NULL)
7629 ++term->tl_job->jv_refcount;
7630
7631 return term->tl_job != NULL
7632 && term->tl_job->jv_channel != NULL
7633 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7634}
7635
7636 static int
7637create_pty_only(term_T *term, jobopt_T *opt)
7638{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007639 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7640 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007641
7642 term->tl_job = job_alloc();
7643 if (term->tl_job == NULL)
7644 return FAIL;
7645 ++term->tl_job->jv_refcount;
7646
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007647 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007648 term->tl_job->jv_status = JOB_FINISHED;
7649
7650 return mch_create_pty_channel(term->tl_job, opt);
7651}
7652
7653/*
7654 * Free the terminal emulator part of "term".
7655 */
7656 static void
7657term_free_vterm(term_T *term)
7658{
7659 if (term->tl_vterm != NULL)
7660 vterm_free(term->tl_vterm);
7661 term->tl_vterm = NULL;
7662}
7663
7664/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007665 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007666 */
7667 static void
7668term_report_winsize(term_T *term, int rows, int cols)
7669{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007670 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007671 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
7672 {
7673 int fd = -1;
7674 int part;
7675
7676 for (part = PART_OUT; part < PART_COUNT; ++part)
7677 {
7678 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01007679 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007680 break;
7681 }
7682 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7683 mch_signal_job(term->tl_job, (char_u *)"winch");
7684 }
7685}
7686
7687# endif
7688
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007689#endif // FEAT_TERMINAL