blob: c0fa1254ebc461279077fb6d0902e42bd9327829 [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 Moolenaara4d158b2022-08-14 14:17:45 +01001289 update_screen(UPD_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/*
Bram Moolenaar9e636b92022-05-29 22:37:05 +01001633 * Return TRUE if the job for "term" is still running, ignoring the job was
1634 * "NONE".
1635 */
1636 int
1637term_job_running_not_none(term_T *term)
1638{
1639 return term_job_running(term) && !term_none_open(term);
1640}
1641
1642/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001643 * Return TRUE if "term" has an active channel and used ":term NONE".
1644 */
1645 int
1646term_none_open(term_T *term)
1647{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001648 // Also consider the job finished when the channel is closed, to avoid a
1649 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001650 return term != NULL
1651 && term->tl_job != NULL
1652 && channel_is_open(term->tl_job->jv_channel)
1653 && term->tl_job->jv_channel->ch_keep_open;
1654}
1655
1656/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001657 * Used when exiting: kill the job in "buf" if so desired.
1658 * Return OK when the job finished.
1659 * Return FAIL when the job is still running.
1660 */
1661 int
1662term_try_stop_job(buf_T *buf)
1663{
1664 int count;
1665 char *how = (char *)buf->b_term->tl_kill;
1666
1667#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaare1004402020-10-24 20:49:43 +02001668 if ((how == NULL || *how == NUL)
1669 && (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)))
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001670 {
1671 char_u buff[DIALOG_MSG_SIZE];
1672 int ret;
1673
Bram Moolenaar00806bc2020-11-05 19:36:38 +01001674 dialog_msg(buff, _("Kill job in \"%s\"?"), buf_get_fname(buf));
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001675 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1676 if (ret == VIM_YES)
1677 how = "kill";
1678 else if (ret == VIM_CANCEL)
1679 return FAIL;
1680 }
1681#endif
1682 if (how == NULL || *how == NUL)
1683 return FAIL;
1684
1685 job_stop(buf->b_term->tl_job, NULL, how);
1686
Bram Moolenaar9172d232019-01-29 23:06:54 +01001687 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001688 for (count = 0; count < 100; ++count)
1689 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001690 job_T *job;
1691
1692 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001693 if (!buf_valid(buf)
1694 || buf->b_term == NULL
1695 || buf->b_term->tl_job == NULL)
1696 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001697 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001698
Bram Moolenaar9172d232019-01-29 23:06:54 +01001699 // Call job_status() to update jv_status. It may cause the job to be
1700 // cleaned up but it won't be freed.
1701 job_status(job);
1702 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001703 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001704
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001705 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001706 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001707 }
1708 return FAIL;
1709}
1710
1711/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001712 * Add the last line of the scrollback buffer to the buffer in the window.
1713 */
1714 static void
1715add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1716{
1717 buf_T *buf = term->tl_buffer;
1718 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1719 linenr_T lnum = buf->b_ml.ml_line_count;
1720
Bram Moolenaar4f974752019-02-17 17:44:42 +01001721#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001722 if (!enc_utf8 && enc_codepage > 0)
1723 {
1724 WCHAR *ret = NULL;
1725 int length = 0;
1726
1727 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1728 &ret, &length);
1729 if (ret != NULL)
1730 {
1731 WideCharToMultiByte_alloc(enc_codepage, 0,
1732 ret, length, (char **)&text, &len, 0, 0);
1733 vim_free(ret);
1734 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1735 vim_free(text);
1736 }
1737 }
1738 else
1739#endif
1740 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1741 if (empty)
1742 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001743 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001744 curbuf = buf;
Bram Moolenaarca70c072020-05-30 20:30:46 +02001745 ml_delete(1);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001746 curbuf = curwin->w_buffer;
1747 }
1748}
1749
1750 static void
1751cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1752{
1753 attr->width = cell->width;
1754 attr->attrs = cell->attrs;
1755 attr->fg = cell->fg;
1756 attr->bg = cell->bg;
1757}
1758
1759 static int
1760equal_celattr(cellattr_T *a, cellattr_T *b)
1761{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02001762 // We only compare the RGB colors, ignoring the ANSI index and type.
1763 // Thus black set explicitly is equal the background black.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001764 return a->fg.red == b->fg.red
1765 && a->fg.green == b->fg.green
1766 && a->fg.blue == b->fg.blue
1767 && a->bg.red == b->bg.red
1768 && a->bg.green == b->bg.green
1769 && a->bg.blue == b->bg.blue;
1770}
1771
Bram Moolenaard96ff162018-02-18 22:13:29 +01001772/*
1773 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1774 * line at this position. Otherwise at the end.
1775 */
1776 static int
1777add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1778{
1779 if (ga_grow(&term->tl_scrollback, 1) == OK)
1780 {
1781 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1782 + term->tl_scrollback.ga_len;
1783
1784 if (lnum > 0)
1785 {
1786 int i;
1787
1788 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1789 {
1790 *line = *(line - 1);
1791 --line;
1792 }
1793 }
1794 line->sb_cols = 0;
1795 line->sb_cells = NULL;
1796 line->sb_fill_attr = *fill_attr;
1797 ++term->tl_scrollback.ga_len;
1798 return OK;
1799 }
1800 return FALSE;
1801}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001802
1803/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001804 * Remove the terminal contents from the scrollback and the buffer.
1805 * Used before adding a new scrollback line or updating the buffer for lines
1806 * displayed in the terminal.
1807 */
1808 static void
1809cleanup_scrollback(term_T *term)
1810{
1811 sb_line_T *line;
1812 garray_T *gap;
1813
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001814 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001815 gap = &term->tl_scrollback;
1816 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1817 && gap->ga_len > 0)
1818 {
Bram Moolenaarca70c072020-05-30 20:30:46 +02001819 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001820 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1821 vim_free(line->sb_cells);
1822 --gap->ga_len;
1823 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001824 curbuf = curwin->w_buffer;
1825 if (curbuf == term->tl_buffer)
1826 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001827}
1828
1829/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001830 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001831 */
1832 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001833update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001834{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001835 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001836 int len;
1837 int lines_skipped = 0;
1838 VTermPos pos;
1839 VTermScreenCell cell;
1840 cellattr_T fill_attr, new_fill_attr;
1841 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001842
1843 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1844 "Adding terminal window snapshot to buffer");
1845
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001846 // First remove the lines that were appended before, they might be
1847 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001848 cleanup_scrollback(term);
1849
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001850 screen = vterm_obtain_screen(term->tl_vterm);
1851 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001852 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1853 {
1854 len = 0;
1855 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1856 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1857 && cell.chars[0] != NUL)
1858 {
1859 len = pos.col + 1;
1860 new_fill_attr = term->tl_default_color;
1861 }
1862 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001863 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001864 cell2cellattr(&cell, &new_fill_attr);
1865
1866 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1867 ++lines_skipped;
1868 else
1869 {
1870 while (lines_skipped > 0)
1871 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001872 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001873 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001874 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001876 }
1877
1878 if (len == 0)
1879 p = NULL;
1880 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001881 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001882 if ((p != NULL || len == 0)
1883 && ga_grow(&term->tl_scrollback, 1) == OK)
1884 {
1885 garray_T ga;
1886 int width;
1887 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1888 + term->tl_scrollback.ga_len;
1889
1890 ga_init2(&ga, 1, 100);
1891 for (pos.col = 0; pos.col < len; pos.col += width)
1892 {
1893 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1894 {
1895 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02001896 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897 if (ga_grow(&ga, 1) == OK)
1898 ga.ga_len += utf_char2bytes(' ',
1899 (char_u *)ga.ga_data + ga.ga_len);
1900 }
1901 else
1902 {
1903 width = cell.width;
1904
1905 cell2cellattr(&cell, &p[pos.col]);
Bram Moolenaar927495b2020-11-06 17:58:35 +01001906 if (width == 2)
1907 // second cell of double-width character has the
1908 // same attributes.
1909 p[pos.col + 1] = p[pos.col];
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001910
Bram Moolenaara79fd562018-12-20 20:47:32 +01001911 // Each character can be up to 6 bytes.
1912 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913 {
1914 int i;
1915 int c;
1916
1917 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1918 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1919 (char_u *)ga.ga_data + ga.ga_len);
1920 }
1921 }
1922 }
1923 line->sb_cols = len;
1924 line->sb_cells = p;
1925 line->sb_fill_attr = new_fill_attr;
1926 fill_attr = new_fill_attr;
1927 ++term->tl_scrollback.ga_len;
1928
1929 if (ga_grow(&ga, 1) == FAIL)
1930 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1931 else
1932 {
1933 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1934 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1935 }
1936 ga_clear(&ga);
1937 }
1938 else
1939 vim_free(p);
1940 }
1941 }
1942
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001943 // Add trailing empty lines.
1944 for (pos.row = term->tl_scrollback.ga_len;
1945 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1946 ++pos.row)
1947 {
1948 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1949 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1950 }
1951
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001952 term->tl_dirty_snapshot = FALSE;
1953#ifdef FEAT_TIMERS
1954 term->tl_timer_set = FALSE;
1955#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001956}
1957
1958/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001959 * Loop over all windows in the current tab, and also curwin, which is not
1960 * encountered when using a terminal in a popup window.
1961 * Return TRUE if "*wp" was set to the next window.
1962 */
1963 static int
1964for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1965{
1966 if (*wp == NULL)
1967 *wp = firstwin;
1968 else if ((*wp)->w_next != NULL)
1969 *wp = (*wp)->w_next;
1970 else if (!*did_curwin)
1971 *wp = curwin;
1972 else
1973 return FALSE;
1974 if (*wp == curwin)
1975 *did_curwin = TRUE;
1976 return TRUE;
1977}
1978
1979/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001980 * If needed, add the current lines of the terminal to scrollback and to the
1981 * buffer. Called after the job has ended and when switching to
1982 * Terminal-Normal mode.
1983 * When "redraw" is TRUE redraw the windows that show the terminal.
1984 */
1985 static void
1986may_move_terminal_to_buffer(term_T *term, int redraw)
1987{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001988 if (term->tl_vterm == NULL)
1989 return;
1990
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001991 // Update the snapshot only if something changes or the buffer does not
1992 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001993 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1994 <= term->tl_scrollback_scrolled)
1995 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001996
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001997 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001998 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1999 &term->tl_default_color.fg, &term->tl_default_color.bg);
2000
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002001 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002002 {
2003 win_T *wp = NULL;
2004 int did_curwin = FALSE;
2005
2006 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002007 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002008 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002009 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002010 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
2011 wp->w_cursor.col = 0;
2012 wp->w_valid = 0;
2013 if (wp->w_cursor.lnum >= wp->w_height)
2014 {
2015 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002017 if (wp->w_topline < min_topline)
2018 wp->w_topline = min_topline;
2019 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002020 redraw_win_later(wp, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002021 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002023 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002024}
2025
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002026#if defined(FEAT_TIMERS) || defined(PROTO)
2027/*
2028 * Check if any terminal timer expired. If so, copy text from the terminal to
2029 * the buffer.
2030 * Return the time until the next timer will expire.
2031 */
2032 int
2033term_check_timers(int next_due_arg, proftime_T *now)
2034{
2035 term_T *term;
2036 int next_due = next_due_arg;
2037
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002038 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002039 {
2040 if (term->tl_timer_set && !term->tl_normal_mode)
2041 {
2042 long this_due = proftime_time_left(&term->tl_timer_due, now);
2043
2044 if (this_due <= 1)
2045 {
2046 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002047 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002048 }
2049 else if (next_due == -1 || next_due > this_due)
2050 next_due = this_due;
2051 }
2052 }
2053
2054 return next_due;
2055}
2056#endif
2057
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002058/*
2059 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
2060 * otherwise end it.
2061 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002062 static void
2063set_terminal_mode(term_T *term, int normal_mode)
2064{
2065 term->tl_normal_mode = normal_mode;
LemonBoy2bf52dd2022-04-09 18:17:34 +01002066 may_trigger_modechanged();
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002067 if (!normal_mode)
2068 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002069 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002070 if (term->tl_buffer == curbuf)
2071 maketitle();
2072}
2073
2074/*
Bram Moolenaare2978022020-04-26 14:47:44 +02002075 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002076 * Move the vterm contents into the scrollback buffer and free the vterm.
2077 */
2078 static void
2079cleanup_vterm(term_T *term)
2080{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002081 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002082 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002083 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002084 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002085}
2086
2087/*
2088 * Switch from Terminal-Job mode to Terminal-Normal mode.
2089 * Suspends updating the terminal window.
2090 */
2091 static void
2092term_enter_normal_mode(void)
2093{
2094 term_T *term = curbuf->b_term;
2095
Bram Moolenaar2bc79952018-05-12 20:36:24 +02002096 set_terminal_mode(term, TRUE);
2097
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002098 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02002099 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002100
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002101 // Move the window cursor to the position of the cursor in the
2102 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002103 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
2104 + term->tl_cursor_pos.row + 1;
2105 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02002106 if (coladvance(term->tl_cursor_pos.col) == FAIL)
2107 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002108 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002109
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002110 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002111 curwin->w_topline = term->tl_scrollback_scrolled + 1;
2112}
2113
2114/*
2115 * Returns TRUE if the current window contains a terminal and we are in
2116 * Terminal-Normal mode.
2117 */
2118 int
2119term_in_normal_mode(void)
2120{
2121 term_T *term = curbuf->b_term;
2122
2123 return term != NULL && term->tl_normal_mode;
2124}
2125
2126/*
2127 * Switch from Terminal-Normal mode to Terminal-Job mode.
2128 * Restores updating the terminal window.
2129 */
2130 void
2131term_enter_job_mode()
2132{
2133 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002134
2135 set_terminal_mode(term, FALSE);
2136
2137 if (term->tl_channel_closed)
2138 cleanup_vterm(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002139 redraw_buf_and_status_later(curbuf, UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002140#ifdef FEAT_PROP_POPUP
2141 if (WIN_IS_POPUP(curwin))
Bram Moolenaara4d158b2022-08-14 14:17:45 +01002142 redraw_later(UPD_NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002143#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002144}
2145
2146/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002147 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002148 * Note: while waiting a terminal may be closed and freed if the channel is
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002149 * closed and ++close was used. This may even happen before we get here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002150 */
2151 static int
2152term_vgetc()
2153{
2154 int c;
2155 int save_State = State;
Bram Moolenaar829c8e82021-12-14 08:41:38 +00002156 int modify_other_keys = curbuf->b_term->tl_vterm == NULL ? FALSE
2157 : vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002158
Bram Moolenaar24959102022-05-07 20:01:16 +01002159 State = MODE_TERMINAL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002160 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002161#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002162 ctrl_break_was_pressed = FALSE;
2163#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002164 if (modify_other_keys)
2165 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166 c = vgetc();
2167 got_int = FALSE;
2168 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002169 if (modify_other_keys)
2170 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002171 return c;
2172}
2173
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002174static int mouse_was_outside = FALSE;
2175
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002176/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002177 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002178 * Return FAIL when the key needs to be handled in Normal mode.
2179 * Return OK when the key was dropped or sent to the terminal.
2180 */
2181 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002182send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002183{
2184 char msg[KEY_BUF_LEN];
2185 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002186 int dragging_outside = FALSE;
2187
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002188 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002189 switch (c)
2190 {
2191 case NUL:
2192 case K_ZERO:
2193 if (typed)
2194 stuffcharReadbuff(c);
2195 return FAIL;
2196
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002197 case K_TABLINE:
2198 stuffcharReadbuff(c);
2199 return FAIL;
2200
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002201 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002202 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002203 return FAIL;
2204
2205 case K_LEFTDRAG:
2206 case K_MIDDLEDRAG:
2207 case K_RIGHTDRAG:
2208 case K_X1DRAG:
2209 case K_X2DRAG:
2210 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002211 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002212 case K_LEFTMOUSE:
2213 case K_LEFTMOUSE_NM:
2214 case K_LEFTRELEASE:
2215 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002216 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002217 case K_MIDDLEMOUSE:
2218 case K_MIDDLERELEASE:
2219 case K_RIGHTMOUSE:
2220 case K_RIGHTRELEASE:
2221 case K_X1MOUSE:
2222 case K_X1RELEASE:
2223 case K_X2MOUSE:
2224 case K_X2RELEASE:
2225
2226 case K_MOUSEUP:
2227 case K_MOUSEDOWN:
2228 case K_MOUSELEFT:
2229 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002230 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002231 int row = mouse_row;
2232 int col = mouse_col;
2233
2234#ifdef FEAT_PROP_POPUP
2235 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002237 row -= popup_top_extra(curwin);
2238 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002239 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002240#endif
2241 if (row < W_WINROW(curwin)
2242 || row >= (W_WINROW(curwin) + curwin->w_height)
2243 || col < curwin->w_wincol
2244 || col >= W_ENDCOL(curwin)
2245 || dragging_outside)
2246 {
2247 // click or scroll outside the current window or on status
2248 // line or vertical separator
2249 if (typed)
2250 {
2251 stuffcharReadbuff(c);
2252 mouse_was_outside = TRUE;
2253 }
2254 return FAIL;
2255 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002256 }
Bram Moolenaar957cf672020-11-12 14:21:06 +01002257 break;
2258
2259 case K_COMMAND:
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002260 case K_SCRIPT_COMMAND:
2261 return do_cmdkey_command(c, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262 }
2263 if (typed)
2264 mouse_was_outside = FALSE;
2265
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002266 // Convert the typed key to a sequence of bytes for the job.
2267 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002268 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002269 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002270 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2271 (char_u *)msg, (int)len, NULL);
2272
2273 return OK;
2274}
2275
2276 static void
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002277position_cursor(win_T *wp, VTermPos *pos)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002278{
2279 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2280 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002281#ifdef FEAT_PROP_POPUP
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002282 if (popup_is_popup(wp))
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002283 {
Bram Moolenaarf5452692020-11-28 21:56:06 +01002284 wp->w_wrow += popup_top_extra(wp);
2285 wp->w_wcol += popup_left_extra(wp);
Bram Moolenaar6a076442020-11-15 20:32:58 +01002286 wp->w_flags |= WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002287 }
Bram Moolenaar6a076442020-11-15 20:32:58 +01002288 else
2289 wp->w_flags &= ~(WFLAG_WCOL_OFF_ADDED | WFLAG_WROW_OFF_ADDED);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002290#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002291 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2292}
2293
2294/*
2295 * Handle CTRL-W "": send register contents to the job.
2296 */
2297 static void
2298term_paste_register(int prev_c UNUSED)
2299{
2300 int c;
2301 list_T *l;
2302 listitem_T *item;
2303 long reglen = 0;
2304 int type;
2305
2306#ifdef FEAT_CMDL_INFO
2307 if (add_to_showcmd(prev_c))
2308 if (add_to_showcmd('"'))
2309 out_flush();
2310#endif
2311 c = term_vgetc();
2312#ifdef FEAT_CMDL_INFO
2313 clear_showcmd();
2314#endif
2315 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002316 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002317 return;
2318
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002319 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002320 if (c == '=' && get_expr_register() != '=')
2321 return;
2322 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002323 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002324 return;
2325
2326 l = (list_T *)get_reg_contents(c, GREG_LIST);
2327 if (l != NULL)
2328 {
2329 type = get_reg_type(c, &reglen);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002330 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002331 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002332 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002333#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002334 char_u *tmp = s;
2335
2336 if (!enc_utf8 && enc_codepage > 0)
2337 {
2338 WCHAR *ret = NULL;
2339 int length = 0;
2340
2341 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2342 (int)STRLEN(s), &ret, &length);
2343 if (ret != NULL)
2344 {
2345 WideCharToMultiByte_alloc(CP_UTF8, 0,
2346 ret, length, (char **)&s, &length, 0, 0);
2347 vim_free(ret);
2348 }
2349 }
2350#endif
2351 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2352 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002353#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002354 if (tmp != s)
2355 vim_free(s);
2356#endif
2357
2358 if (item->li_next != NULL || type == MLINE)
2359 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2360 (char_u *)"\r", 1, NULL);
2361 }
2362 list_free(l);
2363 }
2364}
2365
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002366/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002367 * Return TRUE when waiting for a character in the terminal, the cursor of the
2368 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002369 */
2370 int
2371terminal_is_active()
2372{
2373 return in_terminal_loop != NULL;
2374}
2375
Bram Moolenaar83d47902020-03-26 20:34:00 +01002376/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002377 * Return the highight group ID for the terminal and the window.
Bram Moolenaar83d47902020-03-26 20:34:00 +01002378 */
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002379 static int
2380term_get_highlight_id(term_T *term, win_T *wp)
Bram Moolenaar83d47902020-03-26 20:34:00 +01002381{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002382 char_u *name;
2383
2384 if (wp != NULL && *wp->w_p_wcr != NUL)
2385 name = wp->w_p_wcr;
2386 else if (term->tl_highlight_name != NULL)
2387 name = term->tl_highlight_name;
2388 else
2389 name = (char_u*)"Terminal";
2390
2391 return syn_name2id(name);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002392}
2393
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002394#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002395 cursorentry_T *
2396term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2397{
2398 term_T *term = in_terminal_loop;
2399 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002400 int id;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002401 guicolor_T term_fg = INVALCOLOR;
2402 guicolor_T term_bg = INVALCOLOR;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002403
Bram Moolenaara80faa82020-04-12 19:37:17 +02002404 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002405 entry.shape = entry.mshape =
2406 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2407 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2408 SHAPE_BLOCK;
2409 entry.percentage = 20;
2410 if (term->tl_cursor_blink)
2411 {
2412 entry.blinkwait = 700;
2413 entry.blinkon = 400;
2414 entry.blinkoff = 250;
2415 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002416
Bram Moolenaar83d47902020-03-26 20:34:00 +01002417 // The highlight group overrules the defaults.
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002418 id = term_get_highlight_id(term, curwin);
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002419 if (id != 0)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002420 syn_id2colors(id, &term_fg, &term_bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002421 if (term_bg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002422 *fg = term_bg;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002423 else
2424 *fg = gui.back_pixel;
2425
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002426 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002427 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002428 if (term_fg != INVALCOLOR)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002429 *bg = term_fg;
2430 else
2431 *bg = gui.norm_pixel;
2432 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002433 else
2434 *bg = color_name2handle(term->tl_cursor_color);
2435 entry.name = "n";
2436 entry.used_for = SHAPE_CURSOR;
2437
2438 return &entry;
2439}
2440#endif
2441
Bram Moolenaard317b382018-02-08 22:33:31 +01002442 static void
2443may_output_cursor_props(void)
2444{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002445 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002446 || last_set_cursor_shape != desired_cursor_shape
2447 || last_set_cursor_blink != desired_cursor_blink)
2448 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002449 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002450 last_set_cursor_shape = desired_cursor_shape;
2451 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002452 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002453 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002454 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002455 ui_cursor_shape_forced(TRUE);
2456 else
2457 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2458 }
2459}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002460
Bram Moolenaard317b382018-02-08 22:33:31 +01002461/*
2462 * Set the cursor color and shape, if not last set to these.
2463 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002464 static void
2465may_set_cursor_props(term_T *term)
2466{
2467#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002468 // For the GUI the cursor properties are obtained with
2469 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002470 if (gui.in_use)
2471 return;
2472#endif
2473 if (in_terminal_loop == term)
2474 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002475 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002476 desired_cursor_shape = term->tl_cursor_shape;
2477 desired_cursor_blink = term->tl_cursor_blink;
2478 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002479 }
2480}
2481
Bram Moolenaard317b382018-02-08 22:33:31 +01002482/*
2483 * Reset the desired cursor properties and restore them when needed.
2484 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002485 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002486prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002487{
2488#ifdef FEAT_GUI
2489 if (gui.in_use)
2490 return;
2491#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002492 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002493 desired_cursor_shape = -1;
2494 desired_cursor_blink = -1;
2495 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002496}
2497
2498/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002499 * Returns TRUE if the current window contains a terminal and we are sending
2500 * keys to the job.
2501 * If "check_job_status" is TRUE update the job status.
2502 */
2503 static int
2504term_use_loop_check(int check_job_status)
2505{
2506 term_T *term = curbuf->b_term;
2507
2508 return term != NULL
2509 && !term->tl_normal_mode
2510 && term->tl_vterm != NULL
2511 && term_job_running_check(term, check_job_status);
2512}
2513
2514/*
2515 * Returns TRUE if the current window contains a terminal and we are sending
2516 * keys to the job.
2517 */
2518 int
2519term_use_loop(void)
2520{
2521 return term_use_loop_check(FALSE);
2522}
2523
2524/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002525 * Called when entering a window with the mouse. If this is a terminal window
2526 * we may want to change state.
2527 */
2528 void
2529term_win_entered()
2530{
2531 term_T *term = curbuf->b_term;
2532
2533 if (term != NULL)
2534 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002535 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002536 {
2537 reset_VIsual_and_resel();
Bram Moolenaar24959102022-05-07 20:01:16 +01002538 if (State & MODE_INSERT)
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002539 stop_insert_mode = TRUE;
2540 }
2541 mouse_was_outside = FALSE;
2542 enter_mouse_col = mouse_col;
2543 enter_mouse_row = mouse_row;
2544 }
2545}
2546
Bram Moolenaara48d4e42021-12-08 22:13:38 +00002547 void
2548term_focus_change(int in_focus)
2549{
2550 term_T *term = curbuf->b_term;
2551
2552 if (term != NULL && term->tl_vterm != NULL)
2553 {
2554 VTermState *state = vterm_obtain_state(term->tl_vterm);
2555
2556 if (in_focus)
2557 vterm_state_focus_in(state);
2558 else
2559 vterm_state_focus_out(state);
2560 term_forward_output(term);
2561 }
2562}
2563
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002564/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002565 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2566 * Return the Ctrl-key value in that case.
2567 */
2568 static int
2569raw_c_to_ctrl(int c)
2570{
2571 if ((mod_mask & MOD_MASK_CTRL)
2572 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2573 return c & 0x1f;
2574 return c;
2575}
2576
2577/*
2578 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2579 * May set "mod_mask".
2580 */
2581 static int
2582ctrl_to_raw_c(int c)
2583{
2584 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2585 {
2586 mod_mask |= MOD_MASK_CTRL;
2587 return c + '@';
2588 }
2589 return c;
2590}
2591
2592/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 * Wait for input and send it to the job.
2594 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2595 * when there is no more typahead.
2596 * Return when the start of a CTRL-W command is typed or anything else that
2597 * should be handled as a Normal mode command.
2598 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2599 * the terminal was closed.
2600 */
2601 int
2602terminal_loop(int blocking)
2603{
2604 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002605 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002606 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002607 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002608#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002609 int tty_fd = curbuf->b_term->tl_job->jv_channel
2610 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002611#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002612 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002613
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002614 // Remember the terminal we are sending keys to. However, the terminal
2615 // might be closed while waiting for a character, e.g. typing "exit" in a
2616 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2617 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002618 in_terminal_loop = curbuf->b_term;
2619
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002620 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002621 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002622 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002623 if (termwinkey == Ctrl_W)
2624 termwinkey = 0;
2625 }
Bram Moolenaarebec3e22020-11-28 20:22:06 +01002626 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002627 may_set_cursor_props(curbuf->b_term);
2628
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002629 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002630 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002631#ifdef FEAT_GUI
Bram Moolenaar02764712020-11-14 20:21:55 +01002632 if (curbuf->b_term != NULL && !curbuf->b_term->tl_system)
Bram Moolenaar13568252018-03-16 20:46:58 +01002633#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002634 // TODO: skip screen update when handling a sequence of keys.
2635 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002636 while (must_redraw != 0)
2637 if (update_screen(0) == FAIL)
2638 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002639 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002640 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002641 break;
2642
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002643 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002644 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002645
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002646 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002647 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002648 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002649 // Job finished while waiting for a character. Push back the
2650 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002651 if (raw_c != K_IGNORE)
2652 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002653 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002654 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002655 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002656 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002657 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002658
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002659#ifdef UNIX
2660 /*
2661 * The shell or another program may change the tty settings. Getting
2662 * them for every typed character is a bit of overhead, but it's needed
2663 * for the first character typed, e.g. when Vim starts in a shell.
2664 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002665 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002666 {
2667 ttyinfo_T info;
2668
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002669 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002670 if (get_tty_info(tty_fd, &info) == OK)
2671 term_backspace_char = info.backspace;
2672 }
2673#endif
2674
Bram Moolenaar4f974752019-02-17 17:44:42 +01002675#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002676 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2677 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002678 if (ctrl_break_was_pressed)
2679 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2680#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002681 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2682 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002683 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002684#ifdef FEAT_GUI
2685 && !curbuf->b_term->tl_system
2686#endif
2687 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002688 {
2689 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002690 int prev_raw_c = raw_c;
2691 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002692
2693#ifdef FEAT_CMDL_INFO
2694 if (add_to_showcmd(c))
2695 out_flush();
2696#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002697 raw_c = term_vgetc();
2698 c = raw_c_to_ctrl(raw_c);
2699
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002700#ifdef FEAT_CMDL_INFO
2701 clear_showcmd();
2702#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002703 if (!term_use_loop_check(TRUE)
2704 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002705 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002706 break;
2707
2708 if (prev_c == Ctrl_BSL)
2709 {
2710 if (c == Ctrl_N)
2711 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002712 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002713 term_enter_normal_mode();
2714 ret = FAIL;
2715 goto theend;
2716 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002717 // Send both keys to the terminal, first one here, second one
2718 // below.
2719 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2720 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002721 }
2722 else if (c == Ctrl_C)
2723 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002724 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002725 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2726 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002727 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002728 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002729 // "CTRL-W .": send CTRL-W to the job
2730 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002731 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002732 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002733 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002734 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002735 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002736 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002737 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002738 else if (c == 'N')
2739 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002740 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002741 term_enter_normal_mode();
2742 ret = FAIL;
2743 goto theend;
2744 }
2745 else if (c == '"')
2746 {
2747 term_paste_register(prev_c);
2748 continue;
2749 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002750 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002751 {
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002752 // space for CTRL-W, modifier, multi-byte char and NUL
2753 char_u buf[1 + 3 + MB_MAXBYTES + 1];
Bram Moolenaara4b26992019-08-15 20:58:54 +02002754
2755 // Put the command into the typeahead buffer, when using the
2756 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2757 buf[0] = Ctrl_W;
Bram Moolenaarf43e7ac2020-09-29 21:23:25 +02002758 buf[special_to_buf(c, mod_mask, FALSE, buf + 1) + 1] = NUL;
Bram Moolenaara4b26992019-08-15 20:58:54 +02002759 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002760 ret = OK;
2761 goto theend;
2762 }
2763 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002764# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002765 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002766 {
2767 WCHAR wc;
2768 char_u mb[3];
2769
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002770 mb[0] = (unsigned)raw_c >> 8;
2771 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002772 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002773 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002774 }
2775# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002776 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002777 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002778 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002779 // We are sure to come back here, don't reset the cursor color
2780 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002781 restore_cursor = FALSE;
2782
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002783 ret = OK;
2784 goto theend;
2785 }
2786 }
2787 ret = FAIL;
2788
2789theend:
2790 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002791 if (restore_cursor)
2792 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002793
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002794 // Move a snapshot of the screen contents to the buffer, so that completion
2795 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002796 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2797 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002798
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002799 return ret;
2800}
2801
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002802 static void
2803may_toggle_cursor(term_T *term)
2804{
2805 if (in_terminal_loop == term)
2806 {
2807 if (term->tl_cursor_visible)
2808 cursor_on();
2809 else
2810 cursor_off();
2811 }
2812}
2813
2814/*
2815 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002816 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002817 */
2818 static int
2819color2index(VTermColor *color, int fg, int *boldp)
2820{
2821 int red = color->red;
2822 int blue = color->blue;
2823 int green = color->green;
2824
LemonBoyb2b3acb2022-05-20 10:10:34 +01002825 *boldp = FALSE;
2826
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002827 if (VTERM_COLOR_IS_INVALID(color))
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002828 return 0;
LemonBoyb2b3acb2022-05-20 10:10:34 +01002829
Bram Moolenaare5886cc2020-05-21 20:10:04 +02002830 if (VTERM_COLOR_IS_INDEXED(color))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002831 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01002832 // Use the color as-is if possible, give up otherwise.
2833 if (color->index < t_colors)
2834 return color->index + 1;
2835 // 8-color terminals can actually display twice as many colors by
2836 // setting the high-intensity/bold bit.
2837 else if (t_colors == 8 && fg && color->index < 16)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002838 {
LemonBoyb2b3acb2022-05-20 10:10:34 +01002839 *boldp = TRUE;
2840 return (color->index & 7) + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002841 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01002842 return 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002843 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002844
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002845 if (t_colors >= 256)
2846 {
2847 if (red == blue && red == green)
2848 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002849 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002850 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002851 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2852 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2853 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002854 int i;
2855
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002856 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002857 return 17; // 00/00/00
2858 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002859 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002860 for (i = 0; i < 23; ++i)
2861 if (red < cutoff[i])
2862 return i + 233;
2863 return 256;
2864 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002865 {
2866 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2867 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002868
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002869 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002870 for (ri = 0; ri < 5; ++ri)
2871 if (red < cutoff[ri])
2872 break;
2873 for (gi = 0; gi < 5; ++gi)
2874 if (green < cutoff[gi])
2875 break;
2876 for (bi = 0; bi < 5; ++bi)
2877 if (blue < cutoff[bi])
2878 break;
2879 return 17 + ri * 36 + gi * 6 + bi;
2880 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002881 }
2882 return 0;
2883}
2884
2885/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002886 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002887 */
2888 static int
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002889vtermAttr2hl(VTermScreenCellAttrs *cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002890{
2891 int attr = 0;
2892
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002893 if (cellattrs->bold)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002894 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002895 if (cellattrs->underline)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002896 attr |= HL_UNDERLINE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002897 if (cellattrs->italic)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002898 attr |= HL_ITALIC;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002899 if (cellattrs->strike)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002900 attr |= HL_STRIKETHROUGH;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002901 if (cellattrs->reverse)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002902 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002903 return attr;
2904}
2905
2906/*
2907 * Store Vterm attributes in "cell" from highlight flags.
2908 */
2909 static void
2910hl2vtermAttr(int attr, cellattr_T *cell)
2911{
Bram Moolenaara80faa82020-04-12 19:37:17 +02002912 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002913 if (attr & HL_BOLD)
2914 cell->attrs.bold = 1;
2915 if (attr & HL_UNDERLINE)
2916 cell->attrs.underline = 1;
2917 if (attr & HL_ITALIC)
2918 cell->attrs.italic = 1;
2919 if (attr & HL_STRIKETHROUGH)
2920 cell->attrs.strike = 1;
2921 if (attr & HL_INVERSE)
2922 cell->attrs.reverse = 1;
2923}
2924
2925/*
2926 * Convert the attributes of a vterm cell into an attribute index.
2927 */
2928 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002929cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01002930 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002931 win_T *wp,
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002932 VTermScreenCellAttrs *cellattrs,
2933 VTermColor *cellfg,
2934 VTermColor *cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002935{
2936 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002937 VTermColor *fg = cellfg;
2938 VTermColor *bg = cellbg;
2939 int is_default_fg = VTERM_COLOR_IS_DEFAULT_FG(fg);
2940 int is_default_bg = VTERM_COLOR_IS_DEFAULT_BG(bg);
2941
2942 if (is_default_fg || is_default_bg)
2943 {
2944 if (wp != NULL && *wp->w_p_wcr != NUL)
2945 {
2946 if (is_default_fg)
2947 fg = &wp->w_term_wincolor.fg;
2948 if (is_default_bg)
2949 bg = &wp->w_term_wincolor.bg;
2950 }
2951 else
2952 {
2953 if (is_default_fg)
2954 fg = &term->tl_default_color.fg;
2955 if (is_default_bg)
2956 bg = &term->tl_default_color.bg;
2957 }
2958 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002959
2960#ifdef FEAT_GUI
2961 if (gui.in_use)
2962 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002963 guicolor_T guifg = gui_mch_get_rgb_color(fg->red, fg->green, fg->blue);
2964 guicolor_T guibg = gui_mch_get_rgb_color(bg->red, bg->green, bg->blue);
2965 return get_gui_attr_idx(attr, guifg, guibg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002966 }
2967 else
2968#endif
2969#ifdef FEAT_TERMGUICOLORS
2970 if (p_tgc)
2971 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002972 guicolor_T tgcfg = VTERM_COLOR_IS_INVALID(fg)
2973 ? INVALCOLOR
2974 : gui_get_rgb_color_cmn(fg->red, fg->green, fg->blue);
2975 guicolor_T tgcbg = VTERM_COLOR_IS_INVALID(bg)
2976 ? INVALCOLOR
2977 : gui_get_rgb_color_cmn(bg->red, bg->green, bg->blue);
2978 return get_tgc_attr_idx(attr, tgcfg, tgcbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002979 }
2980 else
2981#endif
2982 {
2983 int bold = MAYBE;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002984 int ctermfg = color2index(fg, TRUE, &bold);
2985 int ctermbg = color2index(bg, FALSE, &bold);
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002986
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002987 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002988 if (bold == TRUE)
2989 attr |= HL_BOLD;
Bram Moolenaar87fd0922021-11-20 13:47:45 +00002990
2991 return get_cterm_attr_idx(attr, ctermfg, ctermbg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002992 }
2993 return 0;
2994}
2995
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002996 static void
2997set_dirty_snapshot(term_T *term)
2998{
2999 term->tl_dirty_snapshot = TRUE;
3000#ifdef FEAT_TIMERS
3001 if (!term->tl_normal_mode)
3002 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003003 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003004 profile_setlimit(100L, &term->tl_timer_due);
3005 term->tl_timer_set = TRUE;
3006 }
3007#endif
3008}
3009
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003010 static int
3011handle_damage(VTermRect rect, void *user)
3012{
3013 term_T *term = (term_T *)user;
3014
3015 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
3016 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003017 set_dirty_snapshot(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003018 redraw_buf_later(term->tl_buffer, UPD_SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003019 return 1;
3020}
3021
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003022 static void
3023term_scroll_up(term_T *term, int start_row, int count)
3024{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003025 win_T *wp = NULL;
3026 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003027 VTermColor fg, bg;
3028 VTermScreenCellAttrs attr;
3029 int clear_attr;
3030
Bram Moolenaara80faa82020-04-12 19:37:17 +02003031 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003032
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003033 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003034 {
3035 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003036 {
3037 // Set the color to clear lines with.
3038 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
3039 &fg, &bg);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003040 clear_attr = cell2attr(term, wp, &attr, &fg, &bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003041 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003042 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003043 }
3044}
3045
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003046 static int
3047handle_moverect(VTermRect dest, VTermRect src, void *user)
3048{
3049 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003050 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003051
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003052 // Scrolling up is done much more efficiently by deleting lines instead of
3053 // redrawing the text. But avoid doing this multiple times, postpone until
3054 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003055 if (dest.start_col == src.start_col
3056 && dest.end_col == src.end_col
3057 && dest.start_row < src.start_row)
3058 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003059 if (dest.start_row == 0)
3060 term->tl_postponed_scroll += count;
3061 else
3062 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003063 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003064
3065 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
3066 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02003067 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003068
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003069 // Note sure if the scrolling will work correctly, let's do a complete
3070 // redraw later.
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003071 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003072 return 1;
3073}
3074
3075 static int
3076handle_movecursor(
3077 VTermPos pos,
3078 VTermPos oldpos UNUSED,
3079 int visible,
3080 void *user)
3081{
3082 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003083 win_T *wp = NULL;
3084 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003085
3086 term->tl_cursor_pos = pos;
3087 term->tl_cursor_visible = visible;
3088
Bram Moolenaare52e0c82020-02-28 22:20:10 +01003089 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003090 {
3091 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003092 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003093 }
3094 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 update_cursor(term, term->tl_cursor_visible);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003096
3097 return 1;
3098}
3099
3100 static int
3101handle_settermprop(
3102 VTermProp prop,
3103 VTermValue *value,
3104 void *user)
3105{
3106 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003107 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003108
3109 switch (prop)
3110 {
3111 case VTERM_PROP_TITLE:
ichizokae1bd872022-01-20 14:57:29 +00003112 if (disable_vterm_title_for_testing)
3113 break;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003114 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003115 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003116 if (strval == NULL)
3117 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003118 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003119 // a blank title isn't useful, make it empty, so that "running" is
3120 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003121 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003122 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003123 // Same as blank
3124 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003125 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003126 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3127 term->tl_title = NULL;
3128 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003129 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003130 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003131#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003132 else if (!enc_utf8 && enc_codepage > 0)
3133 {
3134 WCHAR *ret = NULL;
3135 int length = 0;
3136
3137 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003138 (char*)value->string.str,
3139 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003140 if (ret != NULL)
3141 {
3142 WideCharToMultiByte_alloc(enc_codepage, 0,
3143 ret, length, (char**)&term->tl_title,
3144 &length, 0, 0);
3145 vim_free(ret);
3146 }
3147 }
3148#endif
3149 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003150 {
Bram Moolenaar98f16712020-05-22 13:34:01 +02003151 term->tl_title = strval;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003152 strval = NULL;
3153 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003154 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003155 if (term == curbuf->b_term)
LemonBoy327e6dd2022-06-04 19:57:59 +01003156 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003157 maketitle();
LemonBoy327e6dd2022-06-04 19:57:59 +01003158 curwin->w_redr_status = TRUE;
3159 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003160 break;
3161
3162 case VTERM_PROP_CURSORVISIBLE:
3163 term->tl_cursor_visible = value->boolean;
3164 may_toggle_cursor(term);
3165 out_flush();
3166 break;
3167
3168 case VTERM_PROP_CURSORBLINK:
3169 term->tl_cursor_blink = value->boolean;
3170 may_set_cursor_props(term);
3171 break;
3172
3173 case VTERM_PROP_CURSORSHAPE:
3174 term->tl_cursor_shape = value->number;
3175 may_set_cursor_props(term);
3176 break;
3177
3178 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003179 strval = vim_strnsave((char_u *)value->string.str,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003180 value->string.len);
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003181 if (strval == NULL)
3182 break;
3183 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003184 may_set_cursor_props(term);
3185 break;
3186
3187 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003188 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003189 term->tl_using_altscreen = value->boolean;
3190 break;
3191
3192 default:
3193 break;
3194 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003195 vim_free(strval);
3196
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003197 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003198 return 1;
3199}
3200
3201/*
3202 * The job running in the terminal resized the terminal.
3203 */
3204 static int
3205handle_resize(int rows, int cols, void *user)
3206{
3207 term_T *term = (term_T *)user;
3208 win_T *wp;
3209
3210 term->tl_rows = rows;
3211 term->tl_cols = cols;
3212 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003213 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003214 term->tl_vterm_size_changed = FALSE;
3215 else
3216 {
3217 FOR_ALL_WINDOWS(wp)
3218 {
3219 if (wp->w_buffer == term->tl_buffer)
3220 {
3221 win_setheight_win(rows, wp);
3222 win_setwidth_win(cols, wp);
3223 }
3224 }
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003225 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003226 }
3227 return 1;
3228}
3229
3230/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003231 * If the number of lines that are stored goes over 'termscrollback' then
3232 * delete the first 10%.
3233 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3234 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003235 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003236 static void
3237limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003238{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003239 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003240 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003241 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003242 int i;
3243
3244 curbuf = term->tl_buffer;
3245 for (i = 0; i < todo; ++i)
3246 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003247 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3248 if (update_buffer)
Bram Moolenaarca70c072020-05-30 20:30:46 +02003249 ml_delete(1);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003250 }
3251 curbuf = curwin->w_buffer;
3252
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003253 gap->ga_len -= todo;
3254 mch_memmove(gap->ga_data,
3255 (sb_line_T *)gap->ga_data + todo,
3256 sizeof(sb_line_T) * gap->ga_len);
3257 if (update_buffer)
3258 term->tl_scrollback_scrolled -= todo;
3259 }
3260}
3261
3262/*
3263 * Handle a line that is pushed off the top of the screen.
3264 */
3265 static int
3266handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3267{
3268 term_T *term = (term_T *)user;
3269 garray_T *gap;
3270 int update_buffer;
3271
3272 if (term->tl_normal_mode)
3273 {
3274 // In Terminal-Normal mode the user interacts with the buffer, thus we
3275 // must not change it. Postpone adding the scrollback lines.
3276 gap = &term->tl_scrollback_postponed;
3277 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003278 }
3279 else
3280 {
3281 // First remove the lines that were appended before, the pushed line
3282 // goes above it.
3283 cleanup_scrollback(term);
3284 gap = &term->tl_scrollback;
3285 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003286 }
3287
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003288 limit_scrollback(term, gap, update_buffer);
3289
3290 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003291 {
3292 cellattr_T *p = NULL;
3293 int len = 0;
3294 int i;
3295 int c;
3296 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003297 int text_len;
3298 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003299 sb_line_T *line;
3300 garray_T ga;
3301 cellattr_T fill_attr = term->tl_default_color;
3302
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003303 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003304 for (i = 0; i < cols; ++i)
3305 if (cells[i].chars[0] != 0)
3306 len = i + 1;
3307 else
3308 cell2cellattr(&cells[i], &fill_attr);
3309
3310 ga_init2(&ga, 1, 100);
3311 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003312 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003313 if (p != NULL)
3314 {
3315 for (col = 0; col < len; col += cells[col].width)
3316 {
3317 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3318 {
3319 ga.ga_len = 0;
3320 break;
3321 }
3322 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3323 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3324 (char_u *)ga.ga_data + ga.ga_len);
3325 cell2cellattr(&cells[col], &p[col]);
3326 }
3327 }
3328 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003329 {
3330 if (update_buffer)
3331 text = (char_u *)"";
3332 else
3333 text = vim_strsave((char_u *)"");
3334 text_len = 0;
3335 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003336 else
3337 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003338 text = ga.ga_data;
3339 text_len = ga.ga_len;
3340 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003341 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003342 if (update_buffer)
3343 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003344
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003345 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003346 line->sb_cols = len;
3347 line->sb_cells = p;
3348 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003349 if (update_buffer)
3350 {
3351 line->sb_text = NULL;
3352 ++term->tl_scrollback_scrolled;
3353 ga_clear(&ga); // free the text
3354 }
3355 else
3356 {
3357 line->sb_text = text;
3358 ga_init(&ga); // text is kept in tl_scrollback_postponed
3359 }
3360 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003361 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003362 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003363}
3364
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003365/*
3366 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3367 * received and stored in tl_scrollback_postponed.
3368 */
3369 static void
3370handle_postponed_scrollback(term_T *term)
3371{
3372 int i;
3373
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003374 if (term->tl_scrollback_postponed.ga_len == 0)
3375 return;
3376 ch_log(NULL, "Moving postponed scrollback to scrollback");
3377
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003378 // First remove the lines that were appended before, the pushed lines go
3379 // above it.
3380 cleanup_scrollback(term);
3381
3382 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3383 {
3384 char_u *text;
3385 sb_line_T *pp_line;
3386 sb_line_T *line;
3387
3388 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3389 break;
3390 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3391
3392 text = pp_line->sb_text;
3393 if (text == NULL)
3394 text = (char_u *)"";
3395 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3396 vim_free(pp_line->sb_text);
3397
3398 line = (sb_line_T *)term->tl_scrollback.ga_data
3399 + term->tl_scrollback.ga_len;
3400 line->sb_cols = pp_line->sb_cols;
3401 line->sb_cells = pp_line->sb_cells;
3402 line->sb_fill_attr = pp_line->sb_fill_attr;
3403 line->sb_text = NULL;
3404 ++term->tl_scrollback_scrolled;
3405 ++term->tl_scrollback.ga_len;
3406 }
3407
3408 ga_clear(&term->tl_scrollback_postponed);
3409 limit_scrollback(term, &term->tl_scrollback, TRUE);
3410}
3411
LemonBoy77771d32022-04-13 11:47:25 +01003412/*
3413 * Called when the terminal wants to ring the system bell.
3414 */
3415 static int
3416handle_bell(void *user UNUSED)
3417{
Bram Moolenaaraae97622022-04-13 14:28:07 +01003418 vim_beep(BO_TERM);
LemonBoy77771d32022-04-13 11:47:25 +01003419 return 0;
3420}
3421
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003422static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003423 handle_damage, // damage
3424 handle_moverect, // moverect
3425 handle_movecursor, // movecursor
3426 handle_settermprop, // settermprop
LemonBoy77771d32022-04-13 11:47:25 +01003427 handle_bell, // bell
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003428 handle_resize, // resize
3429 handle_pushline, // sb_pushline
3430 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003431};
3432
3433/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003434 * Do the work after the channel of a terminal was closed.
3435 * Must be called only when updating_screen is FALSE.
3436 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3437 */
3438 static int
3439term_after_channel_closed(term_T *term)
3440{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003441 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003442 if (!term->tl_normal_mode)
3443 {
3444 int fnum = term->tl_buffer->b_fnum;
3445
3446 cleanup_vterm(term);
3447
3448 if (term->tl_finish == TL_FINISH_CLOSE)
3449 {
3450 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003451 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003452#ifdef FEAT_PROP_POPUP
3453 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003454
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003455 // If this was a terminal in a popup window, go back to the
3456 // previous window.
3457 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3458 {
3459 pwin = curwin;
3460 if (win_valid(prevwin))
3461 win_enter(prevwin, FALSE);
3462 }
3463 else
3464#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003465 // If this is the last normal window: exit Vim.
3466 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3467 {
3468 exarg_T ea;
3469
Bram Moolenaara80faa82020-04-12 19:37:17 +02003470 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003471 ex_quit(&ea);
3472 return TRUE;
3473 }
3474
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003475 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003476 ch_log(NULL, "terminal job finished, closing window");
3477 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003478 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003479 if (curwin == aucmd_win)
3480 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003481 if (do_set_w_closing)
3482 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003483 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003484 if (do_set_w_closing)
3485 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003486 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003487#ifdef FEAT_PROP_POPUP
3488 if (pwin != NULL)
3489 popup_close_with_retval(pwin, 0);
3490#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003491 return TRUE;
3492 }
3493 if (term->tl_finish == TL_FINISH_OPEN
3494 && term->tl_buffer->b_nwindows == 0)
3495 {
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003496 char *cmd = term->tl_opencmd == NULL
3497 ? "botright sbuf %d"
3498 : (char *)term->tl_opencmd;
3499 size_t len = strlen(cmd) + 50;
3500 char *buf = alloc(len);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003501
Bram Moolenaar47c5ea42020-11-12 15:12:15 +01003502 if (buf != NULL)
3503 {
3504 ch_log(NULL, "terminal job finished, opening window");
3505 vim_snprintf(buf, len, cmd, fnum);
3506 do_cmdline_cmd((char_u *)buf);
3507 vim_free(buf);
3508 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003509 }
3510 else
3511 ch_log(NULL, "terminal job finished");
3512 }
3513
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003514 redraw_buf_and_status_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003515 return FALSE;
3516}
3517
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003518#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3519/*
3520 * If the current window is a terminal in a popup window and the job has
3521 * finished, close the popup window and to back to the previous window.
3522 * Otherwise return FAIL.
3523 */
3524 int
3525may_close_term_popup(void)
3526{
3527 if (popup_is_popup(curwin) && curbuf->b_term != NULL
Bram Moolenaar9e636b92022-05-29 22:37:05 +01003528 && !term_job_running_not_none(curbuf->b_term))
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003529 {
3530 win_T *pwin = curwin;
3531
3532 if (win_valid(prevwin))
3533 win_enter(prevwin, FALSE);
3534 popup_close_with_retval(pwin, 0);
3535 return OK;
3536 }
3537 return FAIL;
3538}
3539#endif
3540
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003541/*
Bram Moolenaareea32af2021-11-21 14:51:13 +00003542 * Called when a channel is going to be closed, before invoking the close
3543 * callback.
3544 */
3545 void
3546term_channel_closing(channel_T *ch)
3547{
3548 term_T *term;
3549
3550 for (term = first_term; term != NULL; term = term->tl_next)
3551 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
3552 term->tl_channel_closing = TRUE;
3553}
3554
3555/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003556 * Called when a channel has been closed.
3557 * If this was a channel for a terminal window then finish it up.
3558 */
3559 void
3560term_channel_closed(channel_T *ch)
3561{
3562 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003563 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003564 int did_one = FALSE;
3565
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003566 for (term = first_term; term != NULL; term = next_term)
3567 {
3568 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003569 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003570 {
3571 term->tl_channel_closed = TRUE;
3572 did_one = TRUE;
3573
Bram Moolenaard23a8232018-02-10 18:45:26 +01003574 VIM_CLEAR(term->tl_title);
3575 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003576#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003577 if (term->tl_out_fd != NULL)
3578 {
3579 fclose(term->tl_out_fd);
3580 term->tl_out_fd = NULL;
3581 }
3582#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003583
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003584 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003585 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003586 // Cannot open or close windows now. Can happen when
3587 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003588 term->tl_channel_recently_closed = TRUE;
3589 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003590 }
3591
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003592 if (term_after_channel_closed(term))
3593 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003594 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003595 }
3596
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003597 if (did_one)
3598 {
3599 redraw_statuslines();
3600
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003601 // Need to break out of vgetc().
Bram Moolenaarb42c0d52020-05-29 22:41:41 +02003602 ins_char_typebuf(K_IGNORE, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003603 typebuf_was_filled = TRUE;
3604
3605 term = curbuf->b_term;
3606 if (term != NULL)
3607 {
3608 if (term->tl_job == ch->ch_job)
3609 maketitle();
3610 update_cursor(term, term->tl_cursor_visible);
3611 }
3612 }
3613}
3614
3615/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003616 * To be called after resetting updating_screen: handle any terminal where the
3617 * channel was closed.
3618 */
3619 void
3620term_check_channel_closed_recently()
3621{
3622 term_T *term;
3623 term_T *next_term;
3624
3625 for (term = first_term; term != NULL; term = next_term)
3626 {
3627 next_term = term->tl_next;
3628 if (term->tl_channel_recently_closed)
3629 {
3630 term->tl_channel_recently_closed = FALSE;
3631 if (term_after_channel_closed(term))
3632 // start over, the list may have changed
3633 next_term = first_term;
3634 }
3635 }
3636}
3637
3638/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003639 * Fill one screen line from a line of the terminal.
3640 * Advances "pos" to past the last column.
3641 */
3642 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003643term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003644 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003645 win_T *wp,
3646 VTermScreen *screen,
3647 VTermPos *pos,
3648 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003649{
3650 int off = screen_get_current_line_off();
3651
3652 for (pos->col = 0; pos->col < max_col; )
3653 {
3654 VTermScreenCell cell;
3655 int c;
3656
3657 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003658 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003659
3660 c = cell.chars[0];
3661 if (c == NUL)
3662 {
3663 ScreenLines[off] = ' ';
3664 if (enc_utf8)
3665 ScreenLinesUC[off] = NUL;
3666 }
3667 else
3668 {
3669 if (enc_utf8)
3670 {
3671 int i;
3672
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003673 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003674 for (i = 0; i < Screen_mco
3675 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3676 {
3677 ScreenLinesC[i][off] = cell.chars[i + 1];
3678 if (cell.chars[i + 1] == 0)
3679 break;
3680 }
3681 if (c >= 0x80 || (Screen_mco > 0
3682 && ScreenLinesC[0][off] != 0))
3683 {
3684 ScreenLines[off] = ' ';
3685 ScreenLinesUC[off] = c;
3686 }
3687 else
3688 {
3689 ScreenLines[off] = c;
3690 ScreenLinesUC[off] = NUL;
3691 }
3692 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003693#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003694 else if (has_mbyte && c >= 0x80)
3695 {
3696 char_u mb[MB_MAXBYTES+1];
3697 WCHAR wc = c;
3698
3699 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3700 (char*)mb, 2, 0, 0) > 1)
3701 {
3702 ScreenLines[off] = mb[0];
3703 ScreenLines[off + 1] = mb[1];
3704 cell.width = mb_ptr2cells(mb);
3705 }
3706 else
3707 ScreenLines[off] = c;
3708 }
3709#endif
3710 else
Bram Moolenaar927495b2020-11-06 17:58:35 +01003711 // This will only store the lower byte of "c".
Bram Moolenaar13568252018-03-16 20:46:58 +01003712 ScreenLines[off] = c;
3713 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003714 ScreenAttrs[off] = cell2attr(term, wp, &cell.attrs, &cell.fg,
3715 &cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003716
3717 ++pos->col;
3718 ++off;
3719 if (cell.width == 2)
3720 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003721 // don't set the second byte to NUL for a DBCS encoding, it
3722 // has been set above
Bram Moolenaar927495b2020-11-06 17:58:35 +01003723 if (enc_utf8)
3724 {
3725 ScreenLinesUC[off] = NUL;
Bram Moolenaar13568252018-03-16 20:46:58 +01003726 ScreenLines[off] = NUL;
Bram Moolenaar927495b2020-11-06 17:58:35 +01003727 }
3728 else if (!has_mbyte)
3729 {
3730 // Can't show a double-width character with a single-byte
3731 // 'encoding', just use a space.
3732 ScreenLines[off] = ' ';
3733 ScreenAttrs[off] = ScreenAttrs[off - 1];
3734 }
Bram Moolenaar13568252018-03-16 20:46:58 +01003735
3736 ++pos->col;
3737 ++off;
3738 }
3739 }
3740}
3741
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003742#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003743 static void
3744update_system_term(term_T *term)
3745{
3746 VTermPos pos;
3747 VTermScreen *screen;
3748
3749 if (term->tl_vterm == NULL)
3750 return;
3751 screen = vterm_obtain_screen(term->tl_vterm);
3752
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003753 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003754 while (term->tl_toprow > 0
3755 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3756 {
3757 int save_p_more = p_more;
3758
3759 p_more = FALSE;
3760 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003761 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003762 p_more = save_p_more;
3763 --term->tl_toprow;
3764 }
3765
3766 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3767 && pos.row < Rows; ++pos.row)
3768 {
3769 if (pos.row < term->tl_rows)
3770 {
3771 int max_col = MIN(Columns, term->tl_cols);
3772
Bram Moolenaar83d47902020-03-26 20:34:00 +01003773 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003774 }
3775 else
3776 pos.col = 0;
3777
Bram Moolenaar510f0372022-07-04 17:46:22 +01003778 screen_line(curwin, term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003779 }
3780
3781 term->tl_dirty_row_start = MAX_ROW;
3782 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003783}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003784#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003785
3786/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003787 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3788 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003789 * Terminal-Normal mode.
3790 */
3791 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003792term_do_update_window(win_T *wp)
3793{
3794 term_T *term = wp->w_buffer->b_term;
3795
3796 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3797}
3798
3799/*
3800 * Called to update a window that contains an active terminal.
3801 */
3802 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003803term_update_window(win_T *wp)
3804{
3805 term_T *term = wp->w_buffer->b_term;
3806 VTerm *vterm;
3807 VTermScreen *screen;
3808 VTermState *state;
3809 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003810 int rows, cols;
3811 int newrows, newcols;
3812 int minsize;
3813 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003814
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003815 vterm = term->tl_vterm;
3816 screen = vterm_obtain_screen(vterm);
3817 state = vterm_obtain_state(vterm);
3818
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003819 // We use UPD_NOT_VALID on a resize or scroll, redraw everything then.
3820 // With UPD_SOME_VALID only redraw what was marked dirty.
3821 if (wp->w_redr_type > UPD_SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003822 {
3823 term->tl_dirty_row_start = 0;
3824 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003825
3826 if (term->tl_postponed_scroll > 0
3827 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003828 // Scrolling is usually faster than redrawing, when there are only
3829 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003830 term_scroll_up(term, 0, term->tl_postponed_scroll);
3831 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003832 }
3833
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003834 /*
3835 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003836 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003837 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003838 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003839
Bram Moolenaar498c2562018-04-15 23:45:15 +02003840 newrows = 99999;
3841 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003842 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003843 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003844 // Always use curwin, it may be a popup window.
3845 win_T *wwp = twp == NULL ? curwin : twp;
3846
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003847 // When more than one window shows the same terminal, use the
3848 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003849 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003850 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003851 newrows = MIN(newrows, wwp->w_height);
3852 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003853 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003854 if (twp == NULL)
3855 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003856 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003857 if (newrows == 99999 || newcols == 99999)
3858 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003859 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3860 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3861
Bram Moolenaareba13e42021-02-23 17:47:23 +01003862 // If no cell is visible there is no point in resizing. Also, vterm can't
3863 // handle a zero height.
3864 if (newrows == 0 || newcols == 0)
3865 return;
3866
Bram Moolenaar498c2562018-04-15 23:45:15 +02003867 if (term->tl_rows != newrows || term->tl_cols != newcols)
3868 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003869 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003870 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003871 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003872 newrows);
3873 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003874
3875 // Updating the terminal size will cause the snapshot to be cleared.
3876 // When not in terminal_loop() we need to restore it.
3877 if (term != in_terminal_loop)
3878 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003879 }
3880
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003881 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003882 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaarebec3e22020-11-28 20:22:06 +01003883 position_cursor(wp, &pos);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003884
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003885 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3886 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003887 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003888 if (pos.row < term->tl_rows)
3889 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003890 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003891
Bram Moolenaar83d47902020-03-26 20:34:00 +01003892 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003893 }
3894 else
3895 pos.col = 0;
3896
Bram Moolenaar510f0372022-07-04 17:46:22 +01003897 screen_line(wp, wp->w_winrow + pos.row
Bram Moolenaarf118d482018-03-13 13:14:00 +01003898#ifdef FEAT_MENU
3899 + winbar_height(wp)
3900#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003901 , wp->w_wincol, pos.col, wp->w_width,
3902#ifdef FEAT_PROP_POPUP
3903 popup_is_popup(wp) ? SLF_POPUP :
3904#endif
3905 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003906 }
Bram Moolenaar3194e5b2021-12-13 21:59:09 +00003907}
3908
3909/*
3910 * Called after updating all windows: may reset dirty rows.
3911 */
3912 void
3913term_did_update_window(win_T *wp)
3914{
3915 term_T *term = wp->w_buffer->b_term;
3916
3917 if (term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode
3918 && wp->w_redr_type == 0)
3919 {
3920 term->tl_dirty_row_start = MAX_ROW;
3921 term->tl_dirty_row_end = 0;
3922 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003923}
3924
3925/*
3926 * Return TRUE if "wp" is a terminal window where the job has finished.
3927 */
3928 int
3929term_is_finished(buf_T *buf)
3930{
3931 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3932}
3933
3934/*
3935 * Return TRUE if "wp" is a terminal window where the job has finished or we
3936 * are in Terminal-Normal mode, thus we show the buffer contents.
3937 */
3938 int
3939term_show_buffer(buf_T *buf)
3940{
3941 term_T *term = buf->b_term;
3942
3943 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3944}
3945
3946/*
3947 * The current buffer is going to be changed. If there is terminal
3948 * highlighting remove it now.
3949 */
3950 void
3951term_change_in_curbuf(void)
3952{
3953 term_T *term = curbuf->b_term;
3954
3955 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3956 {
3957 free_scrollback(term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01003958 redraw_buf_later(term->tl_buffer, UPD_NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003959
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003960 // The buffer is now like a normal buffer, it cannot be easily
3961 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003962 set_string_option_direct((char_u *)"buftype", -1,
3963 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3964 }
3965}
3966
3967/*
3968 * Get the screen attribute for a position in the buffer.
3969 * Use a negative "col" to get the filler background color.
3970 */
3971 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003972term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003973{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003974 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003975 term_T *term = buf->b_term;
3976 sb_line_T *line;
3977 cellattr_T *cellattr;
3978
3979 if (lnum > term->tl_scrollback.ga_len)
3980 cellattr = &term->tl_default_color;
3981 else
3982 {
3983 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3984 if (col < 0 || col >= line->sb_cols)
3985 cellattr = &line->sb_fill_attr;
3986 else
3987 cellattr = line->sb_cells + col;
3988 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00003989 return cell2attr(term, wp, &cellattr->attrs, &cellattr->fg, &cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003990}
3991
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003992/*
3993 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003994 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003995 */
3996 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003997cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003998{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02003999 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->index);
4000 if (rgb->index == 0)
4001 rgb->type = VTERM_COLOR_RGB;
4002 else
4003 {
4004 rgb->type = VTERM_COLOR_INDEXED;
4005 --rgb->index;
4006 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004007}
4008
4009/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004010 * Initialize vterm color from the synID.
4011 * Returns TRUE if color is set to "fg" and "bg".
4012 * Otherwise returns FALSE.
4013 */
4014 static int
4015get_vterm_color_from_synid(int id, VTermColor *fg, VTermColor *bg)
4016{
4017#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4018 // Use the actual color for the GUI and when 'termguicolors' is set.
4019 if (0
4020# ifdef FEAT_GUI
4021 || gui.in_use
4022# endif
4023# ifdef FEAT_TERMGUICOLORS
4024 || p_tgc
4025# ifdef FEAT_VTP
4026 // Finally get INVALCOLOR on this execution path
4027 || (!p_tgc && t_colors >= 256)
4028# endif
4029# endif
4030 )
4031 {
4032 guicolor_T fg_rgb = INVALCOLOR;
4033 guicolor_T bg_rgb = INVALCOLOR;
4034
4035 if (id > 0)
4036 syn_id2colors(id, &fg_rgb, &bg_rgb);
4037
4038 if (fg_rgb != INVALCOLOR)
4039 {
4040 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
4041 fg->red = (unsigned)(rgb >> 16);
4042 fg->green = (unsigned)(rgb >> 8) & 255;
4043 fg->blue = (unsigned)rgb & 255;
4044 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4045 }
4046 else
4047 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4048
4049 if (bg_rgb != INVALCOLOR)
4050 {
4051 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
4052 bg->red = (unsigned)(rgb >> 16);
4053 bg->green = (unsigned)(rgb >> 8) & 255;
4054 bg->blue = (unsigned)rgb & 255;
4055 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
4056 }
4057 else
4058 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4059
4060 return TRUE;
4061 }
4062 else
4063#endif
4064 if (t_colors >= 16)
4065 {
4066 int cterm_fg = -1;
4067 int cterm_bg = -1;
4068
4069 if (id > 0)
4070 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
4071
4072 if (cterm_fg >= 0)
4073 {
4074 cterm_color2vterm(cterm_fg, fg);
4075 fg->type |= VTERM_COLOR_DEFAULT_FG;
4076 }
4077 else
4078 fg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4079
4080 if (cterm_bg >= 0)
4081 {
4082 cterm_color2vterm(cterm_bg, bg);
4083 bg->type |= VTERM_COLOR_DEFAULT_BG;
4084 }
4085 else
4086 bg->type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4087
4088 return TRUE;
4089 }
4090
4091 return FALSE;
4092}
4093
4094 void
4095term_reset_wincolor(win_T *wp)
4096{
4097 wp->w_term_wincolor.fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4098 wp->w_term_wincolor.bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
4099}
4100
4101/*
4102 * Cache the color of 'wincolor'.
4103 */
4104 void
4105term_update_wincolor(win_T *wp)
4106{
4107 int id = 0;
4108
4109 if (*wp->w_p_wcr != NUL)
4110 id = syn_name2id(wp->w_p_wcr);
4111 if (id == 0 || !get_vterm_color_from_synid(id, &wp->w_term_wincolor.fg,
4112 &wp->w_term_wincolor.bg))
4113 term_reset_wincolor(wp);
4114}
4115
4116/*
4117 * Called when option 'termguicolors' was set,
4118 * or when any highlight is changed.
4119 */
4120 void
4121term_update_wincolor_all()
4122{
4123 win_T *wp = NULL;
4124 int did_curwin = FALSE;
4125
4126 while (for_all_windows_and_curwin(&wp, &did_curwin))
4127 term_update_wincolor(wp);
4128}
4129
4130/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004131 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004132 */
4133 static void
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004134init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004135{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004136 VTermColor *fg, *bg;
4137 int fgval, bgval;
4138 int id;
4139
Bram Moolenaara80faa82020-04-12 19:37:17 +02004140 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004141 term->tl_default_color.width = 1;
4142 fg = &term->tl_default_color.fg;
4143 bg = &term->tl_default_color.bg;
4144
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004145 // Vterm uses a default black background. Set it to white when
4146 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004147 if (*p_bg == 'l')
4148 {
4149 fgval = 0;
4150 bgval = 255;
4151 }
4152 else
4153 {
4154 fgval = 255;
4155 bgval = 0;
4156 }
4157 fg->red = fg->green = fg->blue = fgval;
4158 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004159 fg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_FG;
4160 bg->type = VTERM_COLOR_RGB | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004161
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004162 // The highlight group overrules the defaults.
4163 id = term_get_highlight_id(term, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004164
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004165 if (!get_vterm_color_from_synid(id, fg, bg))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004166 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004167#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004168 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004169#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004170
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004171 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004172 if (cterm_normal_fg_color > 0)
4173 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004174 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004175# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4176# ifdef VIMDLL
4177 if (!gui.in_use)
4178# endif
4179 {
4180 tmp = fg->red;
4181 fg->red = fg->blue;
4182 fg->blue = tmp;
4183 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004184# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004185 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004186# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004187 else
4188 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004189# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004190
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004191 if (cterm_normal_bg_color > 0)
4192 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02004193 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004194# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
4195# ifdef VIMDLL
4196 if (!gui.in_use)
4197# endif
4198 {
4199 tmp = fg->red;
4200 fg->red = fg->blue;
4201 fg->blue = tmp;
4202 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004203# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004204 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02004205# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02004206 else
4207 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02004208# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004209 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01004210}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004211
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004212#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4213/*
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004214 * Return TRUE if the user-defined palette (either g:terminal_ansi_colors or the
4215 * "ansi_colors" argument in term_start()) shall be applied.
4216 */
4217 static int
4218term_use_palette()
4219{
4220 if (0
4221#ifdef FEAT_GUI
4222 || gui.in_use
4223#endif
4224#ifdef FEAT_TERMGUICOLORS
4225 || p_tgc
4226#endif
4227 )
4228 return TRUE;
4229 return FALSE;
4230}
4231
4232/*
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004233 * Set the 16 ANSI colors from array of RGB values
4234 */
4235 static void
4236set_vterm_palette(VTerm *vterm, long_u *rgb)
4237{
4238 int index = 0;
4239 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004240
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004241 for (; index < 16; index++)
4242 {
4243 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004244
Millyb771b6b2021-11-23 12:07:25 +00004245 color.type = VTERM_COLOR_RGB;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004246 color.red = (unsigned)(rgb[index] >> 16);
4247 color.green = (unsigned)(rgb[index] >> 8) & 255;
4248 color.blue = (unsigned)rgb[index] & 255;
Bram Moolenaar68afde42022-02-25 20:48:26 +00004249 color.index = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004250 vterm_state_set_palette_color(state, index, &color);
4251 }
4252}
4253
4254/*
4255 * Set the ANSI color palette from a list of colors
4256 */
4257 static int
4258set_ansi_colors_list(VTerm *vterm, list_T *list)
4259{
4260 int n = 0;
4261 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004262 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004263
Bram Moolenaarb0992022020-01-30 14:55:42 +01004264 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004265 {
4266 char_u *color_name;
4267 guicolor_T guicolor;
4268
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004269 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004270 if (color_name == NULL)
4271 return FAIL;
4272
4273 guicolor = GUI_GET_COLOR(color_name);
4274 if (guicolor == INVALCOLOR)
4275 return FAIL;
4276
4277 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4278 }
4279
4280 if (n != 16 || li != NULL)
4281 return FAIL;
4282
4283 set_vterm_palette(vterm, rgb);
4284
4285 return OK;
4286}
4287
4288/*
4289 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4290 */
4291 static void
4292init_vterm_ansi_colors(VTerm *vterm)
4293{
4294 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4295
LemonBoyb2b3acb2022-05-20 10:10:34 +01004296 if (var == NULL)
4297 return;
4298
4299 if (var->di_tv.v_type != VAR_LIST
4300 || var->di_tv.vval.v_list == NULL
4301 || var->di_tv.vval.v_list->lv_first == &range_list_item
4302 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00004303 semsg(_(e_invalid_argument_str), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004304}
4305#endif
4306
Bram Moolenaar52acb112018-03-18 19:20:22 +01004307/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004308 * Handles a "drop" command from the job in the terminal.
4309 * "item" is the file name, "item->li_next" may have options.
4310 */
4311 static void
4312handle_drop_command(listitem_T *item)
4313{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004314 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004315 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004316 int bufnr;
4317 win_T *wp;
4318 tabpage_T *tp;
4319 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004320 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004321
4322 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4323 FOR_ALL_TAB_WINDOWS(tp, wp)
4324 {
4325 if (wp->w_buffer->b_fnum == bufnr)
4326 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004327 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004328 goto_tabpage_win(tp, wp);
4329 return;
4330 }
4331 }
4332
Bram Moolenaara80faa82020-04-12 19:37:17 +02004333 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004334
4335 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4336 && opt_item->li_tv.vval.v_dict != NULL)
4337 {
4338 dict_T *dict = opt_item->li_tv.vval.v_dict;
4339 char_u *p;
4340
Bram Moolenaard61efa52022-07-23 09:52:04 +01004341 p = dict_get_string(dict, "ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004342 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004343 p = dict_get_string(dict, "fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004344 if (p != NULL)
4345 {
4346 if (check_ff_value(p) == FAIL)
4347 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4348 else
4349 ea.force_ff = *p;
4350 }
Bram Moolenaard61efa52022-07-23 09:52:04 +01004351 p = dict_get_string(dict, "enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004352 if (p == NULL)
Bram Moolenaard61efa52022-07-23 09:52:04 +01004353 p = dict_get_string(dict, "encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004354 if (p != NULL)
4355 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004356 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004357 if (ea.cmd != NULL)
4358 {
4359 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4360 ea.force_enc = 11;
4361 tofree = ea.cmd;
4362 }
4363 }
4364
Bram Moolenaard61efa52022-07-23 09:52:04 +01004365 p = dict_get_string(dict, "bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004366 if (p != NULL)
4367 get_bad_opt(p, &ea);
4368
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004369 if (dict_has_key(dict, "bin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004370 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004371 if (dict_has_key(dict, "binary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004372 ea.force_bin = FORCE_BIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004373 if (dict_has_key(dict, "nobin"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004374 ea.force_bin = FORCE_NOBIN;
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01004375 if (dict_has_key(dict, "nobinary"))
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004376 ea.force_bin = FORCE_NOBIN;
4377 }
4378
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004379 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004380 if (ea.cmd == NULL)
4381 ea.cmd = (char_u *)"split";
4382 ea.arg = fname;
4383 ea.cmdidx = CMD_split;
4384 ex_splitview(&ea);
4385
4386 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004387}
4388
4389/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004390 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4391 */
4392 static int
4393is_permitted_term_api(char_u *func, char_u *pat)
4394{
4395 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4396}
4397
4398/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004399 * Handles a function call from the job running in a terminal.
4400 * "item" is the function name, "item->li_next" has the arguments.
4401 */
4402 static void
4403handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4404{
4405 char_u *func;
4406 typval_T argvars[2];
4407 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004408 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004409
4410 if (item->li_next == NULL)
4411 {
4412 ch_log(channel, "Missing function arguments for call");
4413 return;
4414 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004415 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004416
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004417 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004418 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004419 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004420 return;
4421 }
4422
4423 argvars[0].v_type = VAR_NUMBER;
4424 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4425 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004426 CLEAR_FIELD(funcexe);
Bram Moolenaar851f86b2021-12-13 14:26:44 +00004427 funcexe.fe_firstline = 1L;
4428 funcexe.fe_lastline = 1L;
4429 funcexe.fe_evaluate = TRUE;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004430 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004431 {
4432 clear_tv(&rettv);
4433 ch_log(channel, "Function %s called", func);
4434 }
4435 else
4436 ch_log(channel, "Calling function %s failed", func);
4437}
4438
4439/*
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004440 * URL decoding (also know as Percent-encoding).
4441 *
4442 * Note this function currently is only used for decoding shell's
4443 * OSC 7 escape sequence which we can assume all bytes are valid
4444 * UTF-8 bytes. Thus we don't need to deal with invalid UTF-8
4445 * encoding bytes like 0xfe, 0xff.
4446 */
4447 static size_t
4448url_decode(const char *src, const size_t len, char_u *dst)
4449{
4450 size_t i = 0, j = 0;
4451
4452 while (i < len)
4453 {
4454 if (src[i] == '%' && i + 2 < len)
4455 {
4456 dst[j] = hexhex2nr((char_u *)&src[i + 1]);
4457 j++;
4458 i += 3;
4459 }
4460 else
4461 {
4462 dst[j] = src[i];
4463 i++;
4464 j++;
4465 }
4466 }
4467 dst[j] = '\0';
4468 return j;
4469}
4470
4471/*
4472 * Sync terminal buffer's cwd with shell's pwd with the help of OSC 7.
4473 *
4474 * The OSC 7 sequence has the format of
4475 * "\033]7;file://HOSTNAME/CURRENT/DIR\033\\"
4476 * and what VTerm provides via VTermStringFragment is
4477 * "file://HOSTNAME/CURRENT/DIR"
4478 */
4479 static void
Bram Moolenaar474ad392022-08-21 11:37:17 +01004480sync_shell_dir(garray_T *gap)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004481{
Bram Moolenaar474ad392022-08-21 11:37:17 +01004482 int offset = 7; // len of "file://" is 7
4483 char *pos = (char *)gap->ga_data + offset;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004484 char_u *new_dir;
4485
4486 // remove HOSTNAME to get PWD
Bram Moolenaar474ad392022-08-21 11:37:17 +01004487 while (offset < (int)gap->ga_len && *pos != '/' )
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004488 {
Bram Moolenaar474ad392022-08-21 11:37:17 +01004489 ++offset;
4490 ++pos;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004491 }
4492
Bram Moolenaar474ad392022-08-21 11:37:17 +01004493 if (offset >= (int)gap->ga_len)
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004494 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004495 semsg(_(e_failed_to_extract_pwd_from_str_check_your_shell_config),
Bram Moolenaar474ad392022-08-21 11:37:17 +01004496 gap->ga_data);
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004497 return;
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004498 }
4499
Bram Moolenaar474ad392022-08-21 11:37:17 +01004500 new_dir = alloc(gap->ga_len - offset + 1);
4501 url_decode(pos, gap->ga_len-offset, new_dir);
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004502 changedir_func(new_dir, TRUE, CDSCOPE_WINDOW);
4503 vim_free(new_dir);
4504}
4505
4506/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004507 * Called by libvterm when it cannot recognize an OSC sequence.
4508 * We recognize a terminal API command.
4509 */
4510 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004511parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004512{
4513 term_T *term = (term_T *)user;
4514 js_read_T reader;
4515 typval_T tv;
4516 channel_T *channel = term->tl_job == NULL ? NULL
4517 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004518 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004519
Bram Moolenaar8b9abfd2021-03-29 20:49:05 +02004520 // We recognize only OSC 5 1 ; {command} and OSC 7 ; {command}
Bram Moolenaar474ad392022-08-21 11:37:17 +01004521 if (command != 51 && (command != 7 || !p_asd))
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004522 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004523
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004524 // Concatenate what was received until the final piece is found.
4525 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4526 {
4527 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004528 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004529 }
4530 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
Bram Moolenaarf4b68e92020-05-27 21:22:14 +02004531 gap->ga_len += (int)frag.len;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004532 if (!frag.final)
4533 return 1;
4534
4535 ((char *)gap->ga_data)[gap->ga_len] = 0;
Bram Moolenaar474ad392022-08-21 11:37:17 +01004536
4537 if (command == 7)
4538 {
4539 sync_shell_dir(gap);
4540 ga_clear(gap);
4541 return 1;
4542 }
4543
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004544 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004545 reader.js_fill = NULL;
4546 reader.js_used = 0;
4547 if (json_decode(&reader, &tv, 0) == OK
4548 && tv.v_type == VAR_LIST
4549 && tv.vval.v_list != NULL)
4550 {
4551 listitem_T *item = tv.vval.v_list->lv_first;
4552
4553 if (item == NULL)
4554 ch_log(channel, "Missing command");
4555 else
4556 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004557 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004558
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004559 // Make sure an invoked command doesn't delete the buffer (and the
4560 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004561 ++term->tl_buffer->b_locked;
4562
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004563 item = item->li_next;
4564 if (item == NULL)
4565 ch_log(channel, "Missing argument for %s", cmd);
4566 else if (STRCMP(cmd, "drop") == 0)
4567 handle_drop_command(item);
4568 else if (STRCMP(cmd, "call") == 0)
4569 handle_call_command(term, channel, item);
4570 else
4571 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004572 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004573 }
4574 }
4575 else
4576 ch_log(channel, "Invalid JSON received");
4577
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004578 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004579 clear_tv(&tv);
4580 return 1;
4581}
4582
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004583/*
4584 * Called by libvterm when it cannot recognize a CSI sequence.
4585 * We recognize the window position report.
4586 */
4587 static int
4588parse_csi(
4589 const char *leader UNUSED,
4590 const long args[],
4591 int argcount,
4592 const char *intermed UNUSED,
4593 char command,
4594 void *user)
4595{
4596 term_T *term = (term_T *)user;
4597 char buf[100];
4598 int len;
4599 int x = 0;
4600 int y = 0;
4601 win_T *wp;
4602
4603 // We recognize only CSI 13 t
4604 if (command != 't' || argcount != 1 || args[0] != 13)
4605 return 0; // not handled
4606
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004607 // When getting the window position is not possible or it fails it results
4608 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004609#if defined(FEAT_GUI) \
4610 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4611 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004612 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004613#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004614
4615 FOR_ALL_WINDOWS(wp)
4616 if (wp->w_buffer == term->tl_buffer)
4617 break;
4618 if (wp != NULL)
4619 {
4620#ifdef FEAT_GUI
4621 if (gui.in_use)
4622 {
4623 x += wp->w_wincol * gui.char_width;
4624 y += W_WINROW(wp) * gui.char_height;
4625 }
4626 else
4627#endif
4628 {
4629 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004630 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004631 x += wp->w_wincol * 7;
4632 y += W_WINROW(wp) * 10;
4633 }
4634 }
4635
4636 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4637 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4638 (char_u *)buf, len, NULL);
4639 return 1;
4640}
4641
Bram Moolenaard8637282020-05-20 18:41:41 +02004642static VTermStateFallbacks state_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004643 NULL, // control
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004644 parse_csi, // csi
4645 parse_osc, // osc
Bram Moolenaar7da34152021-11-24 19:30:55 +00004646 NULL, // dcs
4647 NULL, // apc
4648 NULL, // pm
4649 NULL // sos
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004650};
4651
4652/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004653 * Use Vim's allocation functions for vterm so profiling works.
4654 */
4655 static void *
4656vterm_malloc(size_t size, void *data UNUSED)
4657{
Bram Moolenaar88137392021-11-12 16:01:15 +00004658 // make sure that the length is not zero
4659 return alloc_clear(size == 0 ? 1L : size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004660}
4661
4662 static void
4663vterm_memfree(void *ptr, void *data UNUSED)
4664{
4665 vim_free(ptr);
4666}
4667
4668static VTermAllocatorFunctions vterm_allocator = {
4669 &vterm_malloc,
4670 &vterm_memfree
4671};
4672
4673/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004674 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004675 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004676 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004677 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004678create_vterm(term_T *term, int rows, int cols)
4679{
4680 VTerm *vterm;
4681 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004682 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004683 VTermValue value;
4684
Bram Moolenaar756ef112018-04-10 12:04:27 +02004685 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004686 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004687 if (vterm == NULL)
4688 return FAIL;
4689
4690 // Allocate screen and state here, so we can bail out if that fails.
4691 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004692 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004693 if (state == NULL || screen == NULL)
4694 {
4695 vterm_free(vterm);
4696 return FAIL;
4697 }
4698
Bram Moolenaar52acb112018-03-18 19:20:22 +01004699 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004700 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004701 vterm_set_utf8(vterm, 1);
4702
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004703 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004704
4705 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004706 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004707 &term->tl_default_color.fg,
4708 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004709
Bram Moolenaar9e587872019-05-13 20:27:23 +02004710 if (t_colors < 16)
4711 // Less than 16 colors: assume that bold means using a bright color for
4712 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004713 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4714
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004715 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004716 vterm_screen_reset(screen, 1 /* hard */);
4717
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004718 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004719 vterm_screen_enable_altscreen(screen, 1);
4720
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004721 // For unix do not use a blinking cursor. In an xterm this causes the
4722 // cursor to blink if it's blinking in the xterm.
4723 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004724#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004725 if (GetCaretBlinkTime() == INFINITE)
4726 value.boolean = 0;
4727 else
4728 value.boolean = 1;
4729#else
4730 value.boolean = 0;
4731#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004732 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
Bram Moolenaard8637282020-05-20 18:41:41 +02004733 vterm_state_set_unrecognised_fallbacks(state, &state_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004734
4735 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004736}
4737
4738/*
LemonBoyb2b3acb2022-05-20 10:10:34 +01004739 * Reset the terminal palette to its default value.
4740 */
4741 static void
4742term_reset_palette(VTerm *vterm)
4743{
4744 VTermState *state = vterm_obtain_state(vterm);
4745 int index;
4746
4747 for (index = 0; index < 16; index++)
4748 {
4749 VTermColor color;
4750
4751 color.type = VTERM_COLOR_INDEXED;
4752 ansi_color2rgb(index, &color.red, &color.green, &color.blue,
4753 &color.index);
4754 // The first valid index starts at 1.
4755 color.index -= 1;
4756
4757 vterm_state_set_palette_color(state, index, &color);
4758 }
4759}
4760
4761 static void
4762term_update_palette(term_T *term)
4763{
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004764#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01004765 if (term_use_palette()
4766 && (term->tl_palette != NULL
4767 || find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE)
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004768 != NULL))
LemonBoyb2b3acb2022-05-20 10:10:34 +01004769 {
4770 if (term->tl_palette != NULL)
4771 set_vterm_palette(term->tl_vterm, term->tl_palette);
4772 else
4773 init_vterm_ansi_colors(term->tl_vterm);
4774 }
4775 else
Bram Moolenaar30b9a412022-05-26 14:06:37 +01004776#endif
LemonBoyb2b3acb2022-05-20 10:10:34 +01004777 term_reset_palette(term->tl_vterm);
4778}
4779
4780/*
4781 * Called when option 'termguicolors' is changed.
4782 */
4783 void
4784term_update_palette_all()
4785{
4786 term_T *term;
4787
4788 FOR_ALL_TERMS(term)
4789 {
4790 if (term->tl_vterm == NULL)
4791 continue;
4792 term_update_palette(term);
4793 }
4794}
4795
4796/*
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004797 * Called when option 'background' or 'termguicolors' was set,
4798 * or when any highlight is changed.
Bram Moolenaarad431992021-05-03 20:40:38 +02004799 */
4800 void
4801term_update_colors_all(void)
4802{
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004803 term_T *term;
Bram Moolenaarad431992021-05-03 20:40:38 +02004804
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004805 FOR_ALL_TERMS(term)
4806 {
4807 if (term->tl_vterm == NULL)
4808 continue;
4809 init_default_colors(term);
4810 vterm_state_set_default_colors(
4811 vterm_obtain_state(term->tl_vterm),
4812 &term->tl_default_color.fg,
4813 &term->tl_default_color.bg);
4814 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004815}
4816
4817/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004818 * Return the text to show for the buffer name and status.
4819 */
4820 char_u *
4821term_get_status_text(term_T *term)
4822{
4823 if (term->tl_status_text == NULL)
4824 {
4825 char_u *txt;
4826 size_t len;
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004827 char_u *fname;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004828
4829 if (term->tl_normal_mode)
4830 {
4831 if (term_job_running(term))
4832 txt = (char_u *)_("Terminal");
4833 else
4834 txt = (char_u *)_("Terminal-finished");
4835 }
4836 else if (term->tl_title != NULL)
4837 txt = term->tl_title;
4838 else if (term_none_open(term))
4839 txt = (char_u *)_("active");
4840 else if (term_job_running(term))
4841 txt = (char_u *)_("running");
4842 else
4843 txt = (char_u *)_("finished");
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004844 fname = buf_get_fname(term->tl_buffer);
4845 len = 9 + STRLEN(fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004846 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004847 if (term->tl_status_text != NULL)
4848 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
Bram Moolenaar00806bc2020-11-05 19:36:38 +01004849 fname, txt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004850 }
4851 return term->tl_status_text;
4852}
4853
4854/*
Bram Moolenaar3ad69532021-11-19 17:01:08 +00004855 * Clear the cached value of the status text.
4856 */
4857 void
4858term_clear_status_text(term_T *term)
4859{
4860 VIM_CLEAR(term->tl_status_text);
4861}
4862
4863/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004864 * Mark references in jobs of terminals.
4865 */
4866 int
4867set_ref_in_term(int copyID)
4868{
4869 int abort = FALSE;
4870 term_T *term;
4871 typval_T tv;
4872
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004873 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004874 if (term->tl_job != NULL)
4875 {
4876 tv.v_type = VAR_JOB;
4877 tv.vval.v_job = term->tl_job;
4878 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4879 }
4880 return abort;
4881}
4882
4883/*
4884 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004885 * Returns NULL when the buffer is not for a terminal window and logs a message
4886 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004887 */
4888 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004889term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004890{
4891 buf_T *buf;
4892
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004893 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004894 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004895 --emsg_off;
4896 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004897 {
Bram Moolenaar4d05af02020-11-27 20:55:00 +01004898 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004899 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004900 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004901 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004902 return buf;
4903}
4904
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004905 static void
4906clear_cell(VTermScreenCell *cell)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004907{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004908 CLEAR_FIELD(*cell);
Bram Moolenaar87fd0922021-11-20 13:47:45 +00004909 cell->fg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_FG;
4910 cell->bg.type = VTERM_COLOR_INVALID | VTERM_COLOR_DEFAULT_BG;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004911}
4912
4913 static void
4914dump_term_color(FILE *fd, VTermColor *color)
4915{
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004916 int index;
4917
4918 if (VTERM_COLOR_IS_INDEXED(color))
4919 index = color->index + 1;
4920 else if (color->type == 0)
4921 // use RGB values
4922 index = 255;
4923 else
4924 // default color
4925 index = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004926 fprintf(fd, "%02x%02x%02x%d",
4927 (int)color->red, (int)color->green, (int)color->blue,
Bram Moolenaare5886cc2020-05-21 20:10:04 +02004928 index);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004929}
4930
4931/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004932 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004933 *
4934 * Each screen cell in full is:
4935 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4936 * {characters} is a space for an empty cell
4937 * For a double-width character "+" is changed to "*" and the next cell is
4938 * skipped.
4939 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4940 * when "&" use the same as the previous cell.
4941 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4942 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4943 * {color-idx} is a number from 0 to 255
4944 *
4945 * Screen cell with same width, attributes and color as the previous one:
4946 * |{characters}
4947 *
4948 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4949 *
4950 * Repeating the previous screen cell:
4951 * @{count}
4952 */
4953 void
4954f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4955{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02004956 buf_T *buf;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004957 term_T *term;
4958 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004959 int max_height = 0;
4960 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004961 stat_T st;
4962 FILE *fd;
4963 VTermPos pos;
4964 VTermScreen *screen;
4965 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004966 VTermState *state;
4967 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004968
4969 if (check_restricted() || check_secure())
4970 return;
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02004971
4972 if (in_vim9script()
4973 && (check_for_buffer_arg(argvars, 0) == FAIL
4974 || check_for_string_arg(argvars, 1) == FAIL
4975 || check_for_opt_dict_arg(argvars, 2) == FAIL))
4976 return;
4977
4978 buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004979 if (buf == NULL)
4980 return;
4981 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004982 if (term->tl_vterm == NULL)
4983 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00004984 emsg(_(e_job_already_finished));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004985 return;
4986 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004987
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004988 if (argvars[2].v_type != VAR_UNKNOWN)
4989 {
4990 dict_T *d;
4991
4992 if (argvars[2].v_type != VAR_DICT)
4993 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00004994 emsg(_(e_dictionary_required));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004995 return;
4996 }
4997 d = argvars[2].vval.v_dict;
4998 if (d != NULL)
4999 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01005000 max_height = dict_get_number(d, "rows");
5001 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005002 }
5003 }
5004
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005005 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005006 if (fname == NULL)
5007 return;
5008 if (mch_stat((char *)fname, &st) >= 0)
5009 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005010 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005011 return;
5012 }
5013
Bram Moolenaard96ff162018-02-18 22:13:29 +01005014 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5015 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005016 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005017 return;
5018 }
5019
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005020 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005021
5022 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005023 state = vterm_obtain_state(term->tl_vterm);
5024 vterm_state_get_cursorpos(state, &cursor_pos);
5025
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005026 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5027 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005028 {
5029 int repeat = 0;
5030
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005031 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5032 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005033 {
5034 VTermScreenCell cell;
5035 int same_attr;
5036 int same_chars = TRUE;
5037 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005038 int is_cursor_pos = (pos.col == cursor_pos.col
5039 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005040
5041 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005042 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005043
5044 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5045 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005046 int c = cell.chars[i];
5047 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005048 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005049
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005050 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005051 if (i == 0)
5052 {
5053 c = (c == NUL) ? ' ' : c;
5054 pc = (pc == NUL) ? ' ' : pc;
5055 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005056 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005057 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005058 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005059 break;
5060 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005061 same_attr = vtermAttr2hl(&cell.attrs)
5062 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005063 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5064 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005065 if (same_chars && cell.width == prev_cell.width && same_attr
5066 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005067 {
5068 ++repeat;
5069 }
5070 else
5071 {
5072 if (repeat > 0)
5073 {
5074 fprintf(fd, "@%d", repeat);
5075 repeat = 0;
5076 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005077 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005078
5079 if (cell.chars[0] == NUL)
5080 fputs(" ", fd);
5081 else
5082 {
5083 char_u charbuf[10];
5084 int len;
5085
5086 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5087 && cell.chars[i] != NUL; ++i)
5088 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005089 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005090 fwrite(charbuf, len, 1, fd);
5091 }
5092 }
5093
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005094 // When only the characters differ we don't write anything, the
5095 // following "|", "@" or NL will indicate using the same
5096 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005097 if (cell.width != prev_cell.width || !same_attr)
5098 {
5099 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005100 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005101 else
5102 fputs("+", fd);
5103
5104 if (same_attr)
5105 {
5106 fputs("&", fd);
5107 }
5108 else
5109 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005110 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005111 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005112 fputs("&", fd);
5113 else
5114 {
5115 fputs("#", fd);
5116 dump_term_color(fd, &cell.fg);
5117 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005118 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005119 fputs("&", fd);
5120 else
5121 {
5122 fputs("#", fd);
5123 dump_term_color(fd, &cell.bg);
5124 }
5125 }
5126 }
5127
5128 prev_cell = cell;
5129 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005130
5131 if (cell.width == 2)
5132 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005133 }
5134 if (repeat > 0)
5135 fprintf(fd, "@%d", repeat);
5136 fputs("\n", fd);
5137 }
5138
5139 fclose(fd);
5140}
5141
5142/*
5143 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5144 */
5145 static void
5146dump_is_corrupt(garray_T *gap)
5147{
5148 ga_concat(gap, (char_u *)"CORRUPT");
5149}
5150
5151 static void
5152append_cell(garray_T *gap, cellattr_T *cell)
5153{
5154 if (ga_grow(gap, 1) == OK)
5155 {
5156 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5157 ++gap->ga_len;
5158 }
5159}
5160
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005161 static void
5162clear_cellattr(cellattr_T *cell)
5163{
5164 CLEAR_FIELD(*cell);
5165 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5166 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5167}
5168
Bram Moolenaard96ff162018-02-18 22:13:29 +01005169/*
5170 * Read the dump file from "fd" and append lines to the current buffer.
5171 * Return the cell width of the longest line.
5172 */
5173 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005174read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005175{
5176 int c;
5177 garray_T ga_text;
5178 garray_T ga_cell;
5179 char_u *prev_char = NULL;
5180 int attr = 0;
5181 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005182 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005183 term_T *term = curbuf->b_term;
5184 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005185 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005186
5187 ga_init2(&ga_text, 1, 90);
5188 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005189 clear_cellattr(&cell);
5190 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005191 cursor_pos->row = -1;
5192 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005193
5194 c = fgetc(fd);
5195 for (;;)
5196 {
5197 if (c == EOF)
5198 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005199 if (c == '\r')
5200 {
5201 // DOS line endings? Ignore.
5202 c = fgetc(fd);
5203 }
5204 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005205 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005206 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005207 if (ga_text.ga_data == NULL)
5208 dump_is_corrupt(&ga_text);
5209 if (ga_grow(&term->tl_scrollback, 1) == OK)
5210 {
5211 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5212 + term->tl_scrollback.ga_len;
5213
5214 if (max_cells < ga_cell.ga_len)
5215 max_cells = ga_cell.ga_len;
5216 line->sb_cols = ga_cell.ga_len;
5217 line->sb_cells = ga_cell.ga_data;
5218 line->sb_fill_attr = term->tl_default_color;
5219 ++term->tl_scrollback.ga_len;
5220 ga_init(&ga_cell);
5221
5222 ga_append(&ga_text, NUL);
5223 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5224 ga_text.ga_len, FALSE);
5225 }
5226 else
5227 ga_clear(&ga_cell);
5228 ga_text.ga_len = 0;
5229
5230 c = fgetc(fd);
5231 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005232 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005233 {
5234 int prev_len = ga_text.ga_len;
5235
Bram Moolenaar9271d052018-02-25 21:39:46 +01005236 if (c == '>')
5237 {
5238 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005239 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005240 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5241 cursor_pos->col = ga_cell.ga_len;
5242 }
5243
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005244 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005245 c = fgetc(fd);
5246 if (c != EOF)
5247 ga_append(&ga_text, c);
5248 for (;;)
5249 {
5250 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005251 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005252 || c == EOF || c == '\n')
5253 break;
5254 ga_append(&ga_text, c);
5255 }
5256
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005257 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005258 vim_free(prev_char);
5259 if (ga_text.ga_data != NULL)
5260 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5261 ga_text.ga_len - prev_len);
5262
Bram Moolenaar9271d052018-02-25 21:39:46 +01005263 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005264 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005265 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005266 }
5267 else if (c == '+' || c == '*')
5268 {
5269 int is_bg;
5270
5271 cell.width = c == '+' ? 1 : 2;
5272
5273 c = fgetc(fd);
5274 if (c == '&')
5275 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005276 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005277 c = fgetc(fd);
5278 }
5279 else if (isdigit(c))
5280 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005281 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005282 attr = 0;
5283 while (isdigit(c))
5284 {
5285 attr = attr * 10 + (c - '0');
5286 c = fgetc(fd);
5287 }
5288 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005289
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005290 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005291 for (is_bg = 0; is_bg <= 1; ++is_bg)
5292 {
5293 if (c == '&')
5294 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005295 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005296 c = fgetc(fd);
5297 }
5298 else if (c == '#')
5299 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005300 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005301
5302 c = fgetc(fd);
5303 red = hex2nr(c);
5304 c = fgetc(fd);
5305 red = (red << 4) + hex2nr(c);
5306 c = fgetc(fd);
5307 green = hex2nr(c);
5308 c = fgetc(fd);
5309 green = (green << 4) + hex2nr(c);
5310 c = fgetc(fd);
5311 blue = hex2nr(c);
5312 c = fgetc(fd);
5313 blue = (blue << 4) + hex2nr(c);
5314 c = fgetc(fd);
5315 if (!isdigit(c))
5316 dump_is_corrupt(&ga_text);
5317 while (isdigit(c))
5318 {
5319 index = index * 10 + (c - '0');
5320 c = fgetc(fd);
5321 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005322 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005323 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005324 type = VTERM_COLOR_RGB;
5325 if (index == 0)
5326 {
5327 if (is_bg)
5328 type |= VTERM_COLOR_DEFAULT_BG;
5329 else
5330 type |= VTERM_COLOR_DEFAULT_FG;
5331 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005332 }
5333 else
5334 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005335 type = VTERM_COLOR_INDEXED;
5336 index -= 1;
5337 }
5338 if (is_bg)
5339 {
5340 cell.bg.type = type;
5341 cell.bg.red = red;
5342 cell.bg.green = green;
5343 cell.bg.blue = blue;
5344 cell.bg.index = index;
5345 }
5346 else
5347 {
5348 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005349 cell.fg.red = red;
5350 cell.fg.green = green;
5351 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005352 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005353 }
5354 }
5355 else
5356 dump_is_corrupt(&ga_text);
5357 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005358 }
5359 else
5360 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005361 }
5362 else
5363 dump_is_corrupt(&ga_text);
5364
5365 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005366 if (cell.width == 2)
5367 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005368 }
5369 else if (c == '@')
5370 {
5371 if (prev_char == NULL)
5372 dump_is_corrupt(&ga_text);
5373 else
5374 {
5375 int count = 0;
5376
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005377 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005378 for (;;)
5379 {
5380 c = fgetc(fd);
5381 if (!isdigit(c))
5382 break;
5383 count = count * 10 + (c - '0');
5384 }
5385
5386 while (count-- > 0)
5387 {
5388 ga_concat(&ga_text, prev_char);
5389 append_cell(&ga_cell, &cell);
5390 }
5391 }
5392 }
5393 else
5394 {
5395 dump_is_corrupt(&ga_text);
5396 c = fgetc(fd);
5397 }
5398 }
5399
5400 if (ga_text.ga_len > 0)
5401 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005402 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005403 dump_is_corrupt(&ga_text);
5404 ga_append(&ga_text, NUL);
5405 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5406 ga_text.ga_len, FALSE);
5407 }
5408
5409 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005410 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005411 vim_free(prev_char);
5412
5413 return max_cells;
5414}
5415
5416/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005417 * Return an allocated string with at least "text_width" "=" characters and
5418 * "fname" inserted in the middle.
5419 */
5420 static char_u *
5421get_separator(int text_width, char_u *fname)
5422{
5423 int width = MAX(text_width, curwin->w_width);
5424 char_u *textline;
5425 int fname_size;
5426 char_u *p = fname;
5427 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005428 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005429
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005430 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005431 if (textline == NULL)
5432 return NULL;
5433
5434 fname_size = vim_strsize(fname);
5435 if (fname_size < width - 8)
5436 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005437 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005438 width = MAX(text_width, fname_size + 8);
5439 }
5440 else if (fname_size > width - 8)
5441 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005442 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005443 p = gettail(fname);
5444 fname_size = vim_strsize(p);
5445 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005446 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005447 while (fname_size > width - 8)
5448 {
5449 p += (*mb_ptr2len)(p);
5450 fname_size = vim_strsize(p);
5451 }
5452
5453 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5454 textline[i] = '=';
5455 textline[i++] = ' ';
5456
5457 STRCPY(textline + i, p);
5458 off = STRLEN(textline);
5459 textline[off] = ' ';
5460 for (i = 1; i < (width - fname_size) / 2; ++i)
5461 textline[off + i] = '=';
5462 textline[off + i] = NUL;
5463
5464 return textline;
5465}
5466
5467/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005468 * Common for "term_dumpdiff()" and "term_dumpload()".
5469 */
5470 static void
5471term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5472{
5473 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005474 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005475 char_u buf1[NUMBUFLEN];
5476 char_u buf2[NUMBUFLEN];
5477 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005478 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005479 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005480 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005481 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005482 char_u *textline = NULL;
5483
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005484 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005485 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005486 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005487 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005488 if (fname1 == NULL || (do_diff && fname2 == NULL))
5489 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005490 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005491 return;
5492 }
5493 fd1 = mch_fopen((char *)fname1, READBIN);
5494 if (fd1 == NULL)
5495 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005496 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005497 return;
5498 }
5499 if (do_diff)
5500 {
5501 fd2 = mch_fopen((char *)fname2, READBIN);
5502 if (fd2 == NULL)
5503 {
5504 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005505 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005506 return;
5507 }
5508 }
5509
5510 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005511 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5512 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5513 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5514 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5515 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005516
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005517 if (opt.jo_term_name == NULL)
5518 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005519 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005520
Bram Moolenaar51e14382019-05-25 20:21:28 +02005521 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005522 if (fname_tofree != NULL)
5523 {
5524 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5525 opt.jo_term_name = fname_tofree;
5526 }
5527 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005528
Bram Moolenaar87abab92019-06-03 21:14:59 +02005529 if (opt.jo_bufnr_buf != NULL)
5530 {
5531 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5532
5533 // With "bufnr" argument: enter the window with this buffer and make it
5534 // empty.
5535 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005536 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005537 else
5538 {
5539 buf = curbuf;
5540 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005541 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005542 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005543 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005544 }
5545 }
5546 else
5547 // Create a new terminal window.
5548 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5549
Bram Moolenaard96ff162018-02-18 22:13:29 +01005550 if (buf != NULL && buf->b_term != NULL)
5551 {
5552 int i;
5553 linenr_T bot_lnum;
5554 linenr_T lnum;
5555 term_T *term = buf->b_term;
5556 int width;
5557 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005558 VTermPos cursor_pos1;
5559 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005560
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005561 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005562
Bram Moolenaard96ff162018-02-18 22:13:29 +01005563 rettv->vval.v_number = buf->b_fnum;
5564
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005565 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005566 width = read_dump_file(fd1, &cursor_pos1);
5567
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005568 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005569 if (cursor_pos1.row >= 0)
5570 {
5571 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5572 coladvance(cursor_pos1.col);
5573 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005574
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005575 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005576 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005577
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005578 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005579 if (!do_diff)
5580 goto theend;
5581
5582 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5583
Bram Moolenaar4a696342018-04-05 18:45:26 +02005584 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005585 if (textline == NULL)
5586 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005587 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5588 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5589 vim_free(textline);
5590
5591 textline = get_separator(width, fname2);
5592 if (textline == NULL)
5593 goto theend;
5594 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5595 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005596 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005597
5598 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005599 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005600 if (width2 > width)
5601 {
5602 vim_free(textline);
5603 textline = alloc(width2 + 1);
5604 if (textline == NULL)
5605 goto theend;
5606 width = width2;
5607 textline[width] = NUL;
5608 }
5609 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5610
5611 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5612 {
5613 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5614 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005615 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005616 for (i = 0; i < width; ++i)
5617 textline[i] = '-';
5618 }
5619 else
5620 {
5621 char_u *line1;
5622 char_u *line2;
5623 char_u *p1;
5624 char_u *p2;
5625 int col;
5626 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5627 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5628 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5629 ->sb_cells;
5630
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005631 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005632 line1 = vim_strsave(ml_get(lnum));
5633 if (line1 == NULL)
5634 break;
5635 p1 = line1;
5636
5637 line2 = ml_get(lnum + bot_lnum);
5638 p2 = line2;
5639 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5640 {
5641 int len1 = utfc_ptr2len(p1);
5642 int len2 = utfc_ptr2len(p2);
5643
5644 textline[col] = ' ';
5645 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005646 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005647 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005648 else if (lnum == cursor_pos1.row + 1
5649 && col == cursor_pos1.col
5650 && (cursor_pos1.row != cursor_pos2.row
5651 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005652 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005653 textline[col] = '>';
5654 else if (lnum == cursor_pos2.row + 1
5655 && col == cursor_pos2.col
5656 && (cursor_pos1.row != cursor_pos2.row
5657 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005658 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005659 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005660 else if (cellattr1 != NULL && cellattr2 != NULL)
5661 {
5662 if ((cellattr1 + col)->width
5663 != (cellattr2 + col)->width)
5664 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005665 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005666 &(cellattr2 + col)->fg))
5667 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005668 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005669 &(cellattr2 + col)->bg))
5670 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005671 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5672 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005673 textline[col] = 'a';
5674 }
5675 p1 += len1;
5676 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005677 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005678 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005679
5680 while (col < width)
5681 {
5682 if (*p1 == NUL && *p2 == NUL)
5683 textline[col] = '?';
5684 else if (*p1 == NUL)
5685 {
5686 textline[col] = '+';
5687 p2 += utfc_ptr2len(p2);
5688 }
5689 else
5690 {
5691 textline[col] = '-';
5692 p1 += utfc_ptr2len(p1);
5693 }
5694 ++col;
5695 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005696
5697 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005698 }
5699 if (add_empty_scrollback(term, &term->tl_default_color,
5700 term->tl_top_diff_rows) == OK)
5701 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5702 ++bot_lnum;
5703 }
5704
5705 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5706 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005707 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005708 for (i = 0; i < width; ++i)
5709 textline[i] = '+';
5710 if (add_empty_scrollback(term, &term->tl_default_color,
5711 term->tl_top_diff_rows) == OK)
5712 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5713 ++lnum;
5714 ++bot_lnum;
5715 }
5716
5717 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005718
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005719 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005720 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005721 }
5722
5723theend:
5724 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005725 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005726 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005727 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005728 fclose(fd2);
5729}
5730
5731/*
5732 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5733 * bottom files.
5734 * Return FAIL when this is not possible.
5735 */
5736 int
5737term_swap_diff()
5738{
5739 term_T *term = curbuf->b_term;
5740 linenr_T line_count;
5741 linenr_T top_rows;
5742 linenr_T bot_rows;
5743 linenr_T bot_start;
5744 linenr_T lnum;
5745 char_u *p;
5746 sb_line_T *sb_line;
5747
5748 if (term == NULL
5749 || !term_is_finished(curbuf)
5750 || term->tl_top_diff_rows == 0
5751 || term->tl_scrollback.ga_len == 0)
5752 return FAIL;
5753
5754 line_count = curbuf->b_ml.ml_line_count;
5755 top_rows = term->tl_top_diff_rows;
5756 bot_rows = term->tl_bot_diff_rows;
5757 bot_start = line_count - bot_rows;
5758 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5759
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005760 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005761 for (lnum = 1; lnum <= top_rows; ++lnum)
5762 {
5763 p = vim_strsave(ml_get(1));
5764 if (p == NULL)
5765 return OK;
5766 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005767 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005768 vim_free(p);
5769 }
5770
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005771 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005772 for (lnum = 1; lnum <= bot_rows; ++lnum)
5773 {
5774 p = vim_strsave(ml_get(bot_start + lnum));
5775 if (p == NULL)
5776 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005777 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005778 ml_append(lnum - 1, p, 0, FALSE);
5779 vim_free(p);
5780 }
5781
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005782 // move top title to bottom
5783 p = vim_strsave(ml_get(bot_rows + 1));
5784 if (p == NULL)
5785 return OK;
5786 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005787 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005788 vim_free(p);
5789
5790 // move bottom title to top
5791 p = vim_strsave(ml_get(line_count - top_rows));
5792 if (p == NULL)
5793 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005794 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005795 ml_append(bot_rows, p, 0, FALSE);
5796 vim_free(p);
5797
Bram Moolenaard96ff162018-02-18 22:13:29 +01005798 if (top_rows == bot_rows)
5799 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005800 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005801 for (lnum = 0; lnum < top_rows; ++lnum)
5802 {
5803 sb_line_T temp;
5804
5805 temp = *(sb_line + lnum);
5806 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5807 *(sb_line + bot_start + lnum) = temp;
5808 }
5809 }
5810 else
5811 {
5812 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005813 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005814
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005815 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005816 if (temp != NULL)
5817 {
5818 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5819 mch_memmove(term->tl_scrollback.ga_data,
5820 temp + bot_start,
5821 sizeof(sb_line_T) * bot_rows);
5822 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5823 temp + top_rows,
5824 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5825 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5826 + line_count - top_rows,
5827 temp,
5828 sizeof(sb_line_T) * top_rows);
5829 vim_free(temp);
5830 }
5831 }
5832
5833 term->tl_top_diff_rows = bot_rows;
5834 term->tl_bot_diff_rows = top_rows;
5835
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005836 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005837 return OK;
5838}
5839
5840/*
5841 * "term_dumpdiff(filename, filename, options)" function
5842 */
5843 void
5844f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5845{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005846 if (in_vim9script()
5847 && (check_for_string_arg(argvars, 0) == FAIL
5848 || check_for_string_arg(argvars, 1) == FAIL
5849 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5850 return;
5851
Bram Moolenaard96ff162018-02-18 22:13:29 +01005852 term_load_dump(argvars, rettv, TRUE);
5853}
5854
5855/*
5856 * "term_dumpload(filename, options)" function
5857 */
5858 void
5859f_term_dumpload(typval_T *argvars, typval_T *rettv)
5860{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005861 if (in_vim9script()
5862 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02005863 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005864 return;
5865
Bram Moolenaard96ff162018-02-18 22:13:29 +01005866 term_load_dump(argvars, rettv, FALSE);
5867}
5868
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005869/*
5870 * "term_getaltscreen(buf)" function
5871 */
5872 void
5873f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5874{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005875 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005876
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005877 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5878 return;
5879
5880 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005881 if (buf == NULL)
5882 return;
5883 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5884}
5885
5886/*
5887 * "term_getattr(attr, name)" function
5888 */
5889 void
5890f_term_getattr(typval_T *argvars, typval_T *rettv)
5891{
5892 int attr;
5893 size_t i;
5894 char_u *name;
5895
5896 static struct {
5897 char *name;
5898 int attr;
5899 } attrs[] = {
5900 {"bold", HL_BOLD},
5901 {"italic", HL_ITALIC},
5902 {"underline", HL_UNDERLINE},
5903 {"strike", HL_STRIKETHROUGH},
5904 {"reverse", HL_INVERSE},
5905 };
5906
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02005907 if (in_vim9script()
5908 && (check_for_number_arg(argvars, 0) == FAIL
5909 || check_for_string_arg(argvars, 1) == FAIL))
5910 return;
5911
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005912 attr = tv_get_number(&argvars[0]);
5913 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005914 if (name == NULL)
5915 return;
5916
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005917 if (attr > HL_ALL)
5918 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02005919 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005920 if (STRCMP(name, attrs[i].name) == 0)
5921 {
5922 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5923 break;
5924 }
5925}
5926
5927/*
5928 * "term_getcursor(buf)" function
5929 */
5930 void
5931f_term_getcursor(typval_T *argvars, typval_T *rettv)
5932{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005933 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005934 term_T *term;
5935 list_T *l;
5936 dict_T *d;
5937
5938 if (rettv_list_alloc(rettv) == FAIL)
5939 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005940
5941 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5942 return;
5943
5944 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005945 if (buf == NULL)
5946 return;
5947 term = buf->b_term;
5948
5949 l = rettv->vval.v_list;
5950 list_append_number(l, term->tl_cursor_pos.row + 1);
5951 list_append_number(l, term->tl_cursor_pos.col + 1);
5952
5953 d = dict_alloc();
5954 if (d != NULL)
5955 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005956 dict_add_number(d, "visible", term->tl_cursor_visible);
5957 dict_add_number(d, "blink", blink_state_is_inverted()
5958 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5959 dict_add_number(d, "shape", term->tl_cursor_shape);
5960 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005961 list_append_dict(l, d);
5962 }
5963}
5964
5965/*
5966 * "term_getjob(buf)" function
5967 */
5968 void
5969f_term_getjob(typval_T *argvars, typval_T *rettv)
5970{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005971 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005972
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005973 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5974 return;
5975
5976 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005977 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005978 {
5979 rettv->v_type = VAR_SPECIAL;
5980 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005981 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005982 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005983
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005984 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005985 rettv->vval.v_job = buf->b_term->tl_job;
5986 if (rettv->vval.v_job != NULL)
5987 ++rettv->vval.v_job->jv_refcount;
5988}
5989
5990 static int
5991get_row_number(typval_T *tv, term_T *term)
5992{
5993 if (tv->v_type == VAR_STRING
5994 && tv->vval.v_string != NULL
5995 && STRCMP(tv->vval.v_string, ".") == 0)
5996 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005997 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005998}
5999
6000/*
6001 * "term_getline(buf, row)" function
6002 */
6003 void
6004f_term_getline(typval_T *argvars, typval_T *rettv)
6005{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006006 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006007 term_T *term;
6008 int row;
6009
6010 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006011
6012 if (in_vim9script()
6013 && (check_for_buffer_arg(argvars, 0) == FAIL
6014 || check_for_lnum_arg(argvars, 1) == FAIL))
6015 return;
6016
6017 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006018 if (buf == NULL)
6019 return;
6020 term = buf->b_term;
6021 row = get_row_number(&argvars[1], term);
6022
6023 if (term->tl_vterm == NULL)
6024 {
6025 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6026
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006027 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006028 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6029 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6030 }
6031 else
6032 {
6033 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6034 VTermRect rect;
6035 int len;
6036 char_u *p;
6037
6038 if (row < 0 || row >= term->tl_rows)
6039 return;
6040 len = term->tl_cols * MB_MAXBYTES + 1;
6041 p = alloc(len);
6042 if (p == NULL)
6043 return;
6044 rettv->vval.v_string = p;
6045
6046 rect.start_col = 0;
6047 rect.end_col = term->tl_cols;
6048 rect.start_row = row;
6049 rect.end_row = row + 1;
6050 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6051 }
6052}
6053
6054/*
6055 * "term_getscrolled(buf)" function
6056 */
6057 void
6058f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6059{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006060 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006061
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006062 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6063 return;
6064
6065 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006066 if (buf == NULL)
6067 return;
6068 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6069}
6070
6071/*
6072 * "term_getsize(buf)" function
6073 */
6074 void
6075f_term_getsize(typval_T *argvars, typval_T *rettv)
6076{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006077 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006078 list_T *l;
6079
6080 if (rettv_list_alloc(rettv) == FAIL)
6081 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006082
6083 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6084 return;
6085
6086 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006087 if (buf == NULL)
6088 return;
6089
6090 l = rettv->vval.v_list;
6091 list_append_number(l, buf->b_term->tl_rows);
6092 list_append_number(l, buf->b_term->tl_cols);
6093}
6094
6095/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006096 * "term_setsize(buf, rows, cols)" function
6097 */
6098 void
6099f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6100{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006101 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006102 term_T *term;
6103 varnumber_T rows, cols;
6104
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006105 if (in_vim9script()
6106 && (check_for_buffer_arg(argvars, 0) == FAIL
6107 || check_for_number_arg(argvars, 1) == FAIL
6108 || check_for_number_arg(argvars, 2) == FAIL))
6109 return;
6110
6111 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006112 if (buf == NULL)
6113 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006114 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006115 return;
6116 }
6117 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006118 return;
6119 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006120 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006121 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006122 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006123 cols = cols <= 0 ? term->tl_cols : cols;
6124 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006125 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006126
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006127 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006128 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6129 term_report_winsize(term, term->tl_rows, term->tl_cols);
6130}
6131
6132/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006133 * "term_getstatus(buf)" function
6134 */
6135 void
6136f_term_getstatus(typval_T *argvars, typval_T *rettv)
6137{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006138 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006139 term_T *term;
6140 char_u val[100];
6141
6142 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006143
6144 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6145 return;
6146
6147 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006148 if (buf == NULL)
6149 return;
6150 term = buf->b_term;
6151
6152 if (term_job_running(term))
6153 STRCPY(val, "running");
6154 else
6155 STRCPY(val, "finished");
6156 if (term->tl_normal_mode)
6157 STRCAT(val, ",normal");
6158 rettv->vval.v_string = vim_strsave(val);
6159}
6160
6161/*
6162 * "term_gettitle(buf)" function
6163 */
6164 void
6165f_term_gettitle(typval_T *argvars, typval_T *rettv)
6166{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006167 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006168
6169 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006170
6171 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6172 return;
6173
6174 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006175 if (buf == NULL)
6176 return;
6177
6178 if (buf->b_term->tl_title != NULL)
6179 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6180}
6181
6182/*
6183 * "term_gettty(buf)" function
6184 */
6185 void
6186f_term_gettty(typval_T *argvars, typval_T *rettv)
6187{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006188 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006189 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006190 int num = 0;
6191
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006192 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006193 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006194 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6195 return;
6196
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006197 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006198 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006199 if (buf == NULL)
6200 return;
6201 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006202 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006203
6204 switch (num)
6205 {
6206 case 0:
6207 if (buf->b_term->tl_job != NULL)
6208 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006209 break;
6210 case 1:
6211 if (buf->b_term->tl_job != NULL)
6212 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006213 break;
6214 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006215 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006216 return;
6217 }
6218 if (p != NULL)
6219 rettv->vval.v_string = vim_strsave(p);
6220}
6221
6222/*
6223 * "term_list()" function
6224 */
6225 void
6226f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6227{
6228 term_T *tp;
6229 list_T *l;
6230
6231 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6232 return;
6233
6234 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006235 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006236 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006237 if (list_append_number(l,
6238 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6239 return;
6240}
6241
6242/*
6243 * "term_scrape(buf, row)" function
6244 */
6245 void
6246f_term_scrape(typval_T *argvars, typval_T *rettv)
6247{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006248 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006249 VTermScreen *screen = NULL;
6250 VTermPos pos;
6251 list_T *l;
6252 term_T *term;
6253 char_u *p;
6254 sb_line_T *line;
6255
6256 if (rettv_list_alloc(rettv) == FAIL)
6257 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006258
6259 if (in_vim9script()
6260 && (check_for_buffer_arg(argvars, 0) == FAIL
6261 || check_for_lnum_arg(argvars, 1) == FAIL))
6262 return;
6263
6264 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006265 if (buf == NULL)
6266 return;
6267 term = buf->b_term;
6268
6269 l = rettv->vval.v_list;
6270 pos.row = get_row_number(&argvars[1], term);
6271
6272 if (term->tl_vterm != NULL)
6273 {
6274 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006275 if (screen == NULL) // can't really happen
6276 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006277 p = NULL;
6278 line = NULL;
6279 }
6280 else
6281 {
6282 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6283
6284 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6285 return;
6286 p = ml_get_buf(buf, lnum + 1, FALSE);
6287 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6288 }
6289
6290 for (pos.col = 0; pos.col < term->tl_cols; )
6291 {
6292 dict_T *dcell;
6293 int width;
6294 VTermScreenCellAttrs attrs;
6295 VTermColor fg, bg;
6296 char_u rgb[8];
6297 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6298 int off = 0;
6299 int i;
6300
6301 if (screen == NULL)
6302 {
6303 cellattr_T *cellattr;
6304 int len;
6305
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006306 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006307 if (pos.col >= line->sb_cols)
6308 break;
6309 cellattr = line->sb_cells + pos.col;
6310 width = cellattr->width;
6311 attrs = cellattr->attrs;
6312 fg = cellattr->fg;
6313 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006314 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006315 mch_memmove(mbs, p, len);
6316 mbs[len] = NUL;
6317 p += len;
6318 }
6319 else
6320 {
6321 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006322
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006323 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6324 break;
6325 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6326 {
6327 if (cell.chars[i] == 0)
6328 break;
6329 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6330 }
6331 mbs[off] = NUL;
6332 width = cell.width;
6333 attrs = cell.attrs;
6334 fg = cell.fg;
6335 bg = cell.bg;
6336 }
6337 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006338 if (dcell == NULL)
6339 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006340 list_append_dict(l, dcell);
6341
Bram Moolenaare0be1672018-07-08 16:50:37 +02006342 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006343
6344 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6345 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006346 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006347 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6348 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006349 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006350
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006351 dict_add_number(dcell, "attr",
6352 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006353 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006354
6355 ++pos.col;
6356 if (width == 2)
6357 ++pos.col;
6358 }
6359}
6360
6361/*
6362 * "term_sendkeys(buf, keys)" function
6363 */
6364 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006365f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006366{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006367 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006368 char_u *msg;
6369 term_T *term;
6370
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006371 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006372 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006373 || check_for_string_arg(argvars, 1) == FAIL))
6374 return;
6375
6376 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006377 if (buf == NULL)
6378 return;
6379
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006380 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006381 if (msg == NULL)
6382 return;
6383 term = buf->b_term;
6384 if (term->tl_vterm == NULL)
6385 return;
6386
6387 while (*msg != NUL)
6388 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006389 int c;
6390
6391 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6392 {
6393 c = TO_SPECIAL(msg[1], msg[2]);
6394 msg += 3;
6395 }
6396 else
6397 {
6398 c = PTR2CHAR(msg);
6399 msg += MB_CPTR2LEN(msg);
6400 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006401 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006402 }
6403}
6404
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006405#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6406/*
6407 * "term_getansicolors(buf)" function
6408 */
6409 void
6410f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6411{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006412 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006413 term_T *term;
6414 VTermState *state;
6415 VTermColor color;
6416 char_u hexbuf[10];
6417 int index;
6418 list_T *list;
6419
6420 if (rettv_list_alloc(rettv) == FAIL)
6421 return;
6422
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006423 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6424 return;
6425
6426 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006427 if (buf == NULL)
6428 return;
6429 term = buf->b_term;
6430 if (term->tl_vterm == NULL)
6431 return;
6432
6433 list = rettv->vval.v_list;
6434 state = vterm_obtain_state(term->tl_vterm);
6435 for (index = 0; index < 16; index++)
6436 {
6437 vterm_state_get_palette_color(state, index, &color);
6438 sprintf((char *)hexbuf, "#%02x%02x%02x",
6439 color.red, color.green, color.blue);
6440 if (list_append_string(list, hexbuf, 7) == FAIL)
6441 return;
6442 }
6443}
6444
6445/*
6446 * "term_setansicolors(buf, list)" function
6447 */
6448 void
6449f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6450{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006451 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006452 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006453 listitem_T *li;
6454 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006455
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006456 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006457 && (check_for_buffer_arg(argvars, 0) == FAIL
6458 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006459 return;
6460
6461 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006462 if (buf == NULL)
6463 return;
6464 term = buf->b_term;
6465 if (term->tl_vterm == NULL)
6466 return;
6467
6468 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
6469 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006470 emsg(_(e_list_required));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006471 return;
6472 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01006473 if (argvars[1].vval.v_list->lv_first == &range_list_item
6474 || argvars[1].vval.v_list->lv_len != 16)
6475 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006476 emsg(_(e_invalid_argument));
LemonBoyb2b3acb2022-05-20 10:10:34 +01006477 return;
6478 }
6479
6480 if (term->tl_palette == NULL)
6481 term->tl_palette = ALLOC_MULT(long_u, 16);
6482 if (term->tl_palette == NULL)
6483 return;
6484
6485 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6486 {
6487 char_u *color_name;
6488 guicolor_T guicolor;
6489
6490 color_name = tv_get_string_chk(&li->li_tv);
6491 if (color_name == NULL)
6492 return;
6493
6494 guicolor = GUI_GET_COLOR(color_name);
6495 if (guicolor == INVALCOLOR)
6496 {
6497 semsg(_(e_cannot_allocate_color_str), color_name);
6498 return;
6499 }
6500
6501 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6502 }
6503
6504 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006505}
6506#endif
6507
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006508/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006509 * "term_setapi(buf, api)" function
6510 */
6511 void
6512f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6513{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006514 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006515 term_T *term;
6516 char_u *api;
6517
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006518 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006519 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006520 || check_for_string_arg(argvars, 1) == FAIL))
6521 return;
6522
6523 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006524 if (buf == NULL)
6525 return;
6526 term = buf->b_term;
6527 vim_free(term->tl_api);
6528 api = tv_get_string_chk(&argvars[1]);
6529 if (api != NULL)
6530 term->tl_api = vim_strsave(api);
6531 else
6532 term->tl_api = NULL;
6533}
6534
6535/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006536 * "term_setrestore(buf, command)" function
6537 */
6538 void
6539f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6540{
6541#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006542 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006543 term_T *term;
6544 char_u *cmd;
6545
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006546 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006547 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006548 || check_for_string_arg(argvars, 1) == FAIL))
6549 return;
6550
6551 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006552 if (buf == NULL)
6553 return;
6554 term = buf->b_term;
6555 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006556 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006557 if (cmd != NULL)
6558 term->tl_command = vim_strsave(cmd);
6559 else
6560 term->tl_command = NULL;
6561#endif
6562}
6563
6564/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006565 * "term_setkill(buf, how)" function
6566 */
6567 void
6568f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6569{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006570 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006571 term_T *term;
6572 char_u *how;
6573
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006574 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006575 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006576 || check_for_string_arg(argvars, 1) == FAIL))
6577 return;
6578
6579 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006580 if (buf == NULL)
6581 return;
6582 term = buf->b_term;
6583 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006584 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006585 if (how != NULL)
6586 term->tl_kill = vim_strsave(how);
6587 else
6588 term->tl_kill = NULL;
6589}
6590
6591/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006592 * "term_start(command, options)" function
6593 */
6594 void
6595f_term_start(typval_T *argvars, typval_T *rettv)
6596{
6597 jobopt_T opt;
6598 buf_T *buf;
6599
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006600 if (in_vim9script()
6601 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6602 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6603 return;
6604
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006605 init_job_options(&opt);
6606 if (argvars[1].v_type != VAR_UNKNOWN
6607 && get_job_options(&argvars[1], &opt,
6608 JO_TIMEOUT_ALL + JO_STOPONEXIT
6609 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6610 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6611 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6612 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006613 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006614 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006615 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006616 return;
6617
Bram Moolenaar13568252018-03-16 20:46:58 +01006618 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006619
6620 if (buf != NULL && buf->b_term != NULL)
6621 rettv->vval.v_number = buf->b_fnum;
6622}
6623
6624/*
6625 * "term_wait" function
6626 */
6627 void
6628f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6629{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006630 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006631
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006632 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006633 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006634 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006635 return;
6636
6637 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006638 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006639 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006640 if (buf->b_term->tl_job == NULL)
6641 {
6642 ch_log(NULL, "term_wait(): no job to wait for");
6643 return;
6644 }
6645 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006646 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006647 return;
6648
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006649 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006650 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006651 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6652 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006653 // The job is dead, keep reading channel I/O until the channel is
6654 // closed. buf->b_term may become NULL if the terminal was closed while
6655 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006656 ch_log(NULL, "term_wait(): waiting for channel to close");
6657 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6658 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006659 term_flush_messages();
6660
Bram Moolenaard45aa552018-05-21 22:50:29 +02006661 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006662 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006663 // If the terminal is closed when the channel is closed the
6664 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006665 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006666 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6667 // came here from a close callback, only wait one time
6668 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006669 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006670
6671 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006672 }
6673 else
6674 {
6675 long wait = 10L;
6676
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006677 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006678
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006679 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006680 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006681 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006682 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006683
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006684 // Flushing messages on channels is hopefully sufficient.
6685 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006686 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006687 }
6688}
6689
6690/*
6691 * Called when a channel has sent all the lines to a terminal.
6692 * Send a CTRL-D to mark the end of the text.
6693 */
6694 void
6695term_send_eof(channel_T *ch)
6696{
6697 term_T *term;
6698
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006699 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006700 if (term->tl_job == ch->ch_job)
6701 {
6702 if (term->tl_eof_chars != NULL)
6703 {
6704 channel_send(ch, PART_IN, term->tl_eof_chars,
6705 (int)STRLEN(term->tl_eof_chars), NULL);
6706 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6707 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006708# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006709 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006710 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006711 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6712# endif
6713 }
6714}
6715
Bram Moolenaar113e1072019-01-20 15:30:40 +01006716#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006717 job_T *
6718term_getjob(term_T *term)
6719{
6720 return term != NULL ? term->tl_job : NULL;
6721}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006722#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006723
Bram Moolenaar4f974752019-02-17 17:44:42 +01006724# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006725
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006726///////////////////////////////////////
6727// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006728#ifdef PROTO
6729typedef int COORD;
6730typedef int DWORD;
6731typedef int HANDLE;
6732typedef int *DWORD_PTR;
6733typedef int HPCON;
6734typedef int HRESULT;
6735typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006736typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006737typedef int PSIZE_T;
6738typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006739typedef int BOOL;
6740# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006741#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006742
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006743HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6744HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6745HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006746BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6747BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6748void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006749
6750 static int
6751dyn_conpty_init(int verbose)
6752{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006753 static HMODULE hKerneldll = NULL;
6754 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006755 static struct
6756 {
6757 char *name;
6758 FARPROC *ptr;
6759 } conpty_entry[] =
6760 {
6761 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6762 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6763 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6764 {"InitializeProcThreadAttributeList",
6765 (FARPROC*)&pInitializeProcThreadAttributeList},
6766 {"UpdateProcThreadAttribute",
6767 (FARPROC*)&pUpdateProcThreadAttribute},
6768 {"DeleteProcThreadAttributeList",
6769 (FARPROC*)&pDeleteProcThreadAttributeList},
6770 {NULL, NULL}
6771 };
6772
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006773 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006774 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006775 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006776 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006777 return FAIL;
6778 }
6779
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006780 // No need to initialize twice.
6781 if (hKerneldll)
6782 return OK;
6783
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006784 hKerneldll = vimLoadLib("kernel32.dll");
6785 for (i = 0; conpty_entry[i].name != NULL
6786 && conpty_entry[i].ptr != NULL; ++i)
6787 {
6788 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6789 conpty_entry[i].name)) == NULL)
6790 {
6791 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006792 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006793 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006794 return FAIL;
6795 }
6796 }
6797
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006798 return OK;
6799}
6800
6801 static int
6802conpty_term_and_job_init(
6803 term_T *term,
6804 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006805 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006806 jobopt_T *opt,
6807 jobopt_T *orig_opt)
6808{
6809 WCHAR *cmd_wchar = NULL;
6810 WCHAR *cmd_wchar_copy = NULL;
6811 WCHAR *cwd_wchar = NULL;
6812 WCHAR *env_wchar = NULL;
6813 channel_T *channel = NULL;
6814 job_T *job = NULL;
6815 HANDLE jo = NULL;
6816 garray_T ga_cmd, ga_env;
6817 char_u *cmd = NULL;
6818 HRESULT hr;
6819 COORD consize;
6820 SIZE_T breq;
6821 PROCESS_INFORMATION proc_info;
6822 HANDLE i_theirs = NULL;
6823 HANDLE o_theirs = NULL;
6824 HANDLE i_ours = NULL;
6825 HANDLE o_ours = NULL;
6826
Bram Moolenaar04935fb2022-01-08 16:19:22 +00006827 ga_init2(&ga_cmd, sizeof(char*), 20);
6828 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006829
6830 if (argvar->v_type == VAR_STRING)
6831 {
6832 cmd = argvar->vval.v_string;
6833 }
6834 else if (argvar->v_type == VAR_LIST)
6835 {
6836 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6837 goto failed;
6838 cmd = ga_cmd.ga_data;
6839 }
6840 if (cmd == NULL || *cmd == NUL)
6841 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006842 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006843 goto failed;
6844 }
6845
6846 term->tl_arg0_cmd = vim_strsave(cmd);
6847
6848 cmd_wchar = enc_to_utf16(cmd, NULL);
6849
6850 if (cmd_wchar != NULL)
6851 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006852 // Request by CreateProcessW
6853 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006854 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006855 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6856 }
6857
6858 ga_clear(&ga_cmd);
6859 if (cmd_wchar == NULL)
6860 goto failed;
6861 if (opt->jo_cwd != NULL)
6862 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6863
6864 win32_build_env(opt->jo_env, &ga_env, TRUE);
6865 env_wchar = ga_env.ga_data;
6866
6867 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6868 goto failed;
6869 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6870 goto failed;
6871
6872 consize.X = term->tl_cols;
6873 consize.Y = term->tl_rows;
6874 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6875 &term->tl_conpty);
6876 if (FAILED(hr))
6877 goto failed;
6878
6879 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6880
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006881 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006882 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006883 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006884 if (!term->tl_siex.lpAttributeList)
6885 goto failed;
6886 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6887 0, &breq))
6888 goto failed;
6889 if (!pUpdateProcThreadAttribute(
6890 term->tl_siex.lpAttributeList, 0,
6891 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6892 sizeof(HPCON), NULL, NULL))
6893 goto failed;
6894
6895 channel = add_channel();
6896 if (channel == NULL)
6897 goto failed;
6898
6899 job = job_alloc();
6900 if (job == NULL)
6901 goto failed;
6902 if (argvar->v_type == VAR_STRING)
6903 {
6904 int argc;
6905
6906 build_argv_from_string(cmd, &job->jv_argv, &argc);
6907 }
6908 else
6909 {
6910 int argc;
6911
6912 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6913 }
6914
6915 if (opt->jo_set & JO_IN_BUF)
6916 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6917
6918 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6919 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02006920 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006921 env_wchar, cwd_wchar,
6922 &term->tl_siex.StartupInfo, &proc_info))
6923 goto failed;
6924
6925 CloseHandle(i_theirs);
6926 CloseHandle(o_theirs);
6927
6928 channel_set_pipes(channel,
6929 (sock_T)i_ours,
6930 (sock_T)o_ours,
6931 (sock_T)o_ours);
6932
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006933 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006934 channel->ch_write_text_mode = TRUE;
6935
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006936 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006937 channel->ch_anonymous_pipe = TRUE;
6938
6939 jo = CreateJobObject(NULL, NULL);
6940 if (jo == NULL)
6941 goto failed;
6942
6943 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6944 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006945 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006946 CloseHandle(jo);
6947 jo = NULL;
6948 }
6949
6950 ResumeThread(proc_info.hThread);
6951 CloseHandle(proc_info.hThread);
6952
6953 vim_free(cmd_wchar);
6954 vim_free(cmd_wchar_copy);
6955 vim_free(cwd_wchar);
6956 vim_free(env_wchar);
6957
6958 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6959 goto failed;
6960
Bram Moolenaar30b9a412022-05-26 14:06:37 +01006961#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01006962 if (term_use_palette())
6963 {
6964 if (term->tl_palette != NULL)
6965 set_vterm_palette(term->tl_vterm, term->tl_palette);
6966 else
6967 init_vterm_ansi_colors(term->tl_vterm);
6968 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01006969#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006970
6971 channel_set_job(channel, job, opt);
6972 job_set_options(job, opt);
6973
6974 job->jv_channel = channel;
6975 job->jv_proc_info = proc_info;
6976 job->jv_job_object = jo;
6977 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006978 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006979 ++job->jv_refcount;
6980 term->tl_job = job;
6981
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006982 // Redirecting stdout and stderr doesn't work at the job level. Instead
6983 // open the file here and handle it in. opt->jo_io was changed in
6984 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006985 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6986 {
6987 char_u *fname = opt->jo_io_name[PART_OUT];
6988
6989 ch_log(channel, "Opening output file %s", fname);
6990 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6991 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006992 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006993 }
6994
6995 return OK;
6996
6997failed:
6998 ga_clear(&ga_cmd);
6999 ga_clear(&ga_env);
7000 vim_free(cmd_wchar);
7001 vim_free(cmd_wchar_copy);
7002 vim_free(cwd_wchar);
7003 if (channel != NULL)
7004 channel_clear(channel);
7005 if (job != NULL)
7006 {
7007 job->jv_channel = NULL;
7008 job_cleanup(job);
7009 }
7010 term->tl_job = NULL;
7011 if (jo != NULL)
7012 CloseHandle(jo);
7013
7014 if (term->tl_siex.lpAttributeList != NULL)
7015 {
7016 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7017 vim_free(term->tl_siex.lpAttributeList);
7018 }
7019 term->tl_siex.lpAttributeList = NULL;
7020 if (o_theirs != NULL)
7021 CloseHandle(o_theirs);
7022 if (o_ours != NULL)
7023 CloseHandle(o_ours);
7024 if (i_ours != NULL)
7025 CloseHandle(i_ours);
7026 if (i_theirs != NULL)
7027 CloseHandle(i_theirs);
7028 if (term->tl_conpty != NULL)
7029 pClosePseudoConsole(term->tl_conpty);
7030 term->tl_conpty = NULL;
7031 return FAIL;
7032}
7033
7034 static void
7035conpty_term_report_winsize(term_T *term, int rows, int cols)
7036{
7037 COORD consize;
7038
7039 consize.X = cols;
7040 consize.Y = rows;
7041 pResizePseudoConsole(term->tl_conpty, consize);
7042}
7043
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007044 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007045term_free_conpty(term_T *term)
7046{
7047 if (term->tl_siex.lpAttributeList != NULL)
7048 {
7049 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7050 vim_free(term->tl_siex.lpAttributeList);
7051 }
7052 term->tl_siex.lpAttributeList = NULL;
7053 if (term->tl_conpty != NULL)
7054 pClosePseudoConsole(term->tl_conpty);
7055 term->tl_conpty = NULL;
7056}
7057
7058 int
7059use_conpty(void)
7060{
7061 return has_conpty;
7062}
7063
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007064# ifndef PROTO
7065
7066#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7067#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007068#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007069
7070void* (*winpty_config_new)(UINT64, void*);
7071void* (*winpty_open)(void*, void*);
7072void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7073BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7074void (*winpty_config_set_mouse_mode)(void*, int);
7075void (*winpty_config_set_initial_size)(void*, int, int);
7076LPCWSTR (*winpty_conin_name)(void*);
7077LPCWSTR (*winpty_conout_name)(void*);
7078LPCWSTR (*winpty_conerr_name)(void*);
7079void (*winpty_free)(void*);
7080void (*winpty_config_free)(void*);
7081void (*winpty_spawn_config_free)(void*);
7082void (*winpty_error_free)(void*);
7083LPCWSTR (*winpty_error_msg)(void*);
7084BOOL (*winpty_set_size)(void*, int, int, void*);
7085HANDLE (*winpty_agent_process)(void*);
7086
7087#define WINPTY_DLL "winpty.dll"
7088
7089static HINSTANCE hWinPtyDLL = NULL;
7090# endif
7091
7092 static int
7093dyn_winpty_init(int verbose)
7094{
7095 int i;
7096 static struct
7097 {
7098 char *name;
7099 FARPROC *ptr;
7100 } winpty_entry[] =
7101 {
7102 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7103 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7104 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7105 {"winpty_config_set_mouse_mode",
7106 (FARPROC*)&winpty_config_set_mouse_mode},
7107 {"winpty_config_set_initial_size",
7108 (FARPROC*)&winpty_config_set_initial_size},
7109 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7110 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7111 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7112 {"winpty_free", (FARPROC*)&winpty_free},
7113 {"winpty_open", (FARPROC*)&winpty_open},
7114 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7115 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7116 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7117 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7118 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7119 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7120 {NULL, NULL}
7121 };
7122
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007123 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007124 if (hWinPtyDLL)
7125 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007126 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7127 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007128 if (*p_winptydll != NUL)
7129 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7130 if (!hWinPtyDLL)
7131 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7132 if (!hWinPtyDLL)
7133 {
7134 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007135 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007136 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7137 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007138 return FAIL;
7139 }
7140 for (i = 0; winpty_entry[i].name != NULL
7141 && winpty_entry[i].ptr != NULL; ++i)
7142 {
7143 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7144 winpty_entry[i].name)) == NULL)
7145 {
7146 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007147 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007148 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007149 return FAIL;
7150 }
7151 }
7152
7153 return OK;
7154}
7155
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007156 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007157winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007158 term_T *term,
7159 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007160 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007161 jobopt_T *opt,
7162 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007163{
7164 WCHAR *cmd_wchar = NULL;
7165 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007166 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007167 channel_T *channel = NULL;
7168 job_T *job = NULL;
7169 DWORD error;
7170 HANDLE jo = NULL;
7171 HANDLE child_process_handle;
7172 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007173 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007174 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007175 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007176 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007177
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007178 ga_init2(&ga_cmd, sizeof(char*), 20);
7179 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007180
7181 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007182 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007183 cmd = argvar->vval.v_string;
7184 }
7185 else if (argvar->v_type == VAR_LIST)
7186 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007187 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007188 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007189 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007190 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007191 if (cmd == NULL || *cmd == NUL)
7192 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007193 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007194 goto failed;
7195 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007196
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007197 term->tl_arg0_cmd = vim_strsave(cmd);
7198
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007199 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007200 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007201 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007202 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007203 if (opt->jo_cwd != NULL)
7204 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007205
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007206 win32_build_env(opt->jo_env, &ga_env, TRUE);
7207 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007208
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007209 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7210 if (term->tl_winpty_config == NULL)
7211 goto failed;
7212
7213 winpty_config_set_mouse_mode(term->tl_winpty_config,
7214 WINPTY_MOUSE_MODE_FORCE);
7215 winpty_config_set_initial_size(term->tl_winpty_config,
7216 term->tl_cols, term->tl_rows);
7217 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7218 if (term->tl_winpty == NULL)
7219 goto failed;
7220
7221 spawn_config = winpty_spawn_config_new(
7222 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7223 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7224 NULL,
7225 cmd_wchar,
7226 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007227 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007228 &winpty_err);
7229 if (spawn_config == NULL)
7230 goto failed;
7231
7232 channel = add_channel();
7233 if (channel == NULL)
7234 goto failed;
7235
7236 job = job_alloc();
7237 if (job == NULL)
7238 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007239 if (argvar->v_type == VAR_STRING)
7240 {
7241 int argc;
7242
7243 build_argv_from_string(cmd, &job->jv_argv, &argc);
7244 }
7245 else
7246 {
7247 int argc;
7248
7249 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7250 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007251
7252 if (opt->jo_set & JO_IN_BUF)
7253 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7254
7255 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7256 &child_thread_handle, &error, &winpty_err))
7257 goto failed;
7258
7259 channel_set_pipes(channel,
7260 (sock_T)CreateFileW(
7261 winpty_conin_name(term->tl_winpty),
7262 GENERIC_WRITE, 0, NULL,
7263 OPEN_EXISTING, 0, NULL),
7264 (sock_T)CreateFileW(
7265 winpty_conout_name(term->tl_winpty),
7266 GENERIC_READ, 0, NULL,
7267 OPEN_EXISTING, 0, NULL),
7268 (sock_T)CreateFileW(
7269 winpty_conerr_name(term->tl_winpty),
7270 GENERIC_READ, 0, NULL,
7271 OPEN_EXISTING, 0, NULL));
7272
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007273 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007274 channel->ch_write_text_mode = TRUE;
7275
7276 jo = CreateJobObject(NULL, NULL);
7277 if (jo == NULL)
7278 goto failed;
7279
7280 if (!AssignProcessToJobObject(jo, child_process_handle))
7281 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007282 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007283 CloseHandle(jo);
7284 jo = NULL;
7285 }
7286
7287 winpty_spawn_config_free(spawn_config);
7288 vim_free(cmd_wchar);
7289 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007290 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007291
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007292 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7293 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007294
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007295#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007296 if (term_use_palette())
7297 {
7298 if (term->tl_palette != NULL)
7299 set_vterm_palette(term->tl_vterm, term->tl_palette);
7300 else
7301 init_vterm_ansi_colors(term->tl_vterm);
7302 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007303#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007304
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007305 channel_set_job(channel, job, opt);
7306 job_set_options(job, opt);
7307
7308 job->jv_channel = channel;
7309 job->jv_proc_info.hProcess = child_process_handle;
7310 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7311 job->jv_job_object = jo;
7312 job->jv_status = JOB_STARTED;
7313 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007314 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007315 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007316 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007317 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007318 ++job->jv_refcount;
7319 term->tl_job = job;
7320
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007321 // Redirecting stdout and stderr doesn't work at the job level. Instead
7322 // open the file here and handle it in. opt->jo_io was changed in
7323 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007324 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7325 {
7326 char_u *fname = opt->jo_io_name[PART_OUT];
7327
7328 ch_log(channel, "Opening output file %s", fname);
7329 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7330 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007331 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007332 }
7333
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007334 return OK;
7335
7336failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007337 ga_clear(&ga_cmd);
7338 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007339 vim_free(cmd_wchar);
7340 vim_free(cwd_wchar);
7341 if (spawn_config != NULL)
7342 winpty_spawn_config_free(spawn_config);
7343 if (channel != NULL)
7344 channel_clear(channel);
7345 if (job != NULL)
7346 {
7347 job->jv_channel = NULL;
7348 job_cleanup(job);
7349 }
7350 term->tl_job = NULL;
7351 if (jo != NULL)
7352 CloseHandle(jo);
7353 if (term->tl_winpty != NULL)
7354 winpty_free(term->tl_winpty);
7355 term->tl_winpty = NULL;
7356 if (term->tl_winpty_config != NULL)
7357 winpty_config_free(term->tl_winpty_config);
7358 term->tl_winpty_config = NULL;
7359 if (winpty_err != NULL)
7360 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007361 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007362 (short_u *)winpty_error_msg(winpty_err), NULL);
7363
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007364 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007365 winpty_error_free(winpty_err);
7366 }
7367 return FAIL;
7368}
7369
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007370/*
7371 * Create a new terminal of "rows" by "cols" cells.
7372 * Store a reference in "term".
7373 * Return OK or FAIL.
7374 */
7375 static int
7376term_and_job_init(
7377 term_T *term,
7378 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007379 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007380 jobopt_T *opt,
7381 jobopt_T *orig_opt)
7382{
7383 int use_winpty = FALSE;
7384 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007385 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007386
7387 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7388 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7389
7390 if (!has_winpty && !has_conpty)
7391 // If neither is available give the errors for winpty, since when
7392 // conpty is not available it can't be installed either.
7393 return dyn_winpty_init(TRUE);
7394
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007395 if (opt->jo_tty_type != NUL)
7396 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007397
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007398 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007399 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007400 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007401 use_conpty = TRUE;
7402 else if (has_winpty)
7403 use_winpty = TRUE;
7404 // else: error
7405 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007406 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007407 {
7408 if (has_winpty)
7409 use_winpty = TRUE;
7410 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007411 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007412 {
7413 if (has_conpty)
7414 use_conpty = TRUE;
7415 else
7416 return dyn_conpty_init(TRUE);
7417 }
7418
7419 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007420 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007421
7422 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007423 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007424
7425 // error
7426 return dyn_winpty_init(TRUE);
7427}
7428
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007429 static int
7430create_pty_only(term_T *term, jobopt_T *options)
7431{
7432 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7433 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7434 char in_name[80], out_name[80];
7435 channel_T *channel = NULL;
7436
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007437 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7438 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007439
7440 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7441 GetCurrentProcessId(),
7442 curbuf->b_fnum);
7443 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7444 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7445 PIPE_UNLIMITED_INSTANCES,
7446 0, 0, NMPWAIT_NOWAIT, NULL);
7447 if (hPipeIn == INVALID_HANDLE_VALUE)
7448 goto failed;
7449
7450 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7451 GetCurrentProcessId(),
7452 curbuf->b_fnum);
7453 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7454 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7455 PIPE_UNLIMITED_INSTANCES,
7456 0, 0, 0, NULL);
7457 if (hPipeOut == INVALID_HANDLE_VALUE)
7458 goto failed;
7459
7460 ConnectNamedPipe(hPipeIn, NULL);
7461 ConnectNamedPipe(hPipeOut, NULL);
7462
7463 term->tl_job = job_alloc();
7464 if (term->tl_job == NULL)
7465 goto failed;
7466 ++term->tl_job->jv_refcount;
7467
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007468 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007469 term->tl_job->jv_status = JOB_FINISHED;
7470
7471 channel = add_channel();
7472 if (channel == NULL)
7473 goto failed;
7474 term->tl_job->jv_channel = channel;
7475 channel->ch_keep_open = TRUE;
7476 channel->ch_named_pipe = TRUE;
7477
7478 channel_set_pipes(channel,
7479 (sock_T)hPipeIn,
7480 (sock_T)hPipeOut,
7481 (sock_T)hPipeOut);
7482 channel_set_job(channel, term->tl_job, options);
7483 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7484 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7485
7486 return OK;
7487
7488failed:
7489 if (hPipeIn != NULL)
7490 CloseHandle(hPipeIn);
7491 if (hPipeOut != NULL)
7492 CloseHandle(hPipeOut);
7493 return FAIL;
7494}
7495
7496/*
7497 * Free the terminal emulator part of "term".
7498 */
7499 static void
7500term_free_vterm(term_T *term)
7501{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007502 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007503 if (term->tl_winpty != NULL)
7504 winpty_free(term->tl_winpty);
7505 term->tl_winpty = NULL;
7506 if (term->tl_winpty_config != NULL)
7507 winpty_config_free(term->tl_winpty_config);
7508 term->tl_winpty_config = NULL;
7509 if (term->tl_vterm != NULL)
7510 vterm_free(term->tl_vterm);
7511 term->tl_vterm = NULL;
7512}
7513
7514/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007515 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007516 */
7517 static void
7518term_report_winsize(term_T *term, int rows, int cols)
7519{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007520 if (term->tl_conpty)
7521 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007522 if (term->tl_winpty)
7523 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7524}
7525
7526 int
7527terminal_enabled(void)
7528{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007529 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007530}
7531
7532# else
7533
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007534///////////////////////////////////////
7535// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007536
7537/*
7538 * Create a new terminal of "rows" by "cols" cells.
7539 * Start job for "cmd".
7540 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007541 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007542 * Return OK or FAIL.
7543 */
7544 static int
7545term_and_job_init(
7546 term_T *term,
7547 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007548 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007549 jobopt_T *opt,
7550 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007551{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007552 term->tl_arg0_cmd = NULL;
7553
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007554 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7555 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007556
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007557#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007558 if (term_use_palette())
7559 {
7560 if (term->tl_palette != NULL)
7561 set_vterm_palette(term->tl_vterm, term->tl_palette);
7562 else
7563 init_vterm_ansi_colors(term->tl_vterm);
7564 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007565#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007566
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007567 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007568 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007569 if (term->tl_job != NULL)
7570 ++term->tl_job->jv_refcount;
7571
7572 return term->tl_job != NULL
7573 && term->tl_job->jv_channel != NULL
7574 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7575}
7576
7577 static int
7578create_pty_only(term_T *term, jobopt_T *opt)
7579{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007580 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7581 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007582
7583 term->tl_job = job_alloc();
7584 if (term->tl_job == NULL)
7585 return FAIL;
7586 ++term->tl_job->jv_refcount;
7587
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007588 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007589 term->tl_job->jv_status = JOB_FINISHED;
7590
7591 return mch_create_pty_channel(term->tl_job, opt);
7592}
7593
7594/*
7595 * Free the terminal emulator part of "term".
7596 */
7597 static void
7598term_free_vterm(term_T *term)
7599{
7600 if (term->tl_vterm != NULL)
7601 vterm_free(term->tl_vterm);
7602 term->tl_vterm = NULL;
7603}
7604
7605/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007606 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007607 */
7608 static void
7609term_report_winsize(term_T *term, int rows, int cols)
7610{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007611 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007612 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
7613 {
7614 int fd = -1;
7615 int part;
7616
7617 for (part = PART_OUT; part < PART_COUNT; ++part)
7618 {
7619 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01007620 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007621 break;
7622 }
7623 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7624 mch_signal_job(term->tl_job, (char_u *)"winch");
7625 }
7626}
7627
7628# endif
7629
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007630#endif // FEAT_TERMINAL