blob: 6df37220be8b332a2cbd02658389a812d7a0fe64 [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#ifdef FEAT_CMDWIN
449 if (cmdwin_type != 0)
450 {
451 emsg(_(e_cannot_open_terminal_from_command_line_window));
452 return NULL;
453 }
454#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200455
456 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
457 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
458 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100459 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
460 || (argvar != NULL
461 && argvar->v_type == VAR_LIST
462 && argvar->vval.v_list != NULL
463 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200464 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000465 emsg(_(e_invalid_argument));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200466 return NULL;
467 }
468
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200469 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200470 if (term == NULL)
471 return NULL;
472 term->tl_dirty_row_end = MAX_ROW;
473 term->tl_cursor_visible = TRUE;
474 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
475 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100476#ifdef FEAT_GUI
477 term->tl_system = (flags & TERM_START_SYSTEM);
478#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200479 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100480 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200481 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200482
Bram Moolenaaraeed2a62021-04-29 20:18:45 +0200483 setpcmark();
Bram Moolenaara80faa82020-04-12 19:37:17 +0200484 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200485 if (opt->jo_curwin)
486 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100487 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100488 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200489 {
490 no_write_message();
491 vim_free(term);
492 return NULL;
493 }
494 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaarb1009092020-05-31 16:04:42 +0200495 (buf_hide(curwin->w_buffer) ? ECMD_HIDE : 0)
496 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
497 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200498 {
499 vim_free(term);
500 return NULL;
501 }
502 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100503 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200504 {
505 buf_T *buf;
506
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100507 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100508 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200509 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
510 BLN_NEW | BLN_LISTED);
511 if (buf == NULL || ml_open(buf) == FAIL)
512 {
513 vim_free(term);
514 return NULL;
515 }
516 old_curbuf = curbuf;
517 --curbuf->b_nwindows;
518 curbuf = buf;
519 curwin->w_buffer = buf;
520 ++curbuf->b_nwindows;
521 }
522 else
523 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100524 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200525 split_ea.cmdidx = CMD_new;
526 split_ea.cmd = (char_u *)"new";
527 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100528 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200529 {
530 split_ea.line2 = opt->jo_term_rows;
531 split_ea.addr_count = 1;
532 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100533 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200534 {
535 split_ea.line2 = opt->jo_term_cols;
536 split_ea.addr_count = 1;
537 }
538
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100539 if (vertical)
Bram Moolenaare1004402020-10-24 20:49:43 +0200540 cmdmod.cmod_split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200541 ex_splitview(&split_ea);
542 if (curwin == old_curwin)
543 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100544 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200545 vim_free(term);
546 return NULL;
547 }
548 }
549 term->tl_buffer = curbuf;
550 curbuf->b_term = term;
551
552 if (!opt->jo_hidden)
553 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100554 // Only one size was taken care of with :new, do the other one. With
555 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100556 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200557 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100558 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200559 win_setwidth(opt->jo_term_cols);
560 }
561
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100562 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200563 term->tl_next = first_term;
564 first_term = term;
565
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100566 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
567
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100569 {
570 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200571 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100572 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100573 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100574 {
575 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100576 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100577 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200578 else
579 {
580 int i;
581 size_t len;
582 char_u *cmd, *p;
583
584 if (argvar->v_type == VAR_STRING)
585 {
586 cmd = argvar->vval.v_string;
587 if (cmd == NULL)
588 cmd = (char_u *)"";
589 else if (STRCMP(cmd, "NONE") == 0)
590 cmd = (char_u *)"pty";
591 }
592 else if (argvar->v_type != VAR_LIST
593 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100594 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100595 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200596 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
597 cmd = (char_u*)"";
598
599 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200600 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200601
602 for (i = 0; p != NULL; ++i)
603 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100604 // Prepend a ! to the command name to avoid the buffer name equals
605 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200606 if (i == 0)
607 vim_snprintf((char *)p, len, "!%s", cmd);
608 else
609 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
610 if (buflist_findname(p) == NULL)
611 {
612 vim_free(curbuf->b_ffname);
613 curbuf->b_ffname = p;
614 break;
615 }
616 }
617 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100618 vim_free(curbuf->b_sfname);
619 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200620 curbuf->b_fname = curbuf->b_ffname;
621
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100622 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
623
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200624 if (opt->jo_term_opencmd != NULL)
625 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
626
627 if (opt->jo_eof_chars != NULL)
628 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
629
630 set_string_option_direct((char_u *)"buftype", -1,
631 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200632 // Avoid that 'buftype' is reset when this buffer is entered.
633 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200634
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100635 // Mark the buffer as not modifiable. It can only be made modifiable after
636 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200637 curbuf->b_p_ma = FALSE;
638
Bram Moolenaarb936b792020-09-04 18:34:09 +0200639 set_term_and_win_size(term, opt);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100640#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200641 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
642#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200643 setup_job_options(opt, term->tl_rows, term->tl_cols);
644
Bram Moolenaar13568252018-03-16 20:46:58 +0100645 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100646 return curbuf;
647
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100648#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100649 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100650 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100651 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100652 else if (argvar->v_type == VAR_STRING)
653 {
654 char_u *cmd = argvar->vval.v_string;
655
656 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
657 term->tl_command = vim_strsave(cmd);
658 }
659 else if (argvar->v_type == VAR_LIST
660 && argvar->vval.v_list != NULL
661 && argvar->vval.v_list->lv_len > 0)
662 {
663 garray_T ga;
664 listitem_T *item;
665
666 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200667 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100668 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100669 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100670 char_u *p;
671
672 if (s == NULL)
673 break;
Bram Moolenaar21c1a0c2021-10-17 17:20:23 +0100674 p = vim_strsave_fnameescape(s, VSE_NONE);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100675 if (p == NULL)
676 break;
677 ga_concat(&ga, p);
678 vim_free(p);
679 ga_append(&ga, ' ');
680 }
681 if (item == NULL)
682 {
683 ga_append(&ga, NUL);
684 term->tl_command = ga.ga_data;
685 }
686 else
687 ga_clear(&ga);
688 }
689#endif
690
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100691 if (opt->jo_term_kill != NULL)
692 {
693 char_u *p = skiptowhite(opt->jo_term_kill);
694
695 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
696 }
697
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200698 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100699 {
700 char_u *p = skiptowhite(opt->jo_term_api);
701
702 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
703 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200704 else
705 term->tl_api = vim_strsave((char_u *)"Tapi_");
706
Bram Moolenaar83d47902020-03-26 20:34:00 +0100707 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
708 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
709
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100710#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +0100711 // Save the user-defined palette, it is only used in GUI (or 'tgc' is on).
712 if (opt->jo_set2 & JO2_ANSI_COLORS)
713 {
714 term->tl_palette = ALLOC_MULT(long_u, 16);
715 if (term->tl_palette == NULL)
716 {
717 vim_free(term);
718 return NULL;
719 }
720 memcpy(term->tl_palette, opt->jo_ansi_colors, sizeof(long_u) * 16);
721 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +0100722#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +0100723
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100724 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100725 if (argv == NULL
726 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200727 && argvar->vval.v_string != NULL
728 && STRCMP(argvar->vval.v_string, "NONE") == 0)
729 res = create_pty_only(term, opt);
730 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200731 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200732
733 newbuf = curbuf;
734 if (res == OK)
735 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100736 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200737 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
738 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100739#ifdef FEAT_GUI
740 if (term->tl_system)
741 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100742 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100743 term->tl_toprow = msg_row + 1;
744 term->tl_dirty_row_end = 0;
745 }
746#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200747
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100748 // Make sure we don't get stuck on sending keys to the job, it leads to
749 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200750 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
751
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200752 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200753 {
754 --curbuf->b_nwindows;
755 curbuf = old_curbuf;
756 curwin->w_buffer = curbuf;
757 ++curbuf->b_nwindows;
758 }
Bram Moolenaar81035272021-12-16 18:02:07 +0000759 else if (vgetc_busy
760#ifdef FEAT_TIMERS
761 || timer_busy
762#endif
763 || input_busy)
764 {
765 char_u ignore[4];
766
767 // When waiting for input need to return and possibly end up in
768 // terminal_loop() instead.
769 ignore[0] = K_SPECIAL;
770 ignore[1] = KS_EXTRA;
771 ignore[2] = KE_IGNORE;
772 ignore[3] = NUL;
773 ins_typebuf(ignore, REMAP_NONE, 0, TRUE, FALSE);
774 typebuf_was_filled = TRUE;
775 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200776 }
777 else
778 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100779 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200780 return NULL;
781 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100782
Bram Moolenaar13568252018-03-16 20:46:58 +0100783 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200784 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
785 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200786 return newbuf;
787}
788
789/*
790 * ":terminal": open a terminal window and execute a job in it.
791 */
792 void
793ex_terminal(exarg_T *eap)
794{
795 typval_T argvar[2];
796 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100797 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200798 char_u *cmd;
799 char_u *tofree = NULL;
800
801 init_job_options(&opt);
802
803 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100804 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200805 {
806 char_u *p, *ep;
807
808 cmd += 2;
809 p = skiptowhite(cmd);
810 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200811 if (ep != NULL)
812 {
813 if (ep < p)
814 p = ep;
815 else
816 ep = NULL;
817 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200818
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200819# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
820 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
821 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200822 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200823 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100824 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200825 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200826 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200827 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200828 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200829 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200830 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200831 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100832 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100833 else if (OPTARG_HAS("shell"))
834 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200835 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100836 {
837 opt.jo_set2 |= JO2_TERM_KILL;
838 opt.jo_term_kill = ep + 1;
839 p = skiptowhite(cmd);
840 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200841 else if (OPTARG_HAS("api"))
842 {
843 opt.jo_set2 |= JO2_TERM_API;
844 if (ep != NULL)
845 {
846 opt.jo_term_api = ep + 1;
847 p = skiptowhite(cmd);
848 }
849 else
850 opt.jo_term_api = NULL;
851 }
852 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200853 {
854 opt.jo_set2 |= JO2_TERM_ROWS;
855 opt.jo_term_rows = atoi((char *)ep + 1);
856 p = skiptowhite(cmd);
857 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200858 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200859 {
860 opt.jo_set2 |= JO2_TERM_COLS;
861 opt.jo_term_cols = atoi((char *)ep + 1);
862 p = skiptowhite(cmd);
863 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200864 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200865 {
866 char_u *buf = NULL;
867 char_u *keys;
868
Bram Moolenaar21109272020-01-30 16:27:20 +0100869 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200870 p = skiptowhite(cmd);
871 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200872 keys = replace_termcodes(ep + 1, &buf,
873 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200874 opt.jo_set2 |= JO2_EOF_CHARS;
875 opt.jo_eof_chars = vim_strsave(keys);
876 vim_free(buf);
877 *p = ' ';
878 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100879#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100880 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
881 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100882 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100883 int tty_type = NUL;
884
885 p = skiptowhite(cmd);
886 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
887 tty_type = 'w';
888 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
889 tty_type = 'c';
890 else
891 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000892 semsg(e_invalid_value_for_argument_str, "type");
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100893 goto theend;
894 }
895 opt.jo_set2 |= JO2_TTY_TYPE;
896 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100897 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100898#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200899 else
900 {
901 if (*p)
902 *p = NUL;
Bram Moolenaard82a47d2022-01-05 20:24:39 +0000903 semsg(_(e_invalid_attribute_str), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100904 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200905 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200906# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200907 cmd = skipwhite(p);
908 }
909 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100910 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100911 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200912 tofree = cmd = vim_strsave(p_sh);
913
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100914 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100915 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200916 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100917 }
918
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200919 if (eap->addr_count > 0)
920 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100921 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200922 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
923 opt.jo_io[PART_IN] = JIO_BUFFER;
924 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
925 opt.jo_in_top = eap->line1;
926 opt.jo_in_bot = eap->line2;
927 }
928
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100929 if (opt_shell && tofree == NULL)
930 {
931#ifdef UNIX
932 char **argv = NULL;
933 char_u *tofree1 = NULL;
934 char_u *tofree2 = NULL;
935
936 // :term ++shell command
937 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
938 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100939 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100940 vim_free(tofree1);
941 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100942 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100943#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100944# ifdef MSWIN
945 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
946 char_u *newcmd;
947
948 newcmd = alloc(cmdlen);
949 if (newcmd == NULL)
950 goto theend;
951 tofree = newcmd;
952 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
953 cmd = newcmd;
954# else
Bram Moolenaar9a846fb2022-01-01 21:59:18 +0000955 emsg(_(e_sorry_plusplusshell_not_supported_on_this_system));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100956 goto theend;
957# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100958#endif
959 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100960 argvar[0].v_type = VAR_STRING;
961 argvar[0].vval.v_string = cmd;
962 argvar[1].v_type = VAR_UNKNOWN;
963 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100964
965theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100966 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200967 vim_free(opt.jo_eof_chars);
968}
969
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100970#if defined(FEAT_SESSION) || defined(PROTO)
971/*
972 * Write a :terminal command to the session file to restore the terminal in
973 * window "wp".
974 * Return FAIL if writing fails.
975 */
976 int
Bram Moolenaar0e655112020-09-11 20:36:36 +0200977term_write_session(FILE *fd, win_T *wp, hashtab_T *terminal_bufs)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100978{
Bram Moolenaar0e655112020-09-11 20:36:36 +0200979 const int bufnr = wp->w_buffer->b_fnum;
980 term_T *term = wp->w_buffer->b_term;
981
Bram Moolenaarc2c82052020-09-11 22:10:22 +0200982 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +0200983 {
984 // There are multiple views into this terminal buffer. We don't want to
985 // create the terminal multiple times. If it's the first time, create,
986 // otherwise link to the first buffer.
987 char id_as_str[NUMBUFLEN];
988 hashitem_T *entry;
989
990 vim_snprintf(id_as_str, sizeof(id_as_str), "%d", bufnr);
991
992 entry = hash_find(terminal_bufs, (char_u *)id_as_str);
993 if (!HASHITEM_EMPTY(entry))
994 {
995 // we've already opened this terminal buffer
996 if (fprintf(fd, "execute 'buffer ' . s:term_buf_%d", bufnr) < 0)
997 return FAIL;
998 return put_eol(fd);
999 }
1000 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001001
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001002 // Create the terminal and run the command. This is not without
1003 // risk, but let's assume the user only creates a session when this
1004 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001005 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
1006 term->tl_cols, term->tl_rows) < 0)
1007 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001008#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01001009 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
1010 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001011#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001012 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
1013 return FAIL;
Bram Moolenaar0e655112020-09-11 20:36:36 +02001014 if (put_eol(fd) != OK)
1015 return FAIL;
1016
1017 if (fprintf(fd, "let s:term_buf_%d = bufnr()", bufnr) < 0)
1018 return FAIL;
1019
Bram Moolenaarc2c82052020-09-11 22:10:22 +02001020 if (terminal_bufs != NULL && wp->w_buffer->b_nwindows > 1)
Bram Moolenaar0e655112020-09-11 20:36:36 +02001021 {
1022 char *hash_key = alloc(NUMBUFLEN);
1023
1024 vim_snprintf(hash_key, NUMBUFLEN, "%d", bufnr);
1025 hash_add(terminal_bufs, (char_u *)hash_key);
1026 }
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01001027
1028 return put_eol(fd);
1029}
1030
1031/*
1032 * Return TRUE if "buf" has a terminal that should be restored.
1033 */
1034 int
1035term_should_restore(buf_T *buf)
1036{
1037 term_T *term = buf->b_term;
1038
1039 return term != NULL && (term->tl_command == NULL
1040 || STRCMP(term->tl_command, "NONE") != 0);
1041}
1042#endif
1043
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001044/*
1045 * Free the scrollback buffer for "term".
1046 */
1047 static void
1048free_scrollback(term_T *term)
1049{
1050 int i;
1051
1052 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
1053 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
1054 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001055 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
1056 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
1057 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001058}
1059
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001060
1061// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +02001062static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001063
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001064/*
1065 * Free a terminal and everything it refers to.
1066 * Kills the job if there is one.
1067 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001068 * The actual terminal structure is freed later in free_unused_terminals(),
1069 * because callbacks may wipe out a buffer while the terminal is still
1070 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001071 */
1072 void
1073free_terminal(buf_T *buf)
1074{
1075 term_T *term = buf->b_term;
1076 term_T *tp;
1077
1078 if (term == NULL)
1079 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001080
1081 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001082 if (first_term == term)
1083 first_term = term->tl_next;
1084 else
1085 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
1086 if (tp->tl_next == term)
1087 {
1088 tp->tl_next = term->tl_next;
1089 break;
1090 }
1091
1092 if (term->tl_job != NULL)
1093 {
1094 if (term->tl_job->jv_status != JOB_ENDED
1095 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +01001096 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001097 job_stop(term->tl_job, NULL, "kill");
1098 job_unref(term->tl_job);
1099 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001100 term->tl_next = terminals_to_free;
1101 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001102
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001103 buf->b_term = NULL;
1104 if (in_terminal_loop == term)
1105 in_terminal_loop = NULL;
1106}
1107
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001108 void
1109free_unused_terminals()
1110{
1111 while (terminals_to_free != NULL)
1112 {
1113 term_T *term = terminals_to_free;
1114
1115 terminals_to_free = term->tl_next;
1116
1117 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001118 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001119
1120 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001121 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001122 vim_free(term->tl_title);
1123#ifdef FEAT_SESSION
1124 vim_free(term->tl_command);
1125#endif
1126 vim_free(term->tl_kill);
1127 vim_free(term->tl_status_text);
1128 vim_free(term->tl_opencmd);
1129 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001130 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001131#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001132 if (term->tl_out_fd != NULL)
1133 fclose(term->tl_out_fd);
1134#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001135 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001136 vim_free(term->tl_cursor_color);
LemonBoyb2b3acb2022-05-20 10:10:34 +01001137 vim_free(term->tl_palette);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001138 vim_free(term);
1139 }
1140}
1141
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001142/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001143 * Get the part that is connected to the tty. Normally this is PART_IN, but
1144 * when writing buffer lines to the job it can be another. This makes it
1145 * possible to do "1,5term vim -".
1146 */
1147 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001148get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001149{
1150#ifdef UNIX
1151 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1152 int i;
1153
1154 for (i = 0; i < 3; ++i)
1155 {
1156 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1157
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001158 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001159 return parts[i];
1160 }
1161#endif
1162 return PART_IN;
1163}
1164
1165/*
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001166 * Read any vterm output and send it on the channel.
1167 */
1168 static void
1169term_forward_output(term_T *term)
1170{
1171 VTerm *vterm = term->tl_vterm;
1172 char buf[KEY_BUF_LEN];
1173 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1174
1175 if (curlen > 0)
1176 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1177 (char_u *)buf, (int)curlen, NULL);
1178}
1179
1180/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001181 * Write job output "msg[len]" to the vterm.
1182 */
1183 static void
Bram Moolenaar36968af2021-11-15 17:13:11 +00001184term_write_job_output(term_T *term, char_u *msg_arg, size_t len_arg)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001185{
Bram Moolenaar36968af2021-11-15 17:13:11 +00001186 char_u *msg = msg_arg;
1187 size_t len = len_arg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001188 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001189 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar36968af2021-11-15 17:13:11 +00001190 size_t limit = term->tl_buffer->b_p_twsl * term->tl_cols * 3;
1191
1192 // Limit the length to 'termwinscroll' * cols * 3 bytes. Keep the text at
1193 // the end.
1194 if (len > limit)
1195 {
1196 char_u *p = msg + len - limit;
1197
1198 p -= (*mb_head_off)(msg, p);
1199 len -= p - msg;
1200 msg = p;
1201 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001202
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001203 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001204
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001205 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001206 if (prevlen != vterm_output_get_buffer_current(vterm))
Bram Moolenaara48d4e42021-12-08 22:13:38 +00001207 term_forward_output(term);
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001208
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001209 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001210 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1211}
1212
1213 static void
1214update_cursor(term_T *term, int redraw)
1215{
1216 if (term->tl_normal_mode)
1217 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001218#ifdef FEAT_GUI
1219 if (term->tl_system)
1220 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1221 term->tl_cursor_pos.col);
1222 else
1223#endif
1224 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001225 if (redraw)
1226 {
1227 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
1237 }
1238}
1239
1240/*
1241 * Invoked when "msg" output from a job was received. Write it to the terminal
1242 * of "buffer".
1243 */
1244 void
1245write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1246{
1247 size_t len = STRLEN(msg);
1248 term_T *term = buffer->b_term;
1249
Bram Moolenaar4f974752019-02-17 17:44:42 +01001250#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001251 // Win32: Cannot redirect output of the job, intercept it here and write to
1252 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001253 if (term->tl_out_fd != NULL)
1254 {
1255 ch_log(channel, "Writing %d bytes to output file", (int)len);
1256 fwrite(msg, len, 1, term->tl_out_fd);
1257 return;
1258 }
1259#endif
1260
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001261 if (term->tl_vterm == NULL)
1262 {
1263 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1264 return;
1265 }
1266 ch_log(channel, "writing %d bytes to terminal", (int)len);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01001267 cursor_off();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001268 term_write_job_output(term, msg, len);
1269
Bram Moolenaar13568252018-03-16 20:46:58 +01001270#ifdef FEAT_GUI
1271 if (term->tl_system)
1272 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001273 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001274 update_system_term(term);
1275 update_cursor(term, TRUE);
1276 }
1277 else
1278#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001279 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1280 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001281 if (!term->tl_normal_mode)
1282 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001283 // Don't use update_screen() when editing the command line, it gets
1284 // cleared.
1285 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001286 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar24959102022-05-07 20:01:16 +01001287 if (buffer == curbuf && (State & MODE_CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001288 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001289 update_screen(VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001290 // update_screen() can be slow, check the terminal wasn't closed
1291 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001292 if (buffer == curbuf && curbuf->b_term != NULL)
1293 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001294 }
1295 else
Bram Moolenaare5050712021-12-09 10:51:05 +00001296 redraw_after_callback(TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001297 }
1298}
1299
1300/*
1301 * Send a mouse position and click to the vterm
1302 */
1303 static int
1304term_send_mouse(VTerm *vterm, int button, int pressed)
1305{
1306 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001307 int row = mouse_row - W_WINROW(curwin);
1308 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001309
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001310#ifdef FEAT_PROP_POPUP
1311 if (popup_is_popup(curwin))
1312 {
1313 row -= popup_top_extra(curwin);
1314 col -= popup_left_extra(curwin);
1315 }
1316#endif
1317 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001318 if (button != 0)
1319 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001320 return TRUE;
1321}
1322
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001323static int enter_mouse_col = -1;
1324static int enter_mouse_row = -1;
1325
1326/*
1327 * Handle a mouse click, drag or release.
1328 * Return TRUE when a mouse event is sent to the terminal.
1329 */
1330 static int
1331term_mouse_click(VTerm *vterm, int key)
1332{
1333#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001334 // For modeless selection mouse drag and release events are ignored, unless
1335 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001336 static int ignore_drag_release = TRUE;
1337 VTermMouseState mouse_state;
1338
1339 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1340 if (mouse_state.flags == 0)
1341 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001342 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001343 switch (key)
1344 {
1345 case K_LEFTDRAG:
1346 case K_LEFTRELEASE:
1347 case K_RIGHTDRAG:
1348 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001349 // Ignore drag and release events when the button-down wasn't
1350 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001351 if (ignore_drag_release)
1352 {
1353 int save_mouse_col, save_mouse_row;
1354
1355 if (enter_mouse_col < 0)
1356 break;
1357
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001358 // mouse click in the window gave us focus, handle that
1359 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001360 save_mouse_col = mouse_col;
1361 save_mouse_row = mouse_row;
1362 mouse_col = enter_mouse_col;
1363 mouse_row = enter_mouse_row;
1364 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1365 mouse_col = save_mouse_col;
1366 mouse_row = save_mouse_row;
1367 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001368 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001369 case K_LEFTMOUSE:
1370 case K_RIGHTMOUSE:
1371 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1372 ignore_drag_release = TRUE;
1373 else
1374 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001375 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001376 if (clip_star.available)
1377 {
1378 int button, is_click, is_drag;
1379
1380 button = get_mouse_button(KEY2TERMCAP1(key),
1381 &is_click, &is_drag);
1382 if (mouse_model_popup() && button == MOUSE_LEFT
1383 && (mod_mask & MOD_MASK_SHIFT))
1384 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001385 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001386 button = MOUSE_RIGHT;
1387 mod_mask &= ~MOD_MASK_SHIFT;
1388 }
1389 clip_modeless(button, is_click, is_drag);
1390 }
1391 break;
1392
1393 case K_MIDDLEMOUSE:
1394 if (clip_star.available)
1395 insert_reg('*', TRUE);
1396 break;
1397 }
1398 enter_mouse_col = -1;
1399 return FALSE;
1400 }
1401#endif
1402 enter_mouse_col = -1;
1403
1404 switch (key)
1405 {
1406 case K_LEFTMOUSE:
1407 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1408 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1409 case K_LEFTRELEASE:
1410 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1411 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1412 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1413 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1414 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1415 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1416 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1417 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1418 }
1419 return TRUE;
1420}
1421
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001422/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001423 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1424 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001425 * Return the number of bytes in "buf".
1426 */
1427 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001428term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001429{
1430 VTerm *vterm = term->tl_vterm;
1431 VTermKey key = VTERM_KEY_NONE;
1432 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001433 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001434
1435 switch (c)
1436 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001437 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001438
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001439 // don't use VTERM_KEY_BACKSPACE, it always
1440 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001441 case K_BS: c = term_backspace_char; break;
1442
1443 case ESC: key = VTERM_KEY_ESCAPE; break;
1444 case K_DEL: key = VTERM_KEY_DEL; break;
1445 case K_DOWN: key = VTERM_KEY_DOWN; break;
1446 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1447 key = VTERM_KEY_DOWN; break;
1448 case K_END: key = VTERM_KEY_END; break;
1449 case K_S_END: mod = VTERM_MOD_SHIFT;
1450 key = VTERM_KEY_END; break;
1451 case K_C_END: mod = VTERM_MOD_CTRL;
1452 key = VTERM_KEY_END; break;
1453 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1454 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1455 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1456 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1457 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1458 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1459 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1460 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1461 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1462 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1463 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1464 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1465 case K_HOME: key = VTERM_KEY_HOME; break;
1466 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1467 key = VTERM_KEY_HOME; break;
1468 case K_C_HOME: mod = VTERM_MOD_CTRL;
1469 key = VTERM_KEY_HOME; break;
1470 case K_INS: key = VTERM_KEY_INS; break;
1471 case K_K0: key = VTERM_KEY_KP_0; break;
1472 case K_K1: key = VTERM_KEY_KP_1; break;
1473 case K_K2: key = VTERM_KEY_KP_2; break;
1474 case K_K3: key = VTERM_KEY_KP_3; break;
1475 case K_K4: key = VTERM_KEY_KP_4; break;
1476 case K_K5: key = VTERM_KEY_KP_5; break;
1477 case K_K6: key = VTERM_KEY_KP_6; break;
1478 case K_K7: key = VTERM_KEY_KP_7; break;
1479 case K_K8: key = VTERM_KEY_KP_8; break;
1480 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001481 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001482 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001483 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001484 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001485 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1486 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001487 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1488 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001489 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1490 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001491 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1492 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1493 case K_LEFT: key = VTERM_KEY_LEFT; break;
1494 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1495 key = VTERM_KEY_LEFT; break;
1496 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1497 key = VTERM_KEY_LEFT; break;
1498 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1499 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1500 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1501 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1502 key = VTERM_KEY_RIGHT; break;
1503 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1504 key = VTERM_KEY_RIGHT; break;
1505 case K_UP: key = VTERM_KEY_UP; break;
1506 case K_S_UP: mod = VTERM_MOD_SHIFT;
1507 key = VTERM_KEY_UP; break;
1508 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001509 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1510 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001511
Bram Moolenaara42ad572017-11-16 13:08:04 +01001512 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1513 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaard58d4f92020-07-01 15:49:29 +02001514 case K_MOUSELEFT: other = term_send_mouse(vterm, 7, 1); break;
1515 case K_MOUSERIGHT: other = term_send_mouse(vterm, 6, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001516
1517 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001518 case K_LEFTMOUSE_NM:
1519 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001520 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001521 case K_LEFTRELEASE_NM:
1522 case K_MOUSEMOVE:
1523 case K_MIDDLEMOUSE:
1524 case K_MIDDLEDRAG:
1525 case K_MIDDLERELEASE:
1526 case K_RIGHTMOUSE:
1527 case K_RIGHTDRAG:
1528 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1529 return 0;
1530 other = TRUE;
1531 break;
1532
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001533 case K_X1MOUSE: /* TODO */ return 0;
1534 case K_X1DRAG: /* TODO */ return 0;
1535 case K_X1RELEASE: /* TODO */ return 0;
1536 case K_X2MOUSE: /* TODO */ return 0;
1537 case K_X2DRAG: /* TODO */ return 0;
1538 case K_X2RELEASE: /* TODO */ return 0;
1539
1540 case K_IGNORE: return 0;
1541 case K_NOP: return 0;
1542 case K_UNDO: return 0;
1543 case K_HELP: return 0;
1544 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1545 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1546 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1547 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1548 case K_SELECT: return 0;
1549#ifdef FEAT_GUI
1550 case K_VER_SCROLLBAR: return 0;
1551 case K_HOR_SCROLLBAR: return 0;
1552#endif
1553#ifdef FEAT_GUI_TABLINE
1554 case K_TABLINE: return 0;
1555 case K_TABMENU: return 0;
1556#endif
1557#ifdef FEAT_NETBEANS_INTG
1558 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1559#endif
1560#ifdef FEAT_DND
1561 case K_DROP: return 0;
1562#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001563 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001564 case K_PS: vterm_keyboard_start_paste(vterm);
1565 other = TRUE;
1566 break;
1567 case K_PE: vterm_keyboard_end_paste(vterm);
1568 other = TRUE;
1569 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001570 }
1571
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001572 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001573 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001574 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001575 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001576 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001577 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001578 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001579
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001580 /*
1581 * Convert special keys to vterm keys:
1582 * - Write keys to vterm: vterm_keyboard_key()
1583 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001584 */
1585 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001586 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001587 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001588 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001589 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001590 vterm_keyboard_unichar(vterm, c, mod);
1591
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001592 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001593 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1594}
1595
1596/*
1597 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001598 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001599 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001600 */
1601 static int
1602term_job_running_check(term_T *term, int check_job_status)
1603{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001604 // Also consider the job finished when the channel is closed, to avoid a
1605 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001606 if (term != NULL
1607 && term->tl_job != NULL
1608 && channel_is_open(term->tl_job->jv_channel))
1609 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001610 job_T *job = term->tl_job;
1611
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00001612 // Careful: Checking the job status may invoke callbacks, which close
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001613 // the buffer and terminate "term". However, "job" will not be freed
1614 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001615 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001616 job_status(job);
1617 return (job->jv_status == JOB_STARTED
1618 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001619 }
1620 return FALSE;
1621}
1622
1623/*
1624 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001625 */
1626 int
1627term_job_running(term_T *term)
1628{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001629 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001630}
1631
1632/*
1633 * Return TRUE if "term" has an active channel and used ":term NONE".
1634 */
1635 int
1636term_none_open(term_T *term)
1637{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001638 // Also consider the job finished when the channel is closed, to avoid a
1639 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001640 return term != NULL
1641 && term->tl_job != NULL
1642 && channel_is_open(term->tl_job->jv_channel)
1643 && term->tl_job->jv_channel->ch_keep_open;
1644}
1645
1646/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001647 * Used when exiting: kill the job in "buf" if so desired.
1648 * Return OK when the job finished.
1649 * Return FAIL when the job is still running.
1650 */
1651 int
1652term_try_stop_job(buf_T *buf)
1653{
1654 int count;
1655 char *how = (char *)buf->b_term->tl_kill;
1656
1657#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001658 if ((how == NULL || *how == NUL)
1659 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001660 {
1661 char_u buff[DIALOG_MSG_SIZE];
1662 int ret;
1663
Bram Moolenaar00806bc2020-11-05 19:36:38 +01001664 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001665 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1666 if (ret == VIM_YES)
1667 how = "kill";
1668 else if (ret == VIM_CANCEL)
1669 return FAIL;
1670 }
1671#endif
1672 if (how == NULL || *how == NUL)
1673 return FAIL;
1674
1675 job_stop(buf->b_term->tl_job, NULL, how);
1676
Bram Moolenaar9172d232019-01-29 23:06:54 +01001677 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001678 for (count = 0; count < 100; ++count)
1679 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001680 job_T *job;
1681
1682 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001683 if (!buf_valid(buf)
1684 || buf->b_term == NULL
1685 || buf->b_term->tl_job == NULL)
1686 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001687 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001688
Bram Moolenaar9172d232019-01-29 23:06:54 +01001689 // Call job_status() to update jv_status. It may cause the job to be
1690 // cleaned up but it won't be freed.
1691 job_status(job);
1692 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001693 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001694
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001695 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001696 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001697 }
1698 return FAIL;
1699}
1700
1701/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001702 * Add the last line of the scrollback buffer to the buffer in the window.
1703 */
1704 static void
1705add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1706{
1707 buf_T *buf = term->tl_buffer;
1708 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1709 linenr_T lnum = buf->b_ml.ml_line_count;
1710
Bram Moolenaar4f974752019-02-17 17:44:42 +01001711#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001712 if (!enc_utf8 && enc_codepage > 0)
1713 {
1714 WCHAR *ret = NULL;
1715 int length = 0;
1716
1717 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1718 &ret, &length);
1719 if (ret != NULL)
1720 {
1721 WideCharToMultiByte_alloc(enc_codepage, 0,
1722 ret, length, (char **)&text, &len, 0, 0);
1723 vim_free(ret);
1724 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1725 vim_free(text);
1726 }
1727 }
1728 else
1729#endif
1730 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1731 if (empty)
1732 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001733 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001735 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001736 curbuf = curwin->w_buffer;
1737 }
1738}
1739
1740 static void
1741cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1742{
1743 attr->width = cell->width;
1744 attr->attrs = cell->attrs;
1745 attr->fg = cell->fg;
1746 attr->bg = cell->bg;
1747}
1748
1749 static int
1750equal_celattr(cellattr_T *a, cellattr_T *b)
1751{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001752 // We only compare the RGB colors, ignoring the ANSI index and type.
1753 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001754 return a->fg.red == b->fg.red
1755 && a->fg.green == b->fg.green
1756 && a->fg.blue == b->fg.blue
1757 && a->bg.red == b->bg.red
1758 && a->bg.green == b->bg.green
1759 && a->bg.blue == b->bg.blue;
1760}
1761
Bram Moolenaard96ff162018-02-18 22:13:29 +01001762/*
1763 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1764 * line at this position. Otherwise at the end.
1765 */
1766 static int
1767add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1768{
1769 if (ga_grow(&term->tl_scrollback, 1) == OK)
1770 {
1771 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1772 + term->tl_scrollback.ga_len;
1773
1774 if (lnum > 0)
1775 {
1776 int i;
1777
1778 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1779 {
1780 *line = *(line - 1);
1781 --line;
1782 }
1783 }
1784 line->sb_cols = 0;
1785 line->sb_cells = NULL;
1786 line->sb_fill_attr = *fill_attr;
1787 ++term->tl_scrollback.ga_len;
1788 return OK;
1789 }
1790 return FALSE;
1791}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001792
1793/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001794 * Remove the terminal contents from the scrollback and the buffer.
1795 * Used before adding a new scrollback line or updating the buffer for lines
1796 * displayed in the terminal.
1797 */
1798 static void
1799cleanup_scrollback(term_T *term)
1800{
1801 sb_line_T *line;
1802 garray_T *gap;
1803
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001804 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001805 gap = &term->tl_scrollback;
1806 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1807 && gap->ga_len > 0)
1808 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001809 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001810 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1811 vim_free(line->sb_cells);
1812 --gap->ga_len;
1813 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001814 curbuf = curwin->w_buffer;
1815 if (curbuf == term->tl_buffer)
1816 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001817}
1818
1819/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001820 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001821 */
1822 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001823update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001825 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001826 int len;
1827 int lines_skipped = 0;
1828 VTermPos pos;
1829 VTermScreenCell cell;
1830 cellattr_T fill_attr, new_fill_attr;
1831 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001832
1833 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1834 "Adding terminal window snapshot to buffer");
1835
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001836 // First remove the lines that were appended before, they might be
1837 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001838 cleanup_scrollback(term);
1839
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001840 screen = vterm_obtain_screen(term->tl_vterm);
1841 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001842 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1843 {
1844 len = 0;
1845 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1846 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1847 && cell.chars[0] != NUL)
1848 {
1849 len = pos.col + 1;
1850 new_fill_attr = term->tl_default_color;
1851 }
1852 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001853 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001854 cell2cellattr(&cell, &new_fill_attr);
1855
1856 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1857 ++lines_skipped;
1858 else
1859 {
1860 while (lines_skipped > 0)
1861 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001862 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001863 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001864 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001865 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001866 }
1867
1868 if (len == 0)
1869 p = NULL;
1870 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001871 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001872 if ((p != NULL || len == 0)
1873 && ga_grow(&term->tl_scrollback, 1) == OK)
1874 {
1875 garray_T ga;
1876 int width;
1877 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1878 + term->tl_scrollback.ga_len;
1879
1880 ga_init2(&ga, 1, 100);
1881 for (pos.col = 0; pos.col < len; pos.col += width)
1882 {
1883 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1884 {
1885 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02001886 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001887 if (ga_grow(&ga, 1) == OK)
1888 ga.ga_len += utf_char2bytes(' ',
1889 (char_u *)ga.ga_data + ga.ga_len);
1890 }
1891 else
1892 {
1893 width = cell.width;
1894
1895 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01001896 if (width == 2)
1897 // second cell of double-width character has the
1898 // same attributes.
1899 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001900
Bram Moolenaara79fd562018-12-20 20:47:32 +01001901 // Each character can be up to 6 bytes.
1902 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001903 {
1904 int i;
1905 int c;
1906
1907 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1908 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1909 (char_u *)ga.ga_data + ga.ga_len);
1910 }
1911 }
1912 }
1913 line->sb_cols = len;
1914 line->sb_cells = p;
1915 line->sb_fill_attr = new_fill_attr;
1916 fill_attr = new_fill_attr;
1917 ++term->tl_scrollback.ga_len;
1918
1919 if (ga_grow(&ga, 1) == FAIL)
1920 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1921 else
1922 {
1923 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1924 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1925 }
1926 ga_clear(&ga);
1927 }
1928 else
1929 vim_free(p);
1930 }
1931 }
1932
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001933 // Add trailing empty lines.
1934 for (pos.row = term->tl_scrollback.ga_len;
1935 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1936 ++pos.row)
1937 {
1938 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1939 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1940 }
1941
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001942 term->tl_dirty_snapshot = FALSE;
1943#ifdef FEAT_TIMERS
1944 term->tl_timer_set = FALSE;
1945#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001946}
1947
1948/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001949 * Loop over all windows in the current tab, and also curwin, which is not
1950 * encountered when using a terminal in a popup window.
1951 * Return TRUE if "*wp" was set to the next window.
1952 */
1953 static int
1954for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1955{
1956 if (*wp == NULL)
1957 *wp = firstwin;
1958 else if ((*wp)->w_next != NULL)
1959 *wp = (*wp)->w_next;
1960 else if (!*did_curwin)
1961 *wp = curwin;
1962 else
1963 return FALSE;
1964 if (*wp == curwin)
1965 *did_curwin = TRUE;
1966 return TRUE;
1967}
1968
1969/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001970 * If needed, add the current lines of the terminal to scrollback and to the
1971 * buffer. Called after the job has ended and when switching to
1972 * Terminal-Normal mode.
1973 * When "redraw" is TRUE redraw the windows that show the terminal.
1974 */
1975 static void
1976may_move_terminal_to_buffer(term_T *term, int redraw)
1977{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001978 if (term->tl_vterm == NULL)
1979 return;
1980
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001981 // Update the snapshot only if something changes or the buffer does not
1982 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001983 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1984 <= term->tl_scrollback_scrolled)
1985 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001986
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001987 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001988 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1989 &term->tl_default_color.fg, &term->tl_default_color.bg);
1990
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001991 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001992 {
1993 win_T *wp = NULL;
1994 int did_curwin = FALSE;
1995
1996 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001997 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001998 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001999 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002000 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2001 wp->w_cursor.col = 0;
2002 wp->w_valid = 0;
2003 if (wp->w_cursor.lnum >= wp->w_height)
2004 {
2005 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002006
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002007 if (wp->w_topline < min_topline)
2008 wp->w_topline = min_topline;
2009 }
2010 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002012 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002013 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002014}
2015
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002016#if defined(FEAT_TIMERS) || defined(PROTO)
2017/*
2018 * Check if any terminal timer expired. If so, copy text from the terminal to
2019 * the buffer.
2020 * Return the time until the next timer will expire.
2021 */
2022 int
2023term_check_timers(int next_due_arg, proftime_T *now)
2024{
2025 term_T *term;
2026 int next_due = next_due_arg;
2027
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002028 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002029 {
2030 if (term->tl_timer_set && !term->tl_normal_mode)
2031 {
2032 long this_due = proftime_time_left(&term->tl_timer_due, now);
2033
2034 if (this_due <= 1)
2035 {
2036 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002037 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002038 }
2039 else if (next_due == -1 || next_due > this_due)
2040 next_due = this_due;
2041 }
2042 }
2043
2044 return next_due;
2045}
2046#endif
2047
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002048/*
2049 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2050 * otherwise end it.
2051 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002052 static void
2053set_terminal_mode(term_T *term, int normal_mode)
2054{
2055 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002056 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002057 if (!normal_mode)
2058 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002059 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002060 if (term->tl_buffer == curbuf)
2061 maketitle();
2062}
2063
2064/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002065 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002066 * Move the vterm contents into the scrollback buffer and free the vterm.
2067 */
2068 static void
2069cleanup_vterm(term_T *term)
2070{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002071 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002072 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002073 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002074 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002075}
2076
2077/*
2078 * Switch from Terminal-Job mode to Terminal-Normal mode.
2079 * Suspends updating the terminal window.
2080 */
2081 static void
2082term_enter_normal_mode(void)
2083{
2084 term_T *term = curbuf->b_term;
2085
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002086 set_terminal_mode(term, TRUE);
2087
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002088 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002089 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002090
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002091 // Move the window cursor to the position of the cursor in the
2092 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002093 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2094 + term->tl_cursor_pos.row + 1;
2095 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002096 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2097 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002098 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002099
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002100 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002101 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2102}
2103
2104/*
2105 * Returns TRUE if the current window contains a terminal and we are in
2106 * Terminal-Normal mode.
2107 */
2108 int
2109term_in_normal_mode(void)
2110{
2111 term_T *term = curbuf->b_term;
2112
2113 return term != NULL && term->tl_normal_mode;
2114}
2115
2116/*
2117 * Switch from Terminal-Normal mode to Terminal-Job mode.
2118 * Restores updating the terminal window.
2119 */
2120 void
2121term_enter_job_mode()
2122{
2123 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002124
2125 set_terminal_mode(term, FALSE);
2126
2127 if (term->tl_channel_closed)
2128 cleanup_vterm(term);
2129 redraw_buf_and_status_later(curbuf, NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002130#ifdef FEAT_PROP_POPUP
2131 if (WIN_IS_POPUP(curwin))
Bram Moolenaard5bc32d2020-03-22 19:25:50 +01002132 redraw_later(NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002133#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002134}
2135
2136/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002137 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002138 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002139 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002140 */
2141 static int
2142term_vgetc()
2143{
2144 int c;
2145 int save_State = State;
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002146 int modify_other_keys = curbuf->b_term->tl_vterm == NULL ? FALSE
2147 : vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002148
Bram Moolenaar24959102022-05-07 20:01:16 +01002149 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002150 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002151#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002152 ctrl_break_was_pressed = FALSE;
2153#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002154 if (modify_other_keys)
2155 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002156 c = vgetc();
2157 got_int = FALSE;
2158 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002159 if (modify_other_keys)
2160 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002161 return c;
2162}
2163
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002164static int mouse_was_outside = FALSE;
2165
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002167 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002168 * Return FAIL when the key needs to be handled in Normal mode.
2169 * Return OK when the key was dropped or sent to the terminal.
2170 */
2171 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002172send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002173{
2174 char msg[KEY_BUF_LEN];
2175 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002176 int dragging_outside = FALSE;
2177
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002178 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002179 switch (c)
2180 {
2181 case NUL:
2182 case K_ZERO:
2183 if (typed)
2184 stuffcharReadbuff(c);
2185 return FAIL;
2186
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002187 case K_TABLINE:
2188 stuffcharReadbuff(c);
2189 return FAIL;
2190
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002191 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002192 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002193 return FAIL;
2194
2195 case K_LEFTDRAG:
2196 case K_MIDDLEDRAG:
2197 case K_RIGHTDRAG:
2198 case K_X1DRAG:
2199 case K_X2DRAG:
2200 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002201 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002202 case K_LEFTMOUSE:
2203 case K_LEFTMOUSE_NM:
2204 case K_LEFTRELEASE:
2205 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002206 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002207 case K_MIDDLEMOUSE:
2208 case K_MIDDLERELEASE:
2209 case K_RIGHTMOUSE:
2210 case K_RIGHTRELEASE:
2211 case K_X1MOUSE:
2212 case K_X1RELEASE:
2213 case K_X2MOUSE:
2214 case K_X2RELEASE:
2215
2216 case K_MOUSEUP:
2217 case K_MOUSEDOWN:
2218 case K_MOUSELEFT:
2219 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002220 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002221 int row = mouse_row;
2222 int col = mouse_col;
2223
2224#ifdef FEAT_PROP_POPUP
2225 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002226 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002227 row -= popup_top_extra(curwin);
2228 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002229 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002230#endif
2231 if (row < W_WINROW(curwin)
2232 || row >= (W_WINROW(curwin) + curwin->w_height)
2233 || col < curwin->w_wincol
2234 || col >= W_ENDCOL(curwin)
2235 || dragging_outside)
2236 {
2237 // click or scroll outside the current window or on status
2238 // line or vertical separator
2239 if (typed)
2240 {
2241 stuffcharReadbuff(c);
2242 mouse_was_outside = TRUE;
2243 }
2244 return FAIL;
2245 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002246 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002247 break;
2248
2249 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002250 case K_SCRIPT_COMMAND:
2251 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002252 }
2253 if (typed)
2254 mouse_was_outside = FALSE;
2255
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002256 // Convert the typed key to a sequence of bytes for the job.
2257 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002258 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002259 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002260 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2261 (char_u *)msg, (int)len, NULL);
2262
2263 return OK;
2264}
2265
2266 static void
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002267position_cursor(win_T *wp, VTermPos *pos)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002268{
2269 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2270 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002271#ifdef FEAT_PROP_POPUP
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002272 if (popup_is_popup(wp))
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002273 {
Bram Moolenaarf5452692020-11-28 21:56:06 +01002274 wp->w_wrow += popup_top_extra(wp);
2275 wp->w_wcol += popup_left_extra(wp);
Bram Moolenaar6a076442020-11-15 20:32:58 +01002276 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002277 }
Bram Moolenaar6a076442020-11-15 20:32:58 +01002278 else
2279 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002280#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002281 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2282}
2283
2284/*
2285 * Handle CTRL-W "": send register contents to the job.
2286 */
2287 static void
2288term_paste_register(int prev_c UNUSED)
2289{
2290 int c;
2291 list_T *l;
2292 listitem_T *item;
2293 long reglen = 0;
2294 int type;
2295
2296#ifdef FEAT_CMDL_INFO
2297 if (add_to_showcmd(prev_c))
2298 if (add_to_showcmd('"'))
2299 out_flush();
2300#endif
2301 c = term_vgetc();
2302#ifdef FEAT_CMDL_INFO
2303 clear_showcmd();
2304#endif
2305 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002306 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002307 return;
2308
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002309 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002310 if (c == '=' && get_expr_register() != '=')
2311 return;
2312 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002313 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002314 return;
2315
2316 l = (list_T *)get_reg_contents(c, GREG_LIST);
2317 if (l != NULL)
2318 {
2319 type = get_reg_type(c, &reglen);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002320 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002321 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002322 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002323#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002324 char_u *tmp = s;
2325
2326 if (!enc_utf8 && enc_codepage > 0)
2327 {
2328 WCHAR *ret = NULL;
2329 int length = 0;
2330
2331 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2332 (int)STRLEN(s), &ret, &length);
2333 if (ret != NULL)
2334 {
2335 WideCharToMultiByte_alloc(CP_UTF8, 0,
2336 ret, length, (char **)&s, &length, 0, 0);
2337 vim_free(ret);
2338 }
2339 }
2340#endif
2341 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2342 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002343#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002344 if (tmp != s)
2345 vim_free(s);
2346#endif
2347
2348 if (item->li_next != NULL || type == MLINE)
2349 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2350 (char_u *)"\r", 1, NULL);
2351 }
2352 list_free(l);
2353 }
2354}
2355
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002356/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002357 * Return TRUE when waiting for a character in the terminal, the cursor of the
2358 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002359 */
2360 int
2361terminal_is_active()
2362{
2363 return in_terminal_loop != NULL;
2364}
2365
Bram Moolenaar83d47902020-03-26 20:34:00 +01002366/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002367 * Return the highight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002368 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002369 static int
2370term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002371{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002372 char_u *name;
2373
2374 if (wp != NULL && *wp->w_p_wcr != NUL)
2375 name = wp->w_p_wcr;
2376 else if (term->tl_highlight_name != NULL)
2377 name = term->tl_highlight_name;
2378 else
2379 name = (char_u*)"Terminal";
2380
2381 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002382}
2383
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002384#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002385 cursorentry_T *
2386term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2387{
2388 term_T *term = in_terminal_loop;
2389 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002390 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002391 guicolor_T term_fg = INVALCOLOR;
2392 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002393
Bram Moolenaara80faa82020-04-12 19:37:17 +02002394 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002395 entry.shape = entry.mshape =
2396 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2397 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2398 SHAPE_BLOCK;
2399 entry.percentage = 20;
2400 if (term->tl_cursor_blink)
2401 {
2402 entry.blinkwait = 700;
2403 entry.blinkon = 400;
2404 entry.blinkoff = 250;
2405 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002406
Bram Moolenaar83d47902020-03-26 20:34:00 +01002407 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002408 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002409 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002410 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002411 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002412 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002413 else
2414 *fg = gui.back_pixel;
2415
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002416 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002417 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002418 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002419 *bg = term_fg;
2420 else
2421 *bg = gui.norm_pixel;
2422 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002423 else
2424 *bg = color_name2handle(term->tl_cursor_color);
2425 entry.name = "n";
2426 entry.used_for = SHAPE_CURSOR;
2427
2428 return &entry;
2429}
2430#endif
2431
Bram Moolenaard317b382018-02-08 22:33:31 +01002432 static void
2433may_output_cursor_props(void)
2434{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002435 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002436 || last_set_cursor_shape != desired_cursor_shape
2437 || last_set_cursor_blink != desired_cursor_blink)
2438 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002439 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002440 last_set_cursor_shape = desired_cursor_shape;
2441 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002442 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002443 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002444 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002445 ui_cursor_shape_forced(TRUE);
2446 else
2447 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2448 }
2449}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002450
Bram Moolenaard317b382018-02-08 22:33:31 +01002451/*
2452 * Set the cursor color and shape, if not last set to these.
2453 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002454 static void
2455may_set_cursor_props(term_T *term)
2456{
2457#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002458 // For the GUI the cursor properties are obtained with
2459 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002460 if (gui.in_use)
2461 return;
2462#endif
2463 if (in_terminal_loop == term)
2464 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002465 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002466 desired_cursor_shape = term->tl_cursor_shape;
2467 desired_cursor_blink = term->tl_cursor_blink;
2468 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002469 }
2470}
2471
Bram Moolenaard317b382018-02-08 22:33:31 +01002472/*
2473 * Reset the desired cursor properties and restore them when needed.
2474 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002475 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002476prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002477{
2478#ifdef FEAT_GUI
2479 if (gui.in_use)
2480 return;
2481#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002482 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002483 desired_cursor_shape = -1;
2484 desired_cursor_blink = -1;
2485 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002486}
2487
2488/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002489 * Returns TRUE if the current window contains a terminal and we are sending
2490 * keys to the job.
2491 * If "check_job_status" is TRUE update the job status.
2492 */
2493 static int
2494term_use_loop_check(int check_job_status)
2495{
2496 term_T *term = curbuf->b_term;
2497
2498 return term != NULL
2499 && !term->tl_normal_mode
2500 && term->tl_vterm != NULL
2501 && term_job_running_check(term, check_job_status);
2502}
2503
2504/*
2505 * Returns TRUE if the current window contains a terminal and we are sending
2506 * keys to the job.
2507 */
2508 int
2509term_use_loop(void)
2510{
2511 return term_use_loop_check(FALSE);
2512}
2513
2514/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002515 * Called when entering a window with the mouse. If this is a terminal window
2516 * we may want to change state.
2517 */
2518 void
2519term_win_entered()
2520{
2521 term_T *term = curbuf->b_term;
2522
2523 if (term != NULL)
2524 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002525 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002526 {
2527 reset_VIsual_and_resel();
Bram Moolenaar24959102022-05-07 20:01:16 +01002528 if (State & MODE_INSERT)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002529 stop_insert_mode = TRUE;
2530 }
2531 mouse_was_outside = FALSE;
2532 enter_mouse_col = mouse_col;
2533 enter_mouse_row = mouse_row;
2534 }
2535}
2536
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002537 void
2538term_focus_change(int in_focus)
2539{
2540 term_T *term = curbuf->b_term;
2541
2542 if (term != NULL && term->tl_vterm != NULL)
2543 {
2544 VTermState *state = vterm_obtain_state(term->tl_vterm);
2545
2546 if (in_focus)
2547 vterm_state_focus_in(state);
2548 else
2549 vterm_state_focus_out(state);
2550 term_forward_output(term);
2551 }
2552}
2553
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002554/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002555 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2556 * Return the Ctrl-key value in that case.
2557 */
2558 static int
2559raw_c_to_ctrl(int c)
2560{
2561 if ((mod_mask & MOD_MASK_CTRL)
2562 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2563 return c & 0x1f;
2564 return c;
2565}
2566
2567/*
2568 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2569 * May set "mod_mask".
2570 */
2571 static int
2572ctrl_to_raw_c(int c)
2573{
2574 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2575 {
2576 mod_mask |= MOD_MASK_CTRL;
2577 return c + '@';
2578 }
2579 return c;
2580}
2581
2582/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002583 * Wait for input and send it to the job.
2584 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2585 * when there is no more typahead.
2586 * Return when the start of a CTRL-W command is typed or anything else that
2587 * should be handled as a Normal mode command.
2588 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2589 * the terminal was closed.
2590 */
2591 int
2592terminal_loop(int blocking)
2593{
2594 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002595 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002596 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002597 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002598#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002599 int tty_fd = curbuf->b_term->tl_job->jv_channel
2600 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002601#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002602 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002603
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002604 // Remember the terminal we are sending keys to. However, the terminal
2605 // might be closed while waiting for a character, e.g. typing "exit" in a
2606 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2607 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002608 in_terminal_loop = curbuf->b_term;
2609
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002610 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002611 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002612 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002613 if (termwinkey == Ctrl_W)
2614 termwinkey = 0;
2615 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002616 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002617 may_set_cursor_props(curbuf->b_term);
2618
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002619 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002620 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002621#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002622 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002623#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002624 // TODO: skip screen update when handling a sequence of keys.
2625 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002626 while (must_redraw != 0)
2627 if (update_screen(0) == FAIL)
2628 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002629 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002630 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002631 break;
2632
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002633 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002634 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002635
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002636 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002637 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002638 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002639 // Job finished while waiting for a character. Push back the
2640 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002641 if (raw_c != K_IGNORE)
2642 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002643 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002644 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002645 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002646 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002647 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002648
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002649#ifdef UNIX
2650 /*
2651 * The shell or another program may change the tty settings. Getting
2652 * them for every typed character is a bit of overhead, but it's needed
2653 * for the first character typed, e.g. when Vim starts in a shell.
2654 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002655 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002656 {
2657 ttyinfo_T info;
2658
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002659 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002660 if (get_tty_info(tty_fd, &info) == OK)
2661 term_backspace_char = info.backspace;
2662 }
2663#endif
2664
Bram Moolenaar4f974752019-02-17 17:44:42 +01002665#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002666 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2667 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002668 if (ctrl_break_was_pressed)
2669 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2670#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002671 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2672 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002673 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002674#ifdef FEAT_GUI
2675 && !curbuf->b_term->tl_system
2676#endif
2677 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002678 {
2679 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002680 int prev_raw_c = raw_c;
2681 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002682
2683#ifdef FEAT_CMDL_INFO
2684 if (add_to_showcmd(c))
2685 out_flush();
2686#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002687 raw_c = term_vgetc();
2688 c = raw_c_to_ctrl(raw_c);
2689
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002690#ifdef FEAT_CMDL_INFO
2691 clear_showcmd();
2692#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002693 if (!term_use_loop_check(TRUE)
2694 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002695 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002696 break;
2697
2698 if (prev_c == Ctrl_BSL)
2699 {
2700 if (c == Ctrl_N)
2701 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002702 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002703 term_enter_normal_mode();
2704 ret = FAIL;
2705 goto theend;
2706 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002707 // Send both keys to the terminal, first one here, second one
2708 // below.
2709 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2710 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002711 }
2712 else if (c == Ctrl_C)
2713 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002714 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002715 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2716 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002717 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002718 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002719 // "CTRL-W .": send CTRL-W to the job
2720 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002721 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002722 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002723 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002724 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002725 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002726 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002727 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002728 else if (c == 'N')
2729 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002730 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002731 term_enter_normal_mode();
2732 ret = FAIL;
2733 goto theend;
2734 }
2735 else if (c == '"')
2736 {
2737 term_paste_register(prev_c);
2738 continue;
2739 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002740 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002741 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002742 // space for CTRL-W, modifier, multi-byte char and NUL
2743 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002744
2745 // Put the command into the typeahead buffer, when using the
2746 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2747 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002748 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002749 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002750 ret = OK;
2751 goto theend;
2752 }
2753 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002754# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002755 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002756 {
2757 WCHAR wc;
2758 char_u mb[3];
2759
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002760 mb[0] = (unsigned)raw_c >> 8;
2761 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002762 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002763 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002764 }
2765# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002766 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002767 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002768 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002769 // We are sure to come back here, don't reset the cursor color
2770 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002771 restore_cursor = FALSE;
2772
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002773 ret = OK;
2774 goto theend;
2775 }
2776 }
2777 ret = FAIL;
2778
2779theend:
2780 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002781 if (restore_cursor)
2782 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002783
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002784 // Move a snapshot of the screen contents to the buffer, so that completion
2785 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002786 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2787 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002788
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002789 return ret;
2790}
2791
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002792 static void
2793may_toggle_cursor(term_T *term)
2794{
2795 if (in_terminal_loop == term)
2796 {
2797 if (term->tl_cursor_visible)
2798 cursor_on();
2799 else
2800 cursor_off();
2801 }
2802}
2803
2804/*
2805 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002806 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002807 */
2808 static int
2809color2index(VTermColor *color, int fg, int *boldp)
2810{
2811 int red = color->red;
2812 int blue = color->blue;
2813 int green = color->green;
2814
LemonBoyb2b3acb2022-05-20 10:10:34 +01002815 *boldp = FALSE;
2816
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002817 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002818 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01002819
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002820 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002821 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01002822 // Use the color as-is if possible, give up otherwise.
2823 if (color->index < t_colors)
2824 return color->index + 1;
2825 // 8-color terminals can actually display twice as many colors by
2826 // setting the high-intensity/bold bit.
2827 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002828 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01002829 *boldp = TRUE;
2830 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002831 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01002832 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002833 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002834
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002835 if (t_colors >= 256)
2836 {
2837 if (red == blue && red == green)
2838 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002839 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002840 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002841 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2842 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2843 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002844 int i;
2845
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002846 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002847 return 17; // 00/00/00
2848 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002849 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002850 for (i = 0; i < 23; ++i)
2851 if (red < cutoff[i])
2852 return i + 233;
2853 return 256;
2854 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002855 {
2856 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2857 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002858
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002859 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002860 for (ri = 0; ri < 5; ++ri)
2861 if (red < cutoff[ri])
2862 break;
2863 for (gi = 0; gi < 5; ++gi)
2864 if (green < cutoff[gi])
2865 break;
2866 for (bi = 0; bi < 5; ++bi)
2867 if (blue < cutoff[bi])
2868 break;
2869 return 17 + ri * 36 + gi * 6 + bi;
2870 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002871 }
2872 return 0;
2873}
2874
2875/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002876 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002877 */
2878 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002879vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880{
2881 int attr = 0;
2882
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002883 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002884 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002885 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002886 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002887 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002889 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002890 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002891 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002892 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002893 return attr;
2894}
2895
2896/*
2897 * Store Vterm attributes in "cell" from highlight flags.
2898 */
2899 static void
2900hl2vtermAttr(int attr, cellattr_T *cell)
2901{
Bram Moolenaara80faa82020-04-12 19:37:17 +02002902 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002903 if (attr & HL_BOLD)
2904 cell->attrs.bold = 1;
2905 if (attr & HL_UNDERLINE)
2906 cell->attrs.underline = 1;
2907 if (attr & HL_ITALIC)
2908 cell->attrs.italic = 1;
2909 if (attr & HL_STRIKETHROUGH)
2910 cell->attrs.strike = 1;
2911 if (attr & HL_INVERSE)
2912 cell->attrs.reverse = 1;
2913}
2914
2915/*
2916 * Convert the attributes of a vterm cell into an attribute index.
2917 */
2918 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002919cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01002920 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002921 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002922 VTermScreenCellAttrs *cellattrs,
2923 VTermColor *cellfg,
2924 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002925{
2926 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002927 VTermColor *fg = cellfg;
2928 VTermColor *bg = cellbg;
2929 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
2930 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
2931
2932 if (is_default_fg || is_default_bg)
2933 {
2934 if (wp != NULL && *wp->w_p_wcr != NUL)
2935 {
2936 if (is_default_fg)
2937 fg = &wp->w_term_wincolor.fg;
2938 if (is_default_bg)
2939 bg = &wp->w_term_wincolor.bg;
2940 }
2941 else
2942 {
2943 if (is_default_fg)
2944 fg = &term->tl_default_color.fg;
2945 if (is_default_bg)
2946 bg = &term->tl_default_color.bg;
2947 }
2948 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002949
2950#ifdef FEAT_GUI
2951 if (gui.in_use)
2952 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002953 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
2954 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
2955 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002956 }
2957 else
2958#endif
2959#ifdef FEAT_TERMGUICOLORS
2960 if (p_tgc)
2961 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002962 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
2963 ? INVALCOLOR
2964 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
2965 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
2966 ? INVALCOLOR
2967 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
2968 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002969 }
2970 else
2971#endif
2972 {
2973 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002974 int ctermfg = color2index(fg, TRUE, &bold);
2975 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002976
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002977 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002978 if (bold == TRUE)
2979 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002980
2981 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002982 }
2983 return 0;
2984}
2985
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002986 static void
2987set_dirty_snapshot(term_T *term)
2988{
2989 term->tl_dirty_snapshot = TRUE;
2990#ifdef FEAT_TIMERS
2991 if (!term->tl_normal_mode)
2992 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002993 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002994 profile_setlimit(100L, &term->tl_timer_due);
2995 term->tl_timer_set = TRUE;
2996 }
2997#endif
2998}
2999
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003000 static int
3001handle_damage(VTermRect rect, void *user)
3002{
3003 term_T *term = (term_T *)user;
3004
3005 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3006 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003007 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003008 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003009 return 1;
3010}
3011
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003012 static void
3013term_scroll_up(term_T *term, int start_row, int count)
3014{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003015 win_T *wp = NULL;
3016 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003017 VTermColor fg, bg;
3018 VTermScreenCellAttrs attr;
3019 int clear_attr;
3020
Bram Moolenaara80faa82020-04-12 19:37:17 +02003021 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003022
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003023 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003024 {
3025 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003026 {
3027 // Set the color to clear lines with.
3028 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3029 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003030 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003031 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003032 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003033 }
3034}
3035
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003036 static int
3037handle_moverect(VTermRect dest, VTermRect src, void *user)
3038{
3039 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003040 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003041
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003042 // Scrolling up is done much more efficiently by deleting lines instead of
3043 // redrawing the text. But avoid doing this multiple times, postpone until
3044 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003045 if (dest.start_col == src.start_col
3046 && dest.end_col == src.end_col
3047 && dest.start_row < src.start_row)
3048 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003049 if (dest.start_row == 0)
3050 term->tl_postponed_scroll += count;
3051 else
3052 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003053 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003054
3055 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3056 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003057 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003058
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003059 // Note sure if the scrolling will work correctly, let's do a complete
3060 // redraw later.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003061 redraw_buf_later(term->tl_buffer, NOT_VALID);
3062 return 1;
3063}
3064
3065 static int
3066handle_movecursor(
3067 VTermPos pos,
3068 VTermPos oldpos UNUSED,
3069 int visible,
3070 void *user)
3071{
3072 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003073 win_T *wp = NULL;
3074 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003075
3076 term->tl_cursor_pos = pos;
3077 term->tl_cursor_visible = visible;
3078
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003079 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003080 {
3081 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003082 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003083 }
3084 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003085 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003086
3087 return 1;
3088}
3089
3090 static int
3091handle_settermprop(
3092 VTermProp prop,
3093 VTermValue *value,
3094 void *user)
3095{
3096 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003097 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003098
3099 switch (prop)
3100 {
3101 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003102 if (disable_vterm_title_for_testing)
3103 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003104 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003105 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003106 if (strval == NULL)
3107 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003108 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003109 // a blank title isn't useful, make it empty, so that "running" is
3110 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003111 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003112 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003113 // Same as blank
3114 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003115 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003116 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3117 term->tl_title = NULL;
3118 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003119 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003120 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003121#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003122 else if (!enc_utf8 && enc_codepage > 0)
3123 {
3124 WCHAR *ret = NULL;
3125 int length = 0;
3126
3127 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003128 (char*)value->string.str,
3129 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130 if (ret != NULL)
3131 {
3132 WideCharToMultiByte_alloc(enc_codepage, 0,
3133 ret, length, (char**)&term->tl_title,
3134 &length, 0, 0);
3135 vim_free(ret);
3136 }
3137 }
3138#endif
3139 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003140 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003141 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003142 strval = NULL;
3143 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003144 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003145 if (term == curbuf->b_term)
3146 maketitle();
3147 break;
3148
3149 case VTERM_PROP_CURSORVISIBLE:
3150 term->tl_cursor_visible = value->boolean;
3151 may_toggle_cursor(term);
3152 out_flush();
3153 break;
3154
3155 case VTERM_PROP_CURSORBLINK:
3156 term->tl_cursor_blink = value->boolean;
3157 may_set_cursor_props(term);
3158 break;
3159
3160 case VTERM_PROP_CURSORSHAPE:
3161 term->tl_cursor_shape = value->number;
3162 may_set_cursor_props(term);
3163 break;
3164
3165 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003166 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003167 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003168 if (strval == NULL)
3169 break;
3170 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003171 may_set_cursor_props(term);
3172 break;
3173
3174 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003175 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003176 term->tl_using_altscreen = value->boolean;
3177 break;
3178
3179 default:
3180 break;
3181 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003182 vim_free(strval);
3183
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003184 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003185 return 1;
3186}
3187
3188/*
3189 * The job running in the terminal resized the terminal.
3190 */
3191 static int
3192handle_resize(int rows, int cols, void *user)
3193{
3194 term_T *term = (term_T *)user;
3195 win_T *wp;
3196
3197 term->tl_rows = rows;
3198 term->tl_cols = cols;
3199 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003200 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003201 term->tl_vterm_size_changed = FALSE;
3202 else
3203 {
3204 FOR_ALL_WINDOWS(wp)
3205 {
3206 if (wp->w_buffer == term->tl_buffer)
3207 {
3208 win_setheight_win(rows, wp);
3209 win_setwidth_win(cols, wp);
3210 }
3211 }
3212 redraw_buf_later(term->tl_buffer, NOT_VALID);
3213 }
3214 return 1;
3215}
3216
3217/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003218 * If the number of lines that are stored goes over 'termscrollback' then
3219 * delete the first 10%.
3220 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3221 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003222 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003223 static void
3224limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003225{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003226 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003227 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003228 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003229 int i;
3230
3231 curbuf = term->tl_buffer;
3232 for (i = 0; i < todo; ++i)
3233 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003234 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3235 if (update_buffer)
Bram Moolenaarca70c072020-05-30 20:30:46 +02003236 ml_delete(1);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003237 }
3238 curbuf = curwin->w_buffer;
3239
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003240 gap->ga_len -= todo;
3241 mch_memmove(gap->ga_data,
3242 (sb_line_T *)gap->ga_data + todo,
3243 sizeof(sb_line_T) * gap->ga_len);
3244 if (update_buffer)
3245 term->tl_scrollback_scrolled -= todo;
3246 }
3247}
3248
3249/*
3250 * Handle a line that is pushed off the top of the screen.
3251 */
3252 static int
3253handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3254{
3255 term_T *term = (term_T *)user;
3256 garray_T *gap;
3257 int update_buffer;
3258
3259 if (term->tl_normal_mode)
3260 {
3261 // In Terminal-Normal mode the user interacts with the buffer, thus we
3262 // must not change it. Postpone adding the scrollback lines.
3263 gap = &term->tl_scrollback_postponed;
3264 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003265 }
3266 else
3267 {
3268 // First remove the lines that were appended before, the pushed line
3269 // goes above it.
3270 cleanup_scrollback(term);
3271 gap = &term->tl_scrollback;
3272 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003273 }
3274
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003275 limit_scrollback(term, gap, update_buffer);
3276
3277 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003278 {
3279 cellattr_T *p = NULL;
3280 int len = 0;
3281 int i;
3282 int c;
3283 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003284 int text_len;
3285 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003286 sb_line_T *line;
3287 garray_T ga;
3288 cellattr_T fill_attr = term->tl_default_color;
3289
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003290 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003291 for (i = 0; i < cols; ++i)
3292 if (cells[i].chars[0] != 0)
3293 len = i + 1;
3294 else
3295 cell2cellattr(&cells[i], &fill_attr);
3296
3297 ga_init2(&ga, 1, 100);
3298 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003299 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003300 if (p != NULL)
3301 {
3302 for (col = 0; col < len; col += cells[col].width)
3303 {
3304 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3305 {
3306 ga.ga_len = 0;
3307 break;
3308 }
3309 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3310 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3311 (char_u *)ga.ga_data + ga.ga_len);
3312 cell2cellattr(&cells[col], &p[col]);
3313 }
3314 }
3315 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003316 {
3317 if (update_buffer)
3318 text = (char_u *)"";
3319 else
3320 text = vim_strsave((char_u *)"");
3321 text_len = 0;
3322 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003323 else
3324 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003325 text = ga.ga_data;
3326 text_len = ga.ga_len;
3327 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003328 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003329 if (update_buffer)
3330 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003331
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003332 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003333 line->sb_cols = len;
3334 line->sb_cells = p;
3335 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003336 if (update_buffer)
3337 {
3338 line->sb_text = NULL;
3339 ++term->tl_scrollback_scrolled;
3340 ga_clear(&ga); // free the text
3341 }
3342 else
3343 {
3344 line->sb_text = text;
3345 ga_init(&ga); // text is kept in tl_scrollback_postponed
3346 }
3347 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003348 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003349 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003350}
3351
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003352/*
3353 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3354 * received and stored in tl_scrollback_postponed.
3355 */
3356 static void
3357handle_postponed_scrollback(term_T *term)
3358{
3359 int i;
3360
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003361 if (term->tl_scrollback_postponed.ga_len == 0)
3362 return;
3363 ch_log(NULL, "Moving postponed scrollback to scrollback");
3364
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003365 // First remove the lines that were appended before, the pushed lines go
3366 // above it.
3367 cleanup_scrollback(term);
3368
3369 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3370 {
3371 char_u *text;
3372 sb_line_T *pp_line;
3373 sb_line_T *line;
3374
3375 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3376 break;
3377 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3378
3379 text = pp_line->sb_text;
3380 if (text == NULL)
3381 text = (char_u *)"";
3382 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3383 vim_free(pp_line->sb_text);
3384
3385 line = (sb_line_T *)term->tl_scrollback.ga_data
3386 + term->tl_scrollback.ga_len;
3387 line->sb_cols = pp_line->sb_cols;
3388 line->sb_cells = pp_line->sb_cells;
3389 line->sb_fill_attr = pp_line->sb_fill_attr;
3390 line->sb_text = NULL;
3391 ++term->tl_scrollback_scrolled;
3392 ++term->tl_scrollback.ga_len;
3393 }
3394
3395 ga_clear(&term->tl_scrollback_postponed);
3396 limit_scrollback(term, &term->tl_scrollback, TRUE);
3397}
3398
LemonBoy77771d32022-04-13 11:47:25 +01003399/*
3400 * Called when the terminal wants to ring the system bell.
3401 */
3402 static int
3403handle_bell(void *user UNUSED)
3404{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003405 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003406 return 0;
3407}
3408
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003409static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003410 handle_damage, // damage
3411 handle_moverect, // moverect
3412 handle_movecursor, // movecursor
3413 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003414 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003415 handle_resize, // resize
3416 handle_pushline, // sb_pushline
3417 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003418};
3419
3420/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003421 * Do the work after the channel of a terminal was closed.
3422 * Must be called only when updating_screen is FALSE.
3423 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3424 */
3425 static int
3426term_after_channel_closed(term_T *term)
3427{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003428 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003429 if (!term->tl_normal_mode)
3430 {
3431 int fnum = term->tl_buffer->b_fnum;
3432
3433 cleanup_vterm(term);
3434
3435 if (term->tl_finish == TL_FINISH_CLOSE)
3436 {
3437 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003438 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003439#ifdef FEAT_PROP_POPUP
3440 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003441
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003442 // If this was a terminal in a popup window, go back to the
3443 // previous window.
3444 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3445 {
3446 pwin = curwin;
3447 if (win_valid(prevwin))
3448 win_enter(prevwin, FALSE);
3449 }
3450 else
3451#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003452 // If this is the last normal window: exit Vim.
3453 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3454 {
3455 exarg_T ea;
3456
Bram Moolenaara80faa82020-04-12 19:37:17 +02003457 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003458 ex_quit(&ea);
3459 return TRUE;
3460 }
3461
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003462 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003463 ch_log(NULL, "terminal job finished, closing window");
3464 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003465 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003466 if (curwin == aucmd_win)
3467 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003468 if (do_set_w_closing)
3469 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003470 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003471 if (do_set_w_closing)
3472 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003473 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003474#ifdef FEAT_PROP_POPUP
3475 if (pwin != NULL)
3476 popup_close_with_retval(pwin, 0);
3477#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003478 return TRUE;
3479 }
3480 if (term->tl_finish == TL_FINISH_OPEN
3481 && term->tl_buffer->b_nwindows == 0)
3482 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003483 char *cmd = term->tl_opencmd == NULL
3484 ? "botright sbuf %d"
3485 : (char *)term->tl_opencmd;
3486 size_t len = strlen(cmd) + 50;
3487 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003488
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003489 if (buf != NULL)
3490 {
3491 ch_log(NULL, "terminal job finished, opening window");
3492 vim_snprintf(buf, len, cmd, fnum);
3493 do_cmdline_cmd((char_u *)buf);
3494 vim_free(buf);
3495 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003496 }
3497 else
3498 ch_log(NULL, "terminal job finished");
3499 }
3500
3501 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3502 return FALSE;
3503}
3504
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003505#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3506/*
3507 * If the current window is a terminal in a popup window and the job has
3508 * finished, close the popup window and to back to the previous window.
3509 * Otherwise return FAIL.
3510 */
3511 int
3512may_close_term_popup(void)
3513{
3514 if (popup_is_popup(curwin) && curbuf->b_term != NULL
3515 && !term_job_running(curbuf->b_term))
3516 {
3517 win_T *pwin = curwin;
3518
3519 if (win_valid(prevwin))
3520 win_enter(prevwin, FALSE);
3521 popup_close_with_retval(pwin, 0);
3522 return OK;
3523 }
3524 return FAIL;
3525}
3526#endif
3527
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003528/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003529 * Called when a channel is going to be closed, before invoking the close
3530 * callback.
3531 */
3532 void
3533term_channel_closing(channel_T *ch)
3534{
3535 term_T *term;
3536
3537 for (term = first_term; term != NULL; term = term->tl_next)
3538 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3539 term->tl_channel_closing = TRUE;
3540}
3541
3542/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003543 * Called when a channel has been closed.
3544 * If this was a channel for a terminal window then finish it up.
3545 */
3546 void
3547term_channel_closed(channel_T *ch)
3548{
3549 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003550 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003551 int did_one = FALSE;
3552
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003553 for (term = first_term; term != NULL; term = next_term)
3554 {
3555 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003556 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003557 {
3558 term->tl_channel_closed = TRUE;
3559 did_one = TRUE;
3560
Bram Moolenaard23a8232018-02-10 18:45:26 +01003561 VIM_CLEAR(term->tl_title);
3562 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003563#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003564 if (term->tl_out_fd != NULL)
3565 {
3566 fclose(term->tl_out_fd);
3567 term->tl_out_fd = NULL;
3568 }
3569#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003570
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003571 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003572 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003573 // Cannot open or close windows now. Can happen when
3574 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003575 term->tl_channel_recently_closed = TRUE;
3576 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003577 }
3578
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003579 if (term_after_channel_closed(term))
3580 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003581 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003582 }
3583
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003584 if (did_one)
3585 {
3586 redraw_statuslines();
3587
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003588 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003589 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003590 typebuf_was_filled = TRUE;
3591
3592 term = curbuf->b_term;
3593 if (term != NULL)
3594 {
3595 if (term->tl_job == ch->ch_job)
3596 maketitle();
3597 update_cursor(term, term->tl_cursor_visible);
3598 }
3599 }
3600}
3601
3602/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003603 * To be called after resetting updating_screen: handle any terminal where the
3604 * channel was closed.
3605 */
3606 void
3607term_check_channel_closed_recently()
3608{
3609 term_T *term;
3610 term_T *next_term;
3611
3612 for (term = first_term; term != NULL; term = next_term)
3613 {
3614 next_term = term->tl_next;
3615 if (term->tl_channel_recently_closed)
3616 {
3617 term->tl_channel_recently_closed = FALSE;
3618 if (term_after_channel_closed(term))
3619 // start over, the list may have changed
3620 next_term = first_term;
3621 }
3622 }
3623}
3624
3625/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003626 * Fill one screen line from a line of the terminal.
3627 * Advances "pos" to past the last column.
3628 */
3629 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003630term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003631 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003632 win_T *wp,
3633 VTermScreen *screen,
3634 VTermPos *pos,
3635 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003636{
3637 int off = screen_get_current_line_off();
3638
3639 for (pos->col = 0; pos->col < max_col; )
3640 {
3641 VTermScreenCell cell;
3642 int c;
3643
3644 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003645 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003646
3647 c = cell.chars[0];
3648 if (c == NUL)
3649 {
3650 ScreenLines[off] = ' ';
3651 if (enc_utf8)
3652 ScreenLinesUC[off] = NUL;
3653 }
3654 else
3655 {
3656 if (enc_utf8)
3657 {
3658 int i;
3659
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003660 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003661 for (i = 0; i < Screen_mco
3662 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3663 {
3664 ScreenLinesC[i][off] = cell.chars[i + 1];
3665 if (cell.chars[i + 1] == 0)
3666 break;
3667 }
3668 if (c >= 0x80 || (Screen_mco > 0
3669 && ScreenLinesC[0][off] != 0))
3670 {
3671 ScreenLines[off] = ' ';
3672 ScreenLinesUC[off] = c;
3673 }
3674 else
3675 {
3676 ScreenLines[off] = c;
3677 ScreenLinesUC[off] = NUL;
3678 }
3679 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003680#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003681 else if (has_mbyte && c >= 0x80)
3682 {
3683 char_u mb[MB_MAXBYTES+1];
3684 WCHAR wc = c;
3685
3686 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3687 (char*)mb, 2, 0, 0) > 1)
3688 {
3689 ScreenLines[off] = mb[0];
3690 ScreenLines[off + 1] = mb[1];
3691 cell.width = mb_ptr2cells(mb);
3692 }
3693 else
3694 ScreenLines[off] = c;
3695 }
3696#endif
3697 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003698 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003699 ScreenLines[off] = c;
3700 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003701 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3702 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003703
3704 ++pos->col;
3705 ++off;
3706 if (cell.width == 2)
3707 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003708 // don't set the second byte to NUL for a DBCS encoding, it
3709 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003710 if (enc_utf8)
3711 {
3712 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003713 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003714 }
3715 else if (!has_mbyte)
3716 {
3717 // Can't show a double-width character with a single-byte
3718 // 'encoding', just use a space.
3719 ScreenLines[off] = ' ';
3720 ScreenAttrs[off] = ScreenAttrs[off - 1];
3721 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003722
3723 ++pos->col;
3724 ++off;
3725 }
3726 }
3727}
3728
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003729#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003730 static void
3731update_system_term(term_T *term)
3732{
3733 VTermPos pos;
3734 VTermScreen *screen;
3735
3736 if (term->tl_vterm == NULL)
3737 return;
3738 screen = vterm_obtain_screen(term->tl_vterm);
3739
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003740 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003741 while (term->tl_toprow > 0
3742 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3743 {
3744 int save_p_more = p_more;
3745
3746 p_more = FALSE;
3747 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003748 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003749 p_more = save_p_more;
3750 --term->tl_toprow;
3751 }
3752
3753 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3754 && pos.row < Rows; ++pos.row)
3755 {
3756 if (pos.row < term->tl_rows)
3757 {
3758 int max_col = MIN(Columns, term->tl_cols);
3759
Bram Moolenaar83d47902020-03-26 20:34:00 +01003760 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003761 }
3762 else
3763 pos.col = 0;
3764
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003765 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003766 }
3767
3768 term->tl_dirty_row_start = MAX_ROW;
3769 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003770}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003771#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003772
3773/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003774 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3775 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003776 * Terminal-Normal mode.
3777 */
3778 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003779term_do_update_window(win_T *wp)
3780{
3781 term_T *term = wp->w_buffer->b_term;
3782
3783 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3784}
3785
3786/*
3787 * Called to update a window that contains an active terminal.
3788 */
3789 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003790term_update_window(win_T *wp)
3791{
3792 term_T *term = wp->w_buffer->b_term;
3793 VTerm *vterm;
3794 VTermScreen *screen;
3795 VTermState *state;
3796 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003797 int rows, cols;
3798 int newrows, newcols;
3799 int minsize;
3800 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003801
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003802 vterm = term->tl_vterm;
3803 screen = vterm_obtain_screen(vterm);
3804 state = vterm_obtain_state(vterm);
3805
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003806 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3807 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003808 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003809 {
3810 term->tl_dirty_row_start = 0;
3811 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003812
3813 if (term->tl_postponed_scroll > 0
3814 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003815 // Scrolling is usually faster than redrawing, when there are only
3816 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003817 term_scroll_up(term, 0, term->tl_postponed_scroll);
3818 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003819 }
3820
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003821 /*
3822 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003823 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003824 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003825 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003826
Bram Moolenaar498c2562018-04-15 23:45:15 +02003827 newrows = 99999;
3828 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003829 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003830 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003831 // Always use curwin, it may be a popup window.
3832 win_T *wwp = twp == NULL ? curwin : twp;
3833
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003834 // When more than one window shows the same terminal, use the
3835 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003836 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003837 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003838 newrows = MIN(newrows, wwp->w_height);
3839 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003840 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003841 if (twp == NULL)
3842 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003843 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003844 if (newrows == 99999 || newcols == 99999)
3845 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003846 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3847 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3848
Bram Moolenaareba13e42021-02-23 17:47:23 +01003849 // If no cell is visible there is no point in resizing. Also, vterm can't
3850 // handle a zero height.
3851 if (newrows == 0 || newcols == 0)
3852 return;
3853
Bram Moolenaar498c2562018-04-15 23:45:15 +02003854 if (term->tl_rows != newrows || term->tl_cols != newcols)
3855 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003856 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003857 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003858 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003859 newrows);
3860 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003861
3862 // Updating the terminal size will cause the snapshot to be cleared.
3863 // When not in terminal_loop() we need to restore it.
3864 if (term != in_terminal_loop)
3865 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003866 }
3867
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003868 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003869 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003870 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003871
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003872 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3873 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003874 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003875 if (pos.row < term->tl_rows)
3876 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003877 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003878
Bram Moolenaar83d47902020-03-26 20:34:00 +01003879 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003880 }
3881 else
3882 pos.col = 0;
3883
Bram Moolenaarf118d482018-03-13 13:14:00 +01003884 screen_line(wp->w_winrow + pos.row
3885#ifdef FEAT_MENU
3886 + winbar_height(wp)
3887#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003888 , wp->w_wincol, pos.col, wp->w_width,
3889#ifdef FEAT_PROP_POPUP
3890 popup_is_popup(wp) ? SLF_POPUP :
3891#endif
3892 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003893 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00003894}
3895
3896/*
3897 * Called after updating all windows: may reset dirty rows.
3898 */
3899 void
3900term_did_update_window(win_T *wp)
3901{
3902 term_T *term = wp->w_buffer->b_term;
3903
3904 if (term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode
3905 && wp->w_redr_type == 0)
3906 {
3907 term->tl_dirty_row_start = MAX_ROW;
3908 term->tl_dirty_row_end = 0;
3909 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003910}
3911
3912/*
3913 * Return TRUE if "wp" is a terminal window where the job has finished.
3914 */
3915 int
3916term_is_finished(buf_T *buf)
3917{
3918 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3919}
3920
3921/*
3922 * Return TRUE if "wp" is a terminal window where the job has finished or we
3923 * are in Terminal-Normal mode, thus we show the buffer contents.
3924 */
3925 int
3926term_show_buffer(buf_T *buf)
3927{
3928 term_T *term = buf->b_term;
3929
3930 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3931}
3932
3933/*
3934 * The current buffer is going to be changed. If there is terminal
3935 * highlighting remove it now.
3936 */
3937 void
3938term_change_in_curbuf(void)
3939{
3940 term_T *term = curbuf->b_term;
3941
3942 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3943 {
3944 free_scrollback(term);
3945 redraw_buf_later(term->tl_buffer, NOT_VALID);
3946
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003947 // The buffer is now like a normal buffer, it cannot be easily
3948 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003949 set_string_option_direct((char_u *)"buftype", -1,
3950 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3951 }
3952}
3953
3954/*
3955 * Get the screen attribute for a position in the buffer.
3956 * Use a negative "col" to get the filler background color.
3957 */
3958 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003959term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003960{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003961 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003962 term_T *term = buf->b_term;
3963 sb_line_T *line;
3964 cellattr_T *cellattr;
3965
3966 if (lnum > term->tl_scrollback.ga_len)
3967 cellattr = &term->tl_default_color;
3968 else
3969 {
3970 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3971 if (col < 0 || col >= line->sb_cols)
3972 cellattr = &line->sb_fill_attr;
3973 else
3974 cellattr = line->sb_cells + col;
3975 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003976 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003977}
3978
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003979/*
3980 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003981 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003982 */
3983 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003984cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003985{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003986 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
3987 if (rgb->index == 0)
3988 rgb->type = VTERM_COLOR_RGB;
3989 else
3990 {
3991 rgb->type = VTERM_COLOR_INDEXED;
3992 --rgb->index;
3993 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003994}
3995
3996/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003997 * Initialize vterm color from the synID.
3998 * Returns TRUE if color is set to "fg" and "bg".
3999 * Otherwise returns FALSE.
4000 */
4001 static int
4002get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4003{
4004#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4005 // Use the actual color for the GUI and when 'termguicolors' is set.
4006 if (0
4007# ifdef FEAT_GUI
4008 || gui.in_use
4009# endif
4010# ifdef FEAT_TERMGUICOLORS
4011 || p_tgc
4012# ifdef FEAT_VTP
4013 // Finally get INVALCOLOR on this execution path
4014 || (!p_tgc && t_colors >= 256)
4015# endif
4016# endif
4017 )
4018 {
4019 guicolor_T fg_rgb = INVALCOLOR;
4020 guicolor_T bg_rgb = INVALCOLOR;
4021
4022 if (id > 0)
4023 syn_id2colors(id, &fg_rgb, &bg_rgb);
4024
4025 if (fg_rgb != INVALCOLOR)
4026 {
4027 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4028 fg->red = (unsigned)(rgb >> 16);
4029 fg->green = (unsigned)(rgb >> 8) & 255;
4030 fg->blue = (unsigned)rgb & 255;
4031 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4032 }
4033 else
4034 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4035
4036 if (bg_rgb != INVALCOLOR)
4037 {
4038 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4039 bg->red = (unsigned)(rgb >> 16);
4040 bg->green = (unsigned)(rgb >> 8) & 255;
4041 bg->blue = (unsigned)rgb & 255;
4042 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4043 }
4044 else
4045 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4046
4047 return TRUE;
4048 }
4049 else
4050#endif
4051 if (t_colors >= 16)
4052 {
4053 int cterm_fg = -1;
4054 int cterm_bg = -1;
4055
4056 if (id > 0)
4057 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4058
4059 if (cterm_fg >= 0)
4060 {
4061 cterm_color2vterm(cterm_fg, fg);
4062 fg->type |= VTERM_COLOR_DEFAULT_FG;
4063 }
4064 else
4065 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4066
4067 if (cterm_bg >= 0)
4068 {
4069 cterm_color2vterm(cterm_bg, bg);
4070 bg->type |= VTERM_COLOR_DEFAULT_BG;
4071 }
4072 else
4073 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4074
4075 return TRUE;
4076 }
4077
4078 return FALSE;
4079}
4080
4081 void
4082term_reset_wincolor(win_T *wp)
4083{
4084 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4085 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4086}
4087
4088/*
4089 * Cache the color of 'wincolor'.
4090 */
4091 void
4092term_update_wincolor(win_T *wp)
4093{
4094 int id = 0;
4095
4096 if (*wp->w_p_wcr != NUL)
4097 id = syn_name2id(wp->w_p_wcr);
4098 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4099 &wp->w_term_wincolor.bg))
4100 term_reset_wincolor(wp);
4101}
4102
4103/*
4104 * Called when option 'termguicolors' was set,
4105 * or when any highlight is changed.
4106 */
4107 void
4108term_update_wincolor_all()
4109{
4110 win_T *wp = NULL;
4111 int did_curwin = FALSE;
4112
4113 while (for_all_windows_and_curwin(&wp, &did_curwin))
4114 term_update_wincolor(wp);
4115}
4116
4117/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004118 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004119 */
4120 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004121init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004122{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004123 VTermColor *fg, *bg;
4124 int fgval, bgval;
4125 int id;
4126
Bram Moolenaara80faa82020-04-12 19:37:17 +02004127 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004128 term->tl_default_color.width = 1;
4129 fg = &term->tl_default_color.fg;
4130 bg = &term->tl_default_color.bg;
4131
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004132 // Vterm uses a default black background. Set it to white when
4133 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004134 if (*p_bg == 'l')
4135 {
4136 fgval = 0;
4137 bgval = 255;
4138 }
4139 else
4140 {
4141 fgval = 255;
4142 bgval = 0;
4143 }
4144 fg->red = fg->green = fg->blue = fgval;
4145 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004146 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4147 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004148
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004149 // The highlight group overrules the defaults.
4150 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004151
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004152 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004153 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004154#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004155 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004156#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004157
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004158 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004159 if (cterm_normal_fg_color > 0)
4160 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004161 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004162# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4163# ifdef VIMDLL
4164 if (!gui.in_use)
4165# endif
4166 {
4167 tmp = fg->red;
4168 fg->red = fg->blue;
4169 fg->blue = tmp;
4170 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004171# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004172 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004173# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004174 else
4175 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004176# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004177
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004178 if (cterm_normal_bg_color > 0)
4179 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004180 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004181# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4182# ifdef VIMDLL
4183 if (!gui.in_use)
4184# endif
4185 {
4186 tmp = fg->red;
4187 fg->red = fg->blue;
4188 fg->blue = tmp;
4189 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004190# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004191 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004192# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004193 else
4194 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004195# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004196 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004197}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004198
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004199#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4200/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004201 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4202 * "ansi_colors" argument in term_start()) shall be applied.
4203 */
4204 static int
4205term_use_palette()
4206{
4207 if (0
4208#ifdef FEAT_GUI
4209 || gui.in_use
4210#endif
4211#ifdef FEAT_TERMGUICOLORS
4212 || p_tgc
4213#endif
4214 )
4215 return TRUE;
4216 return FALSE;
4217}
4218
4219/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004220 * Set the 16 ANSI colors from array of RGB values
4221 */
4222 static void
4223set_vterm_palette(VTerm *vterm, long_u *rgb)
4224{
4225 int index = 0;
4226 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004227
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004228 for (; index < 16; index++)
4229 {
4230 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004231
Millyb771b6b2021-11-23 12:07:25 +00004232 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004233 color.red = (unsigned)(rgb[index] >> 16);
4234 color.green = (unsigned)(rgb[index] >> 8) & 255;
4235 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004236 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004237 vterm_state_set_palette_color(state, index, &color);
4238 }
4239}
4240
4241/*
4242 * Set the ANSI color palette from a list of colors
4243 */
4244 static int
4245set_ansi_colors_list(VTerm *vterm, list_T *list)
4246{
4247 int n = 0;
4248 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004249 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004250
Bram Moolenaarb0992022020-01-30 14:55:42 +01004251 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004252 {
4253 char_u *color_name;
4254 guicolor_T guicolor;
4255
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004256 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004257 if (color_name == NULL)
4258 return FAIL;
4259
4260 guicolor = GUI_GET_COLOR(color_name);
4261 if (guicolor == INVALCOLOR)
4262 return FAIL;
4263
4264 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4265 }
4266
4267 if (n != 16 || li != NULL)
4268 return FAIL;
4269
4270 set_vterm_palette(vterm, rgb);
4271
4272 return OK;
4273}
4274
4275/*
4276 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4277 */
4278 static void
4279init_vterm_ansi_colors(VTerm *vterm)
4280{
4281 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4282
LemonBoyb2b3acb2022-05-20 10:10:34 +01004283 if (var == NULL)
4284 return;
4285
4286 if (var->di_tv.v_type != VAR_LIST
4287 || var->di_tv.vval.v_list == NULL
4288 || var->di_tv.vval.v_list->lv_first == &range_list_item
4289 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004290 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004291}
4292#endif
4293
Bram Moolenaar52acb112018-03-18 19:20:22 +01004294/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004295 * Handles a "drop" command from the job in the terminal.
4296 * "item" is the file name, "item->li_next" may have options.
4297 */
4298 static void
4299handle_drop_command(listitem_T *item)
4300{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004301 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004302 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004303 int bufnr;
4304 win_T *wp;
4305 tabpage_T *tp;
4306 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004307 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004308
4309 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4310 FOR_ALL_TAB_WINDOWS(tp, wp)
4311 {
4312 if (wp->w_buffer->b_fnum == bufnr)
4313 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004314 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004315 goto_tabpage_win(tp, wp);
4316 return;
4317 }
4318 }
4319
Bram Moolenaara80faa82020-04-12 19:37:17 +02004320 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004321
4322 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4323 && opt_item->li_tv.vval.v_dict != NULL)
4324 {
4325 dict_T *dict = opt_item->li_tv.vval.v_dict;
4326 char_u *p;
4327
Bram Moolenaar8f667172018-12-14 15:38:31 +01004328 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004329 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004330 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004331 if (p != NULL)
4332 {
4333 if (check_ff_value(p) == FAIL)
4334 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4335 else
4336 ea.force_ff = *p;
4337 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01004338 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004339 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004340 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004341 if (p != NULL)
4342 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004343 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004344 if (ea.cmd != NULL)
4345 {
4346 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4347 ea.force_enc = 11;
4348 tofree = ea.cmd;
4349 }
4350 }
4351
Bram Moolenaar8f667172018-12-14 15:38:31 +01004352 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004353 if (p != NULL)
4354 get_bad_opt(p, &ea);
4355
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004356 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004357 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004358 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004359 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004360 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004361 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004362 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004363 ea.force_bin = FORCE_NOBIN;
4364 }
4365
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004366 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004367 if (ea.cmd == NULL)
4368 ea.cmd = (char_u *)"split";
4369 ea.arg = fname;
4370 ea.cmdidx = CMD_split;
4371 ex_splitview(&ea);
4372
4373 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004374}
4375
4376/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004377 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4378 */
4379 static int
4380is_permitted_term_api(char_u *func, char_u *pat)
4381{
4382 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4383}
4384
4385/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004386 * Handles a function call from the job running in a terminal.
4387 * "item" is the function name, "item->li_next" has the arguments.
4388 */
4389 static void
4390handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4391{
4392 char_u *func;
4393 typval_T argvars[2];
4394 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004395 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004396
4397 if (item->li_next == NULL)
4398 {
4399 ch_log(channel, "Missing function arguments for call");
4400 return;
4401 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004402 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004403
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004404 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004405 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004406 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004407 return;
4408 }
4409
4410 argvars[0].v_type = VAR_NUMBER;
4411 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4412 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004413 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004414 funcexe.fe_firstline = 1L;
4415 funcexe.fe_lastline = 1L;
4416 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004417 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004418 {
4419 clear_tv(&rettv);
4420 ch_log(channel, "Function %s called", func);
4421 }
4422 else
4423 ch_log(channel, "Calling function %s failed", func);
4424}
4425
4426/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004427 * URL decoding (also know as Percent-encoding).
4428 *
4429 * Note this function currently is only used for decoding shell's
4430 * OSC 7 escape sequence which we can assume all bytes are valid
4431 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4432 * encoding bytes like 0xfe, 0xff.
4433 */
4434 static size_t
4435url_decode(const char *src, const size_t len, char_u *dst)
4436{
4437 size_t i = 0, j = 0;
4438
4439 while (i < len)
4440 {
4441 if (src[i] == '%' && i + 2 < len)
4442 {
4443 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4444 j++;
4445 i += 3;
4446 }
4447 else
4448 {
4449 dst[j] = src[i];
4450 i++;
4451 j++;
4452 }
4453 }
4454 dst[j] = '\0';
4455 return j;
4456}
4457
4458/*
4459 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4460 *
4461 * The OSC 7 sequence has the format of
4462 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4463 * and what VTerm provides via VTermStringFragment is
4464 * "file://HOSTNAME/CURRENT/DIR"
4465 */
4466 static void
4467sync_shell_dir(VTermStringFragment *frag)
4468{
4469 int offset = 7; // len of "file://" is 7
4470 char *pos = (char *)frag->str + offset;
4471 char_u *new_dir;
4472
4473 // remove HOSTNAME to get PWD
Bram Moolenaar918b0892021-05-08 20:09:24 +02004474 while (*pos != '/' && offset < (int)frag->len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004475 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004476 offset += 1;
4477 pos += 1;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004478 }
4479
Bram Moolenaar918b0892021-05-08 20:09:24 +02004480 if (offset >= (int)frag->len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004481 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004482 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004483 frag->str);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004484 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004485 }
4486
4487 new_dir = alloc(frag->len - offset + 1);
4488 url_decode(pos, frag->len-offset, new_dir);
4489 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4490 vim_free(new_dir);
4491}
4492
4493/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004494 * Called by libvterm when it cannot recognize an OSC sequence.
4495 * We recognize a terminal API command.
4496 */
4497 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004498parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004499{
4500 term_T *term = (term_T *)user;
4501 js_read_T reader;
4502 typval_T tv;
4503 channel_T *channel = term->tl_job == NULL ? NULL
4504 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004505 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004506
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004507 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
4508 if (p_asd && command == 7)
4509 {
4510 sync_shell_dir(&frag);
4511 return 1;
4512 }
4513
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004514 if (command != 51)
4515 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004516
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004517 // Concatenate what was received until the final piece is found.
4518 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4519 {
4520 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004521 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004522 }
4523 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004524 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004525 if (!frag.final)
4526 return 1;
4527
4528 ((char *)gap->ga_data)[gap->ga_len] = 0;
4529 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004530 reader.js_fill = NULL;
4531 reader.js_used = 0;
4532 if (json_decode(&reader, &tv, 0) == OK
4533 && tv.v_type == VAR_LIST
4534 && tv.vval.v_list != NULL)
4535 {
4536 listitem_T *item = tv.vval.v_list->lv_first;
4537
4538 if (item == NULL)
4539 ch_log(channel, "Missing command");
4540 else
4541 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004542 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004543
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004544 // Make sure an invoked command doesn't delete the buffer (and the
4545 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004546 ++term->tl_buffer->b_locked;
4547
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004548 item = item->li_next;
4549 if (item == NULL)
4550 ch_log(channel, "Missing argument for %s", cmd);
4551 else if (STRCMP(cmd, "drop") == 0)
4552 handle_drop_command(item);
4553 else if (STRCMP(cmd, "call") == 0)
4554 handle_call_command(term, channel, item);
4555 else
4556 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004557 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004558 }
4559 }
4560 else
4561 ch_log(channel, "Invalid JSON received");
4562
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004563 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004564 clear_tv(&tv);
4565 return 1;
4566}
4567
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004568/*
4569 * Called by libvterm when it cannot recognize a CSI sequence.
4570 * We recognize the window position report.
4571 */
4572 static int
4573parse_csi(
4574 const char *leader UNUSED,
4575 const long args[],
4576 int argcount,
4577 const char *intermed UNUSED,
4578 char command,
4579 void *user)
4580{
4581 term_T *term = (term_T *)user;
4582 char buf[100];
4583 int len;
4584 int x = 0;
4585 int y = 0;
4586 win_T *wp;
4587
4588 // We recognize only CSI 13 t
4589 if (command != 't' || argcount != 1 || args[0] != 13)
4590 return 0; // not handled
4591
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004592 // When getting the window position is not possible or it fails it results
4593 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004594#if defined(FEAT_GUI) \
4595 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4596 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004597 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004598#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004599
4600 FOR_ALL_WINDOWS(wp)
4601 if (wp->w_buffer == term->tl_buffer)
4602 break;
4603 if (wp != NULL)
4604 {
4605#ifdef FEAT_GUI
4606 if (gui.in_use)
4607 {
4608 x += wp->w_wincol * gui.char_width;
4609 y += W_WINROW(wp) * gui.char_height;
4610 }
4611 else
4612#endif
4613 {
4614 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004615 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004616 x += wp->w_wincol * 7;
4617 y += W_WINROW(wp) * 10;
4618 }
4619 }
4620
4621 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4622 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4623 (char_u *)buf, len, NULL);
4624 return 1;
4625}
4626
Bram Moolenaard8637282020-05-20 18:41:41 +02004627static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004628 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004629 parse_csi, // csi
4630 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004631 NULL, // dcs
4632 NULL, // apc
4633 NULL, // pm
4634 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004635};
4636
4637/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004638 * Use Vim's allocation functions for vterm so profiling works.
4639 */
4640 static void *
4641vterm_malloc(size_t size, void *data UNUSED)
4642{
Bram Moolenaar88137392021-11-12 16:01:15 +00004643 // make sure that the length is not zero
4644 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004645}
4646
4647 static void
4648vterm_memfree(void *ptr, void *data UNUSED)
4649{
4650 vim_free(ptr);
4651}
4652
4653static VTermAllocatorFunctions vterm_allocator = {
4654 &vterm_malloc,
4655 &vterm_memfree
4656};
4657
4658/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004659 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004660 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004661 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004662 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004663create_vterm(term_T *term, int rows, int cols)
4664{
4665 VTerm *vterm;
4666 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004667 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004668 VTermValue value;
4669
Bram Moolenaar756ef112018-04-10 12:04:27 +02004670 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004671 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004672 if (vterm == NULL)
4673 return FAIL;
4674
4675 // Allocate screen and state here, so we can bail out if that fails.
4676 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004677 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004678 if (state == NULL || screen == NULL)
4679 {
4680 vterm_free(vterm);
4681 return FAIL;
4682 }
4683
Bram Moolenaar52acb112018-03-18 19:20:22 +01004684 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004685 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004686 vterm_set_utf8(vterm, 1);
4687
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004688 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004689
4690 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004691 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004692 &term->tl_default_color.fg,
4693 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004694
Bram Moolenaar9e587872019-05-13 20:27:23 +02004695 if (t_colors < 16)
4696 // Less than 16 colors: assume that bold means using a bright color for
4697 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004698 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4699
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004700 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004701 vterm_screen_reset(screen, 1 /* hard */);
4702
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004703 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004704 vterm_screen_enable_altscreen(screen, 1);
4705
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004706 // For unix do not use a blinking cursor. In an xterm this causes the
4707 // cursor to blink if it's blinking in the xterm.
4708 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004709#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004710 if (GetCaretBlinkTime() == INFINITE)
4711 value.boolean = 0;
4712 else
4713 value.boolean = 1;
4714#else
4715 value.boolean = 0;
4716#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004717 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004718 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004719
4720 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004721}
4722
4723/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004724 * Reset the terminal palette to its default value.
4725 */
4726 static void
4727term_reset_palette(VTerm *vterm)
4728{
4729 VTermState *state = vterm_obtain_state(vterm);
4730 int index;
4731
4732 for (index = 0; index < 16; index++)
4733 {
4734 VTermColor color;
4735
4736 color.type = VTERM_COLOR_INDEXED;
4737 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4738 &color.index);
4739 // The first valid index starts at 1.
4740 color.index -= 1;
4741
4742 vterm_state_set_palette_color(state, index, &color);
4743 }
4744}
4745
4746 static void
4747term_update_palette(term_T *term)
4748{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004749#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004750 if (term_use_palette()
4751 && (term->tl_palette != NULL
4752 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004753 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004754 {
4755 if (term->tl_palette != NULL)
4756 set_vterm_palette(term->tl_vterm, term->tl_palette);
4757 else
4758 init_vterm_ansi_colors(term->tl_vterm);
4759 }
4760 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004761#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004762 term_reset_palette(term->tl_vterm);
4763}
4764
4765/*
4766 * Called when option 'termguicolors' is changed.
4767 */
4768 void
4769term_update_palette_all()
4770{
4771 term_T *term;
4772
4773 FOR_ALL_TERMS(term)
4774 {
4775 if (term->tl_vterm == NULL)
4776 continue;
4777 term_update_palette(term);
4778 }
4779}
4780
4781/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004782 * Called when option 'background' or 'termguicolors' was set,
4783 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02004784 */
4785 void
4786term_update_colors_all(void)
4787{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004788 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02004789
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004790 FOR_ALL_TERMS(term)
4791 {
4792 if (term->tl_vterm == NULL)
4793 continue;
4794 init_default_colors(term);
4795 vterm_state_set_default_colors(
4796 vterm_obtain_state(term->tl_vterm),
4797 &term->tl_default_color.fg,
4798 &term->tl_default_color.bg);
4799 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004800}
4801
4802/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004803 * Return the text to show for the buffer name and status.
4804 */
4805 char_u *
4806term_get_status_text(term_T *term)
4807{
4808 if (term->tl_status_text == NULL)
4809 {
4810 char_u *txt;
4811 size_t len;
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004812 char_u *fname;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004813
4814 if (term->tl_normal_mode)
4815 {
4816 if (term_job_running(term))
4817 txt = (char_u *)_("Terminal");
4818 else
4819 txt = (char_u *)_("Terminal-finished");
4820 }
4821 else if (term->tl_title != NULL)
4822 txt = term->tl_title;
4823 else if (term_none_open(term))
4824 txt = (char_u *)_("active");
4825 else if (term_job_running(term))
4826 txt = (char_u *)_("running");
4827 else
4828 txt = (char_u *)_("finished");
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004829 fname = buf_get_fname(term->tl_buffer);
4830 len = 9 + STRLEN(fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004831 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004832 if (term->tl_status_text != NULL)
4833 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004834 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004835 }
4836 return term->tl_status_text;
4837}
4838
4839/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00004840 * Clear the cached value of the status text.
4841 */
4842 void
4843term_clear_status_text(term_T *term)
4844{
4845 VIM_CLEAR(term->tl_status_text);
4846}
4847
4848/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004849 * Mark references in jobs of terminals.
4850 */
4851 int
4852set_ref_in_term(int copyID)
4853{
4854 int abort = FALSE;
4855 term_T *term;
4856 typval_T tv;
4857
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004858 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004859 if (term->tl_job != NULL)
4860 {
4861 tv.v_type = VAR_JOB;
4862 tv.vval.v_job = term->tl_job;
4863 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4864 }
4865 return abort;
4866}
4867
4868/*
4869 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004870 * Returns NULL when the buffer is not for a terminal window and logs a message
4871 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004872 */
4873 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004874term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004875{
4876 buf_T *buf;
4877
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004878 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004879 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004880 --emsg_off;
4881 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004882 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01004883 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004884 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004885 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004886 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004887 return buf;
4888}
4889
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004890 static void
4891clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004892{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004893 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004894 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4895 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004896}
4897
4898 static void
4899dump_term_color(FILE *fd, VTermColor *color)
4900{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004901 int index;
4902
4903 if (VTERM_COLOR_IS_INDEXED(color))
4904 index = color->index + 1;
4905 else if (color->type == 0)
4906 // use RGB values
4907 index = 255;
4908 else
4909 // default color
4910 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004911 fprintf(fd, "%02x%02x%02x%d",
4912 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004913 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004914}
4915
4916/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004917 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004918 *
4919 * Each screen cell in full is:
4920 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4921 * {characters} is a space for an empty cell
4922 * For a double-width character "+" is changed to "*" and the next cell is
4923 * skipped.
4924 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4925 * when "&" use the same as the previous cell.
4926 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4927 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4928 * {color-idx} is a number from 0 to 255
4929 *
4930 * Screen cell with same width, attributes and color as the previous one:
4931 * |{characters}
4932 *
4933 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4934 *
4935 * Repeating the previous screen cell:
4936 * @{count}
4937 */
4938 void
4939f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4940{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02004941 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004942 term_T *term;
4943 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004944 int max_height = 0;
4945 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004946 stat_T st;
4947 FILE *fd;
4948 VTermPos pos;
4949 VTermScreen *screen;
4950 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004951 VTermState *state;
4952 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004953
4954 if (check_restricted() || check_secure())
4955 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02004956
4957 if (in_vim9script()
4958 && (check_for_buffer_arg(argvars, 0) == FAIL
4959 || check_for_string_arg(argvars, 1) == FAIL
4960 || check_for_opt_dict_arg(argvars, 2) == FAIL))
4961 return;
4962
4963 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004964 if (buf == NULL)
4965 return;
4966 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004967 if (term->tl_vterm == NULL)
4968 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00004969 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004970 return;
4971 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004972
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004973 if (argvars[2].v_type != VAR_UNKNOWN)
4974 {
4975 dict_T *d;
4976
4977 if (argvars[2].v_type != VAR_DICT)
4978 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00004979 emsg(_(e_dictionary_required));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004980 return;
4981 }
4982 d = argvars[2].vval.v_dict;
4983 if (d != NULL)
4984 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004985 max_height = dict_get_number(d, (char_u *)"rows");
4986 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004987 }
4988 }
4989
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004990 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004991 if (fname == NULL)
4992 return;
4993 if (mch_stat((char *)fname, &st) >= 0)
4994 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00004995 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004996 return;
4997 }
4998
Bram Moolenaard96ff162018-02-18 22:13:29 +01004999 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5000 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005001 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005002 return;
5003 }
5004
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005005 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005006
5007 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005008 state = vterm_obtain_state(term->tl_vterm);
5009 vterm_state_get_cursorpos(state, &cursor_pos);
5010
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005011 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5012 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005013 {
5014 int repeat = 0;
5015
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005016 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5017 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005018 {
5019 VTermScreenCell cell;
5020 int same_attr;
5021 int same_chars = TRUE;
5022 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005023 int is_cursor_pos = (pos.col == cursor_pos.col
5024 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005025
5026 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005027 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005028
5029 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5030 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005031 int c = cell.chars[i];
5032 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005033 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005034
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005035 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005036 if (i == 0)
5037 {
5038 c = (c == NUL) ? ' ' : c;
5039 pc = (pc == NUL) ? ' ' : pc;
5040 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005041 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005042 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005043 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005044 break;
5045 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005046 same_attr = vtermAttr2hl(&cell.attrs)
5047 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005048 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5049 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005050 if (same_chars && cell.width == prev_cell.width && same_attr
5051 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005052 {
5053 ++repeat;
5054 }
5055 else
5056 {
5057 if (repeat > 0)
5058 {
5059 fprintf(fd, "@%d", repeat);
5060 repeat = 0;
5061 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005062 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005063
5064 if (cell.chars[0] == NUL)
5065 fputs(" ", fd);
5066 else
5067 {
5068 char_u charbuf[10];
5069 int len;
5070
5071 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5072 && cell.chars[i] != NUL; ++i)
5073 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005074 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005075 fwrite(charbuf, len, 1, fd);
5076 }
5077 }
5078
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005079 // When only the characters differ we don't write anything, the
5080 // following "|", "@" or NL will indicate using the same
5081 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005082 if (cell.width != prev_cell.width || !same_attr)
5083 {
5084 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005085 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005086 else
5087 fputs("+", fd);
5088
5089 if (same_attr)
5090 {
5091 fputs("&", fd);
5092 }
5093 else
5094 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005095 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005096 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005097 fputs("&", fd);
5098 else
5099 {
5100 fputs("#", fd);
5101 dump_term_color(fd, &cell.fg);
5102 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005103 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005104 fputs("&", fd);
5105 else
5106 {
5107 fputs("#", fd);
5108 dump_term_color(fd, &cell.bg);
5109 }
5110 }
5111 }
5112
5113 prev_cell = cell;
5114 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005115
5116 if (cell.width == 2)
5117 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005118 }
5119 if (repeat > 0)
5120 fprintf(fd, "@%d", repeat);
5121 fputs("\n", fd);
5122 }
5123
5124 fclose(fd);
5125}
5126
5127/*
5128 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5129 */
5130 static void
5131dump_is_corrupt(garray_T *gap)
5132{
5133 ga_concat(gap, (char_u *)"CORRUPT");
5134}
5135
5136 static void
5137append_cell(garray_T *gap, cellattr_T *cell)
5138{
5139 if (ga_grow(gap, 1) == OK)
5140 {
5141 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5142 ++gap->ga_len;
5143 }
5144}
5145
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005146 static void
5147clear_cellattr(cellattr_T *cell)
5148{
5149 CLEAR_FIELD(*cell);
5150 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5151 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5152}
5153
Bram Moolenaard96ff162018-02-18 22:13:29 +01005154/*
5155 * Read the dump file from "fd" and append lines to the current buffer.
5156 * Return the cell width of the longest line.
5157 */
5158 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005159read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005160{
5161 int c;
5162 garray_T ga_text;
5163 garray_T ga_cell;
5164 char_u *prev_char = NULL;
5165 int attr = 0;
5166 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005167 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005168 term_T *term = curbuf->b_term;
5169 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005170 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005171
5172 ga_init2(&ga_text, 1, 90);
5173 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005174 clear_cellattr(&cell);
5175 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005176 cursor_pos->row = -1;
5177 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005178
5179 c = fgetc(fd);
5180 for (;;)
5181 {
5182 if (c == EOF)
5183 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005184 if (c == '\r')
5185 {
5186 // DOS line endings? Ignore.
5187 c = fgetc(fd);
5188 }
5189 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005190 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005191 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005192 if (ga_text.ga_data == NULL)
5193 dump_is_corrupt(&ga_text);
5194 if (ga_grow(&term->tl_scrollback, 1) == OK)
5195 {
5196 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5197 + term->tl_scrollback.ga_len;
5198
5199 if (max_cells < ga_cell.ga_len)
5200 max_cells = ga_cell.ga_len;
5201 line->sb_cols = ga_cell.ga_len;
5202 line->sb_cells = ga_cell.ga_data;
5203 line->sb_fill_attr = term->tl_default_color;
5204 ++term->tl_scrollback.ga_len;
5205 ga_init(&ga_cell);
5206
5207 ga_append(&ga_text, NUL);
5208 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5209 ga_text.ga_len, FALSE);
5210 }
5211 else
5212 ga_clear(&ga_cell);
5213 ga_text.ga_len = 0;
5214
5215 c = fgetc(fd);
5216 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005217 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005218 {
5219 int prev_len = ga_text.ga_len;
5220
Bram Moolenaar9271d052018-02-25 21:39:46 +01005221 if (c == '>')
5222 {
5223 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005224 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005225 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5226 cursor_pos->col = ga_cell.ga_len;
5227 }
5228
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005229 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005230 c = fgetc(fd);
5231 if (c != EOF)
5232 ga_append(&ga_text, c);
5233 for (;;)
5234 {
5235 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005236 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005237 || c == EOF || c == '\n')
5238 break;
5239 ga_append(&ga_text, c);
5240 }
5241
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005242 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005243 vim_free(prev_char);
5244 if (ga_text.ga_data != NULL)
5245 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5246 ga_text.ga_len - prev_len);
5247
Bram Moolenaar9271d052018-02-25 21:39:46 +01005248 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005249 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005250 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005251 }
5252 else if (c == '+' || c == '*')
5253 {
5254 int is_bg;
5255
5256 cell.width = c == '+' ? 1 : 2;
5257
5258 c = fgetc(fd);
5259 if (c == '&')
5260 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005261 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005262 c = fgetc(fd);
5263 }
5264 else if (isdigit(c))
5265 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005266 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005267 attr = 0;
5268 while (isdigit(c))
5269 {
5270 attr = attr * 10 + (c - '0');
5271 c = fgetc(fd);
5272 }
5273 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005274
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005275 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005276 for (is_bg = 0; is_bg <= 1; ++is_bg)
5277 {
5278 if (c == '&')
5279 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005280 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005281 c = fgetc(fd);
5282 }
5283 else if (c == '#')
5284 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005285 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005286
5287 c = fgetc(fd);
5288 red = hex2nr(c);
5289 c = fgetc(fd);
5290 red = (red << 4) + hex2nr(c);
5291 c = fgetc(fd);
5292 green = hex2nr(c);
5293 c = fgetc(fd);
5294 green = (green << 4) + hex2nr(c);
5295 c = fgetc(fd);
5296 blue = hex2nr(c);
5297 c = fgetc(fd);
5298 blue = (blue << 4) + hex2nr(c);
5299 c = fgetc(fd);
5300 if (!isdigit(c))
5301 dump_is_corrupt(&ga_text);
5302 while (isdigit(c))
5303 {
5304 index = index * 10 + (c - '0');
5305 c = fgetc(fd);
5306 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005307 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005308 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005309 type = VTERM_COLOR_RGB;
5310 if (index == 0)
5311 {
5312 if (is_bg)
5313 type |= VTERM_COLOR_DEFAULT_BG;
5314 else
5315 type |= VTERM_COLOR_DEFAULT_FG;
5316 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005317 }
5318 else
5319 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005320 type = VTERM_COLOR_INDEXED;
5321 index -= 1;
5322 }
5323 if (is_bg)
5324 {
5325 cell.bg.type = type;
5326 cell.bg.red = red;
5327 cell.bg.green = green;
5328 cell.bg.blue = blue;
5329 cell.bg.index = index;
5330 }
5331 else
5332 {
5333 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005334 cell.fg.red = red;
5335 cell.fg.green = green;
5336 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005337 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005338 }
5339 }
5340 else
5341 dump_is_corrupt(&ga_text);
5342 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005343 }
5344 else
5345 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005346 }
5347 else
5348 dump_is_corrupt(&ga_text);
5349
5350 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005351 if (cell.width == 2)
5352 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005353 }
5354 else if (c == '@')
5355 {
5356 if (prev_char == NULL)
5357 dump_is_corrupt(&ga_text);
5358 else
5359 {
5360 int count = 0;
5361
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005362 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005363 for (;;)
5364 {
5365 c = fgetc(fd);
5366 if (!isdigit(c))
5367 break;
5368 count = count * 10 + (c - '0');
5369 }
5370
5371 while (count-- > 0)
5372 {
5373 ga_concat(&ga_text, prev_char);
5374 append_cell(&ga_cell, &cell);
5375 }
5376 }
5377 }
5378 else
5379 {
5380 dump_is_corrupt(&ga_text);
5381 c = fgetc(fd);
5382 }
5383 }
5384
5385 if (ga_text.ga_len > 0)
5386 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005387 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005388 dump_is_corrupt(&ga_text);
5389 ga_append(&ga_text, NUL);
5390 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5391 ga_text.ga_len, FALSE);
5392 }
5393
5394 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005395 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005396 vim_free(prev_char);
5397
5398 return max_cells;
5399}
5400
5401/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005402 * Return an allocated string with at least "text_width" "=" characters and
5403 * "fname" inserted in the middle.
5404 */
5405 static char_u *
5406get_separator(int text_width, char_u *fname)
5407{
5408 int width = MAX(text_width, curwin->w_width);
5409 char_u *textline;
5410 int fname_size;
5411 char_u *p = fname;
5412 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005413 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005414
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005415 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005416 if (textline == NULL)
5417 return NULL;
5418
5419 fname_size = vim_strsize(fname);
5420 if (fname_size < width - 8)
5421 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005422 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005423 width = MAX(text_width, fname_size + 8);
5424 }
5425 else if (fname_size > width - 8)
5426 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005427 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005428 p = gettail(fname);
5429 fname_size = vim_strsize(p);
5430 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005431 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005432 while (fname_size > width - 8)
5433 {
5434 p += (*mb_ptr2len)(p);
5435 fname_size = vim_strsize(p);
5436 }
5437
5438 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5439 textline[i] = '=';
5440 textline[i++] = ' ';
5441
5442 STRCPY(textline + i, p);
5443 off = STRLEN(textline);
5444 textline[off] = ' ';
5445 for (i = 1; i < (width - fname_size) / 2; ++i)
5446 textline[off + i] = '=';
5447 textline[off + i] = NUL;
5448
5449 return textline;
5450}
5451
5452/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005453 * Common for "term_dumpdiff()" and "term_dumpload()".
5454 */
5455 static void
5456term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5457{
5458 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005459 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005460 char_u buf1[NUMBUFLEN];
5461 char_u buf2[NUMBUFLEN];
5462 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005463 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005464 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005465 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005466 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005467 char_u *textline = NULL;
5468
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005469 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005470 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005471 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005472 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005473 if (fname1 == NULL || (do_diff && fname2 == NULL))
5474 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005475 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005476 return;
5477 }
5478 fd1 = mch_fopen((char *)fname1, READBIN);
5479 if (fd1 == NULL)
5480 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005481 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005482 return;
5483 }
5484 if (do_diff)
5485 {
5486 fd2 = mch_fopen((char *)fname2, READBIN);
5487 if (fd2 == NULL)
5488 {
5489 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005490 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005491 return;
5492 }
5493 }
5494
5495 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005496 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5497 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5498 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5499 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5500 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005501
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005502 if (opt.jo_term_name == NULL)
5503 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005504 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005505
Bram Moolenaar51e14382019-05-25 20:21:28 +02005506 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005507 if (fname_tofree != NULL)
5508 {
5509 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5510 opt.jo_term_name = fname_tofree;
5511 }
5512 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005513
Bram Moolenaar87abab92019-06-03 21:14:59 +02005514 if (opt.jo_bufnr_buf != NULL)
5515 {
5516 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5517
5518 // With "bufnr" argument: enter the window with this buffer and make it
5519 // empty.
5520 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005521 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005522 else
5523 {
5524 buf = curbuf;
5525 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005526 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005527 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005528 redraw_later(NOT_VALID);
5529 }
5530 }
5531 else
5532 // Create a new terminal window.
5533 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5534
Bram Moolenaard96ff162018-02-18 22:13:29 +01005535 if (buf != NULL && buf->b_term != NULL)
5536 {
5537 int i;
5538 linenr_T bot_lnum;
5539 linenr_T lnum;
5540 term_T *term = buf->b_term;
5541 int width;
5542 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005543 VTermPos cursor_pos1;
5544 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005545
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005546 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005547
Bram Moolenaard96ff162018-02-18 22:13:29 +01005548 rettv->vval.v_number = buf->b_fnum;
5549
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005550 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005551 width = read_dump_file(fd1, &cursor_pos1);
5552
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005553 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005554 if (cursor_pos1.row >= 0)
5555 {
5556 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5557 coladvance(cursor_pos1.col);
5558 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005559
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005560 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005561 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005562
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005563 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005564 if (!do_diff)
5565 goto theend;
5566
5567 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5568
Bram Moolenaar4a696342018-04-05 18:45:26 +02005569 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005570 if (textline == NULL)
5571 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005572 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5573 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5574 vim_free(textline);
5575
5576 textline = get_separator(width, fname2);
5577 if (textline == NULL)
5578 goto theend;
5579 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5580 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005581 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005582
5583 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005584 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005585 if (width2 > width)
5586 {
5587 vim_free(textline);
5588 textline = alloc(width2 + 1);
5589 if (textline == NULL)
5590 goto theend;
5591 width = width2;
5592 textline[width] = NUL;
5593 }
5594 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5595
5596 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5597 {
5598 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5599 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005600 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005601 for (i = 0; i < width; ++i)
5602 textline[i] = '-';
5603 }
5604 else
5605 {
5606 char_u *line1;
5607 char_u *line2;
5608 char_u *p1;
5609 char_u *p2;
5610 int col;
5611 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5612 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5613 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5614 ->sb_cells;
5615
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005616 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005617 line1 = vim_strsave(ml_get(lnum));
5618 if (line1 == NULL)
5619 break;
5620 p1 = line1;
5621
5622 line2 = ml_get(lnum + bot_lnum);
5623 p2 = line2;
5624 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5625 {
5626 int len1 = utfc_ptr2len(p1);
5627 int len2 = utfc_ptr2len(p2);
5628
5629 textline[col] = ' ';
5630 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005631 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005632 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005633 else if (lnum == cursor_pos1.row + 1
5634 && col == cursor_pos1.col
5635 && (cursor_pos1.row != cursor_pos2.row
5636 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005637 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005638 textline[col] = '>';
5639 else if (lnum == cursor_pos2.row + 1
5640 && col == cursor_pos2.col
5641 && (cursor_pos1.row != cursor_pos2.row
5642 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005643 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005644 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005645 else if (cellattr1 != NULL && cellattr2 != NULL)
5646 {
5647 if ((cellattr1 + col)->width
5648 != (cellattr2 + col)->width)
5649 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005650 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005651 &(cellattr2 + col)->fg))
5652 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005653 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005654 &(cellattr2 + col)->bg))
5655 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005656 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5657 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005658 textline[col] = 'a';
5659 }
5660 p1 += len1;
5661 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005662 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005663 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005664
5665 while (col < width)
5666 {
5667 if (*p1 == NUL && *p2 == NUL)
5668 textline[col] = '?';
5669 else if (*p1 == NUL)
5670 {
5671 textline[col] = '+';
5672 p2 += utfc_ptr2len(p2);
5673 }
5674 else
5675 {
5676 textline[col] = '-';
5677 p1 += utfc_ptr2len(p1);
5678 }
5679 ++col;
5680 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005681
5682 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005683 }
5684 if (add_empty_scrollback(term, &term->tl_default_color,
5685 term->tl_top_diff_rows) == OK)
5686 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5687 ++bot_lnum;
5688 }
5689
5690 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5691 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005692 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005693 for (i = 0; i < width; ++i)
5694 textline[i] = '+';
5695 if (add_empty_scrollback(term, &term->tl_default_color,
5696 term->tl_top_diff_rows) == OK)
5697 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5698 ++lnum;
5699 ++bot_lnum;
5700 }
5701
5702 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005703
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005704 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005705 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005706 }
5707
5708theend:
5709 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005710 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005711 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005712 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005713 fclose(fd2);
5714}
5715
5716/*
5717 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5718 * bottom files.
5719 * Return FAIL when this is not possible.
5720 */
5721 int
5722term_swap_diff()
5723{
5724 term_T *term = curbuf->b_term;
5725 linenr_T line_count;
5726 linenr_T top_rows;
5727 linenr_T bot_rows;
5728 linenr_T bot_start;
5729 linenr_T lnum;
5730 char_u *p;
5731 sb_line_T *sb_line;
5732
5733 if (term == NULL
5734 || !term_is_finished(curbuf)
5735 || term->tl_top_diff_rows == 0
5736 || term->tl_scrollback.ga_len == 0)
5737 return FAIL;
5738
5739 line_count = curbuf->b_ml.ml_line_count;
5740 top_rows = term->tl_top_diff_rows;
5741 bot_rows = term->tl_bot_diff_rows;
5742 bot_start = line_count - bot_rows;
5743 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5744
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005745 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005746 for (lnum = 1; lnum <= top_rows; ++lnum)
5747 {
5748 p = vim_strsave(ml_get(1));
5749 if (p == NULL)
5750 return OK;
5751 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005752 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005753 vim_free(p);
5754 }
5755
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005756 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005757 for (lnum = 1; lnum <= bot_rows; ++lnum)
5758 {
5759 p = vim_strsave(ml_get(bot_start + lnum));
5760 if (p == NULL)
5761 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005762 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005763 ml_append(lnum - 1, p, 0, FALSE);
5764 vim_free(p);
5765 }
5766
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005767 // move top title to bottom
5768 p = vim_strsave(ml_get(bot_rows + 1));
5769 if (p == NULL)
5770 return OK;
5771 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005772 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005773 vim_free(p);
5774
5775 // move bottom title to top
5776 p = vim_strsave(ml_get(line_count - top_rows));
5777 if (p == NULL)
5778 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005779 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005780 ml_append(bot_rows, p, 0, FALSE);
5781 vim_free(p);
5782
Bram Moolenaard96ff162018-02-18 22:13:29 +01005783 if (top_rows == bot_rows)
5784 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005785 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005786 for (lnum = 0; lnum < top_rows; ++lnum)
5787 {
5788 sb_line_T temp;
5789
5790 temp = *(sb_line + lnum);
5791 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5792 *(sb_line + bot_start + lnum) = temp;
5793 }
5794 }
5795 else
5796 {
5797 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005798 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005799
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005800 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005801 if (temp != NULL)
5802 {
5803 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5804 mch_memmove(term->tl_scrollback.ga_data,
5805 temp + bot_start,
5806 sizeof(sb_line_T) * bot_rows);
5807 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5808 temp + top_rows,
5809 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5810 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5811 + line_count - top_rows,
5812 temp,
5813 sizeof(sb_line_T) * top_rows);
5814 vim_free(temp);
5815 }
5816 }
5817
5818 term->tl_top_diff_rows = bot_rows;
5819 term->tl_bot_diff_rows = top_rows;
5820
5821 update_screen(NOT_VALID);
5822 return OK;
5823}
5824
5825/*
5826 * "term_dumpdiff(filename, filename, options)" function
5827 */
5828 void
5829f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5830{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005831 if (in_vim9script()
5832 && (check_for_string_arg(argvars, 0) == FAIL
5833 || check_for_string_arg(argvars, 1) == FAIL
5834 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5835 return;
5836
Bram Moolenaard96ff162018-02-18 22:13:29 +01005837 term_load_dump(argvars, rettv, TRUE);
5838}
5839
5840/*
5841 * "term_dumpload(filename, options)" function
5842 */
5843 void
5844f_term_dumpload(typval_T *argvars, typval_T *rettv)
5845{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005846 if (in_vim9script()
5847 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02005848 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005849 return;
5850
Bram Moolenaard96ff162018-02-18 22:13:29 +01005851 term_load_dump(argvars, rettv, FALSE);
5852}
5853
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005854/*
5855 * "term_getaltscreen(buf)" function
5856 */
5857 void
5858f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5859{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005860 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005861
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005862 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5863 return;
5864
5865 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005866 if (buf == NULL)
5867 return;
5868 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5869}
5870
5871/*
5872 * "term_getattr(attr, name)" function
5873 */
5874 void
5875f_term_getattr(typval_T *argvars, typval_T *rettv)
5876{
5877 int attr;
5878 size_t i;
5879 char_u *name;
5880
5881 static struct {
5882 char *name;
5883 int attr;
5884 } attrs[] = {
5885 {"bold", HL_BOLD},
5886 {"italic", HL_ITALIC},
5887 {"underline", HL_UNDERLINE},
5888 {"strike", HL_STRIKETHROUGH},
5889 {"reverse", HL_INVERSE},
5890 };
5891
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02005892 if (in_vim9script()
5893 && (check_for_number_arg(argvars, 0) == FAIL
5894 || check_for_string_arg(argvars, 1) == FAIL))
5895 return;
5896
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005897 attr = tv_get_number(&argvars[0]);
5898 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005899 if (name == NULL)
5900 return;
5901
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005902 if (attr > HL_ALL)
5903 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02005904 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005905 if (STRCMP(name, attrs[i].name) == 0)
5906 {
5907 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5908 break;
5909 }
5910}
5911
5912/*
5913 * "term_getcursor(buf)" function
5914 */
5915 void
5916f_term_getcursor(typval_T *argvars, typval_T *rettv)
5917{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005918 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005919 term_T *term;
5920 list_T *l;
5921 dict_T *d;
5922
5923 if (rettv_list_alloc(rettv) == FAIL)
5924 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005925
5926 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5927 return;
5928
5929 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005930 if (buf == NULL)
5931 return;
5932 term = buf->b_term;
5933
5934 l = rettv->vval.v_list;
5935 list_append_number(l, term->tl_cursor_pos.row + 1);
5936 list_append_number(l, term->tl_cursor_pos.col + 1);
5937
5938 d = dict_alloc();
5939 if (d != NULL)
5940 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005941 dict_add_number(d, "visible", term->tl_cursor_visible);
5942 dict_add_number(d, "blink", blink_state_is_inverted()
5943 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5944 dict_add_number(d, "shape", term->tl_cursor_shape);
5945 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005946 list_append_dict(l, d);
5947 }
5948}
5949
5950/*
5951 * "term_getjob(buf)" function
5952 */
5953 void
5954f_term_getjob(typval_T *argvars, typval_T *rettv)
5955{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005956 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005957
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005958 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5959 return;
5960
5961 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005962 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005963 {
5964 rettv->v_type = VAR_SPECIAL;
5965 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005966 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005967 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005968
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005969 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005970 rettv->vval.v_job = buf->b_term->tl_job;
5971 if (rettv->vval.v_job != NULL)
5972 ++rettv->vval.v_job->jv_refcount;
5973}
5974
5975 static int
5976get_row_number(typval_T *tv, term_T *term)
5977{
5978 if (tv->v_type == VAR_STRING
5979 && tv->vval.v_string != NULL
5980 && STRCMP(tv->vval.v_string, ".") == 0)
5981 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005982 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005983}
5984
5985/*
5986 * "term_getline(buf, row)" function
5987 */
5988 void
5989f_term_getline(typval_T *argvars, typval_T *rettv)
5990{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02005991 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005992 term_T *term;
5993 int row;
5994
5995 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02005996
5997 if (in_vim9script()
5998 && (check_for_buffer_arg(argvars, 0) == FAIL
5999 || check_for_lnum_arg(argvars, 1) == FAIL))
6000 return;
6001
6002 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006003 if (buf == NULL)
6004 return;
6005 term = buf->b_term;
6006 row = get_row_number(&argvars[1], term);
6007
6008 if (term->tl_vterm == NULL)
6009 {
6010 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6011
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006012 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006013 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6014 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6015 }
6016 else
6017 {
6018 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6019 VTermRect rect;
6020 int len;
6021 char_u *p;
6022
6023 if (row < 0 || row >= term->tl_rows)
6024 return;
6025 len = term->tl_cols * MB_MAXBYTES + 1;
6026 p = alloc(len);
6027 if (p == NULL)
6028 return;
6029 rettv->vval.v_string = p;
6030
6031 rect.start_col = 0;
6032 rect.end_col = term->tl_cols;
6033 rect.start_row = row;
6034 rect.end_row = row + 1;
6035 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6036 }
6037}
6038
6039/*
6040 * "term_getscrolled(buf)" function
6041 */
6042 void
6043f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6044{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006045 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006046
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006047 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6048 return;
6049
6050 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006051 if (buf == NULL)
6052 return;
6053 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6054}
6055
6056/*
6057 * "term_getsize(buf)" function
6058 */
6059 void
6060f_term_getsize(typval_T *argvars, typval_T *rettv)
6061{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006062 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006063 list_T *l;
6064
6065 if (rettv_list_alloc(rettv) == FAIL)
6066 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006067
6068 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6069 return;
6070
6071 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006072 if (buf == NULL)
6073 return;
6074
6075 l = rettv->vval.v_list;
6076 list_append_number(l, buf->b_term->tl_rows);
6077 list_append_number(l, buf->b_term->tl_cols);
6078}
6079
6080/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006081 * "term_setsize(buf, rows, cols)" function
6082 */
6083 void
6084f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6085{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006086 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006087 term_T *term;
6088 varnumber_T rows, cols;
6089
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006090 if (in_vim9script()
6091 && (check_for_buffer_arg(argvars, 0) == FAIL
6092 || check_for_number_arg(argvars, 1) == FAIL
6093 || check_for_number_arg(argvars, 2) == FAIL))
6094 return;
6095
6096 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006097 if (buf == NULL)
6098 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006099 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006100 return;
6101 }
6102 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006103 return;
6104 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006105 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006106 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006107 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006108 cols = cols <= 0 ? term->tl_cols : cols;
6109 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006110 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006111
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006112 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006113 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6114 term_report_winsize(term, term->tl_rows, term->tl_cols);
6115}
6116
6117/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006118 * "term_getstatus(buf)" function
6119 */
6120 void
6121f_term_getstatus(typval_T *argvars, typval_T *rettv)
6122{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006123 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006124 term_T *term;
6125 char_u val[100];
6126
6127 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006128
6129 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6130 return;
6131
6132 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006133 if (buf == NULL)
6134 return;
6135 term = buf->b_term;
6136
6137 if (term_job_running(term))
6138 STRCPY(val, "running");
6139 else
6140 STRCPY(val, "finished");
6141 if (term->tl_normal_mode)
6142 STRCAT(val, ",normal");
6143 rettv->vval.v_string = vim_strsave(val);
6144}
6145
6146/*
6147 * "term_gettitle(buf)" function
6148 */
6149 void
6150f_term_gettitle(typval_T *argvars, typval_T *rettv)
6151{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006152 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006153
6154 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006155
6156 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6157 return;
6158
6159 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006160 if (buf == NULL)
6161 return;
6162
6163 if (buf->b_term->tl_title != NULL)
6164 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6165}
6166
6167/*
6168 * "term_gettty(buf)" function
6169 */
6170 void
6171f_term_gettty(typval_T *argvars, typval_T *rettv)
6172{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006173 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006174 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006175 int num = 0;
6176
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006177 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006178 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006179 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6180 return;
6181
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006182 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006183 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006184 if (buf == NULL)
6185 return;
6186 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006187 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006188
6189 switch (num)
6190 {
6191 case 0:
6192 if (buf->b_term->tl_job != NULL)
6193 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006194 break;
6195 case 1:
6196 if (buf->b_term->tl_job != NULL)
6197 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006198 break;
6199 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006200 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006201 return;
6202 }
6203 if (p != NULL)
6204 rettv->vval.v_string = vim_strsave(p);
6205}
6206
6207/*
6208 * "term_list()" function
6209 */
6210 void
6211f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6212{
6213 term_T *tp;
6214 list_T *l;
6215
6216 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6217 return;
6218
6219 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006220 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006221 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006222 if (list_append_number(l,
6223 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6224 return;
6225}
6226
6227/*
6228 * "term_scrape(buf, row)" function
6229 */
6230 void
6231f_term_scrape(typval_T *argvars, typval_T *rettv)
6232{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006233 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006234 VTermScreen *screen = NULL;
6235 VTermPos pos;
6236 list_T *l;
6237 term_T *term;
6238 char_u *p;
6239 sb_line_T *line;
6240
6241 if (rettv_list_alloc(rettv) == FAIL)
6242 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006243
6244 if (in_vim9script()
6245 && (check_for_buffer_arg(argvars, 0) == FAIL
6246 || check_for_lnum_arg(argvars, 1) == FAIL))
6247 return;
6248
6249 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006250 if (buf == NULL)
6251 return;
6252 term = buf->b_term;
6253
6254 l = rettv->vval.v_list;
6255 pos.row = get_row_number(&argvars[1], term);
6256
6257 if (term->tl_vterm != NULL)
6258 {
6259 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006260 if (screen == NULL) // can't really happen
6261 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006262 p = NULL;
6263 line = NULL;
6264 }
6265 else
6266 {
6267 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6268
6269 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6270 return;
6271 p = ml_get_buf(buf, lnum + 1, FALSE);
6272 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6273 }
6274
6275 for (pos.col = 0; pos.col < term->tl_cols; )
6276 {
6277 dict_T *dcell;
6278 int width;
6279 VTermScreenCellAttrs attrs;
6280 VTermColor fg, bg;
6281 char_u rgb[8];
6282 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6283 int off = 0;
6284 int i;
6285
6286 if (screen == NULL)
6287 {
6288 cellattr_T *cellattr;
6289 int len;
6290
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006291 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006292 if (pos.col >= line->sb_cols)
6293 break;
6294 cellattr = line->sb_cells + pos.col;
6295 width = cellattr->width;
6296 attrs = cellattr->attrs;
6297 fg = cellattr->fg;
6298 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006299 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006300 mch_memmove(mbs, p, len);
6301 mbs[len] = NUL;
6302 p += len;
6303 }
6304 else
6305 {
6306 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006307
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006308 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6309 break;
6310 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6311 {
6312 if (cell.chars[i] == 0)
6313 break;
6314 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6315 }
6316 mbs[off] = NUL;
6317 width = cell.width;
6318 attrs = cell.attrs;
6319 fg = cell.fg;
6320 bg = cell.bg;
6321 }
6322 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006323 if (dcell == NULL)
6324 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006325 list_append_dict(l, dcell);
6326
Bram Moolenaare0be1672018-07-08 16:50:37 +02006327 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006328
6329 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6330 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006331 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006332 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6333 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006334 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006335
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006336 dict_add_number(dcell, "attr",
6337 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006338 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006339
6340 ++pos.col;
6341 if (width == 2)
6342 ++pos.col;
6343 }
6344}
6345
6346/*
6347 * "term_sendkeys(buf, keys)" function
6348 */
6349 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006350f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006351{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006352 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006353 char_u *msg;
6354 term_T *term;
6355
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006356 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006357 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006358 || check_for_string_arg(argvars, 1) == FAIL))
6359 return;
6360
6361 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006362 if (buf == NULL)
6363 return;
6364
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006365 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006366 if (msg == NULL)
6367 return;
6368 term = buf->b_term;
6369 if (term->tl_vterm == NULL)
6370 return;
6371
6372 while (*msg != NUL)
6373 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006374 int c;
6375
6376 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6377 {
6378 c = TO_SPECIAL(msg[1], msg[2]);
6379 msg += 3;
6380 }
6381 else
6382 {
6383 c = PTR2CHAR(msg);
6384 msg += MB_CPTR2LEN(msg);
6385 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006386 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006387 }
6388}
6389
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006390#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6391/*
6392 * "term_getansicolors(buf)" function
6393 */
6394 void
6395f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6396{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006397 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006398 term_T *term;
6399 VTermState *state;
6400 VTermColor color;
6401 char_u hexbuf[10];
6402 int index;
6403 list_T *list;
6404
6405 if (rettv_list_alloc(rettv) == FAIL)
6406 return;
6407
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006408 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6409 return;
6410
6411 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006412 if (buf == NULL)
6413 return;
6414 term = buf->b_term;
6415 if (term->tl_vterm == NULL)
6416 return;
6417
6418 list = rettv->vval.v_list;
6419 state = vterm_obtain_state(term->tl_vterm);
6420 for (index = 0; index < 16; index++)
6421 {
6422 vterm_state_get_palette_color(state, index, &color);
6423 sprintf((char *)hexbuf, "#%02x%02x%02x",
6424 color.red, color.green, color.blue);
6425 if (list_append_string(list, hexbuf, 7) == FAIL)
6426 return;
6427 }
6428}
6429
6430/*
6431 * "term_setansicolors(buf, list)" function
6432 */
6433 void
6434f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6435{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006436 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006437 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006438 listitem_T *li;
6439 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006440
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006441 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006442 && (check_for_buffer_arg(argvars, 0) == FAIL
6443 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006444 return;
6445
6446 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006447 if (buf == NULL)
6448 return;
6449 term = buf->b_term;
6450 if (term->tl_vterm == NULL)
6451 return;
6452
6453 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
6454 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006455 emsg(_(e_list_required));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006456 return;
6457 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01006458 if (argvars[1].vval.v_list->lv_first == &range_list_item
6459 || argvars[1].vval.v_list->lv_len != 16)
6460 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006461 emsg(_(e_invalid_argument));
LemonBoyb2b3acb2022-05-20 10:10:34 +01006462 return;
6463 }
6464
6465 if (term->tl_palette == NULL)
6466 term->tl_palette = ALLOC_MULT(long_u, 16);
6467 if (term->tl_palette == NULL)
6468 return;
6469
6470 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6471 {
6472 char_u *color_name;
6473 guicolor_T guicolor;
6474
6475 color_name = tv_get_string_chk(&li->li_tv);
6476 if (color_name == NULL)
6477 return;
6478
6479 guicolor = GUI_GET_COLOR(color_name);
6480 if (guicolor == INVALCOLOR)
6481 {
6482 semsg(_(e_cannot_allocate_color_str), color_name);
6483 return;
6484 }
6485
6486 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6487 }
6488
6489 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006490}
6491#endif
6492
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006493/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006494 * "term_setapi(buf, api)" function
6495 */
6496 void
6497f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6498{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006499 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006500 term_T *term;
6501 char_u *api;
6502
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006503 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006504 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006505 || check_for_string_arg(argvars, 1) == FAIL))
6506 return;
6507
6508 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006509 if (buf == NULL)
6510 return;
6511 term = buf->b_term;
6512 vim_free(term->tl_api);
6513 api = tv_get_string_chk(&argvars[1]);
6514 if (api != NULL)
6515 term->tl_api = vim_strsave(api);
6516 else
6517 term->tl_api = NULL;
6518}
6519
6520/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006521 * "term_setrestore(buf, command)" function
6522 */
6523 void
6524f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6525{
6526#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006527 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006528 term_T *term;
6529 char_u *cmd;
6530
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006531 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006532 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006533 || check_for_string_arg(argvars, 1) == FAIL))
6534 return;
6535
6536 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006537 if (buf == NULL)
6538 return;
6539 term = buf->b_term;
6540 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006541 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006542 if (cmd != NULL)
6543 term->tl_command = vim_strsave(cmd);
6544 else
6545 term->tl_command = NULL;
6546#endif
6547}
6548
6549/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006550 * "term_setkill(buf, how)" function
6551 */
6552 void
6553f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6554{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006555 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006556 term_T *term;
6557 char_u *how;
6558
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006559 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006560 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006561 || check_for_string_arg(argvars, 1) == FAIL))
6562 return;
6563
6564 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006565 if (buf == NULL)
6566 return;
6567 term = buf->b_term;
6568 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006569 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006570 if (how != NULL)
6571 term->tl_kill = vim_strsave(how);
6572 else
6573 term->tl_kill = NULL;
6574}
6575
6576/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006577 * "term_start(command, options)" function
6578 */
6579 void
6580f_term_start(typval_T *argvars, typval_T *rettv)
6581{
6582 jobopt_T opt;
6583 buf_T *buf;
6584
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006585 if (in_vim9script()
6586 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6587 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6588 return;
6589
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006590 init_job_options(&opt);
6591 if (argvars[1].v_type != VAR_UNKNOWN
6592 && get_job_options(&argvars[1], &opt,
6593 JO_TIMEOUT_ALL + JO_STOPONEXIT
6594 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6595 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6596 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6597 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006598 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006599 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006600 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006601 return;
6602
Bram Moolenaar13568252018-03-16 20:46:58 +01006603 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006604
6605 if (buf != NULL && buf->b_term != NULL)
6606 rettv->vval.v_number = buf->b_fnum;
6607}
6608
6609/*
6610 * "term_wait" function
6611 */
6612 void
6613f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6614{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006615 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006616
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006617 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006618 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006619 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006620 return;
6621
6622 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006623 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006624 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006625 if (buf->b_term->tl_job == NULL)
6626 {
6627 ch_log(NULL, "term_wait(): no job to wait for");
6628 return;
6629 }
6630 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006631 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006632 return;
6633
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006634 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006635 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006636 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6637 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006638 // The job is dead, keep reading channel I/O until the channel is
6639 // closed. buf->b_term may become NULL if the terminal was closed while
6640 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006641 ch_log(NULL, "term_wait(): waiting for channel to close");
6642 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6643 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006644 term_flush_messages();
6645
Bram Moolenaard45aa552018-05-21 22:50:29 +02006646 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006647 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006648 // If the terminal is closed when the channel is closed the
6649 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006650 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006651 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6652 // came here from a close callback, only wait one time
6653 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006654 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006655
6656 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006657 }
6658 else
6659 {
6660 long wait = 10L;
6661
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006662 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006663
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006664 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006665 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006666 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006667 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006668
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006669 // Flushing messages on channels is hopefully sufficient.
6670 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006671 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006672 }
6673}
6674
6675/*
6676 * Called when a channel has sent all the lines to a terminal.
6677 * Send a CTRL-D to mark the end of the text.
6678 */
6679 void
6680term_send_eof(channel_T *ch)
6681{
6682 term_T *term;
6683
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006684 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006685 if (term->tl_job == ch->ch_job)
6686 {
6687 if (term->tl_eof_chars != NULL)
6688 {
6689 channel_send(ch, PART_IN, term->tl_eof_chars,
6690 (int)STRLEN(term->tl_eof_chars), NULL);
6691 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6692 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006693# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006694 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006695 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006696 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6697# endif
6698 }
6699}
6700
Bram Moolenaar113e1072019-01-20 15:30:40 +01006701#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006702 job_T *
6703term_getjob(term_T *term)
6704{
6705 return term != NULL ? term->tl_job : NULL;
6706}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006707#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006708
Bram Moolenaar4f974752019-02-17 17:44:42 +01006709# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006710
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006711///////////////////////////////////////
6712// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006713#ifdef PROTO
6714typedef int COORD;
6715typedef int DWORD;
6716typedef int HANDLE;
6717typedef int *DWORD_PTR;
6718typedef int HPCON;
6719typedef int HRESULT;
6720typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006721typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006722typedef int PSIZE_T;
6723typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006724typedef int BOOL;
6725# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006726#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006727
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006728HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6729HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6730HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006731BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6732BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6733void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006734
6735 static int
6736dyn_conpty_init(int verbose)
6737{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006738 static HMODULE hKerneldll = NULL;
6739 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006740 static struct
6741 {
6742 char *name;
6743 FARPROC *ptr;
6744 } conpty_entry[] =
6745 {
6746 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6747 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6748 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6749 {"InitializeProcThreadAttributeList",
6750 (FARPROC*)&pInitializeProcThreadAttributeList},
6751 {"UpdateProcThreadAttribute",
6752 (FARPROC*)&pUpdateProcThreadAttribute},
6753 {"DeleteProcThreadAttributeList",
6754 (FARPROC*)&pDeleteProcThreadAttributeList},
6755 {NULL, NULL}
6756 };
6757
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006758 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006759 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006760 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006761 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006762 return FAIL;
6763 }
6764
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006765 // No need to initialize twice.
6766 if (hKerneldll)
6767 return OK;
6768
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006769 hKerneldll = vimLoadLib("kernel32.dll");
6770 for (i = 0; conpty_entry[i].name != NULL
6771 && conpty_entry[i].ptr != NULL; ++i)
6772 {
6773 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6774 conpty_entry[i].name)) == NULL)
6775 {
6776 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006777 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006778 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006779 return FAIL;
6780 }
6781 }
6782
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006783 return OK;
6784}
6785
6786 static int
6787conpty_term_and_job_init(
6788 term_T *term,
6789 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006790 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006791 jobopt_T *opt,
6792 jobopt_T *orig_opt)
6793{
6794 WCHAR *cmd_wchar = NULL;
6795 WCHAR *cmd_wchar_copy = NULL;
6796 WCHAR *cwd_wchar = NULL;
6797 WCHAR *env_wchar = NULL;
6798 channel_T *channel = NULL;
6799 job_T *job = NULL;
6800 HANDLE jo = NULL;
6801 garray_T ga_cmd, ga_env;
6802 char_u *cmd = NULL;
6803 HRESULT hr;
6804 COORD consize;
6805 SIZE_T breq;
6806 PROCESS_INFORMATION proc_info;
6807 HANDLE i_theirs = NULL;
6808 HANDLE o_theirs = NULL;
6809 HANDLE i_ours = NULL;
6810 HANDLE o_ours = NULL;
6811
Bram Moolenaar04935fb2022-01-08 16:19:22 +00006812 ga_init2(&ga_cmd, sizeof(char*), 20);
6813 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006814
6815 if (argvar->v_type == VAR_STRING)
6816 {
6817 cmd = argvar->vval.v_string;
6818 }
6819 else if (argvar->v_type == VAR_LIST)
6820 {
6821 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6822 goto failed;
6823 cmd = ga_cmd.ga_data;
6824 }
6825 if (cmd == NULL || *cmd == NUL)
6826 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006827 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006828 goto failed;
6829 }
6830
6831 term->tl_arg0_cmd = vim_strsave(cmd);
6832
6833 cmd_wchar = enc_to_utf16(cmd, NULL);
6834
6835 if (cmd_wchar != NULL)
6836 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006837 // Request by CreateProcessW
6838 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006839 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006840 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6841 }
6842
6843 ga_clear(&ga_cmd);
6844 if (cmd_wchar == NULL)
6845 goto failed;
6846 if (opt->jo_cwd != NULL)
6847 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6848
6849 win32_build_env(opt->jo_env, &ga_env, TRUE);
6850 env_wchar = ga_env.ga_data;
6851
6852 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6853 goto failed;
6854 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6855 goto failed;
6856
6857 consize.X = term->tl_cols;
6858 consize.Y = term->tl_rows;
6859 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6860 &term->tl_conpty);
6861 if (FAILED(hr))
6862 goto failed;
6863
6864 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6865
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006866 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006867 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006868 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006869 if (!term->tl_siex.lpAttributeList)
6870 goto failed;
6871 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6872 0, &breq))
6873 goto failed;
6874 if (!pUpdateProcThreadAttribute(
6875 term->tl_siex.lpAttributeList, 0,
6876 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6877 sizeof(HPCON), NULL, NULL))
6878 goto failed;
6879
6880 channel = add_channel();
6881 if (channel == NULL)
6882 goto failed;
6883
6884 job = job_alloc();
6885 if (job == NULL)
6886 goto failed;
6887 if (argvar->v_type == VAR_STRING)
6888 {
6889 int argc;
6890
6891 build_argv_from_string(cmd, &job->jv_argv, &argc);
6892 }
6893 else
6894 {
6895 int argc;
6896
6897 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6898 }
6899
6900 if (opt->jo_set & JO_IN_BUF)
6901 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6902
6903 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6904 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02006905 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006906 env_wchar, cwd_wchar,
6907 &term->tl_siex.StartupInfo, &proc_info))
6908 goto failed;
6909
6910 CloseHandle(i_theirs);
6911 CloseHandle(o_theirs);
6912
6913 channel_set_pipes(channel,
6914 (sock_T)i_ours,
6915 (sock_T)o_ours,
6916 (sock_T)o_ours);
6917
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006918 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006919 channel->ch_write_text_mode = TRUE;
6920
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006921 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006922 channel->ch_anonymous_pipe = TRUE;
6923
6924 jo = CreateJobObject(NULL, NULL);
6925 if (jo == NULL)
6926 goto failed;
6927
6928 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6929 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006930 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006931 CloseHandle(jo);
6932 jo = NULL;
6933 }
6934
6935 ResumeThread(proc_info.hThread);
6936 CloseHandle(proc_info.hThread);
6937
6938 vim_free(cmd_wchar);
6939 vim_free(cmd_wchar_copy);
6940 vim_free(cwd_wchar);
6941 vim_free(env_wchar);
6942
6943 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6944 goto failed;
6945
Bram Moolenaar30b9a412022-05-26 14:06:37 +01006946#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01006947 if (term_use_palette())
6948 {
6949 if (term->tl_palette != NULL)
6950 set_vterm_palette(term->tl_vterm, term->tl_palette);
6951 else
6952 init_vterm_ansi_colors(term->tl_vterm);
6953 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01006954#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006955
6956 channel_set_job(channel, job, opt);
6957 job_set_options(job, opt);
6958
6959 job->jv_channel = channel;
6960 job->jv_proc_info = proc_info;
6961 job->jv_job_object = jo;
6962 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006963 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006964 ++job->jv_refcount;
6965 term->tl_job = job;
6966
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006967 // Redirecting stdout and stderr doesn't work at the job level. Instead
6968 // open the file here and handle it in. opt->jo_io was changed in
6969 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006970 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6971 {
6972 char_u *fname = opt->jo_io_name[PART_OUT];
6973
6974 ch_log(channel, "Opening output file %s", fname);
6975 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6976 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006977 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006978 }
6979
6980 return OK;
6981
6982failed:
6983 ga_clear(&ga_cmd);
6984 ga_clear(&ga_env);
6985 vim_free(cmd_wchar);
6986 vim_free(cmd_wchar_copy);
6987 vim_free(cwd_wchar);
6988 if (channel != NULL)
6989 channel_clear(channel);
6990 if (job != NULL)
6991 {
6992 job->jv_channel = NULL;
6993 job_cleanup(job);
6994 }
6995 term->tl_job = NULL;
6996 if (jo != NULL)
6997 CloseHandle(jo);
6998
6999 if (term->tl_siex.lpAttributeList != NULL)
7000 {
7001 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7002 vim_free(term->tl_siex.lpAttributeList);
7003 }
7004 term->tl_siex.lpAttributeList = NULL;
7005 if (o_theirs != NULL)
7006 CloseHandle(o_theirs);
7007 if (o_ours != NULL)
7008 CloseHandle(o_ours);
7009 if (i_ours != NULL)
7010 CloseHandle(i_ours);
7011 if (i_theirs != NULL)
7012 CloseHandle(i_theirs);
7013 if (term->tl_conpty != NULL)
7014 pClosePseudoConsole(term->tl_conpty);
7015 term->tl_conpty = NULL;
7016 return FAIL;
7017}
7018
7019 static void
7020conpty_term_report_winsize(term_T *term, int rows, int cols)
7021{
7022 COORD consize;
7023
7024 consize.X = cols;
7025 consize.Y = rows;
7026 pResizePseudoConsole(term->tl_conpty, consize);
7027}
7028
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007029 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007030term_free_conpty(term_T *term)
7031{
7032 if (term->tl_siex.lpAttributeList != NULL)
7033 {
7034 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7035 vim_free(term->tl_siex.lpAttributeList);
7036 }
7037 term->tl_siex.lpAttributeList = NULL;
7038 if (term->tl_conpty != NULL)
7039 pClosePseudoConsole(term->tl_conpty);
7040 term->tl_conpty = NULL;
7041}
7042
7043 int
7044use_conpty(void)
7045{
7046 return has_conpty;
7047}
7048
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007049# ifndef PROTO
7050
7051#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7052#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007053#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007054
7055void* (*winpty_config_new)(UINT64, void*);
7056void* (*winpty_open)(void*, void*);
7057void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7058BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7059void (*winpty_config_set_mouse_mode)(void*, int);
7060void (*winpty_config_set_initial_size)(void*, int, int);
7061LPCWSTR (*winpty_conin_name)(void*);
7062LPCWSTR (*winpty_conout_name)(void*);
7063LPCWSTR (*winpty_conerr_name)(void*);
7064void (*winpty_free)(void*);
7065void (*winpty_config_free)(void*);
7066void (*winpty_spawn_config_free)(void*);
7067void (*winpty_error_free)(void*);
7068LPCWSTR (*winpty_error_msg)(void*);
7069BOOL (*winpty_set_size)(void*, int, int, void*);
7070HANDLE (*winpty_agent_process)(void*);
7071
7072#define WINPTY_DLL "winpty.dll"
7073
7074static HINSTANCE hWinPtyDLL = NULL;
7075# endif
7076
7077 static int
7078dyn_winpty_init(int verbose)
7079{
7080 int i;
7081 static struct
7082 {
7083 char *name;
7084 FARPROC *ptr;
7085 } winpty_entry[] =
7086 {
7087 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7088 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7089 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7090 {"winpty_config_set_mouse_mode",
7091 (FARPROC*)&winpty_config_set_mouse_mode},
7092 {"winpty_config_set_initial_size",
7093 (FARPROC*)&winpty_config_set_initial_size},
7094 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7095 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7096 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7097 {"winpty_free", (FARPROC*)&winpty_free},
7098 {"winpty_open", (FARPROC*)&winpty_open},
7099 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7100 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7101 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7102 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7103 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7104 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7105 {NULL, NULL}
7106 };
7107
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007108 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007109 if (hWinPtyDLL)
7110 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007111 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7112 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007113 if (*p_winptydll != NUL)
7114 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7115 if (!hWinPtyDLL)
7116 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7117 if (!hWinPtyDLL)
7118 {
7119 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007120 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007121 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7122 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007123 return FAIL;
7124 }
7125 for (i = 0; winpty_entry[i].name != NULL
7126 && winpty_entry[i].ptr != NULL; ++i)
7127 {
7128 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7129 winpty_entry[i].name)) == NULL)
7130 {
7131 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007132 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007133 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007134 return FAIL;
7135 }
7136 }
7137
7138 return OK;
7139}
7140
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007141 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007142winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007143 term_T *term,
7144 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007145 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007146 jobopt_T *opt,
7147 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007148{
7149 WCHAR *cmd_wchar = NULL;
7150 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007151 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007152 channel_T *channel = NULL;
7153 job_T *job = NULL;
7154 DWORD error;
7155 HANDLE jo = NULL;
7156 HANDLE child_process_handle;
7157 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007158 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007159 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007160 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007161 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007162
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007163 ga_init2(&ga_cmd, sizeof(char*), 20);
7164 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007165
7166 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007167 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007168 cmd = argvar->vval.v_string;
7169 }
7170 else if (argvar->v_type == VAR_LIST)
7171 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007172 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007173 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007174 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007175 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007176 if (cmd == NULL || *cmd == NUL)
7177 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007178 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007179 goto failed;
7180 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007181
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007182 term->tl_arg0_cmd = vim_strsave(cmd);
7183
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007184 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007185 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007186 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007187 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007188 if (opt->jo_cwd != NULL)
7189 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007190
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007191 win32_build_env(opt->jo_env, &ga_env, TRUE);
7192 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007193
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007194 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7195 if (term->tl_winpty_config == NULL)
7196 goto failed;
7197
7198 winpty_config_set_mouse_mode(term->tl_winpty_config,
7199 WINPTY_MOUSE_MODE_FORCE);
7200 winpty_config_set_initial_size(term->tl_winpty_config,
7201 term->tl_cols, term->tl_rows);
7202 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7203 if (term->tl_winpty == NULL)
7204 goto failed;
7205
7206 spawn_config = winpty_spawn_config_new(
7207 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7208 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7209 NULL,
7210 cmd_wchar,
7211 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007212 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007213 &winpty_err);
7214 if (spawn_config == NULL)
7215 goto failed;
7216
7217 channel = add_channel();
7218 if (channel == NULL)
7219 goto failed;
7220
7221 job = job_alloc();
7222 if (job == NULL)
7223 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007224 if (argvar->v_type == VAR_STRING)
7225 {
7226 int argc;
7227
7228 build_argv_from_string(cmd, &job->jv_argv, &argc);
7229 }
7230 else
7231 {
7232 int argc;
7233
7234 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7235 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007236
7237 if (opt->jo_set & JO_IN_BUF)
7238 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7239
7240 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7241 &child_thread_handle, &error, &winpty_err))
7242 goto failed;
7243
7244 channel_set_pipes(channel,
7245 (sock_T)CreateFileW(
7246 winpty_conin_name(term->tl_winpty),
7247 GENERIC_WRITE, 0, NULL,
7248 OPEN_EXISTING, 0, NULL),
7249 (sock_T)CreateFileW(
7250 winpty_conout_name(term->tl_winpty),
7251 GENERIC_READ, 0, NULL,
7252 OPEN_EXISTING, 0, NULL),
7253 (sock_T)CreateFileW(
7254 winpty_conerr_name(term->tl_winpty),
7255 GENERIC_READ, 0, NULL,
7256 OPEN_EXISTING, 0, NULL));
7257
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007258 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007259 channel->ch_write_text_mode = TRUE;
7260
7261 jo = CreateJobObject(NULL, NULL);
7262 if (jo == NULL)
7263 goto failed;
7264
7265 if (!AssignProcessToJobObject(jo, child_process_handle))
7266 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007267 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007268 CloseHandle(jo);
7269 jo = NULL;
7270 }
7271
7272 winpty_spawn_config_free(spawn_config);
7273 vim_free(cmd_wchar);
7274 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007275 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007276
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007277 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7278 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007279
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007280#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007281 if (term_use_palette())
7282 {
7283 if (term->tl_palette != NULL)
7284 set_vterm_palette(term->tl_vterm, term->tl_palette);
7285 else
7286 init_vterm_ansi_colors(term->tl_vterm);
7287 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007288#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007289
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007290 channel_set_job(channel, job, opt);
7291 job_set_options(job, opt);
7292
7293 job->jv_channel = channel;
7294 job->jv_proc_info.hProcess = child_process_handle;
7295 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7296 job->jv_job_object = jo;
7297 job->jv_status = JOB_STARTED;
7298 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007299 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007300 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007301 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007302 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007303 ++job->jv_refcount;
7304 term->tl_job = job;
7305
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007306 // Redirecting stdout and stderr doesn't work at the job level. Instead
7307 // open the file here and handle it in. opt->jo_io was changed in
7308 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007309 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7310 {
7311 char_u *fname = opt->jo_io_name[PART_OUT];
7312
7313 ch_log(channel, "Opening output file %s", fname);
7314 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7315 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007316 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007317 }
7318
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007319 return OK;
7320
7321failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007322 ga_clear(&ga_cmd);
7323 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007324 vim_free(cmd_wchar);
7325 vim_free(cwd_wchar);
7326 if (spawn_config != NULL)
7327 winpty_spawn_config_free(spawn_config);
7328 if (channel != NULL)
7329 channel_clear(channel);
7330 if (job != NULL)
7331 {
7332 job->jv_channel = NULL;
7333 job_cleanup(job);
7334 }
7335 term->tl_job = NULL;
7336 if (jo != NULL)
7337 CloseHandle(jo);
7338 if (term->tl_winpty != NULL)
7339 winpty_free(term->tl_winpty);
7340 term->tl_winpty = NULL;
7341 if (term->tl_winpty_config != NULL)
7342 winpty_config_free(term->tl_winpty_config);
7343 term->tl_winpty_config = NULL;
7344 if (winpty_err != NULL)
7345 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007346 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007347 (short_u *)winpty_error_msg(winpty_err), NULL);
7348
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007349 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007350 winpty_error_free(winpty_err);
7351 }
7352 return FAIL;
7353}
7354
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007355/*
7356 * Create a new terminal of "rows" by "cols" cells.
7357 * Store a reference in "term".
7358 * Return OK or FAIL.
7359 */
7360 static int
7361term_and_job_init(
7362 term_T *term,
7363 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007364 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007365 jobopt_T *opt,
7366 jobopt_T *orig_opt)
7367{
7368 int use_winpty = FALSE;
7369 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007370 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007371
7372 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7373 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7374
7375 if (!has_winpty && !has_conpty)
7376 // If neither is available give the errors for winpty, since when
7377 // conpty is not available it can't be installed either.
7378 return dyn_winpty_init(TRUE);
7379
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007380 if (opt->jo_tty_type != NUL)
7381 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007382
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007383 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007384 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007385 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007386 use_conpty = TRUE;
7387 else if (has_winpty)
7388 use_winpty = TRUE;
7389 // else: error
7390 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007391 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007392 {
7393 if (has_winpty)
7394 use_winpty = TRUE;
7395 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007396 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007397 {
7398 if (has_conpty)
7399 use_conpty = TRUE;
7400 else
7401 return dyn_conpty_init(TRUE);
7402 }
7403
7404 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007405 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007406
7407 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007408 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007409
7410 // error
7411 return dyn_winpty_init(TRUE);
7412}
7413
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007414 static int
7415create_pty_only(term_T *term, jobopt_T *options)
7416{
7417 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7418 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7419 char in_name[80], out_name[80];
7420 channel_T *channel = NULL;
7421
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007422 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7423 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007424
7425 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7426 GetCurrentProcessId(),
7427 curbuf->b_fnum);
7428 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7429 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7430 PIPE_UNLIMITED_INSTANCES,
7431 0, 0, NMPWAIT_NOWAIT, NULL);
7432 if (hPipeIn == INVALID_HANDLE_VALUE)
7433 goto failed;
7434
7435 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7436 GetCurrentProcessId(),
7437 curbuf->b_fnum);
7438 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7439 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7440 PIPE_UNLIMITED_INSTANCES,
7441 0, 0, 0, NULL);
7442 if (hPipeOut == INVALID_HANDLE_VALUE)
7443 goto failed;
7444
7445 ConnectNamedPipe(hPipeIn, NULL);
7446 ConnectNamedPipe(hPipeOut, NULL);
7447
7448 term->tl_job = job_alloc();
7449 if (term->tl_job == NULL)
7450 goto failed;
7451 ++term->tl_job->jv_refcount;
7452
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007453 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007454 term->tl_job->jv_status = JOB_FINISHED;
7455
7456 channel = add_channel();
7457 if (channel == NULL)
7458 goto failed;
7459 term->tl_job->jv_channel = channel;
7460 channel->ch_keep_open = TRUE;
7461 channel->ch_named_pipe = TRUE;
7462
7463 channel_set_pipes(channel,
7464 (sock_T)hPipeIn,
7465 (sock_T)hPipeOut,
7466 (sock_T)hPipeOut);
7467 channel_set_job(channel, term->tl_job, options);
7468 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7469 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7470
7471 return OK;
7472
7473failed:
7474 if (hPipeIn != NULL)
7475 CloseHandle(hPipeIn);
7476 if (hPipeOut != NULL)
7477 CloseHandle(hPipeOut);
7478 return FAIL;
7479}
7480
7481/*
7482 * Free the terminal emulator part of "term".
7483 */
7484 static void
7485term_free_vterm(term_T *term)
7486{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007487 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007488 if (term->tl_winpty != NULL)
7489 winpty_free(term->tl_winpty);
7490 term->tl_winpty = NULL;
7491 if (term->tl_winpty_config != NULL)
7492 winpty_config_free(term->tl_winpty_config);
7493 term->tl_winpty_config = NULL;
7494 if (term->tl_vterm != NULL)
7495 vterm_free(term->tl_vterm);
7496 term->tl_vterm = NULL;
7497}
7498
7499/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007500 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007501 */
7502 static void
7503term_report_winsize(term_T *term, int rows, int cols)
7504{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007505 if (term->tl_conpty)
7506 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007507 if (term->tl_winpty)
7508 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7509}
7510
7511 int
7512terminal_enabled(void)
7513{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007514 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007515}
7516
7517# else
7518
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007519///////////////////////////////////////
7520// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007521
7522/*
7523 * Create a new terminal of "rows" by "cols" cells.
7524 * Start job for "cmd".
7525 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007526 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007527 * Return OK or FAIL.
7528 */
7529 static int
7530term_and_job_init(
7531 term_T *term,
7532 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007533 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007534 jobopt_T *opt,
7535 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007536{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007537 term->tl_arg0_cmd = NULL;
7538
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007539 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7540 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007541
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007542#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007543 if (term_use_palette())
7544 {
7545 if (term->tl_palette != NULL)
7546 set_vterm_palette(term->tl_vterm, term->tl_palette);
7547 else
7548 init_vterm_ansi_colors(term->tl_vterm);
7549 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007550#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007551
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007552 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007553 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007554 if (term->tl_job != NULL)
7555 ++term->tl_job->jv_refcount;
7556
7557 return term->tl_job != NULL
7558 && term->tl_job->jv_channel != NULL
7559 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7560}
7561
7562 static int
7563create_pty_only(term_T *term, jobopt_T *opt)
7564{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007565 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7566 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007567
7568 term->tl_job = job_alloc();
7569 if (term->tl_job == NULL)
7570 return FAIL;
7571 ++term->tl_job->jv_refcount;
7572
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007573 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007574 term->tl_job->jv_status = JOB_FINISHED;
7575
7576 return mch_create_pty_channel(term->tl_job, opt);
7577}
7578
7579/*
7580 * Free the terminal emulator part of "term".
7581 */
7582 static void
7583term_free_vterm(term_T *term)
7584{
7585 if (term->tl_vterm != NULL)
7586 vterm_free(term->tl_vterm);
7587 term->tl_vterm = NULL;
7588}
7589
7590/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007591 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007592 */
7593 static void
7594term_report_winsize(term_T *term, int rows, int cols)
7595{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007596 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007597 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
7598 {
7599 int fd = -1;
7600 int part;
7601
7602 for (part = PART_OUT; part < PART_COUNT; ++part)
7603 {
7604 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01007605 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007606 break;
7607 }
7608 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7609 mch_signal_job(term->tl_job, (char_u *)"winch");
7610 }
7611}
7612
7613# endif
7614
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007615#endif // FEAT_TERMINAL