blob: 0283267af116839162ee4b05c499e6529baf9bdf [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
Yegappan Lakshmanan04c4c572022-08-30 19:48:24 +01004992 if (check_for_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004993 return;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004994 d = argvars[2].vval.v_dict;
4995 if (d != NULL)
4996 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01004997 max_height = dict_get_number(d, "rows");
4998 max_width = dict_get_number(d, "columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004999 }
5000 }
5001
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005002 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005003 if (fname == NULL)
5004 return;
5005 if (mch_stat((char *)fname, &st) >= 0)
5006 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00005007 semsg(_(e_file_exists_str), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005008 return;
5009 }
5010
Bram Moolenaard96ff162018-02-18 22:13:29 +01005011 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
5012 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005013 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005014 return;
5015 }
5016
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005017 clear_cell(&prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005018
5019 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005020 state = vterm_obtain_state(term->tl_vterm);
5021 vterm_state_get_cursorpos(state, &cursor_pos);
5022
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005023 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
5024 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005025 {
5026 int repeat = 0;
5027
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01005028 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
5029 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005030 {
5031 VTermScreenCell cell;
5032 int same_attr;
5033 int same_chars = TRUE;
5034 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005035 int is_cursor_pos = (pos.col == cursor_pos.col
5036 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005037
5038 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005039 clear_cell(&cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005040
5041 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5042 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01005043 int c = cell.chars[i];
5044 int pc = prev_cell.chars[i];
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005045 int should_break = c == NUL || pc == NUL;
Bram Moolenaar47015b82018-03-23 22:10:34 +01005046
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005047 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01005048 if (i == 0)
5049 {
5050 c = (c == NUL) ? ' ' : c;
5051 pc = (pc == NUL) ? ' ' : pc;
5052 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02005053 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005054 same_chars = FALSE;
Bram Moolenaar9c24cd12020-10-23 15:40:39 +02005055 if (should_break)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005056 break;
5057 }
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005058 same_attr = vtermAttr2hl(&cell.attrs)
5059 == vtermAttr2hl(&prev_cell.attrs)
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005060 && vterm_color_is_equal(&cell.fg, &prev_cell.fg)
5061 && vterm_color_is_equal(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005062 if (same_chars && cell.width == prev_cell.width && same_attr
5063 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005064 {
5065 ++repeat;
5066 }
5067 else
5068 {
5069 if (repeat > 0)
5070 {
5071 fprintf(fd, "@%d", repeat);
5072 repeat = 0;
5073 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005074 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005075
5076 if (cell.chars[0] == NUL)
5077 fputs(" ", fd);
5078 else
5079 {
5080 char_u charbuf[10];
5081 int len;
5082
5083 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
5084 && cell.chars[i] != NUL; ++i)
5085 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02005086 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005087 fwrite(charbuf, len, 1, fd);
5088 }
5089 }
5090
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005091 // When only the characters differ we don't write anything, the
5092 // following "|", "@" or NL will indicate using the same
5093 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005094 if (cell.width != prev_cell.width || !same_attr)
5095 {
5096 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005097 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005098 else
5099 fputs("+", fd);
5100
5101 if (same_attr)
5102 {
5103 fputs("&", fd);
5104 }
5105 else
5106 {
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005107 fprintf(fd, "%d", vtermAttr2hl(&cell.attrs));
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005108 if (vterm_color_is_equal(&cell.fg, &prev_cell.fg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005109 fputs("&", fd);
5110 else
5111 {
5112 fputs("#", fd);
5113 dump_term_color(fd, &cell.fg);
5114 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005115 if (vterm_color_is_equal(&cell.bg, &prev_cell.bg))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005116 fputs("&", fd);
5117 else
5118 {
5119 fputs("#", fd);
5120 dump_term_color(fd, &cell.bg);
5121 }
5122 }
5123 }
5124
5125 prev_cell = cell;
5126 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005127
5128 if (cell.width == 2)
5129 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005130 }
5131 if (repeat > 0)
5132 fprintf(fd, "@%d", repeat);
5133 fputs("\n", fd);
5134 }
5135
5136 fclose(fd);
5137}
5138
5139/*
5140 * Called when a dump is corrupted. Put a breakpoint here when debugging.
5141 */
5142 static void
5143dump_is_corrupt(garray_T *gap)
5144{
5145 ga_concat(gap, (char_u *)"CORRUPT");
5146}
5147
5148 static void
5149append_cell(garray_T *gap, cellattr_T *cell)
5150{
5151 if (ga_grow(gap, 1) == OK)
5152 {
5153 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
5154 ++gap->ga_len;
5155 }
5156}
5157
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005158 static void
5159clear_cellattr(cellattr_T *cell)
5160{
5161 CLEAR_FIELD(*cell);
5162 cell->fg.type = VTERM_COLOR_DEFAULT_FG;
5163 cell->bg.type = VTERM_COLOR_DEFAULT_BG;
5164}
5165
Bram Moolenaard96ff162018-02-18 22:13:29 +01005166/*
5167 * Read the dump file from "fd" and append lines to the current buffer.
5168 * Return the cell width of the longest line.
5169 */
5170 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01005171read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005172{
5173 int c;
5174 garray_T ga_text;
5175 garray_T ga_cell;
5176 char_u *prev_char = NULL;
5177 int attr = 0;
5178 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005179 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005180 term_T *term = curbuf->b_term;
5181 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005182 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005183
5184 ga_init2(&ga_text, 1, 90);
5185 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005186 clear_cellattr(&cell);
5187 clear_cellattr(&empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005188 cursor_pos->row = -1;
5189 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005190
5191 c = fgetc(fd);
5192 for (;;)
5193 {
5194 if (c == EOF)
5195 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02005196 if (c == '\r')
5197 {
5198 // DOS line endings? Ignore.
5199 c = fgetc(fd);
5200 }
5201 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005202 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005203 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005204 if (ga_text.ga_data == NULL)
5205 dump_is_corrupt(&ga_text);
5206 if (ga_grow(&term->tl_scrollback, 1) == OK)
5207 {
5208 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
5209 + term->tl_scrollback.ga_len;
5210
5211 if (max_cells < ga_cell.ga_len)
5212 max_cells = ga_cell.ga_len;
5213 line->sb_cols = ga_cell.ga_len;
5214 line->sb_cells = ga_cell.ga_data;
5215 line->sb_fill_attr = term->tl_default_color;
5216 ++term->tl_scrollback.ga_len;
5217 ga_init(&ga_cell);
5218
5219 ga_append(&ga_text, NUL);
5220 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5221 ga_text.ga_len, FALSE);
5222 }
5223 else
5224 ga_clear(&ga_cell);
5225 ga_text.ga_len = 0;
5226
5227 c = fgetc(fd);
5228 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01005229 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005230 {
5231 int prev_len = ga_text.ga_len;
5232
Bram Moolenaar9271d052018-02-25 21:39:46 +01005233 if (c == '>')
5234 {
5235 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005236 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005237 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
5238 cursor_pos->col = ga_cell.ga_len;
5239 }
5240
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005241 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005242 c = fgetc(fd);
5243 if (c != EOF)
5244 ga_append(&ga_text, c);
5245 for (;;)
5246 {
5247 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01005248 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01005249 || c == EOF || c == '\n')
5250 break;
5251 ga_append(&ga_text, c);
5252 }
5253
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005254 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01005255 vim_free(prev_char);
5256 if (ga_text.ga_data != NULL)
5257 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
5258 ga_text.ga_len - prev_len);
5259
Bram Moolenaar9271d052018-02-25 21:39:46 +01005260 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01005261 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005262 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005263 }
5264 else if (c == '+' || c == '*')
5265 {
5266 int is_bg;
5267
5268 cell.width = c == '+' ? 1 : 2;
5269
5270 c = fgetc(fd);
5271 if (c == '&')
5272 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005273 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01005274 c = fgetc(fd);
5275 }
5276 else if (isdigit(c))
5277 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005278 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01005279 attr = 0;
5280 while (isdigit(c))
5281 {
5282 attr = attr * 10 + (c - '0');
5283 c = fgetc(fd);
5284 }
5285 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005286
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005287 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005288 for (is_bg = 0; is_bg <= 1; ++is_bg)
5289 {
5290 if (c == '&')
5291 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005292 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005293 c = fgetc(fd);
5294 }
5295 else if (c == '#')
5296 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005297 int red, green, blue, index = 0, type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005298
5299 c = fgetc(fd);
5300 red = hex2nr(c);
5301 c = fgetc(fd);
5302 red = (red << 4) + hex2nr(c);
5303 c = fgetc(fd);
5304 green = hex2nr(c);
5305 c = fgetc(fd);
5306 green = (green << 4) + hex2nr(c);
5307 c = fgetc(fd);
5308 blue = hex2nr(c);
5309 c = fgetc(fd);
5310 blue = (blue << 4) + hex2nr(c);
5311 c = fgetc(fd);
5312 if (!isdigit(c))
5313 dump_is_corrupt(&ga_text);
5314 while (isdigit(c))
5315 {
5316 index = index * 10 + (c - '0');
5317 c = fgetc(fd);
5318 }
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005319 if (index == 0 || index == 255)
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005320 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005321 type = VTERM_COLOR_RGB;
5322 if (index == 0)
5323 {
5324 if (is_bg)
5325 type |= VTERM_COLOR_DEFAULT_BG;
5326 else
5327 type |= VTERM_COLOR_DEFAULT_FG;
5328 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005329 }
5330 else
5331 {
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005332 type = VTERM_COLOR_INDEXED;
5333 index -= 1;
5334 }
5335 if (is_bg)
5336 {
5337 cell.bg.type = type;
5338 cell.bg.red = red;
5339 cell.bg.green = green;
5340 cell.bg.blue = blue;
5341 cell.bg.index = index;
5342 }
5343 else
5344 {
5345 cell.fg.type = type;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005346 cell.fg.red = red;
5347 cell.fg.green = green;
5348 cell.fg.blue = blue;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005349 cell.fg.index = index;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005350 }
5351 }
5352 else
5353 dump_is_corrupt(&ga_text);
5354 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005355 }
5356 else
5357 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005358 }
5359 else
5360 dump_is_corrupt(&ga_text);
5361
5362 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01005363 if (cell.width == 2)
5364 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005365 }
5366 else if (c == '@')
5367 {
5368 if (prev_char == NULL)
5369 dump_is_corrupt(&ga_text);
5370 else
5371 {
5372 int count = 0;
5373
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005374 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01005375 for (;;)
5376 {
5377 c = fgetc(fd);
5378 if (!isdigit(c))
5379 break;
5380 count = count * 10 + (c - '0');
5381 }
5382
5383 while (count-- > 0)
5384 {
5385 ga_concat(&ga_text, prev_char);
5386 append_cell(&ga_cell, &cell);
5387 }
5388 }
5389 }
5390 else
5391 {
5392 dump_is_corrupt(&ga_text);
5393 c = fgetc(fd);
5394 }
5395 }
5396
5397 if (ga_text.ga_len > 0)
5398 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005399 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01005400 dump_is_corrupt(&ga_text);
5401 ga_append(&ga_text, NUL);
5402 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
5403 ga_text.ga_len, FALSE);
5404 }
5405
5406 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02005407 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005408 vim_free(prev_char);
5409
5410 return max_cells;
5411}
5412
5413/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02005414 * Return an allocated string with at least "text_width" "=" characters and
5415 * "fname" inserted in the middle.
5416 */
5417 static char_u *
5418get_separator(int text_width, char_u *fname)
5419{
5420 int width = MAX(text_width, curwin->w_width);
5421 char_u *textline;
5422 int fname_size;
5423 char_u *p = fname;
5424 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005425 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005426
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02005427 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02005428 if (textline == NULL)
5429 return NULL;
5430
5431 fname_size = vim_strsize(fname);
5432 if (fname_size < width - 8)
5433 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005434 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005435 width = MAX(text_width, fname_size + 8);
5436 }
5437 else if (fname_size > width - 8)
5438 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005439 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005440 p = gettail(fname);
5441 fname_size = vim_strsize(p);
5442 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005443 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005444 while (fname_size > width - 8)
5445 {
5446 p += (*mb_ptr2len)(p);
5447 fname_size = vim_strsize(p);
5448 }
5449
5450 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5451 textline[i] = '=';
5452 textline[i++] = ' ';
5453
5454 STRCPY(textline + i, p);
5455 off = STRLEN(textline);
5456 textline[off] = ' ';
5457 for (i = 1; i < (width - fname_size) / 2; ++i)
5458 textline[off + i] = '=';
5459 textline[off + i] = NUL;
5460
5461 return textline;
5462}
5463
5464/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005465 * Common for "term_dumpdiff()" and "term_dumpload()".
5466 */
5467 static void
5468term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5469{
5470 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005471 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005472 char_u buf1[NUMBUFLEN];
5473 char_u buf2[NUMBUFLEN];
5474 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005475 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005476 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005477 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005478 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005479 char_u *textline = NULL;
5480
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005481 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005482 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005483 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005484 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005485 if (fname1 == NULL || (do_diff && fname2 == NULL))
5486 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005487 emsg(_(e_invalid_argument));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005488 return;
5489 }
5490 fd1 = mch_fopen((char *)fname1, READBIN);
5491 if (fd1 == NULL)
5492 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005493 semsg(_(e_cant_read_file_str), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005494 return;
5495 }
5496 if (do_diff)
5497 {
5498 fd2 = mch_fopen((char *)fname2, READBIN);
5499 if (fd2 == NULL)
5500 {
5501 fclose(fd1);
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00005502 semsg(_(e_cant_read_file_str), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005503 return;
5504 }
5505 }
5506
5507 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005508 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5509 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5510 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5511 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5512 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005513
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005514 if (opt.jo_term_name == NULL)
5515 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005516 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005517
Bram Moolenaar51e14382019-05-25 20:21:28 +02005518 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005519 if (fname_tofree != NULL)
5520 {
5521 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5522 opt.jo_term_name = fname_tofree;
5523 }
5524 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005525
Bram Moolenaar87abab92019-06-03 21:14:59 +02005526 if (opt.jo_bufnr_buf != NULL)
5527 {
5528 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5529
5530 // With "bufnr" argument: enter the window with this buffer and make it
5531 // empty.
5532 if (wp == NULL)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00005533 semsg(_(e_invalid_argument_str), "bufnr");
Bram Moolenaar87abab92019-06-03 21:14:59 +02005534 else
5535 {
5536 buf = curbuf;
5537 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
Bram Moolenaarca70c072020-05-30 20:30:46 +02005538 ml_delete((linenr_T)1);
Bram Moolenaar86173482019-10-01 17:02:16 +02005539 free_scrollback(curbuf->b_term);
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005540 redraw_later(UPD_NOT_VALID);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005541 }
5542 }
5543 else
5544 // Create a new terminal window.
5545 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5546
Bram Moolenaard96ff162018-02-18 22:13:29 +01005547 if (buf != NULL && buf->b_term != NULL)
5548 {
5549 int i;
5550 linenr_T bot_lnum;
5551 linenr_T lnum;
5552 term_T *term = buf->b_term;
5553 int width;
5554 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005555 VTermPos cursor_pos1;
5556 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005557
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005558 init_default_colors(term);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005559
Bram Moolenaard96ff162018-02-18 22:13:29 +01005560 rettv->vval.v_number = buf->b_fnum;
5561
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005562 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005563 width = read_dump_file(fd1, &cursor_pos1);
5564
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005565 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005566 if (cursor_pos1.row >= 0)
5567 {
5568 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5569 coladvance(cursor_pos1.col);
5570 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005571
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005572 // Delete the empty line that was in the empty buffer.
Bram Moolenaarca70c072020-05-30 20:30:46 +02005573 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005574
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005575 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005576 if (!do_diff)
5577 goto theend;
5578
5579 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5580
Bram Moolenaar4a696342018-04-05 18:45:26 +02005581 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005582 if (textline == NULL)
5583 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005584 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5585 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5586 vim_free(textline);
5587
5588 textline = get_separator(width, fname2);
5589 if (textline == NULL)
5590 goto theend;
5591 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5592 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005593 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005594
5595 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005596 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005597 if (width2 > width)
5598 {
5599 vim_free(textline);
5600 textline = alloc(width2 + 1);
5601 if (textline == NULL)
5602 goto theend;
5603 width = width2;
5604 textline[width] = NUL;
5605 }
5606 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5607
5608 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5609 {
5610 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5611 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005612 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005613 for (i = 0; i < width; ++i)
5614 textline[i] = '-';
5615 }
5616 else
5617 {
5618 char_u *line1;
5619 char_u *line2;
5620 char_u *p1;
5621 char_u *p2;
5622 int col;
5623 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5624 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5625 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5626 ->sb_cells;
5627
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005628 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005629 line1 = vim_strsave(ml_get(lnum));
5630 if (line1 == NULL)
5631 break;
5632 p1 = line1;
5633
5634 line2 = ml_get(lnum + bot_lnum);
5635 p2 = line2;
5636 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5637 {
5638 int len1 = utfc_ptr2len(p1);
5639 int len2 = utfc_ptr2len(p2);
5640
5641 textline[col] = ' ';
5642 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005643 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005644 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005645 else if (lnum == cursor_pos1.row + 1
5646 && col == cursor_pos1.col
5647 && (cursor_pos1.row != cursor_pos2.row
5648 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005649 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005650 textline[col] = '>';
5651 else if (lnum == cursor_pos2.row + 1
5652 && col == cursor_pos2.col
5653 && (cursor_pos1.row != cursor_pos2.row
5654 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005655 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005656 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005657 else if (cellattr1 != NULL && cellattr2 != NULL)
5658 {
5659 if ((cellattr1 + col)->width
5660 != (cellattr2 + col)->width)
5661 textline[col] = 'w';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005662 else if (!vterm_color_is_equal(&(cellattr1 + col)->fg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005663 &(cellattr2 + col)->fg))
5664 textline[col] = 'f';
Bram Moolenaare5886cc2020-05-21 20:10:04 +02005665 else if (!vterm_color_is_equal(&(cellattr1 + col)->bg,
Bram Moolenaard96ff162018-02-18 22:13:29 +01005666 &(cellattr2 + col)->bg))
5667 textline[col] = 'b';
Bram Moolenaar87fd0922021-11-20 13:47:45 +00005668 else if (vtermAttr2hl(&(cellattr1 + col)->attrs)
5669 != vtermAttr2hl(&((cellattr2 + col)->attrs)))
Bram Moolenaard96ff162018-02-18 22:13:29 +01005670 textline[col] = 'a';
5671 }
5672 p1 += len1;
5673 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005674 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005675 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005676
5677 while (col < width)
5678 {
5679 if (*p1 == NUL && *p2 == NUL)
5680 textline[col] = '?';
5681 else if (*p1 == NUL)
5682 {
5683 textline[col] = '+';
5684 p2 += utfc_ptr2len(p2);
5685 }
5686 else
5687 {
5688 textline[col] = '-';
5689 p1 += utfc_ptr2len(p1);
5690 }
5691 ++col;
5692 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005693
5694 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005695 }
5696 if (add_empty_scrollback(term, &term->tl_default_color,
5697 term->tl_top_diff_rows) == OK)
5698 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5699 ++bot_lnum;
5700 }
5701
5702 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5703 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005704 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005705 for (i = 0; i < width; ++i)
5706 textline[i] = '+';
5707 if (add_empty_scrollback(term, &term->tl_default_color,
5708 term->tl_top_diff_rows) == OK)
5709 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5710 ++lnum;
5711 ++bot_lnum;
5712 }
5713
5714 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005715
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005716 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005717 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005718 }
5719
5720theend:
5721 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005722 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005723 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005724 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005725 fclose(fd2);
5726}
5727
5728/*
5729 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5730 * bottom files.
5731 * Return FAIL when this is not possible.
5732 */
5733 int
5734term_swap_diff()
5735{
5736 term_T *term = curbuf->b_term;
5737 linenr_T line_count;
5738 linenr_T top_rows;
5739 linenr_T bot_rows;
5740 linenr_T bot_start;
5741 linenr_T lnum;
5742 char_u *p;
5743 sb_line_T *sb_line;
5744
5745 if (term == NULL
5746 || !term_is_finished(curbuf)
5747 || term->tl_top_diff_rows == 0
5748 || term->tl_scrollback.ga_len == 0)
5749 return FAIL;
5750
5751 line_count = curbuf->b_ml.ml_line_count;
5752 top_rows = term->tl_top_diff_rows;
5753 bot_rows = term->tl_bot_diff_rows;
5754 bot_start = line_count - bot_rows;
5755 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5756
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005757 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005758 for (lnum = 1; lnum <= top_rows; ++lnum)
5759 {
5760 p = vim_strsave(ml_get(1));
5761 if (p == NULL)
5762 return OK;
5763 ml_append(bot_start, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005764 ml_delete(1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005765 vim_free(p);
5766 }
5767
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005768 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005769 for (lnum = 1; lnum <= bot_rows; ++lnum)
5770 {
5771 p = vim_strsave(ml_get(bot_start + lnum));
5772 if (p == NULL)
5773 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005774 ml_delete(bot_start + lnum);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005775 ml_append(lnum - 1, p, 0, FALSE);
5776 vim_free(p);
5777 }
5778
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005779 // move top title to bottom
5780 p = vim_strsave(ml_get(bot_rows + 1));
5781 if (p == NULL)
5782 return OK;
5783 ml_append(line_count - top_rows - 1, p, 0, FALSE);
Bram Moolenaarca70c072020-05-30 20:30:46 +02005784 ml_delete(bot_rows + 1);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005785 vim_free(p);
5786
5787 // move bottom title to top
5788 p = vim_strsave(ml_get(line_count - top_rows));
5789 if (p == NULL)
5790 return OK;
Bram Moolenaarca70c072020-05-30 20:30:46 +02005791 ml_delete(line_count - top_rows);
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005792 ml_append(bot_rows, p, 0, FALSE);
5793 vim_free(p);
5794
Bram Moolenaard96ff162018-02-18 22:13:29 +01005795 if (top_rows == bot_rows)
5796 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005797 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005798 for (lnum = 0; lnum < top_rows; ++lnum)
5799 {
5800 sb_line_T temp;
5801
5802 temp = *(sb_line + lnum);
5803 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5804 *(sb_line + bot_start + lnum) = temp;
5805 }
5806 }
5807 else
5808 {
5809 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005810 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005811
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005812 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005813 if (temp != NULL)
5814 {
5815 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5816 mch_memmove(term->tl_scrollback.ga_data,
5817 temp + bot_start,
5818 sizeof(sb_line_T) * bot_rows);
5819 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5820 temp + top_rows,
5821 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5822 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5823 + line_count - top_rows,
5824 temp,
5825 sizeof(sb_line_T) * top_rows);
5826 vim_free(temp);
5827 }
5828 }
5829
5830 term->tl_top_diff_rows = bot_rows;
5831 term->tl_bot_diff_rows = top_rows;
5832
Bram Moolenaara4d158b2022-08-14 14:17:45 +01005833 update_screen(UPD_NOT_VALID);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005834 return OK;
5835}
5836
5837/*
5838 * "term_dumpdiff(filename, filename, options)" function
5839 */
5840 void
5841f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5842{
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02005843 if (in_vim9script()
5844 && (check_for_string_arg(argvars, 0) == FAIL
5845 || check_for_string_arg(argvars, 1) == FAIL
5846 || check_for_opt_dict_arg(argvars, 2) == FAIL))
5847 return;
5848
Bram Moolenaard96ff162018-02-18 22:13:29 +01005849 term_load_dump(argvars, rettv, TRUE);
5850}
5851
5852/*
5853 * "term_dumpload(filename, options)" function
5854 */
5855 void
5856f_term_dumpload(typval_T *argvars, typval_T *rettv)
5857{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005858 if (in_vim9script()
5859 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmananfc3b7752021-09-08 14:57:42 +02005860 || check_for_opt_dict_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005861 return;
5862
Bram Moolenaard96ff162018-02-18 22:13:29 +01005863 term_load_dump(argvars, rettv, FALSE);
5864}
5865
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005866/*
5867 * "term_getaltscreen(buf)" function
5868 */
5869 void
5870f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5871{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005872 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005873
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005874 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5875 return;
5876
5877 buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005878 if (buf == NULL)
5879 return;
5880 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5881}
5882
5883/*
5884 * "term_getattr(attr, name)" function
5885 */
5886 void
5887f_term_getattr(typval_T *argvars, typval_T *rettv)
5888{
5889 int attr;
5890 size_t i;
5891 char_u *name;
5892
5893 static struct {
5894 char *name;
5895 int attr;
5896 } attrs[] = {
5897 {"bold", HL_BOLD},
5898 {"italic", HL_ITALIC},
5899 {"underline", HL_UNDERLINE},
5900 {"strike", HL_STRIKETHROUGH},
5901 {"reverse", HL_INVERSE},
5902 };
5903
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02005904 if (in_vim9script()
5905 && (check_for_number_arg(argvars, 0) == FAIL
5906 || check_for_string_arg(argvars, 1) == FAIL))
5907 return;
5908
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005909 attr = tv_get_number(&argvars[0]);
5910 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005911 if (name == NULL)
5912 return;
5913
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005914 if (attr > HL_ALL)
5915 attr = syn_attr2attr(attr);
K.Takataeeec2542021-06-02 13:28:16 +02005916 for (i = 0; i < ARRAY_LENGTH(attrs); ++i)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005917 if (STRCMP(name, attrs[i].name) == 0)
5918 {
5919 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5920 break;
5921 }
5922}
5923
5924/*
5925 * "term_getcursor(buf)" function
5926 */
5927 void
5928f_term_getcursor(typval_T *argvars, typval_T *rettv)
5929{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005930 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005931 term_T *term;
5932 list_T *l;
5933 dict_T *d;
5934
5935 if (rettv_list_alloc(rettv) == FAIL)
5936 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005937
5938 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5939 return;
5940
5941 buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005942 if (buf == NULL)
5943 return;
5944 term = buf->b_term;
5945
5946 l = rettv->vval.v_list;
5947 list_append_number(l, term->tl_cursor_pos.row + 1);
5948 list_append_number(l, term->tl_cursor_pos.col + 1);
5949
5950 d = dict_alloc();
5951 if (d != NULL)
5952 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005953 dict_add_number(d, "visible", term->tl_cursor_visible);
5954 dict_add_number(d, "blink", blink_state_is_inverted()
5955 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5956 dict_add_number(d, "shape", term->tl_cursor_shape);
5957 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005958 list_append_dict(l, d);
5959 }
5960}
5961
5962/*
5963 * "term_getjob(buf)" function
5964 */
5965 void
5966f_term_getjob(typval_T *argvars, typval_T *rettv)
5967{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005968 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005969
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02005970 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
5971 return;
5972
5973 buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005974 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005975 {
5976 rettv->v_type = VAR_SPECIAL;
5977 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005978 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005979 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005980
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005981 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005982 rettv->vval.v_job = buf->b_term->tl_job;
5983 if (rettv->vval.v_job != NULL)
5984 ++rettv->vval.v_job->jv_refcount;
5985}
5986
5987 static int
5988get_row_number(typval_T *tv, term_T *term)
5989{
5990 if (tv->v_type == VAR_STRING
5991 && tv->vval.v_string != NULL
5992 && STRCMP(tv->vval.v_string, ".") == 0)
5993 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005994 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005995}
5996
5997/*
5998 * "term_getline(buf, row)" function
5999 */
6000 void
6001f_term_getline(typval_T *argvars, typval_T *rettv)
6002{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006003 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006004 term_T *term;
6005 int row;
6006
6007 rettv->v_type = VAR_STRING;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006008
6009 if (in_vim9script()
6010 && (check_for_buffer_arg(argvars, 0) == FAIL
6011 || check_for_lnum_arg(argvars, 1) == FAIL))
6012 return;
6013
6014 buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006015 if (buf == NULL)
6016 return;
6017 term = buf->b_term;
6018 row = get_row_number(&argvars[1], term);
6019
6020 if (term->tl_vterm == NULL)
6021 {
6022 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
6023
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006024 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006025 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
6026 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
6027 }
6028 else
6029 {
6030 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
6031 VTermRect rect;
6032 int len;
6033 char_u *p;
6034
6035 if (row < 0 || row >= term->tl_rows)
6036 return;
6037 len = term->tl_cols * MB_MAXBYTES + 1;
6038 p = alloc(len);
6039 if (p == NULL)
6040 return;
6041 rettv->vval.v_string = p;
6042
6043 rect.start_col = 0;
6044 rect.end_col = term->tl_cols;
6045 rect.start_row = row;
6046 rect.end_row = row + 1;
6047 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
6048 }
6049}
6050
6051/*
6052 * "term_getscrolled(buf)" function
6053 */
6054 void
6055f_term_getscrolled(typval_T *argvars, typval_T *rettv)
6056{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006057 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006058
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006059 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6060 return;
6061
6062 buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006063 if (buf == NULL)
6064 return;
6065 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
6066}
6067
6068/*
6069 * "term_getsize(buf)" function
6070 */
6071 void
6072f_term_getsize(typval_T *argvars, typval_T *rettv)
6073{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006074 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006075 list_T *l;
6076
6077 if (rettv_list_alloc(rettv) == FAIL)
6078 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006079
6080 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6081 return;
6082
6083 buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006084 if (buf == NULL)
6085 return;
6086
6087 l = rettv->vval.v_list;
6088 list_append_number(l, buf->b_term->tl_rows);
6089 list_append_number(l, buf->b_term->tl_cols);
6090}
6091
6092/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006093 * "term_setsize(buf, rows, cols)" function
6094 */
6095 void
6096f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6097{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006098 buf_T *buf;
Bram Moolenaara42d3632018-04-14 17:05:38 +02006099 term_T *term;
6100 varnumber_T rows, cols;
6101
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006102 if (in_vim9script()
6103 && (check_for_buffer_arg(argvars, 0) == FAIL
6104 || check_for_number_arg(argvars, 1) == FAIL
6105 || check_for_number_arg(argvars, 2) == FAIL))
6106 return;
6107
6108 buf = term_get_buf(argvars, "term_setsize()");
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006109 if (buf == NULL)
6110 {
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006111 emsg(_(e_not_terminal_buffer));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02006112 return;
6113 }
6114 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02006115 return;
6116 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006117 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006118 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006119 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02006120 cols = cols <= 0 ? term->tl_cols : cols;
6121 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006122 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02006123
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006124 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02006125 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
6126 term_report_winsize(term, term->tl_rows, term->tl_cols);
6127}
6128
6129/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006130 * "term_getstatus(buf)" function
6131 */
6132 void
6133f_term_getstatus(typval_T *argvars, typval_T *rettv)
6134{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006135 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006136 term_T *term;
6137 char_u val[100];
6138
6139 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006140
6141 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6142 return;
6143
6144 buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006145 if (buf == NULL)
6146 return;
6147 term = buf->b_term;
6148
6149 if (term_job_running(term))
6150 STRCPY(val, "running");
6151 else
6152 STRCPY(val, "finished");
6153 if (term->tl_normal_mode)
6154 STRCAT(val, ",normal");
6155 rettv->vval.v_string = vim_strsave(val);
6156}
6157
6158/*
6159 * "term_gettitle(buf)" function
6160 */
6161 void
6162f_term_gettitle(typval_T *argvars, typval_T *rettv)
6163{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006164 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006165
6166 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006167
6168 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6169 return;
6170
6171 buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006172 if (buf == NULL)
6173 return;
6174
6175 if (buf->b_term->tl_title != NULL)
6176 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
6177}
6178
6179/*
6180 * "term_gettty(buf)" function
6181 */
6182 void
6183f_term_gettty(typval_T *argvars, typval_T *rettv)
6184{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006185 buf_T *buf;
Bram Moolenaar9b50f362018-05-07 20:10:17 +02006186 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006187 int num = 0;
6188
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006189 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006190 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006191 || check_for_opt_bool_arg(argvars, 1) == FAIL))
6192 return;
6193
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006194 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006195 buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006196 if (buf == NULL)
6197 return;
6198 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaarad304702020-09-06 18:22:53 +02006199 num = tv_get_bool(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006200
6201 switch (num)
6202 {
6203 case 0:
6204 if (buf->b_term->tl_job != NULL)
6205 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006206 break;
6207 case 1:
6208 if (buf->b_term->tl_job != NULL)
6209 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006210 break;
6211 default:
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006212 semsg(_(e_invalid_argument_str), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006213 return;
6214 }
6215 if (p != NULL)
6216 rettv->vval.v_string = vim_strsave(p);
6217}
6218
6219/*
6220 * "term_list()" function
6221 */
6222 void
6223f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
6224{
6225 term_T *tp;
6226 list_T *l;
6227
6228 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
6229 return;
6230
6231 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006232 FOR_ALL_TERMS(tp)
Bram Moolenaarad431992021-05-03 20:40:38 +02006233 if (tp->tl_buffer != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006234 if (list_append_number(l,
6235 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
6236 return;
6237}
6238
6239/*
6240 * "term_scrape(buf, row)" function
6241 */
6242 void
6243f_term_scrape(typval_T *argvars, typval_T *rettv)
6244{
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006245 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006246 VTermScreen *screen = NULL;
6247 VTermPos pos;
6248 list_T *l;
6249 term_T *term;
6250 char_u *p;
6251 sb_line_T *line;
6252
6253 if (rettv_list_alloc(rettv) == FAIL)
6254 return;
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006255
6256 if (in_vim9script()
6257 && (check_for_buffer_arg(argvars, 0) == FAIL
6258 || check_for_lnum_arg(argvars, 1) == FAIL))
6259 return;
6260
6261 buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006262 if (buf == NULL)
6263 return;
6264 term = buf->b_term;
6265
6266 l = rettv->vval.v_list;
6267 pos.row = get_row_number(&argvars[1], term);
6268
6269 if (term->tl_vterm != NULL)
6270 {
6271 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01006272 if (screen == NULL) // can't really happen
6273 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006274 p = NULL;
6275 line = NULL;
6276 }
6277 else
6278 {
6279 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
6280
6281 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
6282 return;
6283 p = ml_get_buf(buf, lnum + 1, FALSE);
6284 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
6285 }
6286
6287 for (pos.col = 0; pos.col < term->tl_cols; )
6288 {
6289 dict_T *dcell;
6290 int width;
6291 VTermScreenCellAttrs attrs;
6292 VTermColor fg, bg;
6293 char_u rgb[8];
6294 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
6295 int off = 0;
6296 int i;
6297
6298 if (screen == NULL)
6299 {
6300 cellattr_T *cellattr;
6301 int len;
6302
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006303 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006304 if (pos.col >= line->sb_cols)
6305 break;
6306 cellattr = line->sb_cells + pos.col;
6307 width = cellattr->width;
6308 attrs = cellattr->attrs;
6309 fg = cellattr->fg;
6310 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02006311 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006312 mch_memmove(mbs, p, len);
6313 mbs[len] = NUL;
6314 p += len;
6315 }
6316 else
6317 {
6318 VTermScreenCell cell;
Bram Moolenaare5886cc2020-05-21 20:10:04 +02006319
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006320 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
6321 break;
6322 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
6323 {
6324 if (cell.chars[i] == 0)
6325 break;
6326 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
6327 }
6328 mbs[off] = NUL;
6329 width = cell.width;
6330 attrs = cell.attrs;
6331 fg = cell.fg;
6332 bg = cell.bg;
6333 }
6334 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01006335 if (dcell == NULL)
6336 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006337 list_append_dict(l, dcell);
6338
Bram Moolenaare0be1672018-07-08 16:50:37 +02006339 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006340
6341 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6342 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006343 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006344 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
6345 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02006346 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006347
Bram Moolenaar87fd0922021-11-20 13:47:45 +00006348 dict_add_number(dcell, "attr",
6349 cell2attr(term, NULL, &attrs, &fg, &bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02006350 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006351
6352 ++pos.col;
6353 if (width == 2)
6354 ++pos.col;
6355 }
6356}
6357
6358/*
6359 * "term_sendkeys(buf, keys)" function
6360 */
6361 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01006362f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006363{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006364 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006365 char_u *msg;
6366 term_T *term;
6367
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006368 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006369 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006370 || check_for_string_arg(argvars, 1) == FAIL))
6371 return;
6372
6373 buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006374 if (buf == NULL)
6375 return;
6376
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006377 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006378 if (msg == NULL)
6379 return;
6380 term = buf->b_term;
6381 if (term->tl_vterm == NULL)
6382 return;
6383
6384 while (*msg != NUL)
6385 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02006386 int c;
6387
6388 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
6389 {
6390 c = TO_SPECIAL(msg[1], msg[2]);
6391 msg += 3;
6392 }
6393 else
6394 {
6395 c = PTR2CHAR(msg);
6396 msg += MB_CPTR2LEN(msg);
6397 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006398 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006399 }
6400}
6401
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006402#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
6403/*
6404 * "term_getansicolors(buf)" function
6405 */
6406 void
6407f_term_getansicolors(typval_T *argvars, typval_T *rettv)
6408{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006409 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006410 term_T *term;
6411 VTermState *state;
6412 VTermColor color;
6413 char_u hexbuf[10];
6414 int index;
6415 list_T *list;
6416
6417 if (rettv_list_alloc(rettv) == FAIL)
6418 return;
6419
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006420 if (in_vim9script() && check_for_buffer_arg(argvars, 0) == FAIL)
6421 return;
6422
6423 buf = term_get_buf(argvars, "term_getansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006424 if (buf == NULL)
6425 return;
6426 term = buf->b_term;
6427 if (term->tl_vterm == NULL)
6428 return;
6429
6430 list = rettv->vval.v_list;
6431 state = vterm_obtain_state(term->tl_vterm);
6432 for (index = 0; index < 16; index++)
6433 {
6434 vterm_state_get_palette_color(state, index, &color);
6435 sprintf((char *)hexbuf, "#%02x%02x%02x",
6436 color.red, color.green, color.blue);
6437 if (list_append_string(list, hexbuf, 7) == FAIL)
6438 return;
6439 }
6440}
6441
6442/*
6443 * "term_setansicolors(buf, list)" function
6444 */
6445 void
6446f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
6447{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006448 buf_T *buf;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006449 term_T *term;
LemonBoyb2b3acb2022-05-20 10:10:34 +01006450 listitem_T *li;
6451 int n = 0;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006452
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006453 if (in_vim9script()
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02006454 && (check_for_buffer_arg(argvars, 0) == FAIL
6455 || check_for_list_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006456 return;
6457
6458 buf = term_get_buf(argvars, "term_setansicolors()");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006459 if (buf == NULL)
6460 return;
6461 term = buf->b_term;
6462 if (term->tl_vterm == NULL)
6463 return;
6464
6465 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
6466 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006467 emsg(_(e_list_required));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006468 return;
6469 }
LemonBoyb2b3acb2022-05-20 10:10:34 +01006470 if (argvars[1].vval.v_list->lv_first == &range_list_item
6471 || argvars[1].vval.v_list->lv_len != 16)
6472 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006473 emsg(_(e_invalid_argument));
LemonBoyb2b3acb2022-05-20 10:10:34 +01006474 return;
6475 }
6476
6477 if (term->tl_palette == NULL)
6478 term->tl_palette = ALLOC_MULT(long_u, 16);
6479 if (term->tl_palette == NULL)
6480 return;
6481
6482 FOR_ALL_LIST_ITEMS(argvars[1].vval.v_list, li)
6483 {
6484 char_u *color_name;
6485 guicolor_T guicolor;
6486
6487 color_name = tv_get_string_chk(&li->li_tv);
6488 if (color_name == NULL)
6489 return;
6490
6491 guicolor = GUI_GET_COLOR(color_name);
6492 if (guicolor == INVALCOLOR)
6493 {
6494 semsg(_(e_cannot_allocate_color_str), color_name);
6495 return;
6496 }
6497
6498 term->tl_palette[n++] = GUI_MCH_GET_RGB(guicolor);
6499 }
6500
6501 term_update_palette(term);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006502}
6503#endif
6504
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006505/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006506 * "term_setapi(buf, api)" function
6507 */
6508 void
6509f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
6510{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006511 buf_T *buf;
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006512 term_T *term;
6513 char_u *api;
6514
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006515 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006516 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006517 || check_for_string_arg(argvars, 1) == FAIL))
6518 return;
6519
6520 buf = term_get_buf(argvars, "term_setapi()");
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006521 if (buf == NULL)
6522 return;
6523 term = buf->b_term;
6524 vim_free(term->tl_api);
6525 api = tv_get_string_chk(&argvars[1]);
6526 if (api != NULL)
6527 term->tl_api = vim_strsave(api);
6528 else
6529 term->tl_api = NULL;
6530}
6531
6532/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006533 * "term_setrestore(buf, command)" function
6534 */
6535 void
6536f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6537{
6538#if defined(FEAT_SESSION)
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006539 buf_T *buf;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006540 term_T *term;
6541 char_u *cmd;
6542
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006543 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006544 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006545 || check_for_string_arg(argvars, 1) == FAIL))
6546 return;
6547
6548 buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006549 if (buf == NULL)
6550 return;
6551 term = buf->b_term;
6552 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006553 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006554 if (cmd != NULL)
6555 term->tl_command = vim_strsave(cmd);
6556 else
6557 term->tl_command = NULL;
6558#endif
6559}
6560
6561/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006562 * "term_setkill(buf, how)" function
6563 */
6564 void
6565f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6566{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006567 buf_T *buf;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006568 term_T *term;
6569 char_u *how;
6570
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006571 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006572 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006573 || check_for_string_arg(argvars, 1) == FAIL))
6574 return;
6575
6576 buf = term_get_buf(argvars, "term_setkill()");
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006577 if (buf == NULL)
6578 return;
6579 term = buf->b_term;
6580 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006581 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006582 if (how != NULL)
6583 term->tl_kill = vim_strsave(how);
6584 else
6585 term->tl_kill = NULL;
6586}
6587
6588/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006589 * "term_start(command, options)" function
6590 */
6591 void
6592f_term_start(typval_T *argvars, typval_T *rettv)
6593{
6594 jobopt_T opt;
6595 buf_T *buf;
6596
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006597 if (in_vim9script()
6598 && (check_for_string_or_list_arg(argvars, 0) == FAIL
6599 || check_for_opt_dict_arg(argvars, 1) == FAIL))
6600 return;
6601
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006602 init_job_options(&opt);
6603 if (argvars[1].v_type != VAR_UNKNOWN
6604 && get_job_options(&argvars[1], &opt,
6605 JO_TIMEOUT_ALL + JO_STOPONEXIT
6606 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6607 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6608 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6609 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006610 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006611 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006612 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006613 return;
6614
Bram Moolenaar13568252018-03-16 20:46:58 +01006615 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006616
6617 if (buf != NULL && buf->b_term != NULL)
6618 rettv->vval.v_number = buf->b_fnum;
6619}
6620
6621/*
6622 * "term_wait" function
6623 */
6624 void
6625f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6626{
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006627 buf_T *buf;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006628
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006629 if (in_vim9script()
Yegappan Lakshmanancd917202021-07-21 19:09:09 +02006630 && (check_for_buffer_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02006631 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanana9a7c0c2021-07-17 19:11:07 +02006632 return;
6633
6634 buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006635 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006636 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006637 if (buf->b_term->tl_job == NULL)
6638 {
6639 ch_log(NULL, "term_wait(): no job to wait for");
6640 return;
6641 }
6642 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006643 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006644 return;
6645
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006646 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006647 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006648 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6649 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006650 // The job is dead, keep reading channel I/O until the channel is
6651 // closed. buf->b_term may become NULL if the terminal was closed while
6652 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006653 ch_log(NULL, "term_wait(): waiting for channel to close");
6654 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6655 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006656 term_flush_messages();
6657
Bram Moolenaard45aa552018-05-21 22:50:29 +02006658 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006659 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006660 // If the terminal is closed when the channel is closed the
6661 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006662 break;
Bram Moolenaareea32af2021-11-21 14:51:13 +00006663 if (buf->b_term == NULL || buf->b_term->tl_channel_closing)
6664 // came here from a close callback, only wait one time
6665 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006666 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006667
6668 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006669 }
6670 else
6671 {
6672 long wait = 10L;
6673
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006674 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006675
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006676 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006677 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006678 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006679 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006680
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006681 // Flushing messages on channels is hopefully sufficient.
6682 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006683 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006684 }
6685}
6686
6687/*
6688 * Called when a channel has sent all the lines to a terminal.
6689 * Send a CTRL-D to mark the end of the text.
6690 */
6691 void
6692term_send_eof(channel_T *ch)
6693{
6694 term_T *term;
6695
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006696 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006697 if (term->tl_job == ch->ch_job)
6698 {
6699 if (term->tl_eof_chars != NULL)
6700 {
6701 channel_send(ch, PART_IN, term->tl_eof_chars,
6702 (int)STRLEN(term->tl_eof_chars), NULL);
6703 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6704 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006705# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006706 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006707 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006708 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6709# endif
6710 }
6711}
6712
Bram Moolenaar113e1072019-01-20 15:30:40 +01006713#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006714 job_T *
6715term_getjob(term_T *term)
6716{
6717 return term != NULL ? term->tl_job : NULL;
6718}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006719#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006720
Bram Moolenaar4f974752019-02-17 17:44:42 +01006721# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006722
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006723///////////////////////////////////////
6724// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006725#ifdef PROTO
6726typedef int COORD;
6727typedef int DWORD;
6728typedef int HANDLE;
6729typedef int *DWORD_PTR;
6730typedef int HPCON;
6731typedef int HRESULT;
6732typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006733typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006734typedef int PSIZE_T;
6735typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006736typedef int BOOL;
6737# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006738#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006739
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006740HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6741HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6742HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006743BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6744BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6745void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006746
6747 static int
6748dyn_conpty_init(int verbose)
6749{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006750 static HMODULE hKerneldll = NULL;
6751 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006752 static struct
6753 {
6754 char *name;
6755 FARPROC *ptr;
6756 } conpty_entry[] =
6757 {
6758 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6759 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6760 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6761 {"InitializeProcThreadAttributeList",
6762 (FARPROC*)&pInitializeProcThreadAttributeList},
6763 {"UpdateProcThreadAttribute",
6764 (FARPROC*)&pUpdateProcThreadAttribute},
6765 {"DeleteProcThreadAttributeList",
6766 (FARPROC*)&pDeleteProcThreadAttributeList},
6767 {NULL, NULL}
6768 };
6769
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006770 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006771 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006772 if (verbose)
Bram Moolenaard82a47d2022-01-05 20:24:39 +00006773 emsg(_(e_conpty_is_not_available));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006774 return FAIL;
6775 }
6776
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006777 // No need to initialize twice.
6778 if (hKerneldll)
6779 return OK;
6780
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006781 hKerneldll = vimLoadLib("kernel32.dll");
6782 for (i = 0; conpty_entry[i].name != NULL
6783 && conpty_entry[i].ptr != NULL; ++i)
6784 {
6785 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6786 conpty_entry[i].name)) == NULL)
6787 {
6788 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006789 semsg(_(e_could_not_load_library_function_str), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006790 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006791 return FAIL;
6792 }
6793 }
6794
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006795 return OK;
6796}
6797
6798 static int
6799conpty_term_and_job_init(
6800 term_T *term,
6801 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006802 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006803 jobopt_T *opt,
6804 jobopt_T *orig_opt)
6805{
6806 WCHAR *cmd_wchar = NULL;
6807 WCHAR *cmd_wchar_copy = NULL;
6808 WCHAR *cwd_wchar = NULL;
6809 WCHAR *env_wchar = NULL;
6810 channel_T *channel = NULL;
6811 job_T *job = NULL;
6812 HANDLE jo = NULL;
6813 garray_T ga_cmd, ga_env;
6814 char_u *cmd = NULL;
6815 HRESULT hr;
6816 COORD consize;
6817 SIZE_T breq;
6818 PROCESS_INFORMATION proc_info;
6819 HANDLE i_theirs = NULL;
6820 HANDLE o_theirs = NULL;
6821 HANDLE i_ours = NULL;
6822 HANDLE o_ours = NULL;
6823
Bram Moolenaar04935fb2022-01-08 16:19:22 +00006824 ga_init2(&ga_cmd, sizeof(char*), 20);
6825 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006826
6827 if (argvar->v_type == VAR_STRING)
6828 {
6829 cmd = argvar->vval.v_string;
6830 }
6831 else if (argvar->v_type == VAR_LIST)
6832 {
6833 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6834 goto failed;
6835 cmd = ga_cmd.ga_data;
6836 }
6837 if (cmd == NULL || *cmd == NUL)
6838 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00006839 emsg(_(e_invalid_argument));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006840 goto failed;
6841 }
6842
6843 term->tl_arg0_cmd = vim_strsave(cmd);
6844
6845 cmd_wchar = enc_to_utf16(cmd, NULL);
6846
6847 if (cmd_wchar != NULL)
6848 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006849 // Request by CreateProcessW
6850 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006851 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006852 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6853 }
6854
6855 ga_clear(&ga_cmd);
6856 if (cmd_wchar == NULL)
6857 goto failed;
6858 if (opt->jo_cwd != NULL)
6859 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6860
6861 win32_build_env(opt->jo_env, &ga_env, TRUE);
6862 env_wchar = ga_env.ga_data;
6863
6864 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6865 goto failed;
6866 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6867 goto failed;
6868
6869 consize.X = term->tl_cols;
6870 consize.Y = term->tl_rows;
6871 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6872 &term->tl_conpty);
6873 if (FAILED(hr))
6874 goto failed;
6875
6876 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6877
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006878 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006879 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006880 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006881 if (!term->tl_siex.lpAttributeList)
6882 goto failed;
6883 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6884 0, &breq))
6885 goto failed;
6886 if (!pUpdateProcThreadAttribute(
6887 term->tl_siex.lpAttributeList, 0,
6888 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6889 sizeof(HPCON), NULL, NULL))
6890 goto failed;
6891
6892 channel = add_channel();
6893 if (channel == NULL)
6894 goto failed;
6895
6896 job = job_alloc();
6897 if (job == NULL)
6898 goto failed;
6899 if (argvar->v_type == VAR_STRING)
6900 {
6901 int argc;
6902
6903 build_argv_from_string(cmd, &job->jv_argv, &argc);
6904 }
6905 else
6906 {
6907 int argc;
6908
6909 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6910 }
6911
6912 if (opt->jo_set & JO_IN_BUF)
6913 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6914
6915 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6916 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02006917 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006918 env_wchar, cwd_wchar,
6919 &term->tl_siex.StartupInfo, &proc_info))
6920 goto failed;
6921
6922 CloseHandle(i_theirs);
6923 CloseHandle(o_theirs);
6924
6925 channel_set_pipes(channel,
6926 (sock_T)i_ours,
6927 (sock_T)o_ours,
6928 (sock_T)o_ours);
6929
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006930 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006931 channel->ch_write_text_mode = TRUE;
6932
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006933 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006934 channel->ch_anonymous_pipe = TRUE;
6935
6936 jo = CreateJobObject(NULL, NULL);
6937 if (jo == NULL)
6938 goto failed;
6939
6940 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6941 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006942 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006943 CloseHandle(jo);
6944 jo = NULL;
6945 }
6946
6947 ResumeThread(proc_info.hThread);
6948 CloseHandle(proc_info.hThread);
6949
6950 vim_free(cmd_wchar);
6951 vim_free(cmd_wchar_copy);
6952 vim_free(cwd_wchar);
6953 vim_free(env_wchar);
6954
6955 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6956 goto failed;
6957
Bram Moolenaar30b9a412022-05-26 14:06:37 +01006958#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01006959 if (term_use_palette())
6960 {
6961 if (term->tl_palette != NULL)
6962 set_vterm_palette(term->tl_vterm, term->tl_palette);
6963 else
6964 init_vterm_ansi_colors(term->tl_vterm);
6965 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01006966#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006967
6968 channel_set_job(channel, job, opt);
6969 job_set_options(job, opt);
6970
6971 job->jv_channel = channel;
6972 job->jv_proc_info = proc_info;
6973 job->jv_job_object = jo;
6974 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006975 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006976 ++job->jv_refcount;
6977 term->tl_job = job;
6978
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006979 // Redirecting stdout and stderr doesn't work at the job level. Instead
6980 // open the file here and handle it in. opt->jo_io was changed in
6981 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006982 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6983 {
6984 char_u *fname = opt->jo_io_name[PART_OUT];
6985
6986 ch_log(channel, "Opening output file %s", fname);
6987 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6988 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00006989 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006990 }
6991
6992 return OK;
6993
6994failed:
6995 ga_clear(&ga_cmd);
6996 ga_clear(&ga_env);
6997 vim_free(cmd_wchar);
6998 vim_free(cmd_wchar_copy);
6999 vim_free(cwd_wchar);
7000 if (channel != NULL)
7001 channel_clear(channel);
7002 if (job != NULL)
7003 {
7004 job->jv_channel = NULL;
7005 job_cleanup(job);
7006 }
7007 term->tl_job = NULL;
7008 if (jo != NULL)
7009 CloseHandle(jo);
7010
7011 if (term->tl_siex.lpAttributeList != NULL)
7012 {
7013 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7014 vim_free(term->tl_siex.lpAttributeList);
7015 }
7016 term->tl_siex.lpAttributeList = NULL;
7017 if (o_theirs != NULL)
7018 CloseHandle(o_theirs);
7019 if (o_ours != NULL)
7020 CloseHandle(o_ours);
7021 if (i_ours != NULL)
7022 CloseHandle(i_ours);
7023 if (i_theirs != NULL)
7024 CloseHandle(i_theirs);
7025 if (term->tl_conpty != NULL)
7026 pClosePseudoConsole(term->tl_conpty);
7027 term->tl_conpty = NULL;
7028 return FAIL;
7029}
7030
7031 static void
7032conpty_term_report_winsize(term_T *term, int rows, int cols)
7033{
7034 COORD consize;
7035
7036 consize.X = cols;
7037 consize.Y = rows;
7038 pResizePseudoConsole(term->tl_conpty, consize);
7039}
7040
Bram Moolenaar840d16f2019-09-10 21:27:18 +02007041 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007042term_free_conpty(term_T *term)
7043{
7044 if (term->tl_siex.lpAttributeList != NULL)
7045 {
7046 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
7047 vim_free(term->tl_siex.lpAttributeList);
7048 }
7049 term->tl_siex.lpAttributeList = NULL;
7050 if (term->tl_conpty != NULL)
7051 pClosePseudoConsole(term->tl_conpty);
7052 term->tl_conpty = NULL;
7053}
7054
7055 int
7056use_conpty(void)
7057{
7058 return has_conpty;
7059}
7060
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007061# ifndef PROTO
7062
7063#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
7064#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01007065#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007066
7067void* (*winpty_config_new)(UINT64, void*);
7068void* (*winpty_open)(void*, void*);
7069void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
7070BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
7071void (*winpty_config_set_mouse_mode)(void*, int);
7072void (*winpty_config_set_initial_size)(void*, int, int);
7073LPCWSTR (*winpty_conin_name)(void*);
7074LPCWSTR (*winpty_conout_name)(void*);
7075LPCWSTR (*winpty_conerr_name)(void*);
7076void (*winpty_free)(void*);
7077void (*winpty_config_free)(void*);
7078void (*winpty_spawn_config_free)(void*);
7079void (*winpty_error_free)(void*);
7080LPCWSTR (*winpty_error_msg)(void*);
7081BOOL (*winpty_set_size)(void*, int, int, void*);
7082HANDLE (*winpty_agent_process)(void*);
7083
7084#define WINPTY_DLL "winpty.dll"
7085
7086static HINSTANCE hWinPtyDLL = NULL;
7087# endif
7088
7089 static int
7090dyn_winpty_init(int verbose)
7091{
7092 int i;
7093 static struct
7094 {
7095 char *name;
7096 FARPROC *ptr;
7097 } winpty_entry[] =
7098 {
7099 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
7100 {"winpty_config_free", (FARPROC*)&winpty_config_free},
7101 {"winpty_config_new", (FARPROC*)&winpty_config_new},
7102 {"winpty_config_set_mouse_mode",
7103 (FARPROC*)&winpty_config_set_mouse_mode},
7104 {"winpty_config_set_initial_size",
7105 (FARPROC*)&winpty_config_set_initial_size},
7106 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
7107 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
7108 {"winpty_error_free", (FARPROC*)&winpty_error_free},
7109 {"winpty_free", (FARPROC*)&winpty_free},
7110 {"winpty_open", (FARPROC*)&winpty_open},
7111 {"winpty_spawn", (FARPROC*)&winpty_spawn},
7112 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
7113 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
7114 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
7115 {"winpty_set_size", (FARPROC*)&winpty_set_size},
7116 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
7117 {NULL, NULL}
7118 };
7119
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007120 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007121 if (hWinPtyDLL)
7122 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007123 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
7124 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007125 if (*p_winptydll != NUL)
7126 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
7127 if (!hWinPtyDLL)
7128 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
7129 if (!hWinPtyDLL)
7130 {
7131 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007132 semsg(_(e_could_not_load_library_str_str),
Martin Tournoij1a3e5742021-07-24 13:57:29 +02007133 (*p_winptydll != NUL ? p_winptydll : (char_u *)WINPTY_DLL),
7134 GetWin32Error());
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007135 return FAIL;
7136 }
7137 for (i = 0; winpty_entry[i].name != NULL
7138 && winpty_entry[i].ptr != NULL; ++i)
7139 {
7140 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
7141 winpty_entry[i].name)) == NULL)
7142 {
7143 if (verbose)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007144 semsg(_(e_could_not_load_library_function_str), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01007145 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007146 return FAIL;
7147 }
7148 }
7149
7150 return OK;
7151}
7152
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007153 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007154winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007155 term_T *term,
7156 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007157 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007158 jobopt_T *opt,
7159 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007160{
7161 WCHAR *cmd_wchar = NULL;
7162 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007163 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007164 channel_T *channel = NULL;
7165 job_T *job = NULL;
7166 DWORD error;
7167 HANDLE jo = NULL;
7168 HANDLE child_process_handle;
7169 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01007170 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007171 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007172 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007173 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007174
Bram Moolenaar04935fb2022-01-08 16:19:22 +00007175 ga_init2(&ga_cmd, sizeof(char*), 20);
7176 ga_init2(&ga_env, sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007177
7178 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007179 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007180 cmd = argvar->vval.v_string;
7181 }
7182 else if (argvar->v_type == VAR_LIST)
7183 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007184 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007185 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007186 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007187 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007188 if (cmd == NULL || *cmd == NUL)
7189 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00007190 emsg(_(e_invalid_argument));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007191 goto failed;
7192 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007193
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007194 term->tl_arg0_cmd = vim_strsave(cmd);
7195
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007196 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007197 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007198 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007199 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007200 if (opt->jo_cwd != NULL)
7201 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007202
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01007203 win32_build_env(opt->jo_env, &ga_env, TRUE);
7204 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007205
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007206 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
7207 if (term->tl_winpty_config == NULL)
7208 goto failed;
7209
7210 winpty_config_set_mouse_mode(term->tl_winpty_config,
7211 WINPTY_MOUSE_MODE_FORCE);
7212 winpty_config_set_initial_size(term->tl_winpty_config,
7213 term->tl_cols, term->tl_rows);
7214 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
7215 if (term->tl_winpty == NULL)
7216 goto failed;
7217
7218 spawn_config = winpty_spawn_config_new(
7219 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
7220 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
7221 NULL,
7222 cmd_wchar,
7223 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01007224 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007225 &winpty_err);
7226 if (spawn_config == NULL)
7227 goto failed;
7228
7229 channel = add_channel();
7230 if (channel == NULL)
7231 goto failed;
7232
7233 job = job_alloc();
7234 if (job == NULL)
7235 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02007236 if (argvar->v_type == VAR_STRING)
7237 {
7238 int argc;
7239
7240 build_argv_from_string(cmd, &job->jv_argv, &argc);
7241 }
7242 else
7243 {
7244 int argc;
7245
7246 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
7247 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007248
7249 if (opt->jo_set & JO_IN_BUF)
7250 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
7251
7252 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
7253 &child_thread_handle, &error, &winpty_err))
7254 goto failed;
7255
7256 channel_set_pipes(channel,
7257 (sock_T)CreateFileW(
7258 winpty_conin_name(term->tl_winpty),
7259 GENERIC_WRITE, 0, NULL,
7260 OPEN_EXISTING, 0, NULL),
7261 (sock_T)CreateFileW(
7262 winpty_conout_name(term->tl_winpty),
7263 GENERIC_READ, 0, NULL,
7264 OPEN_EXISTING, 0, NULL),
7265 (sock_T)CreateFileW(
7266 winpty_conerr_name(term->tl_winpty),
7267 GENERIC_READ, 0, NULL,
7268 OPEN_EXISTING, 0, NULL));
7269
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007270 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007271 channel->ch_write_text_mode = TRUE;
7272
7273 jo = CreateJobObject(NULL, NULL);
7274 if (jo == NULL)
7275 goto failed;
7276
7277 if (!AssignProcessToJobObject(jo, child_process_handle))
7278 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007279 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007280 CloseHandle(jo);
7281 jo = NULL;
7282 }
7283
7284 winpty_spawn_config_free(spawn_config);
7285 vim_free(cmd_wchar);
7286 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007287 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007288
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007289 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7290 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007291
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007292#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007293 if (term_use_palette())
7294 {
7295 if (term->tl_palette != NULL)
7296 set_vterm_palette(term->tl_vterm, term->tl_palette);
7297 else
7298 init_vterm_ansi_colors(term->tl_vterm);
7299 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007300#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007301
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007302 channel_set_job(channel, job, opt);
7303 job_set_options(job, opt);
7304
7305 job->jv_channel = channel;
7306 job->jv_proc_info.hProcess = child_process_handle;
7307 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
7308 job->jv_job_object = jo;
7309 job->jv_status = JOB_STARTED;
7310 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007311 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007312 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007313 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01007314 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007315 ++job->jv_refcount;
7316 term->tl_job = job;
7317
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007318 // Redirecting stdout and stderr doesn't work at the job level. Instead
7319 // open the file here and handle it in. opt->jo_io was changed in
7320 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007321 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
7322 {
7323 char_u *fname = opt->jo_io_name[PART_OUT];
7324
7325 ch_log(channel, "Opening output file %s", fname);
7326 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
7327 if (term->tl_out_fd == NULL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00007328 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007329 }
7330
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007331 return OK;
7332
7333failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01007334 ga_clear(&ga_cmd);
7335 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007336 vim_free(cmd_wchar);
7337 vim_free(cwd_wchar);
7338 if (spawn_config != NULL)
7339 winpty_spawn_config_free(spawn_config);
7340 if (channel != NULL)
7341 channel_clear(channel);
7342 if (job != NULL)
7343 {
7344 job->jv_channel = NULL;
7345 job_cleanup(job);
7346 }
7347 term->tl_job = NULL;
7348 if (jo != NULL)
7349 CloseHandle(jo);
7350 if (term->tl_winpty != NULL)
7351 winpty_free(term->tl_winpty);
7352 term->tl_winpty = NULL;
7353 if (term->tl_winpty_config != NULL)
7354 winpty_config_free(term->tl_winpty_config);
7355 term->tl_winpty_config = NULL;
7356 if (winpty_err != NULL)
7357 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007358 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007359 (short_u *)winpty_error_msg(winpty_err), NULL);
7360
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007361 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007362 winpty_error_free(winpty_err);
7363 }
7364 return FAIL;
7365}
7366
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007367/*
7368 * Create a new terminal of "rows" by "cols" cells.
7369 * Store a reference in "term".
7370 * Return OK or FAIL.
7371 */
7372 static int
7373term_and_job_init(
7374 term_T *term,
7375 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01007376 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007377 jobopt_T *opt,
7378 jobopt_T *orig_opt)
7379{
7380 int use_winpty = FALSE;
7381 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007382 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007383
7384 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
7385 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
7386
7387 if (!has_winpty && !has_conpty)
7388 // If neither is available give the errors for winpty, since when
7389 // conpty is not available it can't be installed either.
7390 return dyn_winpty_init(TRUE);
7391
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007392 if (opt->jo_tty_type != NUL)
7393 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007394
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007395 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007396 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007397 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007398 use_conpty = TRUE;
7399 else if (has_winpty)
7400 use_winpty = TRUE;
7401 // else: error
7402 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007403 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007404 {
7405 if (has_winpty)
7406 use_winpty = TRUE;
7407 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01007408 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007409 {
7410 if (has_conpty)
7411 use_conpty = TRUE;
7412 else
7413 return dyn_conpty_init(TRUE);
7414 }
7415
7416 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007417 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007418
7419 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007420 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007421
7422 // error
7423 return dyn_winpty_init(TRUE);
7424}
7425
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007426 static int
7427create_pty_only(term_T *term, jobopt_T *options)
7428{
7429 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
7430 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
7431 char in_name[80], out_name[80];
7432 channel_T *channel = NULL;
7433
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007434 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7435 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007436
7437 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
7438 GetCurrentProcessId(),
7439 curbuf->b_fnum);
7440 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
7441 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7442 PIPE_UNLIMITED_INSTANCES,
7443 0, 0, NMPWAIT_NOWAIT, NULL);
7444 if (hPipeIn == INVALID_HANDLE_VALUE)
7445 goto failed;
7446
7447 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
7448 GetCurrentProcessId(),
7449 curbuf->b_fnum);
7450 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
7451 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
7452 PIPE_UNLIMITED_INSTANCES,
7453 0, 0, 0, NULL);
7454 if (hPipeOut == INVALID_HANDLE_VALUE)
7455 goto failed;
7456
7457 ConnectNamedPipe(hPipeIn, NULL);
7458 ConnectNamedPipe(hPipeOut, NULL);
7459
7460 term->tl_job = job_alloc();
7461 if (term->tl_job == NULL)
7462 goto failed;
7463 ++term->tl_job->jv_refcount;
7464
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007465 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007466 term->tl_job->jv_status = JOB_FINISHED;
7467
7468 channel = add_channel();
7469 if (channel == NULL)
7470 goto failed;
7471 term->tl_job->jv_channel = channel;
7472 channel->ch_keep_open = TRUE;
7473 channel->ch_named_pipe = TRUE;
7474
7475 channel_set_pipes(channel,
7476 (sock_T)hPipeIn,
7477 (sock_T)hPipeOut,
7478 (sock_T)hPipeOut);
7479 channel_set_job(channel, term->tl_job, options);
7480 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
7481 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
7482
7483 return OK;
7484
7485failed:
7486 if (hPipeIn != NULL)
7487 CloseHandle(hPipeIn);
7488 if (hPipeOut != NULL)
7489 CloseHandle(hPipeOut);
7490 return FAIL;
7491}
7492
7493/*
7494 * Free the terminal emulator part of "term".
7495 */
7496 static void
7497term_free_vterm(term_T *term)
7498{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007499 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007500 if (term->tl_winpty != NULL)
7501 winpty_free(term->tl_winpty);
7502 term->tl_winpty = NULL;
7503 if (term->tl_winpty_config != NULL)
7504 winpty_config_free(term->tl_winpty_config);
7505 term->tl_winpty_config = NULL;
7506 if (term->tl_vterm != NULL)
7507 vterm_free(term->tl_vterm);
7508 term->tl_vterm = NULL;
7509}
7510
7511/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007512 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007513 */
7514 static void
7515term_report_winsize(term_T *term, int rows, int cols)
7516{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007517 if (term->tl_conpty)
7518 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007519 if (term->tl_winpty)
7520 winpty_set_size(term->tl_winpty, cols, rows, NULL);
7521}
7522
7523 int
7524terminal_enabled(void)
7525{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007526 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007527}
7528
7529# else
7530
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007531///////////////////////////////////////
7532// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007533
7534/*
7535 * Create a new terminal of "rows" by "cols" cells.
7536 * Start job for "cmd".
7537 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01007538 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007539 * Return OK or FAIL.
7540 */
7541 static int
7542term_and_job_init(
7543 term_T *term,
7544 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01007545 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02007546 jobopt_T *opt,
7547 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007548{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007549 term->tl_arg0_cmd = NULL;
7550
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007551 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7552 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007553
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007554#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
LemonBoyb2b3acb2022-05-20 10:10:34 +01007555 if (term_use_palette())
7556 {
7557 if (term->tl_palette != NULL)
7558 set_vterm_palette(term->tl_vterm, term->tl_palette);
7559 else
7560 init_vterm_ansi_colors(term->tl_vterm);
7561 }
Bram Moolenaar30b9a412022-05-26 14:06:37 +01007562#endif
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02007563
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007564 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01007565 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007566 if (term->tl_job != NULL)
7567 ++term->tl_job->jv_refcount;
7568
7569 return term->tl_job != NULL
7570 && term->tl_job->jv_channel != NULL
7571 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
7572}
7573
7574 static int
7575create_pty_only(term_T *term, jobopt_T *opt)
7576{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01007577 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
7578 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007579
7580 term->tl_job = job_alloc();
7581 if (term->tl_job == NULL)
7582 return FAIL;
7583 ++term->tl_job->jv_refcount;
7584
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007585 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007586 term->tl_job->jv_status = JOB_FINISHED;
7587
7588 return mch_create_pty_channel(term->tl_job, opt);
7589}
7590
7591/*
7592 * Free the terminal emulator part of "term".
7593 */
7594 static void
7595term_free_vterm(term_T *term)
7596{
7597 if (term->tl_vterm != NULL)
7598 vterm_free(term->tl_vterm);
7599 term->tl_vterm = NULL;
7600}
7601
7602/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007603 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007604 */
7605 static void
7606term_report_winsize(term_T *term, int rows, int cols)
7607{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007608 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007609 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
7610 {
7611 int fd = -1;
7612 int part;
7613
7614 for (part = PART_OUT; part < PART_COUNT; ++part)
7615 {
7616 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01007617 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007618 break;
7619 }
7620 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7621 mch_signal_job(term->tl_job, (char_u *)"winch");
7622 }
7623}
7624
7625# endif
7626
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007627#endif // FEAT_TERMINAL