blob: 7f92ab1a445da41f36f5c9dd478d512e96a34c5c [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 Moolenaar2e6ab182017-09-20 10:03:07 +0200102 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200103 int tl_channel_recently_closed; // still need to handle tl_finish
104
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100105 int tl_finish;
106#define TL_FINISH_UNSET NUL
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100107#define TL_FINISH_CLOSE 'c' // ++close or :terminal without argument
108#define TL_FINISH_NOCLOSE 'n' // ++noclose
109#define TL_FINISH_OPEN 'o' // ++open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200110 char_u *tl_opencmd;
111 char_u *tl_eof_chars;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200112 char_u *tl_api; // prefix for terminal API function
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200113
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100114 char_u *tl_arg0_cmd; // To format the status bar
115
Bram Moolenaar4f974752019-02-17 17:44:42 +0100116#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200117 void *tl_winpty_config;
118 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200119
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100120 HPCON tl_conpty;
121 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
122
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200123 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200124#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100125#if defined(FEAT_SESSION)
126 char_u *tl_command;
127#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100128 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200129
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100130 // last known vterm size
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200131 int tl_rows;
132 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200133
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100134 char_u *tl_title; // NULL or allocated
135 char_u *tl_status_text; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200136
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100137 // Range of screen rows to update. Zero based.
138 int tl_dirty_row_start; // MAX_ROW if nothing dirty
139 int tl_dirty_row_end; // row below last one to update
140 int tl_dirty_snapshot; // text updated after making snapshot
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200141#ifdef FEAT_TIMERS
142 int tl_timer_set;
143 proftime_T tl_timer_due;
144#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100145 int tl_postponed_scroll; // to be scrolled up
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200146
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200147 garray_T tl_scrollback;
148 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100149 garray_T tl_scrollback_postponed;
150
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200151 cellattr_T tl_default_color;
152
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100153 linenr_T tl_top_diff_rows; // rows of top diff file or zero
154 linenr_T tl_bot_diff_rows; // rows of bottom diff file
Bram Moolenaard96ff162018-02-18 22:13:29 +0100155
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200156 VTermPos tl_cursor_pos;
157 int tl_cursor_visible;
158 int tl_cursor_blink;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100159 int tl_cursor_shape; // 1: block, 2: underline, 3: bar
160 char_u *tl_cursor_color; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200161
162 int tl_using_altscreen;
163};
164
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100165#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
166#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167
168/*
169 * List of all active terminals.
170 */
171static term_T *first_term = NULL;
172
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100173// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200174static term_T *in_terminal_loop = NULL;
175
Bram Moolenaar4f974752019-02-17 17:44:42 +0100176#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100177static BOOL has_winpty = FALSE;
178static BOOL has_conpty = FALSE;
179#endif
180
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100181#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200182#define KEY_BUF_LEN 200
183
184/*
185 * Functions with separate implementation for MS-Windows and Unix-like systems.
186 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200187static 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 +0200188static int create_pty_only(term_T *term, jobopt_T *opt);
189static void term_report_winsize(term_T *term, int rows, int cols);
190static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100191#ifdef FEAT_GUI
192static void update_system_term(term_T *term);
193#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200194
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100195static void handle_postponed_scrollback(term_T *term);
196
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100197// The character that we know (or assume) that the terminal expects for the
198// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200199static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200200
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100201// "Terminal" highlight group colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100202static int term_default_cterm_fg = -1;
203static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200204
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100205// Store the last set and the desired cursor properties, so that we only update
206// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200207static char_u *last_set_cursor_color = NULL;
208static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100209static int last_set_cursor_shape = -1;
210static int desired_cursor_shape = -1;
211static int last_set_cursor_blink = -1;
212static int desired_cursor_blink = -1;
213
214
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100215///////////////////////////////////////
216// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200217
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200218 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200219cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
220{
221 if (lhs_color != NULL && rhs_color != NULL)
222 return STRCMP(lhs_color, rhs_color) == 0;
223 return lhs_color == NULL && rhs_color == NULL;
224}
225
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200226 static void
227cursor_color_copy(char_u **to_color, char_u *from_color)
228{
229 // Avoid a free & alloc if the value is already right.
230 if (cursor_color_equal(*to_color, from_color))
231 return;
232 vim_free(*to_color);
233 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
234}
235
236 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200237cursor_color_get(char_u *color)
238{
239 return (color == NULL) ? (char_u *)"" : color;
240}
241
242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200243/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200244 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200245 * current window.
246 * Sets "rows" and/or "cols" to zero when it should follow the window size.
247 * Return TRUE if the size is the minimum size: "24*80".
248 */
249 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200250parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200251{
252 int minsize = FALSE;
253
254 *rows = 0;
255 *cols = 0;
256
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200257 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200258 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200259 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200260
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100261 // Syntax of value was already checked when it's set.
Bram Moolenaar498c2562018-04-15 23:45:15 +0200262 if (p == NULL)
263 {
264 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200265 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200266 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200267 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200268 *cols = atoi((char *)p + 1);
269 }
270 return minsize;
271}
272
273/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200274 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200275 */
276 static void
277set_term_and_win_size(term_T *term)
278{
Bram Moolenaar13568252018-03-16 20:46:58 +0100279#ifdef FEAT_GUI
280 if (term->tl_system)
281 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100282 // Use the whole screen for the system command. However, it will start
283 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100284 term->tl_rows = Rows;
285 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200286 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100287 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100288#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200289 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200290 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200291 if (term->tl_rows != 0)
292 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
293 if (term->tl_cols != 0)
294 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200295 }
296 if (term->tl_rows == 0)
297 term->tl_rows = curwin->w_height;
298 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200299 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 if (term->tl_cols == 0)
301 term->tl_cols = curwin->w_width;
302 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200303 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200304}
305
306/*
307 * Initialize job options for a terminal job.
308 * Caller may overrule some of them.
309 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100310 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311init_job_options(jobopt_T *opt)
312{
313 clear_job_options(opt);
314
315 opt->jo_mode = MODE_RAW;
316 opt->jo_out_mode = MODE_RAW;
317 opt->jo_err_mode = MODE_RAW;
318 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
319}
320
321/*
322 * Set job options mandatory for a terminal job.
323 */
324 static void
325setup_job_options(jobopt_T *opt, int rows, int cols)
326{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100327#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100328 // Win32: Redirecting the job output won't work, thus always connect stdout
329 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200330 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200331#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200332 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100333 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200334 opt->jo_io[PART_OUT] = JIO_BUFFER;
335 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
336 opt->jo_modifiable[PART_OUT] = 0;
337 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
338 }
339
Bram Moolenaar4f974752019-02-17 17:44:42 +0100340#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100341 // Win32: Redirecting the job output won't work, thus always connect stderr
342 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200343 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200344#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200345 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100346 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200347 opt->jo_io[PART_ERR] = JIO_BUFFER;
348 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
349 opt->jo_modifiable[PART_ERR] = 0;
350 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
351 }
352
353 opt->jo_pty = TRUE;
354 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
355 opt->jo_term_rows = rows;
356 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
357 opt->jo_term_cols = cols;
358}
359
360/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200361 * Flush messages on channels.
362 */
363 static void
364term_flush_messages()
365{
366 mch_check_messages();
367 parse_queued_messages();
368}
369
370/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100371 * Close a terminal buffer (and its window). Used when creating the terminal
372 * fails.
373 */
374 static void
375term_close_buffer(buf_T *buf, buf_T *old_curbuf)
376{
377 free_terminal(buf);
378 if (old_curbuf != NULL)
379 {
380 --curbuf->b_nwindows;
381 curbuf = old_curbuf;
382 curwin->w_buffer = curbuf;
383 ++curbuf->b_nwindows;
384 }
385
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100386 // Wiping out the buffer will also close the window and call
387 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100388 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
389}
390
391/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200392 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100393 * Use either "argvar" or "argv", the other must be NULL.
394 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
395 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200396 * Returns NULL when failed.
397 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100398 buf_T *
399term_start(
400 typval_T *argvar,
401 char **argv,
402 jobopt_T *opt,
403 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200404{
405 exarg_T split_ea;
406 win_T *old_curwin = curwin;
407 term_T *term;
408 buf_T *old_curbuf = NULL;
409 int res;
410 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100411 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200412 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200413
414 if (check_restricted() || check_secure())
415 return NULL;
416
417 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
418 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
419 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100420 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
421 || (argvar != NULL
422 && argvar->v_type == VAR_LIST
423 && argvar->vval.v_list != NULL
424 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200425 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100426 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200427 return NULL;
428 }
429
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200430 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200431 if (term == NULL)
432 return NULL;
433 term->tl_dirty_row_end = MAX_ROW;
434 term->tl_cursor_visible = TRUE;
435 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
436 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100437#ifdef FEAT_GUI
438 term->tl_system = (flags & TERM_START_SYSTEM);
439#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200440 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100441 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200442
443 vim_memset(&split_ea, 0, sizeof(split_ea));
444 if (opt->jo_curwin)
445 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100446 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100447 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200448 {
449 no_write_message();
450 vim_free(term);
451 return NULL;
452 }
453 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100454 ECMD_HIDE
455 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
456 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200457 {
458 vim_free(term);
459 return NULL;
460 }
461 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100462 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200463 {
464 buf_T *buf;
465
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100466 // Create a new buffer without a window. Make it the current buffer for
467 // a moment to be able to do the initialisations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200468 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
469 BLN_NEW | BLN_LISTED);
470 if (buf == NULL || ml_open(buf) == FAIL)
471 {
472 vim_free(term);
473 return NULL;
474 }
475 old_curbuf = curbuf;
476 --curbuf->b_nwindows;
477 curbuf = buf;
478 curwin->w_buffer = buf;
479 ++curbuf->b_nwindows;
480 }
481 else
482 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100483 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200484 split_ea.cmdidx = CMD_new;
485 split_ea.cmd = (char_u *)"new";
486 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100487 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200488 {
489 split_ea.line2 = opt->jo_term_rows;
490 split_ea.addr_count = 1;
491 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100492 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200493 {
494 split_ea.line2 = opt->jo_term_cols;
495 split_ea.addr_count = 1;
496 }
497
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100498 if (vertical)
499 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200500 ex_splitview(&split_ea);
501 if (curwin == old_curwin)
502 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100503 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200504 vim_free(term);
505 return NULL;
506 }
507 }
508 term->tl_buffer = curbuf;
509 curbuf->b_term = term;
510
511 if (!opt->jo_hidden)
512 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100513 // Only one size was taken care of with :new, do the other one. With
514 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100515 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200516 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100517 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200518 win_setwidth(opt->jo_term_cols);
519 }
520
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100521 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200522 term->tl_next = first_term;
523 first_term = term;
524
525 if (opt->jo_term_name != NULL)
526 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100527 else if (argv != NULL)
528 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200529 else
530 {
531 int i;
532 size_t len;
533 char_u *cmd, *p;
534
535 if (argvar->v_type == VAR_STRING)
536 {
537 cmd = argvar->vval.v_string;
538 if (cmd == NULL)
539 cmd = (char_u *)"";
540 else if (STRCMP(cmd, "NONE") == 0)
541 cmd = (char_u *)"pty";
542 }
543 else if (argvar->v_type != VAR_LIST
544 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100545 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100546 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200547 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
548 cmd = (char_u*)"";
549
550 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200551 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200552
553 for (i = 0; p != NULL; ++i)
554 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100555 // Prepend a ! to the command name to avoid the buffer name equals
556 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200557 if (i == 0)
558 vim_snprintf((char *)p, len, "!%s", cmd);
559 else
560 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
561 if (buflist_findname(p) == NULL)
562 {
563 vim_free(curbuf->b_ffname);
564 curbuf->b_ffname = p;
565 break;
566 }
567 }
568 }
569 curbuf->b_fname = curbuf->b_ffname;
570
571 if (opt->jo_term_opencmd != NULL)
572 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
573
574 if (opt->jo_eof_chars != NULL)
575 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
576
577 set_string_option_direct((char_u *)"buftype", -1,
578 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200579 // Avoid that 'buftype' is reset when this buffer is entered.
580 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200581
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100582 // Mark the buffer as not modifiable. It can only be made modifiable after
583 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200584 curbuf->b_p_ma = FALSE;
585
586 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100587#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200588 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
589#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200590 setup_job_options(opt, term->tl_rows, term->tl_cols);
591
Bram Moolenaar13568252018-03-16 20:46:58 +0100592 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100593 return curbuf;
594
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100595#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100596 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100597 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100598 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100599 else if (argvar->v_type == VAR_STRING)
600 {
601 char_u *cmd = argvar->vval.v_string;
602
603 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
604 term->tl_command = vim_strsave(cmd);
605 }
606 else if (argvar->v_type == VAR_LIST
607 && argvar->vval.v_list != NULL
608 && argvar->vval.v_list->lv_len > 0)
609 {
610 garray_T ga;
611 listitem_T *item;
612
613 ga_init2(&ga, 1, 100);
614 for (item = argvar->vval.v_list->lv_first;
615 item != NULL; item = item->li_next)
616 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100617 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100618 char_u *p;
619
620 if (s == NULL)
621 break;
622 p = vim_strsave_fnameescape(s, FALSE);
623 if (p == NULL)
624 break;
625 ga_concat(&ga, p);
626 vim_free(p);
627 ga_append(&ga, ' ');
628 }
629 if (item == NULL)
630 {
631 ga_append(&ga, NUL);
632 term->tl_command = ga.ga_data;
633 }
634 else
635 ga_clear(&ga);
636 }
637#endif
638
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100639 if (opt->jo_term_kill != NULL)
640 {
641 char_u *p = skiptowhite(opt->jo_term_kill);
642
643 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
644 }
645
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200646 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100647 {
648 char_u *p = skiptowhite(opt->jo_term_api);
649
650 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
651 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200652 else
653 term->tl_api = vim_strsave((char_u *)"Tapi_");
654
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100655 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100656 if (argv == NULL
657 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200658 && argvar->vval.v_string != NULL
659 && STRCMP(argvar->vval.v_string, "NONE") == 0)
660 res = create_pty_only(term, opt);
661 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200662 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200663
664 newbuf = curbuf;
665 if (res == OK)
666 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100667 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200668 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
669 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100670#ifdef FEAT_GUI
671 if (term->tl_system)
672 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100673 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100674 term->tl_toprow = msg_row + 1;
675 term->tl_dirty_row_end = 0;
676 }
677#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200678
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100679 // Make sure we don't get stuck on sending keys to the job, it leads to
680 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200681 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
682
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200683 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200684 {
685 --curbuf->b_nwindows;
686 curbuf = old_curbuf;
687 curwin->w_buffer = curbuf;
688 ++curbuf->b_nwindows;
689 }
690 }
691 else
692 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100693 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200694 return NULL;
695 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100696
Bram Moolenaar13568252018-03-16 20:46:58 +0100697 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200698 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
699 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200700 return newbuf;
701}
702
703/*
704 * ":terminal": open a terminal window and execute a job in it.
705 */
706 void
707ex_terminal(exarg_T *eap)
708{
709 typval_T argvar[2];
710 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100711 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200712 char_u *cmd;
713 char_u *tofree = NULL;
714
715 init_job_options(&opt);
716
717 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100718 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200719 {
720 char_u *p, *ep;
721
722 cmd += 2;
723 p = skiptowhite(cmd);
724 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200725 if (ep != NULL)
726 {
727 if (ep < p)
728 p = ep;
729 else
730 ep = NULL;
731 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200732
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200733# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
734 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
735 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200736 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200737 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100738 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200739 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200740 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200741 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200742 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200743 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200744 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200745 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100746 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100747 else if (OPTARG_HAS("shell"))
748 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200749 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100750 {
751 opt.jo_set2 |= JO2_TERM_KILL;
752 opt.jo_term_kill = ep + 1;
753 p = skiptowhite(cmd);
754 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200755 else if (OPTARG_HAS("api"))
756 {
757 opt.jo_set2 |= JO2_TERM_API;
758 if (ep != NULL)
759 {
760 opt.jo_term_api = ep + 1;
761 p = skiptowhite(cmd);
762 }
763 else
764 opt.jo_term_api = NULL;
765 }
766 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200767 {
768 opt.jo_set2 |= JO2_TERM_ROWS;
769 opt.jo_term_rows = atoi((char *)ep + 1);
770 p = skiptowhite(cmd);
771 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200772 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200773 {
774 opt.jo_set2 |= JO2_TERM_COLS;
775 opt.jo_term_cols = atoi((char *)ep + 1);
776 p = skiptowhite(cmd);
777 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200778 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200779 {
780 char_u *buf = NULL;
781 char_u *keys;
782
Bram Moolenaar21109272020-01-30 16:27:20 +0100783 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200784 p = skiptowhite(cmd);
785 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200786 keys = replace_termcodes(ep + 1, &buf,
787 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788 opt.jo_set2 |= JO2_EOF_CHARS;
789 opt.jo_eof_chars = vim_strsave(keys);
790 vim_free(buf);
791 *p = ' ';
792 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100793#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100794 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
795 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100796 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100797 int tty_type = NUL;
798
799 p = skiptowhite(cmd);
800 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
801 tty_type = 'w';
802 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
803 tty_type = 'c';
804 else
805 {
806 semsg(e_invargval, "type");
807 goto theend;
808 }
809 opt.jo_set2 |= JO2_TTY_TYPE;
810 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100811 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100812#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200813 else
814 {
815 if (*p)
816 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100817 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100818 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200819 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200820# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200821 cmd = skipwhite(p);
822 }
823 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100824 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100825 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200826 tofree = cmd = vim_strsave(p_sh);
827
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100828 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100829 if (opt.jo_term_finish == NUL)
830 opt.jo_term_finish = 'c';
831 }
832
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200833 if (eap->addr_count > 0)
834 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100835 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200836 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
837 opt.jo_io[PART_IN] = JIO_BUFFER;
838 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
839 opt.jo_in_top = eap->line1;
840 opt.jo_in_bot = eap->line2;
841 }
842
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100843 if (opt_shell && tofree == NULL)
844 {
845#ifdef UNIX
846 char **argv = NULL;
847 char_u *tofree1 = NULL;
848 char_u *tofree2 = NULL;
849
850 // :term ++shell command
851 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
852 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100853 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100854 vim_free(tofree1);
855 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100856 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100857#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100858# ifdef MSWIN
859 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
860 char_u *newcmd;
861
862 newcmd = alloc(cmdlen);
863 if (newcmd == NULL)
864 goto theend;
865 tofree = newcmd;
866 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
867 cmd = newcmd;
868# else
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100869 emsg(_("E279: Sorry, ++shell is not supported on this system"));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100870 goto theend;
871# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100872#endif
873 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100874 argvar[0].v_type = VAR_STRING;
875 argvar[0].vval.v_string = cmd;
876 argvar[1].v_type = VAR_UNKNOWN;
877 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100878
879theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100880 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200881 vim_free(opt.jo_eof_chars);
882}
883
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100884#if defined(FEAT_SESSION) || defined(PROTO)
885/*
886 * Write a :terminal command to the session file to restore the terminal in
887 * window "wp".
888 * Return FAIL if writing fails.
889 */
890 int
891term_write_session(FILE *fd, win_T *wp)
892{
893 term_T *term = wp->w_buffer->b_term;
894
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100895 // Create the terminal and run the command. This is not without
896 // risk, but let's assume the user only creates a session when this
897 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100898 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
899 term->tl_cols, term->tl_rows) < 0)
900 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100901#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100902 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
903 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100904#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100905 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
906 return FAIL;
907
908 return put_eol(fd);
909}
910
911/*
912 * Return TRUE if "buf" has a terminal that should be restored.
913 */
914 int
915term_should_restore(buf_T *buf)
916{
917 term_T *term = buf->b_term;
918
919 return term != NULL && (term->tl_command == NULL
920 || STRCMP(term->tl_command, "NONE") != 0);
921}
922#endif
923
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200924/*
925 * Free the scrollback buffer for "term".
926 */
927 static void
928free_scrollback(term_T *term)
929{
930 int i;
931
932 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
933 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
934 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100935 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
936 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
937 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200938}
939
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100940
941// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200942static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100943
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200944/*
945 * Free a terminal and everything it refers to.
946 * Kills the job if there is one.
947 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100948 * The actual terminal structure is freed later in free_unused_terminals(),
949 * because callbacks may wipe out a buffer while the terminal is still
950 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200951 */
952 void
953free_terminal(buf_T *buf)
954{
955 term_T *term = buf->b_term;
956 term_T *tp;
957
958 if (term == NULL)
959 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100960
961 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200962 if (first_term == term)
963 first_term = term->tl_next;
964 else
965 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
966 if (tp->tl_next == term)
967 {
968 tp->tl_next = term->tl_next;
969 break;
970 }
971
972 if (term->tl_job != NULL)
973 {
974 if (term->tl_job->jv_status != JOB_ENDED
975 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100976 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200977 job_stop(term->tl_job, NULL, "kill");
978 job_unref(term->tl_job);
979 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100980 term->tl_next = terminals_to_free;
981 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200982
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200983 buf->b_term = NULL;
984 if (in_terminal_loop == term)
985 in_terminal_loop = NULL;
986}
987
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100988 void
989free_unused_terminals()
990{
991 while (terminals_to_free != NULL)
992 {
993 term_T *term = terminals_to_free;
994
995 terminals_to_free = term->tl_next;
996
997 free_scrollback(term);
998
999 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001000 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001001 vim_free(term->tl_title);
1002#ifdef FEAT_SESSION
1003 vim_free(term->tl_command);
1004#endif
1005 vim_free(term->tl_kill);
1006 vim_free(term->tl_status_text);
1007 vim_free(term->tl_opencmd);
1008 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001009 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001010#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001011 if (term->tl_out_fd != NULL)
1012 fclose(term->tl_out_fd);
1013#endif
1014 vim_free(term->tl_cursor_color);
1015 vim_free(term);
1016 }
1017}
1018
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001019/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001020 * Get the part that is connected to the tty. Normally this is PART_IN, but
1021 * when writing buffer lines to the job it can be another. This makes it
1022 * possible to do "1,5term vim -".
1023 */
1024 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001025get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001026{
1027#ifdef UNIX
1028 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1029 int i;
1030
1031 for (i = 0; i < 3; ++i)
1032 {
1033 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1034
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001035 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001036 return parts[i];
1037 }
1038#endif
1039 return PART_IN;
1040}
1041
1042/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001043 * Write job output "msg[len]" to the vterm.
1044 */
1045 static void
1046term_write_job_output(term_T *term, char_u *msg, size_t len)
1047{
1048 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001049 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001050
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001051 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001052
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001053 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001054 if (prevlen != vterm_output_get_buffer_current(vterm))
1055 {
1056 char buf[KEY_BUF_LEN];
1057 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1058
1059 if (curlen > 0)
1060 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1061 (char_u *)buf, (int)curlen, NULL);
1062 }
1063
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001064 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001065 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1066}
1067
1068 static void
1069update_cursor(term_T *term, int redraw)
1070{
1071 if (term->tl_normal_mode)
1072 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001073#ifdef FEAT_GUI
1074 if (term->tl_system)
1075 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1076 term->tl_cursor_pos.col);
1077 else
1078#endif
1079 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001080 if (redraw)
1081 {
1082 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1083 cursor_on();
1084 out_flush();
1085#ifdef FEAT_GUI
1086 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001087 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001088 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001089 gui_mch_flush();
1090 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001091#endif
1092 }
1093}
1094
1095/*
1096 * Invoked when "msg" output from a job was received. Write it to the terminal
1097 * of "buffer".
1098 */
1099 void
1100write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1101{
1102 size_t len = STRLEN(msg);
1103 term_T *term = buffer->b_term;
1104
Bram Moolenaar4f974752019-02-17 17:44:42 +01001105#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001106 // Win32: Cannot redirect output of the job, intercept it here and write to
1107 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001108 if (term->tl_out_fd != NULL)
1109 {
1110 ch_log(channel, "Writing %d bytes to output file", (int)len);
1111 fwrite(msg, len, 1, term->tl_out_fd);
1112 return;
1113 }
1114#endif
1115
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001116 if (term->tl_vterm == NULL)
1117 {
1118 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1119 return;
1120 }
1121 ch_log(channel, "writing %d bytes to terminal", (int)len);
1122 term_write_job_output(term, msg, len);
1123
Bram Moolenaar13568252018-03-16 20:46:58 +01001124#ifdef FEAT_GUI
1125 if (term->tl_system)
1126 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001127 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001128 update_system_term(term);
1129 update_cursor(term, TRUE);
1130 }
1131 else
1132#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001133 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1134 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001135 if (!term->tl_normal_mode)
1136 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001137 // Don't use update_screen() when editing the command line, it gets
1138 // cleared.
1139 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001140 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001141 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001142 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001143 update_screen(VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001144 // update_screen() can be slow, check the terminal wasn't closed
1145 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001146 if (buffer == curbuf && curbuf->b_term != NULL)
1147 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001148 }
1149 else
1150 redraw_after_callback(TRUE);
1151 }
1152}
1153
1154/*
1155 * Send a mouse position and click to the vterm
1156 */
1157 static int
1158term_send_mouse(VTerm *vterm, int button, int pressed)
1159{
1160 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001161 int row = mouse_row - W_WINROW(curwin);
1162 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001163
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001164#ifdef FEAT_PROP_POPUP
1165 if (popup_is_popup(curwin))
1166 {
1167 row -= popup_top_extra(curwin);
1168 col -= popup_left_extra(curwin);
1169 }
1170#endif
1171 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001172 if (button != 0)
1173 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001174 return TRUE;
1175}
1176
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001177static int enter_mouse_col = -1;
1178static int enter_mouse_row = -1;
1179
1180/*
1181 * Handle a mouse click, drag or release.
1182 * Return TRUE when a mouse event is sent to the terminal.
1183 */
1184 static int
1185term_mouse_click(VTerm *vterm, int key)
1186{
1187#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001188 // For modeless selection mouse drag and release events are ignored, unless
1189 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001190 static int ignore_drag_release = TRUE;
1191 VTermMouseState mouse_state;
1192
1193 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1194 if (mouse_state.flags == 0)
1195 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001196 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001197 switch (key)
1198 {
1199 case K_LEFTDRAG:
1200 case K_LEFTRELEASE:
1201 case K_RIGHTDRAG:
1202 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001203 // Ignore drag and release events when the button-down wasn't
1204 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001205 if (ignore_drag_release)
1206 {
1207 int save_mouse_col, save_mouse_row;
1208
1209 if (enter_mouse_col < 0)
1210 break;
1211
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001212 // mouse click in the window gave us focus, handle that
1213 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001214 save_mouse_col = mouse_col;
1215 save_mouse_row = mouse_row;
1216 mouse_col = enter_mouse_col;
1217 mouse_row = enter_mouse_row;
1218 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1219 mouse_col = save_mouse_col;
1220 mouse_row = save_mouse_row;
1221 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001222 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001223 case K_LEFTMOUSE:
1224 case K_RIGHTMOUSE:
1225 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1226 ignore_drag_release = TRUE;
1227 else
1228 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001229 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001230 if (clip_star.available)
1231 {
1232 int button, is_click, is_drag;
1233
1234 button = get_mouse_button(KEY2TERMCAP1(key),
1235 &is_click, &is_drag);
1236 if (mouse_model_popup() && button == MOUSE_LEFT
1237 && (mod_mask & MOD_MASK_SHIFT))
1238 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001239 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001240 button = MOUSE_RIGHT;
1241 mod_mask &= ~MOD_MASK_SHIFT;
1242 }
1243 clip_modeless(button, is_click, is_drag);
1244 }
1245 break;
1246
1247 case K_MIDDLEMOUSE:
1248 if (clip_star.available)
1249 insert_reg('*', TRUE);
1250 break;
1251 }
1252 enter_mouse_col = -1;
1253 return FALSE;
1254 }
1255#endif
1256 enter_mouse_col = -1;
1257
1258 switch (key)
1259 {
1260 case K_LEFTMOUSE:
1261 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1262 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1263 case K_LEFTRELEASE:
1264 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1265 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1266 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1267 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1268 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1269 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1270 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1271 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1272 }
1273 return TRUE;
1274}
1275
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001276/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001277 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1278 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001279 * Return the number of bytes in "buf".
1280 */
1281 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001282term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001283{
1284 VTerm *vterm = term->tl_vterm;
1285 VTermKey key = VTERM_KEY_NONE;
1286 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001287 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001288
1289 switch (c)
1290 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001291 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001292
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001293 // don't use VTERM_KEY_BACKSPACE, it always
1294 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001295 case K_BS: c = term_backspace_char; break;
1296
1297 case ESC: key = VTERM_KEY_ESCAPE; break;
1298 case K_DEL: key = VTERM_KEY_DEL; break;
1299 case K_DOWN: key = VTERM_KEY_DOWN; break;
1300 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1301 key = VTERM_KEY_DOWN; break;
1302 case K_END: key = VTERM_KEY_END; break;
1303 case K_S_END: mod = VTERM_MOD_SHIFT;
1304 key = VTERM_KEY_END; break;
1305 case K_C_END: mod = VTERM_MOD_CTRL;
1306 key = VTERM_KEY_END; break;
1307 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1308 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1309 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1310 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1311 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1312 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1313 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1314 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1315 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1316 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1317 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1318 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1319 case K_HOME: key = VTERM_KEY_HOME; break;
1320 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1321 key = VTERM_KEY_HOME; break;
1322 case K_C_HOME: mod = VTERM_MOD_CTRL;
1323 key = VTERM_KEY_HOME; break;
1324 case K_INS: key = VTERM_KEY_INS; break;
1325 case K_K0: key = VTERM_KEY_KP_0; break;
1326 case K_K1: key = VTERM_KEY_KP_1; break;
1327 case K_K2: key = VTERM_KEY_KP_2; break;
1328 case K_K3: key = VTERM_KEY_KP_3; break;
1329 case K_K4: key = VTERM_KEY_KP_4; break;
1330 case K_K5: key = VTERM_KEY_KP_5; break;
1331 case K_K6: key = VTERM_KEY_KP_6; break;
1332 case K_K7: key = VTERM_KEY_KP_7; break;
1333 case K_K8: key = VTERM_KEY_KP_8; break;
1334 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001335 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001336 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001337 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001338 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001339 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1340 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001341 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1342 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001343 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1344 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001345 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1346 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1347 case K_LEFT: key = VTERM_KEY_LEFT; break;
1348 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1349 key = VTERM_KEY_LEFT; break;
1350 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1351 key = VTERM_KEY_LEFT; break;
1352 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1353 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1354 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1355 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1356 key = VTERM_KEY_RIGHT; break;
1357 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1358 key = VTERM_KEY_RIGHT; break;
1359 case K_UP: key = VTERM_KEY_UP; break;
1360 case K_S_UP: mod = VTERM_MOD_SHIFT;
1361 key = VTERM_KEY_UP; break;
1362 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001363 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1364 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001365
Bram Moolenaara42ad572017-11-16 13:08:04 +01001366 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1367 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001368 case K_MOUSELEFT: /* TODO */ return 0;
1369 case K_MOUSERIGHT: /* TODO */ return 0;
1370
1371 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001372 case K_LEFTMOUSE_NM:
1373 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001374 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001375 case K_LEFTRELEASE_NM:
1376 case K_MOUSEMOVE:
1377 case K_MIDDLEMOUSE:
1378 case K_MIDDLEDRAG:
1379 case K_MIDDLERELEASE:
1380 case K_RIGHTMOUSE:
1381 case K_RIGHTDRAG:
1382 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1383 return 0;
1384 other = TRUE;
1385 break;
1386
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001387 case K_X1MOUSE: /* TODO */ return 0;
1388 case K_X1DRAG: /* TODO */ return 0;
1389 case K_X1RELEASE: /* TODO */ return 0;
1390 case K_X2MOUSE: /* TODO */ return 0;
1391 case K_X2DRAG: /* TODO */ return 0;
1392 case K_X2RELEASE: /* TODO */ return 0;
1393
1394 case K_IGNORE: return 0;
1395 case K_NOP: return 0;
1396 case K_UNDO: return 0;
1397 case K_HELP: return 0;
1398 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1399 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1400 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1401 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1402 case K_SELECT: return 0;
1403#ifdef FEAT_GUI
1404 case K_VER_SCROLLBAR: return 0;
1405 case K_HOR_SCROLLBAR: return 0;
1406#endif
1407#ifdef FEAT_GUI_TABLINE
1408 case K_TABLINE: return 0;
1409 case K_TABMENU: return 0;
1410#endif
1411#ifdef FEAT_NETBEANS_INTG
1412 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1413#endif
1414#ifdef FEAT_DND
1415 case K_DROP: return 0;
1416#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001417 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001418 case K_PS: vterm_keyboard_start_paste(vterm);
1419 other = TRUE;
1420 break;
1421 case K_PE: vterm_keyboard_end_paste(vterm);
1422 other = TRUE;
1423 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001424 }
1425
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001426 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001427 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001428 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001429 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001430 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001431 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001432 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001433
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001434 /*
1435 * Convert special keys to vterm keys:
1436 * - Write keys to vterm: vterm_keyboard_key()
1437 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001438 */
1439 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001440 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001441 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001442 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001443 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001444 vterm_keyboard_unichar(vterm, c, mod);
1445
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001446 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001447 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1448}
1449
1450/*
1451 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001452 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001453 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001454 */
1455 static int
1456term_job_running_check(term_T *term, int check_job_status)
1457{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001458 // Also consider the job finished when the channel is closed, to avoid a
1459 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001460 if (term != NULL
1461 && term->tl_job != NULL
1462 && channel_is_open(term->tl_job->jv_channel))
1463 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001464 job_T *job = term->tl_job;
1465
1466 // Careful: Checking the job status may invoked callbacks, which close
1467 // the buffer and terminate "term". However, "job" will not be freed
1468 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001469 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001470 job_status(job);
1471 return (job->jv_status == JOB_STARTED
1472 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001473 }
1474 return FALSE;
1475}
1476
1477/*
1478 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001479 */
1480 int
1481term_job_running(term_T *term)
1482{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001483 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001484}
1485
1486/*
1487 * Return TRUE if "term" has an active channel and used ":term NONE".
1488 */
1489 int
1490term_none_open(term_T *term)
1491{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001492 // Also consider the job finished when the channel is closed, to avoid a
1493 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001494 return term != NULL
1495 && term->tl_job != NULL
1496 && channel_is_open(term->tl_job->jv_channel)
1497 && term->tl_job->jv_channel->ch_keep_open;
1498}
1499
1500/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001501 * Used when exiting: kill the job in "buf" if so desired.
1502 * Return OK when the job finished.
1503 * Return FAIL when the job is still running.
1504 */
1505 int
1506term_try_stop_job(buf_T *buf)
1507{
1508 int count;
1509 char *how = (char *)buf->b_term->tl_kill;
1510
1511#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1512 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1513 {
1514 char_u buff[DIALOG_MSG_SIZE];
1515 int ret;
1516
1517 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1518 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1519 if (ret == VIM_YES)
1520 how = "kill";
1521 else if (ret == VIM_CANCEL)
1522 return FAIL;
1523 }
1524#endif
1525 if (how == NULL || *how == NUL)
1526 return FAIL;
1527
1528 job_stop(buf->b_term->tl_job, NULL, how);
1529
Bram Moolenaar9172d232019-01-29 23:06:54 +01001530 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001531 for (count = 0; count < 100; ++count)
1532 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001533 job_T *job;
1534
1535 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001536 if (!buf_valid(buf)
1537 || buf->b_term == NULL
1538 || buf->b_term->tl_job == NULL)
1539 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001540 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001541
Bram Moolenaar9172d232019-01-29 23:06:54 +01001542 // Call job_status() to update jv_status. It may cause the job to be
1543 // cleaned up but it won't be freed.
1544 job_status(job);
1545 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001546 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001547
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001548 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001549 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001550 }
1551 return FAIL;
1552}
1553
1554/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001555 * Add the last line of the scrollback buffer to the buffer in the window.
1556 */
1557 static void
1558add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1559{
1560 buf_T *buf = term->tl_buffer;
1561 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1562 linenr_T lnum = buf->b_ml.ml_line_count;
1563
Bram Moolenaar4f974752019-02-17 17:44:42 +01001564#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001565 if (!enc_utf8 && enc_codepage > 0)
1566 {
1567 WCHAR *ret = NULL;
1568 int length = 0;
1569
1570 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1571 &ret, &length);
1572 if (ret != NULL)
1573 {
1574 WideCharToMultiByte_alloc(enc_codepage, 0,
1575 ret, length, (char **)&text, &len, 0, 0);
1576 vim_free(ret);
1577 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1578 vim_free(text);
1579 }
1580 }
1581 else
1582#endif
1583 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1584 if (empty)
1585 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001586 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001587 curbuf = buf;
1588 ml_delete(1, FALSE);
1589 curbuf = curwin->w_buffer;
1590 }
1591}
1592
1593 static void
1594cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1595{
1596 attr->width = cell->width;
1597 attr->attrs = cell->attrs;
1598 attr->fg = cell->fg;
1599 attr->bg = cell->bg;
1600}
1601
1602 static int
1603equal_celattr(cellattr_T *a, cellattr_T *b)
1604{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001605 // Comparing the colors should be sufficient.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001606 return a->fg.red == b->fg.red
1607 && a->fg.green == b->fg.green
1608 && a->fg.blue == b->fg.blue
1609 && a->bg.red == b->bg.red
1610 && a->bg.green == b->bg.green
1611 && a->bg.blue == b->bg.blue;
1612}
1613
Bram Moolenaard96ff162018-02-18 22:13:29 +01001614/*
1615 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1616 * line at this position. Otherwise at the end.
1617 */
1618 static int
1619add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1620{
1621 if (ga_grow(&term->tl_scrollback, 1) == OK)
1622 {
1623 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1624 + term->tl_scrollback.ga_len;
1625
1626 if (lnum > 0)
1627 {
1628 int i;
1629
1630 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1631 {
1632 *line = *(line - 1);
1633 --line;
1634 }
1635 }
1636 line->sb_cols = 0;
1637 line->sb_cells = NULL;
1638 line->sb_fill_attr = *fill_attr;
1639 ++term->tl_scrollback.ga_len;
1640 return OK;
1641 }
1642 return FALSE;
1643}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001644
1645/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001646 * Remove the terminal contents from the scrollback and the buffer.
1647 * Used before adding a new scrollback line or updating the buffer for lines
1648 * displayed in the terminal.
1649 */
1650 static void
1651cleanup_scrollback(term_T *term)
1652{
1653 sb_line_T *line;
1654 garray_T *gap;
1655
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001656 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001657 gap = &term->tl_scrollback;
1658 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1659 && gap->ga_len > 0)
1660 {
1661 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1662 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1663 vim_free(line->sb_cells);
1664 --gap->ga_len;
1665 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001666 curbuf = curwin->w_buffer;
1667 if (curbuf == term->tl_buffer)
1668 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001669}
1670
1671/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001672 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001673 */
1674 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001675update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001676{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001677 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001678 int len;
1679 int lines_skipped = 0;
1680 VTermPos pos;
1681 VTermScreenCell cell;
1682 cellattr_T fill_attr, new_fill_attr;
1683 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001684
1685 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1686 "Adding terminal window snapshot to buffer");
1687
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001688 // First remove the lines that were appended before, they might be
1689 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001690 cleanup_scrollback(term);
1691
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001692 screen = vterm_obtain_screen(term->tl_vterm);
1693 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001694 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1695 {
1696 len = 0;
1697 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1698 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1699 && cell.chars[0] != NUL)
1700 {
1701 len = pos.col + 1;
1702 new_fill_attr = term->tl_default_color;
1703 }
1704 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001705 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001706 cell2cellattr(&cell, &new_fill_attr);
1707
1708 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1709 ++lines_skipped;
1710 else
1711 {
1712 while (lines_skipped > 0)
1713 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001714 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001715 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001716 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001717 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001718 }
1719
1720 if (len == 0)
1721 p = NULL;
1722 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001723 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001724 if ((p != NULL || len == 0)
1725 && ga_grow(&term->tl_scrollback, 1) == OK)
1726 {
1727 garray_T ga;
1728 int width;
1729 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1730 + term->tl_scrollback.ga_len;
1731
1732 ga_init2(&ga, 1, 100);
1733 for (pos.col = 0; pos.col < len; pos.col += width)
1734 {
1735 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1736 {
1737 width = 1;
1738 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1739 if (ga_grow(&ga, 1) == OK)
1740 ga.ga_len += utf_char2bytes(' ',
1741 (char_u *)ga.ga_data + ga.ga_len);
1742 }
1743 else
1744 {
1745 width = cell.width;
1746
1747 cell2cellattr(&cell, &p[pos.col]);
1748
Bram Moolenaara79fd562018-12-20 20:47:32 +01001749 // Each character can be up to 6 bytes.
1750 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001751 {
1752 int i;
1753 int c;
1754
1755 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1756 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1757 (char_u *)ga.ga_data + ga.ga_len);
1758 }
1759 }
1760 }
1761 line->sb_cols = len;
1762 line->sb_cells = p;
1763 line->sb_fill_attr = new_fill_attr;
1764 fill_attr = new_fill_attr;
1765 ++term->tl_scrollback.ga_len;
1766
1767 if (ga_grow(&ga, 1) == FAIL)
1768 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1769 else
1770 {
1771 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1772 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1773 }
1774 ga_clear(&ga);
1775 }
1776 else
1777 vim_free(p);
1778 }
1779 }
1780
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001781 // Add trailing empty lines.
1782 for (pos.row = term->tl_scrollback.ga_len;
1783 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1784 ++pos.row)
1785 {
1786 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1787 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1788 }
1789
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001790 term->tl_dirty_snapshot = FALSE;
1791#ifdef FEAT_TIMERS
1792 term->tl_timer_set = FALSE;
1793#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001794}
1795
1796/*
1797 * If needed, add the current lines of the terminal to scrollback and to the
1798 * buffer. Called after the job has ended and when switching to
1799 * Terminal-Normal mode.
1800 * When "redraw" is TRUE redraw the windows that show the terminal.
1801 */
1802 static void
1803may_move_terminal_to_buffer(term_T *term, int redraw)
1804{
1805 win_T *wp;
1806
1807 if (term->tl_vterm == NULL)
1808 return;
1809
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001810 // Update the snapshot only if something changes or the buffer does not
1811 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001812 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1813 <= term->tl_scrollback_scrolled)
1814 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001815
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001816 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001817 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1818 &term->tl_default_color.fg, &term->tl_default_color.bg);
1819
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001820 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001821 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001822 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001823 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001825 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1826 wp->w_cursor.col = 0;
1827 wp->w_valid = 0;
1828 if (wp->w_cursor.lnum >= wp->w_height)
1829 {
1830 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001831
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001832 if (wp->w_topline < min_topline)
1833 wp->w_topline = min_topline;
1834 }
1835 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001836 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001837 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001838}
1839
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001840#if defined(FEAT_TIMERS) || defined(PROTO)
1841/*
1842 * Check if any terminal timer expired. If so, copy text from the terminal to
1843 * the buffer.
1844 * Return the time until the next timer will expire.
1845 */
1846 int
1847term_check_timers(int next_due_arg, proftime_T *now)
1848{
1849 term_T *term;
1850 int next_due = next_due_arg;
1851
1852 for (term = first_term; term != NULL; term = term->tl_next)
1853 {
1854 if (term->tl_timer_set && !term->tl_normal_mode)
1855 {
1856 long this_due = proftime_time_left(&term->tl_timer_due, now);
1857
1858 if (this_due <= 1)
1859 {
1860 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001861 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001862 }
1863 else if (next_due == -1 || next_due > this_due)
1864 next_due = this_due;
1865 }
1866 }
1867
1868 return next_due;
1869}
1870#endif
1871
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001872/*
1873 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1874 * otherwise end it.
1875 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001876 static void
1877set_terminal_mode(term_T *term, int normal_mode)
1878{
1879 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001880 if (!normal_mode)
1881 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001882 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001883 if (term->tl_buffer == curbuf)
1884 maketitle();
1885}
1886
1887/*
1888 * Called after the job if finished and Terminal mode is not active:
1889 * Move the vterm contents into the scrollback buffer and free the vterm.
1890 */
1891 static void
1892cleanup_vterm(term_T *term)
1893{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001894 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001895 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001896 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001898}
1899
1900/*
1901 * Switch from Terminal-Job mode to Terminal-Normal mode.
1902 * Suspends updating the terminal window.
1903 */
1904 static void
1905term_enter_normal_mode(void)
1906{
1907 term_T *term = curbuf->b_term;
1908
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001909 set_terminal_mode(term, TRUE);
1910
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001911 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001912 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001914 // Move the window cursor to the position of the cursor in the
1915 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001916 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1917 + term->tl_cursor_pos.row + 1;
1918 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001919 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1920 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001921
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001922 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001923 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1924}
1925
1926/*
1927 * Returns TRUE if the current window contains a terminal and we are in
1928 * Terminal-Normal mode.
1929 */
1930 int
1931term_in_normal_mode(void)
1932{
1933 term_T *term = curbuf->b_term;
1934
1935 return term != NULL && term->tl_normal_mode;
1936}
1937
1938/*
1939 * Switch from Terminal-Normal mode to Terminal-Job mode.
1940 * Restores updating the terminal window.
1941 */
1942 void
1943term_enter_job_mode()
1944{
1945 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001946
1947 set_terminal_mode(term, FALSE);
1948
1949 if (term->tl_channel_closed)
1950 cleanup_vterm(term);
1951 redraw_buf_and_status_later(curbuf, NOT_VALID);
1952}
1953
1954/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001955 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001956 * Note: while waiting a terminal may be closed and freed if the channel is
1957 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001958 */
1959 static int
1960term_vgetc()
1961{
1962 int c;
1963 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001964 int modify_other_keys =
1965 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001966
1967 State = TERMINAL;
1968 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001969#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001970 ctrl_break_was_pressed = FALSE;
1971#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001972 if (modify_other_keys)
1973 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001974 c = vgetc();
1975 got_int = FALSE;
1976 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001977 if (modify_other_keys)
1978 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001979 return c;
1980}
1981
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001982static int mouse_was_outside = FALSE;
1983
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001984/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001985 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001986 * Return FAIL when the key needs to be handled in Normal mode.
1987 * Return OK when the key was dropped or sent to the terminal.
1988 */
1989 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001990send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001991{
1992 char msg[KEY_BUF_LEN];
1993 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001994 int dragging_outside = FALSE;
1995
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001996 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001997 switch (c)
1998 {
1999 case NUL:
2000 case K_ZERO:
2001 if (typed)
2002 stuffcharReadbuff(c);
2003 return FAIL;
2004
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002005 case K_TABLINE:
2006 stuffcharReadbuff(c);
2007 return FAIL;
2008
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002009 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002010 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 return FAIL;
2012
2013 case K_LEFTDRAG:
2014 case K_MIDDLEDRAG:
2015 case K_RIGHTDRAG:
2016 case K_X1DRAG:
2017 case K_X2DRAG:
2018 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002019 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002020 case K_LEFTMOUSE:
2021 case K_LEFTMOUSE_NM:
2022 case K_LEFTRELEASE:
2023 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002024 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002025 case K_MIDDLEMOUSE:
2026 case K_MIDDLERELEASE:
2027 case K_RIGHTMOUSE:
2028 case K_RIGHTRELEASE:
2029 case K_X1MOUSE:
2030 case K_X1RELEASE:
2031 case K_X2MOUSE:
2032 case K_X2RELEASE:
2033
2034 case K_MOUSEUP:
2035 case K_MOUSEDOWN:
2036 case K_MOUSELEFT:
2037 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002038 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002039 int row = mouse_row;
2040 int col = mouse_col;
2041
2042#ifdef FEAT_PROP_POPUP
2043 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002044 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002045 row -= popup_top_extra(curwin);
2046 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002047 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002048#endif
2049 if (row < W_WINROW(curwin)
2050 || row >= (W_WINROW(curwin) + curwin->w_height)
2051 || col < curwin->w_wincol
2052 || col >= W_ENDCOL(curwin)
2053 || dragging_outside)
2054 {
2055 // click or scroll outside the current window or on status
2056 // line or vertical separator
2057 if (typed)
2058 {
2059 stuffcharReadbuff(c);
2060 mouse_was_outside = TRUE;
2061 }
2062 return FAIL;
2063 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002064 }
2065 }
2066 if (typed)
2067 mouse_was_outside = FALSE;
2068
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002069 // Convert the typed key to a sequence of bytes for the job.
2070 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002071 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002072 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002073 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2074 (char_u *)msg, (int)len, NULL);
2075
2076 return OK;
2077}
2078
2079 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002080position_cursor(win_T *wp, VTermPos *pos, int add_off UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002081{
2082 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2083 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002084#ifdef FEAT_PROP_POPUP
2085 if (add_off && popup_is_popup(curwin))
2086 {
2087 wp->w_wrow += popup_top_extra(curwin);
2088 wp->w_wcol += popup_left_extra(curwin);
2089 }
2090#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002091 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2092}
2093
2094/*
2095 * Handle CTRL-W "": send register contents to the job.
2096 */
2097 static void
2098term_paste_register(int prev_c UNUSED)
2099{
2100 int c;
2101 list_T *l;
2102 listitem_T *item;
2103 long reglen = 0;
2104 int type;
2105
2106#ifdef FEAT_CMDL_INFO
2107 if (add_to_showcmd(prev_c))
2108 if (add_to_showcmd('"'))
2109 out_flush();
2110#endif
2111 c = term_vgetc();
2112#ifdef FEAT_CMDL_INFO
2113 clear_showcmd();
2114#endif
2115 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002116 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002117 return;
2118
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002119 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002120 if (c == '=' && get_expr_register() != '=')
2121 return;
2122 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002123 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002124 return;
2125
2126 l = (list_T *)get_reg_contents(c, GREG_LIST);
2127 if (l != NULL)
2128 {
2129 type = get_reg_type(c, &reglen);
2130 for (item = l->lv_first; item != NULL; item = item->li_next)
2131 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002132 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002133#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002134 char_u *tmp = s;
2135
2136 if (!enc_utf8 && enc_codepage > 0)
2137 {
2138 WCHAR *ret = NULL;
2139 int length = 0;
2140
2141 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2142 (int)STRLEN(s), &ret, &length);
2143 if (ret != NULL)
2144 {
2145 WideCharToMultiByte_alloc(CP_UTF8, 0,
2146 ret, length, (char **)&s, &length, 0, 0);
2147 vim_free(ret);
2148 }
2149 }
2150#endif
2151 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2152 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002153#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002154 if (tmp != s)
2155 vim_free(s);
2156#endif
2157
2158 if (item->li_next != NULL || type == MLINE)
2159 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2160 (char_u *)"\r", 1, NULL);
2161 }
2162 list_free(l);
2163 }
2164}
2165
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002167 * Return TRUE when waiting for a character in the terminal, the cursor of the
2168 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002169 */
2170 int
2171terminal_is_active()
2172{
2173 return in_terminal_loop != NULL;
2174}
2175
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002176#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002177 cursorentry_T *
2178term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2179{
2180 term_T *term = in_terminal_loop;
2181 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002182 int id;
2183 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002184
2185 vim_memset(&entry, 0, sizeof(entry));
2186 entry.shape = entry.mshape =
2187 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2188 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2189 SHAPE_BLOCK;
2190 entry.percentage = 20;
2191 if (term->tl_cursor_blink)
2192 {
2193 entry.blinkwait = 700;
2194 entry.blinkon = 400;
2195 entry.blinkoff = 250;
2196 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002197
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002198 // The "Terminal" highlight group overrules the defaults.
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002199 id = syn_name2id((char_u *)"Terminal");
2200 if (id != 0)
2201 {
2202 syn_id2colors(id, &term_fg, &term_bg);
2203 *fg = term_bg;
2204 }
2205 else
2206 *fg = gui.back_pixel;
2207
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002208 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002209 {
2210 if (id != 0)
2211 *bg = term_fg;
2212 else
2213 *bg = gui.norm_pixel;
2214 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002215 else
2216 *bg = color_name2handle(term->tl_cursor_color);
2217 entry.name = "n";
2218 entry.used_for = SHAPE_CURSOR;
2219
2220 return &entry;
2221}
2222#endif
2223
Bram Moolenaard317b382018-02-08 22:33:31 +01002224 static void
2225may_output_cursor_props(void)
2226{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002227 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002228 || last_set_cursor_shape != desired_cursor_shape
2229 || last_set_cursor_blink != desired_cursor_blink)
2230 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002231 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002232 last_set_cursor_shape = desired_cursor_shape;
2233 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002234 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002235 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002236 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002237 ui_cursor_shape_forced(TRUE);
2238 else
2239 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2240 }
2241}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002242
Bram Moolenaard317b382018-02-08 22:33:31 +01002243/*
2244 * Set the cursor color and shape, if not last set to these.
2245 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002246 static void
2247may_set_cursor_props(term_T *term)
2248{
2249#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002250 // For the GUI the cursor properties are obtained with
2251 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002252 if (gui.in_use)
2253 return;
2254#endif
2255 if (in_terminal_loop == term)
2256 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002257 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002258 desired_cursor_shape = term->tl_cursor_shape;
2259 desired_cursor_blink = term->tl_cursor_blink;
2260 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002261 }
2262}
2263
Bram Moolenaard317b382018-02-08 22:33:31 +01002264/*
2265 * Reset the desired cursor properties and restore them when needed.
2266 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002267 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002268prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002269{
2270#ifdef FEAT_GUI
2271 if (gui.in_use)
2272 return;
2273#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002274 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002275 desired_cursor_shape = -1;
2276 desired_cursor_blink = -1;
2277 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002278}
2279
2280/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002281 * Returns TRUE if the current window contains a terminal and we are sending
2282 * keys to the job.
2283 * If "check_job_status" is TRUE update the job status.
2284 */
2285 static int
2286term_use_loop_check(int check_job_status)
2287{
2288 term_T *term = curbuf->b_term;
2289
2290 return term != NULL
2291 && !term->tl_normal_mode
2292 && term->tl_vterm != NULL
2293 && term_job_running_check(term, check_job_status);
2294}
2295
2296/*
2297 * Returns TRUE if the current window contains a terminal and we are sending
2298 * keys to the job.
2299 */
2300 int
2301term_use_loop(void)
2302{
2303 return term_use_loop_check(FALSE);
2304}
2305
2306/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002307 * Called when entering a window with the mouse. If this is a terminal window
2308 * we may want to change state.
2309 */
2310 void
2311term_win_entered()
2312{
2313 term_T *term = curbuf->b_term;
2314
2315 if (term != NULL)
2316 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002317 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002318 {
2319 reset_VIsual_and_resel();
2320 if (State & INSERT)
2321 stop_insert_mode = TRUE;
2322 }
2323 mouse_was_outside = FALSE;
2324 enter_mouse_col = mouse_col;
2325 enter_mouse_row = mouse_row;
2326 }
2327}
2328
2329/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002330 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2331 * Return the Ctrl-key value in that case.
2332 */
2333 static int
2334raw_c_to_ctrl(int c)
2335{
2336 if ((mod_mask & MOD_MASK_CTRL)
2337 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2338 return c & 0x1f;
2339 return c;
2340}
2341
2342/*
2343 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2344 * May set "mod_mask".
2345 */
2346 static int
2347ctrl_to_raw_c(int c)
2348{
2349 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2350 {
2351 mod_mask |= MOD_MASK_CTRL;
2352 return c + '@';
2353 }
2354 return c;
2355}
2356
2357/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358 * Wait for input and send it to the job.
2359 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2360 * when there is no more typahead.
2361 * Return when the start of a CTRL-W command is typed or anything else that
2362 * should be handled as a Normal mode command.
2363 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2364 * the terminal was closed.
2365 */
2366 int
2367terminal_loop(int blocking)
2368{
2369 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002370 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002371 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002372 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002373#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002374 int tty_fd = curbuf->b_term->tl_job->jv_channel
2375 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002376#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002377 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002378
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002379 // Remember the terminal we are sending keys to. However, the terminal
2380 // might be closed while waiting for a character, e.g. typing "exit" in a
2381 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2382 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002383 in_terminal_loop = curbuf->b_term;
2384
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002385 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002386 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002387 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002388 if (termwinkey == Ctrl_W)
2389 termwinkey = 0;
2390 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002391 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002392 may_set_cursor_props(curbuf->b_term);
2393
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002394 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002395 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002396#ifdef FEAT_GUI
2397 if (!curbuf->b_term->tl_system)
2398#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002399 // TODO: skip screen update when handling a sequence of keys.
2400 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002401 while (must_redraw != 0)
2402 if (update_screen(0) == FAIL)
2403 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002404 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002405 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002406 break;
2407
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002408 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002409 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002410
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002411 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002412 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002413 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002414 // Job finished while waiting for a character. Push back the
2415 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002416 if (raw_c != K_IGNORE)
2417 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002418 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002419 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002420 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002421 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002422 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002423
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002424#ifdef UNIX
2425 /*
2426 * The shell or another program may change the tty settings. Getting
2427 * them for every typed character is a bit of overhead, but it's needed
2428 * for the first character typed, e.g. when Vim starts in a shell.
2429 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002430 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002431 {
2432 ttyinfo_T info;
2433
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002434 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002435 if (get_tty_info(tty_fd, &info) == OK)
2436 term_backspace_char = info.backspace;
2437 }
2438#endif
2439
Bram Moolenaar4f974752019-02-17 17:44:42 +01002440#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002441 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2442 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002443 if (ctrl_break_was_pressed)
2444 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2445#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002446 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2447 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002448 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002449#ifdef FEAT_GUI
2450 && !curbuf->b_term->tl_system
2451#endif
2452 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002453 {
2454 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002455 int prev_raw_c = raw_c;
2456 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002457
2458#ifdef FEAT_CMDL_INFO
2459 if (add_to_showcmd(c))
2460 out_flush();
2461#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002462 raw_c = term_vgetc();
2463 c = raw_c_to_ctrl(raw_c);
2464
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002465#ifdef FEAT_CMDL_INFO
2466 clear_showcmd();
2467#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002468 if (!term_use_loop_check(TRUE)
2469 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002470 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002471 break;
2472
2473 if (prev_c == Ctrl_BSL)
2474 {
2475 if (c == Ctrl_N)
2476 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002477 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002478 term_enter_normal_mode();
2479 ret = FAIL;
2480 goto theend;
2481 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002482 // Send both keys to the terminal, first one here, second one
2483 // below.
2484 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2485 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002486 }
2487 else if (c == Ctrl_C)
2488 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002489 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002490 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2491 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002492 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002493 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002494 // "CTRL-W .": send CTRL-W to the job
2495 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002496 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002497 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002498 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002499 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002500 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002501 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002502 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 else if (c == 'N')
2504 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002505 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002506 term_enter_normal_mode();
2507 ret = FAIL;
2508 goto theend;
2509 }
2510 else if (c == '"')
2511 {
2512 term_paste_register(prev_c);
2513 continue;
2514 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002515 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002516 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002517 char_u buf[MB_MAXBYTES + 2];
2518
2519 // Put the command into the typeahead buffer, when using the
2520 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2521 buf[0] = Ctrl_W;
2522 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2523 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002524 ret = OK;
2525 goto theend;
2526 }
2527 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002528# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002529 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002530 {
2531 WCHAR wc;
2532 char_u mb[3];
2533
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002534 mb[0] = (unsigned)raw_c >> 8;
2535 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002536 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002537 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002538 }
2539# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002540 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002541 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002542 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002543 // We are sure to come back here, don't reset the cursor color
2544 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002545 restore_cursor = FALSE;
2546
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002547 ret = OK;
2548 goto theend;
2549 }
2550 }
2551 ret = FAIL;
2552
2553theend:
2554 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002555 if (restore_cursor)
2556 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002557
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002558 // Move a snapshot of the screen contents to the buffer, so that completion
2559 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002560 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2561 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002562
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002563 return ret;
2564}
2565
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002566 static void
2567may_toggle_cursor(term_T *term)
2568{
2569 if (in_terminal_loop == term)
2570 {
2571 if (term->tl_cursor_visible)
2572 cursor_on();
2573 else
2574 cursor_off();
2575 }
2576}
2577
2578/*
2579 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002580 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002581 */
2582 static int
2583color2index(VTermColor *color, int fg, int *boldp)
2584{
2585 int red = color->red;
2586 int blue = color->blue;
2587 int green = color->green;
2588
Bram Moolenaar46359e12017-11-29 22:33:38 +01002589 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002590 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002591 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002592 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002594 case 0: return 0;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002595 case 1: return lookup_color( 0, fg, boldp) + 1; // black
2596 case 2: return lookup_color( 4, fg, boldp) + 1; // dark red
2597 case 3: return lookup_color( 2, fg, boldp) + 1; // dark green
2598 case 4: return lookup_color( 6, fg, boldp) + 1; // brown
2599 case 5: return lookup_color( 1, fg, boldp) + 1; // dark blue
2600 case 6: return lookup_color( 5, fg, boldp) + 1; // dark magenta
2601 case 7: return lookup_color( 3, fg, boldp) + 1; // dark cyan
2602 case 8: return lookup_color( 8, fg, boldp) + 1; // light grey
2603 case 9: return lookup_color(12, fg, boldp) + 1; // dark grey
2604 case 10: return lookup_color(20, fg, boldp) + 1; // red
2605 case 11: return lookup_color(16, fg, boldp) + 1; // green
2606 case 12: return lookup_color(24, fg, boldp) + 1; // yellow
2607 case 13: return lookup_color(14, fg, boldp) + 1; // blue
2608 case 14: return lookup_color(22, fg, boldp) + 1; // magenta
2609 case 15: return lookup_color(18, fg, boldp) + 1; // cyan
2610 case 16: return lookup_color(26, fg, boldp) + 1; // white
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002611 }
2612 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002613
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002614 if (t_colors >= 256)
2615 {
2616 if (red == blue && red == green)
2617 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002618 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002619 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002620 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2621 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2622 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002623 int i;
2624
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002625 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002626 return 17; // 00/00/00
2627 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002628 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002629 for (i = 0; i < 23; ++i)
2630 if (red < cutoff[i])
2631 return i + 233;
2632 return 256;
2633 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002634 {
2635 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2636 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002637
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002638 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002639 for (ri = 0; ri < 5; ++ri)
2640 if (red < cutoff[ri])
2641 break;
2642 for (gi = 0; gi < 5; ++gi)
2643 if (green < cutoff[gi])
2644 break;
2645 for (bi = 0; bi < 5; ++bi)
2646 if (blue < cutoff[bi])
2647 break;
2648 return 17 + ri * 36 + gi * 6 + bi;
2649 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002650 }
2651 return 0;
2652}
2653
2654/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002655 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002656 */
2657 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002658vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002659{
2660 int attr = 0;
2661
2662 if (cellattrs.bold)
2663 attr |= HL_BOLD;
2664 if (cellattrs.underline)
2665 attr |= HL_UNDERLINE;
2666 if (cellattrs.italic)
2667 attr |= HL_ITALIC;
2668 if (cellattrs.strike)
2669 attr |= HL_STRIKETHROUGH;
2670 if (cellattrs.reverse)
2671 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002672 return attr;
2673}
2674
2675/*
2676 * Store Vterm attributes in "cell" from highlight flags.
2677 */
2678 static void
2679hl2vtermAttr(int attr, cellattr_T *cell)
2680{
2681 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2682 if (attr & HL_BOLD)
2683 cell->attrs.bold = 1;
2684 if (attr & HL_UNDERLINE)
2685 cell->attrs.underline = 1;
2686 if (attr & HL_ITALIC)
2687 cell->attrs.italic = 1;
2688 if (attr & HL_STRIKETHROUGH)
2689 cell->attrs.strike = 1;
2690 if (attr & HL_INVERSE)
2691 cell->attrs.reverse = 1;
2692}
2693
2694/*
2695 * Convert the attributes of a vterm cell into an attribute index.
2696 */
2697 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002698cell2attr(
2699 win_T *wp,
2700 VTermScreenCellAttrs cellattrs,
2701 VTermColor cellfg,
2702 VTermColor cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002703{
2704 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002705
2706#ifdef FEAT_GUI
2707 if (gui.in_use)
2708 {
2709 guicolor_T fg, bg;
2710
2711 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2712 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2713 return get_gui_attr_idx(attr, fg, bg);
2714 }
2715 else
2716#endif
2717#ifdef FEAT_TERMGUICOLORS
2718 if (p_tgc)
2719 {
2720 guicolor_T fg, bg;
2721
2722 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2723 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2724
2725 return get_tgc_attr_idx(attr, fg, bg);
2726 }
2727 else
2728#endif
2729 {
2730 int bold = MAYBE;
2731 int fg = color2index(&cellfg, TRUE, &bold);
2732 int bg = color2index(&cellbg, FALSE, &bold);
2733
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002734 // Use the 'wincolor' or "Terminal" highlighting for the default
2735 // colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002736 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002737 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002738 int wincolor_fg = -1;
2739 int wincolor_bg = -1;
2740
2741 if (wp != NULL && *wp->w_p_wcr != NUL)
2742 {
2743 int id = syn_name2id(curwin->w_p_wcr);
2744
2745 // Get the 'wincolor' group colors.
2746 if (id > 0)
2747 syn_id2cterm_bg(id, &wincolor_fg, &wincolor_bg);
2748 }
2749 if (fg == 0)
2750 {
2751 if (wincolor_fg >= 0)
2752 fg = wincolor_fg + 1;
2753 else if (term_default_cterm_fg >= 0)
2754 fg = term_default_cterm_fg + 1;
2755 }
2756 if (bg == 0)
2757 {
2758 if (wincolor_bg >= 0)
2759 bg = wincolor_bg + 1;
2760 else if (term_default_cterm_bg >= 0)
2761 bg = term_default_cterm_bg + 1;
2762 }
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002763 }
2764
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002765 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002766 if (bold == TRUE)
2767 attr |= HL_BOLD;
2768 return get_cterm_attr_idx(attr, fg, bg);
2769 }
2770 return 0;
2771}
2772
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002773 static void
2774set_dirty_snapshot(term_T *term)
2775{
2776 term->tl_dirty_snapshot = TRUE;
2777#ifdef FEAT_TIMERS
2778 if (!term->tl_normal_mode)
2779 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002780 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002781 profile_setlimit(100L, &term->tl_timer_due);
2782 term->tl_timer_set = TRUE;
2783 }
2784#endif
2785}
2786
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002787 static int
2788handle_damage(VTermRect rect, void *user)
2789{
2790 term_T *term = (term_T *)user;
2791
2792 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2793 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002794 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002795 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002796 return 1;
2797}
2798
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002799 static void
2800term_scroll_up(term_T *term, int start_row, int count)
2801{
2802 win_T *wp;
2803 VTermColor fg, bg;
2804 VTermScreenCellAttrs attr;
2805 int clear_attr;
2806
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002807 vim_memset(&attr, 0, sizeof(attr));
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002808
2809 FOR_ALL_WINDOWS(wp)
2810 {
2811 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002812 {
2813 // Set the color to clear lines with.
2814 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2815 &fg, &bg);
2816 clear_attr = cell2attr(wp, attr, fg, bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002817 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002818 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002819 }
2820}
2821
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002822 static int
2823handle_moverect(VTermRect dest, VTermRect src, void *user)
2824{
2825 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002826 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002827
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002828 // Scrolling up is done much more efficiently by deleting lines instead of
2829 // redrawing the text. But avoid doing this multiple times, postpone until
2830 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002831 if (dest.start_col == src.start_col
2832 && dest.end_col == src.end_col
2833 && dest.start_row < src.start_row)
2834 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002835 if (dest.start_row == 0)
2836 term->tl_postponed_scroll += count;
2837 else
2838 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002839 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002840
2841 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2842 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002843 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002844
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002845 // Note sure if the scrolling will work correctly, let's do a complete
2846 // redraw later.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002847 redraw_buf_later(term->tl_buffer, NOT_VALID);
2848 return 1;
2849}
2850
2851 static int
2852handle_movecursor(
2853 VTermPos pos,
2854 VTermPos oldpos UNUSED,
2855 int visible,
2856 void *user)
2857{
2858 term_T *term = (term_T *)user;
2859 win_T *wp;
2860
2861 term->tl_cursor_pos = pos;
2862 term->tl_cursor_visible = visible;
2863
2864 FOR_ALL_WINDOWS(wp)
2865 {
2866 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002867 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002868 }
2869 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2870 {
2871 may_toggle_cursor(term);
2872 update_cursor(term, term->tl_cursor_visible);
2873 }
2874
2875 return 1;
2876}
2877
2878 static int
2879handle_settermprop(
2880 VTermProp prop,
2881 VTermValue *value,
2882 void *user)
2883{
2884 term_T *term = (term_T *)user;
2885
2886 switch (prop)
2887 {
2888 case VTERM_PROP_TITLE:
2889 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002890 // a blank title isn't useful, make it empty, so that "running" is
2891 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002892 if (*skipwhite((char_u *)value->string) == NUL)
2893 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002894 // Same as blank
2895 else if (term->tl_arg0_cmd != NULL
2896 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2897 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2898 term->tl_title = NULL;
2899 // Empty corrupted data of winpty
2900 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2901 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002902#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002903 else if (!enc_utf8 && enc_codepage > 0)
2904 {
2905 WCHAR *ret = NULL;
2906 int length = 0;
2907
2908 MultiByteToWideChar_alloc(CP_UTF8, 0,
2909 (char*)value->string, (int)STRLEN(value->string),
2910 &ret, &length);
2911 if (ret != NULL)
2912 {
2913 WideCharToMultiByte_alloc(enc_codepage, 0,
2914 ret, length, (char**)&term->tl_title,
2915 &length, 0, 0);
2916 vim_free(ret);
2917 }
2918 }
2919#endif
2920 else
2921 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002922 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002923 if (term == curbuf->b_term)
2924 maketitle();
2925 break;
2926
2927 case VTERM_PROP_CURSORVISIBLE:
2928 term->tl_cursor_visible = value->boolean;
2929 may_toggle_cursor(term);
2930 out_flush();
2931 break;
2932
2933 case VTERM_PROP_CURSORBLINK:
2934 term->tl_cursor_blink = value->boolean;
2935 may_set_cursor_props(term);
2936 break;
2937
2938 case VTERM_PROP_CURSORSHAPE:
2939 term->tl_cursor_shape = value->number;
2940 may_set_cursor_props(term);
2941 break;
2942
2943 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002944 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002945 may_set_cursor_props(term);
2946 break;
2947
2948 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002949 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002950 term->tl_using_altscreen = value->boolean;
2951 break;
2952
2953 default:
2954 break;
2955 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002956 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002957 return 1;
2958}
2959
2960/*
2961 * The job running in the terminal resized the terminal.
2962 */
2963 static int
2964handle_resize(int rows, int cols, void *user)
2965{
2966 term_T *term = (term_T *)user;
2967 win_T *wp;
2968
2969 term->tl_rows = rows;
2970 term->tl_cols = cols;
2971 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002972 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002973 term->tl_vterm_size_changed = FALSE;
2974 else
2975 {
2976 FOR_ALL_WINDOWS(wp)
2977 {
2978 if (wp->w_buffer == term->tl_buffer)
2979 {
2980 win_setheight_win(rows, wp);
2981 win_setwidth_win(cols, wp);
2982 }
2983 }
2984 redraw_buf_later(term->tl_buffer, NOT_VALID);
2985 }
2986 return 1;
2987}
2988
2989/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002990 * If the number of lines that are stored goes over 'termscrollback' then
2991 * delete the first 10%.
2992 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2993 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002994 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002995 static void
2996limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002997{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002998 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002999 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003000 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003001 int i;
3002
3003 curbuf = term->tl_buffer;
3004 for (i = 0; i < todo; ++i)
3005 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003006 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3007 if (update_buffer)
3008 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003009 }
3010 curbuf = curwin->w_buffer;
3011
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003012 gap->ga_len -= todo;
3013 mch_memmove(gap->ga_data,
3014 (sb_line_T *)gap->ga_data + todo,
3015 sizeof(sb_line_T) * gap->ga_len);
3016 if (update_buffer)
3017 term->tl_scrollback_scrolled -= todo;
3018 }
3019}
3020
3021/*
3022 * Handle a line that is pushed off the top of the screen.
3023 */
3024 static int
3025handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3026{
3027 term_T *term = (term_T *)user;
3028 garray_T *gap;
3029 int update_buffer;
3030
3031 if (term->tl_normal_mode)
3032 {
3033 // In Terminal-Normal mode the user interacts with the buffer, thus we
3034 // must not change it. Postpone adding the scrollback lines.
3035 gap = &term->tl_scrollback_postponed;
3036 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003037 }
3038 else
3039 {
3040 // First remove the lines that were appended before, the pushed line
3041 // goes above it.
3042 cleanup_scrollback(term);
3043 gap = &term->tl_scrollback;
3044 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003045 }
3046
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003047 limit_scrollback(term, gap, update_buffer);
3048
3049 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003050 {
3051 cellattr_T *p = NULL;
3052 int len = 0;
3053 int i;
3054 int c;
3055 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003056 int text_len;
3057 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003058 sb_line_T *line;
3059 garray_T ga;
3060 cellattr_T fill_attr = term->tl_default_color;
3061
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003062 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003063 for (i = 0; i < cols; ++i)
3064 if (cells[i].chars[0] != 0)
3065 len = i + 1;
3066 else
3067 cell2cellattr(&cells[i], &fill_attr);
3068
3069 ga_init2(&ga, 1, 100);
3070 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003071 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003072 if (p != NULL)
3073 {
3074 for (col = 0; col < len; col += cells[col].width)
3075 {
3076 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3077 {
3078 ga.ga_len = 0;
3079 break;
3080 }
3081 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3082 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3083 (char_u *)ga.ga_data + ga.ga_len);
3084 cell2cellattr(&cells[col], &p[col]);
3085 }
3086 }
3087 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003088 {
3089 if (update_buffer)
3090 text = (char_u *)"";
3091 else
3092 text = vim_strsave((char_u *)"");
3093 text_len = 0;
3094 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 else
3096 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003097 text = ga.ga_data;
3098 text_len = ga.ga_len;
3099 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003100 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003101 if (update_buffer)
3102 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003103
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003104 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003105 line->sb_cols = len;
3106 line->sb_cells = p;
3107 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003108 if (update_buffer)
3109 {
3110 line->sb_text = NULL;
3111 ++term->tl_scrollback_scrolled;
3112 ga_clear(&ga); // free the text
3113 }
3114 else
3115 {
3116 line->sb_text = text;
3117 ga_init(&ga); // text is kept in tl_scrollback_postponed
3118 }
3119 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003120 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003121 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003122}
3123
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003124/*
3125 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3126 * received and stored in tl_scrollback_postponed.
3127 */
3128 static void
3129handle_postponed_scrollback(term_T *term)
3130{
3131 int i;
3132
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003133 if (term->tl_scrollback_postponed.ga_len == 0)
3134 return;
3135 ch_log(NULL, "Moving postponed scrollback to scrollback");
3136
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003137 // First remove the lines that were appended before, the pushed lines go
3138 // above it.
3139 cleanup_scrollback(term);
3140
3141 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3142 {
3143 char_u *text;
3144 sb_line_T *pp_line;
3145 sb_line_T *line;
3146
3147 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3148 break;
3149 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3150
3151 text = pp_line->sb_text;
3152 if (text == NULL)
3153 text = (char_u *)"";
3154 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3155 vim_free(pp_line->sb_text);
3156
3157 line = (sb_line_T *)term->tl_scrollback.ga_data
3158 + term->tl_scrollback.ga_len;
3159 line->sb_cols = pp_line->sb_cols;
3160 line->sb_cells = pp_line->sb_cells;
3161 line->sb_fill_attr = pp_line->sb_fill_attr;
3162 line->sb_text = NULL;
3163 ++term->tl_scrollback_scrolled;
3164 ++term->tl_scrollback.ga_len;
3165 }
3166
3167 ga_clear(&term->tl_scrollback_postponed);
3168 limit_scrollback(term, &term->tl_scrollback, TRUE);
3169}
3170
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003171static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003172 handle_damage, // damage
3173 handle_moverect, // moverect
3174 handle_movecursor, // movecursor
3175 handle_settermprop, // settermprop
3176 NULL, // bell
3177 handle_resize, // resize
3178 handle_pushline, // sb_pushline
3179 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003180};
3181
3182/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003183 * Do the work after the channel of a terminal was closed.
3184 * Must be called only when updating_screen is FALSE.
3185 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3186 */
3187 static int
3188term_after_channel_closed(term_T *term)
3189{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003190 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003191 if (!term->tl_normal_mode)
3192 {
3193 int fnum = term->tl_buffer->b_fnum;
3194
3195 cleanup_vterm(term);
3196
3197 if (term->tl_finish == TL_FINISH_CLOSE)
3198 {
3199 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003200 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003201#ifdef FEAT_PROP_POPUP
3202 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003203
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003204 // If this was a terminal in a popup window, go back to the
3205 // previous window.
3206 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3207 {
3208 pwin = curwin;
3209 if (win_valid(prevwin))
3210 win_enter(prevwin, FALSE);
3211 }
3212 else
3213#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003214 // If this is the last normal window: exit Vim.
3215 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3216 {
3217 exarg_T ea;
3218
3219 vim_memset(&ea, 0, sizeof(ea));
3220 ex_quit(&ea);
3221 return TRUE;
3222 }
3223
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003224 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003225 ch_log(NULL, "terminal job finished, closing window");
3226 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003227 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003228 if (curwin == aucmd_win)
3229 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003230 if (do_set_w_closing)
3231 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003232 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003233 if (do_set_w_closing)
3234 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003235 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003236#ifdef FEAT_PROP_POPUP
3237 if (pwin != NULL)
3238 popup_close_with_retval(pwin, 0);
3239#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003240 return TRUE;
3241 }
3242 if (term->tl_finish == TL_FINISH_OPEN
3243 && term->tl_buffer->b_nwindows == 0)
3244 {
3245 char buf[50];
3246
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003247 // TODO: use term_opencmd
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003248 ch_log(NULL, "terminal job finished, opening window");
3249 vim_snprintf(buf, sizeof(buf),
3250 term->tl_opencmd == NULL
3251 ? "botright sbuf %d"
3252 : (char *)term->tl_opencmd, fnum);
3253 do_cmdline_cmd((char_u *)buf);
3254 }
3255 else
3256 ch_log(NULL, "terminal job finished");
3257 }
3258
3259 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3260 return FALSE;
3261}
3262
3263/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003264 * Called when a channel has been closed.
3265 * If this was a channel for a terminal window then finish it up.
3266 */
3267 void
3268term_channel_closed(channel_T *ch)
3269{
3270 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003271 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003272 int did_one = FALSE;
3273
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003274 for (term = first_term; term != NULL; term = next_term)
3275 {
3276 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003277 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003278 {
3279 term->tl_channel_closed = TRUE;
3280 did_one = TRUE;
3281
Bram Moolenaard23a8232018-02-10 18:45:26 +01003282 VIM_CLEAR(term->tl_title);
3283 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003284#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003285 if (term->tl_out_fd != NULL)
3286 {
3287 fclose(term->tl_out_fd);
3288 term->tl_out_fd = NULL;
3289 }
3290#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003291
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003292 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003293 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003294 // Cannot open or close windows now. Can happen when
3295 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003296 term->tl_channel_recently_closed = TRUE;
3297 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003298 }
3299
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003300 if (term_after_channel_closed(term))
3301 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003302 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003303 }
3304
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003305 if (did_one)
3306 {
3307 redraw_statuslines();
3308
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003309 // Need to break out of vgetc().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003310 ins_char_typebuf(K_IGNORE);
3311 typebuf_was_filled = TRUE;
3312
3313 term = curbuf->b_term;
3314 if (term != NULL)
3315 {
3316 if (term->tl_job == ch->ch_job)
3317 maketitle();
3318 update_cursor(term, term->tl_cursor_visible);
3319 }
3320 }
3321}
3322
3323/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003324 * To be called after resetting updating_screen: handle any terminal where the
3325 * channel was closed.
3326 */
3327 void
3328term_check_channel_closed_recently()
3329{
3330 term_T *term;
3331 term_T *next_term;
3332
3333 for (term = first_term; term != NULL; term = next_term)
3334 {
3335 next_term = term->tl_next;
3336 if (term->tl_channel_recently_closed)
3337 {
3338 term->tl_channel_recently_closed = FALSE;
3339 if (term_after_channel_closed(term))
3340 // start over, the list may have changed
3341 next_term = first_term;
3342 }
3343 }
3344}
3345
3346/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003347 * Fill one screen line from a line of the terminal.
3348 * Advances "pos" to past the last column.
3349 */
3350 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003351term_line2screenline(
3352 win_T *wp,
3353 VTermScreen *screen,
3354 VTermPos *pos,
3355 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003356{
3357 int off = screen_get_current_line_off();
3358
3359 for (pos->col = 0; pos->col < max_col; )
3360 {
3361 VTermScreenCell cell;
3362 int c;
3363
3364 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3365 vim_memset(&cell, 0, sizeof(cell));
3366
3367 c = cell.chars[0];
3368 if (c == NUL)
3369 {
3370 ScreenLines[off] = ' ';
3371 if (enc_utf8)
3372 ScreenLinesUC[off] = NUL;
3373 }
3374 else
3375 {
3376 if (enc_utf8)
3377 {
3378 int i;
3379
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003380 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003381 for (i = 0; i < Screen_mco
3382 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3383 {
3384 ScreenLinesC[i][off] = cell.chars[i + 1];
3385 if (cell.chars[i + 1] == 0)
3386 break;
3387 }
3388 if (c >= 0x80 || (Screen_mco > 0
3389 && ScreenLinesC[0][off] != 0))
3390 {
3391 ScreenLines[off] = ' ';
3392 ScreenLinesUC[off] = c;
3393 }
3394 else
3395 {
3396 ScreenLines[off] = c;
3397 ScreenLinesUC[off] = NUL;
3398 }
3399 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003400#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003401 else if (has_mbyte && c >= 0x80)
3402 {
3403 char_u mb[MB_MAXBYTES+1];
3404 WCHAR wc = c;
3405
3406 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3407 (char*)mb, 2, 0, 0) > 1)
3408 {
3409 ScreenLines[off] = mb[0];
3410 ScreenLines[off + 1] = mb[1];
3411 cell.width = mb_ptr2cells(mb);
3412 }
3413 else
3414 ScreenLines[off] = c;
3415 }
3416#endif
3417 else
3418 ScreenLines[off] = c;
3419 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003420 ScreenAttrs[off] = cell2attr(wp, cell.attrs, cell.fg, cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003421
3422 ++pos->col;
3423 ++off;
3424 if (cell.width == 2)
3425 {
3426 if (enc_utf8)
3427 ScreenLinesUC[off] = NUL;
3428
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003429 // don't set the second byte to NUL for a DBCS encoding, it
3430 // has been set above
Bram Moolenaar13568252018-03-16 20:46:58 +01003431 if (enc_utf8 || !has_mbyte)
3432 ScreenLines[off] = NUL;
3433
3434 ++pos->col;
3435 ++off;
3436 }
3437 }
3438}
3439
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003440#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003441 static void
3442update_system_term(term_T *term)
3443{
3444 VTermPos pos;
3445 VTermScreen *screen;
3446
3447 if (term->tl_vterm == NULL)
3448 return;
3449 screen = vterm_obtain_screen(term->tl_vterm);
3450
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003451 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003452 while (term->tl_toprow > 0
3453 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3454 {
3455 int save_p_more = p_more;
3456
3457 p_more = FALSE;
3458 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003459 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003460 p_more = save_p_more;
3461 --term->tl_toprow;
3462 }
3463
3464 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3465 && pos.row < Rows; ++pos.row)
3466 {
3467 if (pos.row < term->tl_rows)
3468 {
3469 int max_col = MIN(Columns, term->tl_cols);
3470
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003471 term_line2screenline(NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003472 }
3473 else
3474 pos.col = 0;
3475
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003476 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003477 }
3478
3479 term->tl_dirty_row_start = MAX_ROW;
3480 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003481}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003482#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003483
3484/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003485 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3486 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003487 * Terminal-Normal mode.
3488 */
3489 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003490term_do_update_window(win_T *wp)
3491{
3492 term_T *term = wp->w_buffer->b_term;
3493
3494 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3495}
3496
3497/*
3498 * Called to update a window that contains an active terminal.
3499 */
3500 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003501term_update_window(win_T *wp)
3502{
3503 term_T *term = wp->w_buffer->b_term;
3504 VTerm *vterm;
3505 VTermScreen *screen;
3506 VTermState *state;
3507 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003508 int rows, cols;
3509 int newrows, newcols;
3510 int minsize;
3511 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003512
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003513 vterm = term->tl_vterm;
3514 screen = vterm_obtain_screen(vterm);
3515 state = vterm_obtain_state(vterm);
3516
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003517 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3518 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003519 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003520 {
3521 term->tl_dirty_row_start = 0;
3522 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003523
3524 if (term->tl_postponed_scroll > 0
3525 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003526 // Scrolling is usually faster than redrawing, when there are only
3527 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003528 term_scroll_up(term, 0, term->tl_postponed_scroll);
3529 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003530 }
3531
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003532 /*
3533 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003534 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003535 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003536 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003537
Bram Moolenaar498c2562018-04-15 23:45:15 +02003538 newrows = 99999;
3539 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003540 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003541 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003542 // Always use curwin, it may be a popup window.
3543 win_T *wwp = twp == NULL ? curwin : twp;
3544
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003545 // When more than one window shows the same terminal, use the
3546 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003547 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003548 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003549 newrows = MIN(newrows, wwp->w_height);
3550 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003551 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003552 if (twp == NULL)
3553 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003554 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003555 if (newrows == 99999 || newcols == 99999)
3556 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003557 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3558 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3559
3560 if (term->tl_rows != newrows || term->tl_cols != newcols)
3561 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003562 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003563 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003564 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003565 newrows);
3566 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003567
3568 // Updating the terminal size will cause the snapshot to be cleared.
3569 // When not in terminal_loop() we need to restore it.
3570 if (term != in_terminal_loop)
3571 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003572 }
3573
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003574 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003575 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003576 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003577
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003578 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3579 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003580 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003581 if (pos.row < term->tl_rows)
3582 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003583 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003584
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003585 term_line2screenline(wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003586 }
3587 else
3588 pos.col = 0;
3589
Bram Moolenaarf118d482018-03-13 13:14:00 +01003590 screen_line(wp->w_winrow + pos.row
3591#ifdef FEAT_MENU
3592 + winbar_height(wp)
3593#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003594 , wp->w_wincol, pos.col, wp->w_width,
3595#ifdef FEAT_PROP_POPUP
3596 popup_is_popup(wp) ? SLF_POPUP :
3597#endif
3598 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003599 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003600 term->tl_dirty_row_start = MAX_ROW;
3601 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003602}
3603
3604/*
3605 * Return TRUE if "wp" is a terminal window where the job has finished.
3606 */
3607 int
3608term_is_finished(buf_T *buf)
3609{
3610 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3611}
3612
3613/*
3614 * Return TRUE if "wp" is a terminal window where the job has finished or we
3615 * are in Terminal-Normal mode, thus we show the buffer contents.
3616 */
3617 int
3618term_show_buffer(buf_T *buf)
3619{
3620 term_T *term = buf->b_term;
3621
3622 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3623}
3624
3625/*
3626 * The current buffer is going to be changed. If there is terminal
3627 * highlighting remove it now.
3628 */
3629 void
3630term_change_in_curbuf(void)
3631{
3632 term_T *term = curbuf->b_term;
3633
3634 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3635 {
3636 free_scrollback(term);
3637 redraw_buf_later(term->tl_buffer, NOT_VALID);
3638
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003639 // The buffer is now like a normal buffer, it cannot be easily
3640 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003641 set_string_option_direct((char_u *)"buftype", -1,
3642 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3643 }
3644}
3645
3646/*
3647 * Get the screen attribute for a position in the buffer.
3648 * Use a negative "col" to get the filler background color.
3649 */
3650 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003651term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003652{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003653 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003654 term_T *term = buf->b_term;
3655 sb_line_T *line;
3656 cellattr_T *cellattr;
3657
3658 if (lnum > term->tl_scrollback.ga_len)
3659 cellattr = &term->tl_default_color;
3660 else
3661 {
3662 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3663 if (col < 0 || col >= line->sb_cols)
3664 cellattr = &line->sb_fill_attr;
3665 else
3666 cellattr = line->sb_cells + col;
3667 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003668 return cell2attr(wp, cellattr->attrs, cellattr->fg, cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003669}
3670
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003671/*
3672 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003673 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003674 */
3675 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003676cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003677{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003678 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003679}
3680
3681/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003682 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003683 */
3684 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003685init_default_colors(term_T *term, win_T *wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003686{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003687 VTermColor *fg, *bg;
3688 int fgval, bgval;
3689 int id;
3690
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003691 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3692 term->tl_default_color.width = 1;
3693 fg = &term->tl_default_color.fg;
3694 bg = &term->tl_default_color.bg;
3695
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003696 // Vterm uses a default black background. Set it to white when
3697 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003698 if (*p_bg == 'l')
3699 {
3700 fgval = 0;
3701 bgval = 255;
3702 }
3703 else
3704 {
3705 fgval = 255;
3706 bgval = 0;
3707 }
3708 fg->red = fg->green = fg->blue = fgval;
3709 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003710 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003711
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003712 // The 'wincolor' or "Terminal" highlight group overrules the defaults.
3713 if (wp != NULL && *wp->w_p_wcr != NUL)
3714 id = syn_name2id(wp->w_p_wcr);
3715 else
3716 id = syn_name2id((char_u *)"Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003717
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003718 // Use the actual color for the GUI and when 'termguicolors' is set.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003719#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3720 if (0
3721# ifdef FEAT_GUI
3722 || gui.in_use
3723# endif
3724# ifdef FEAT_TERMGUICOLORS
3725 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003726# ifdef FEAT_VTP
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003727 // Finally get INVALCOLOR on this execution path
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003728 || (!p_tgc && t_colors >= 256)
3729# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003730# endif
3731 )
3732 {
3733 guicolor_T fg_rgb = INVALCOLOR;
3734 guicolor_T bg_rgb = INVALCOLOR;
3735
3736 if (id != 0)
3737 syn_id2colors(id, &fg_rgb, &bg_rgb);
3738
3739# ifdef FEAT_GUI
3740 if (gui.in_use)
3741 {
3742 if (fg_rgb == INVALCOLOR)
3743 fg_rgb = gui.norm_pixel;
3744 if (bg_rgb == INVALCOLOR)
3745 bg_rgb = gui.back_pixel;
3746 }
3747# ifdef FEAT_TERMGUICOLORS
3748 else
3749# endif
3750# endif
3751# ifdef FEAT_TERMGUICOLORS
3752 {
3753 if (fg_rgb == INVALCOLOR)
3754 fg_rgb = cterm_normal_fg_gui_color;
3755 if (bg_rgb == INVALCOLOR)
3756 bg_rgb = cterm_normal_bg_gui_color;
3757 }
3758# endif
3759 if (fg_rgb != INVALCOLOR)
3760 {
3761 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3762
3763 fg->red = (unsigned)(rgb >> 16);
3764 fg->green = (unsigned)(rgb >> 8) & 255;
3765 fg->blue = (unsigned)rgb & 255;
3766 }
3767 if (bg_rgb != INVALCOLOR)
3768 {
3769 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3770
3771 bg->red = (unsigned)(rgb >> 16);
3772 bg->green = (unsigned)(rgb >> 8) & 255;
3773 bg->blue = (unsigned)rgb & 255;
3774 }
3775 }
3776 else
3777#endif
3778 if (id != 0 && t_colors >= 16)
3779 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003780 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003781 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003782 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003783 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003784 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003785 else
3786 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003787#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003788 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003789#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003790
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003791 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003792 if (cterm_normal_fg_color > 0)
3793 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003794 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003795# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3796# ifdef VIMDLL
3797 if (!gui.in_use)
3798# endif
3799 {
3800 tmp = fg->red;
3801 fg->red = fg->blue;
3802 fg->blue = tmp;
3803 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003804# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003805 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003806# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003807 else
3808 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003809# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003810
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003811 if (cterm_normal_bg_color > 0)
3812 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003813 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003814# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3815# ifdef VIMDLL
3816 if (!gui.in_use)
3817# endif
3818 {
3819 tmp = fg->red;
3820 fg->red = fg->blue;
3821 fg->blue = tmp;
3822 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003823# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003824 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003825# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003826 else
3827 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003828# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003829 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003830}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003831
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003832#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3833/*
3834 * Set the 16 ANSI colors from array of RGB values
3835 */
3836 static void
3837set_vterm_palette(VTerm *vterm, long_u *rgb)
3838{
3839 int index = 0;
3840 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003841
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003842 for (; index < 16; index++)
3843 {
3844 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003845
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003846 color.red = (unsigned)(rgb[index] >> 16);
3847 color.green = (unsigned)(rgb[index] >> 8) & 255;
3848 color.blue = (unsigned)rgb[index] & 255;
3849 vterm_state_set_palette_color(state, index, &color);
3850 }
3851}
3852
3853/*
3854 * Set the ANSI color palette from a list of colors
3855 */
3856 static int
3857set_ansi_colors_list(VTerm *vterm, list_T *list)
3858{
3859 int n = 0;
3860 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01003861 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003862
Bram Moolenaarb0992022020-01-30 14:55:42 +01003863 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003864 {
3865 char_u *color_name;
3866 guicolor_T guicolor;
3867
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003868 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003869 if (color_name == NULL)
3870 return FAIL;
3871
3872 guicolor = GUI_GET_COLOR(color_name);
3873 if (guicolor == INVALCOLOR)
3874 return FAIL;
3875
3876 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3877 }
3878
3879 if (n != 16 || li != NULL)
3880 return FAIL;
3881
3882 set_vterm_palette(vterm, rgb);
3883
3884 return OK;
3885}
3886
3887/*
3888 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3889 */
3890 static void
3891init_vterm_ansi_colors(VTerm *vterm)
3892{
3893 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3894
3895 if (var != NULL
3896 && (var->di_tv.v_type != VAR_LIST
3897 || var->di_tv.vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +01003898 || var->di_tv.vval.v_list->lv_first == &range_list_item
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003899 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003900 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003901}
3902#endif
3903
Bram Moolenaar52acb112018-03-18 19:20:22 +01003904/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003905 * Handles a "drop" command from the job in the terminal.
3906 * "item" is the file name, "item->li_next" may have options.
3907 */
3908 static void
3909handle_drop_command(listitem_T *item)
3910{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003911 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003912 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003913 int bufnr;
3914 win_T *wp;
3915 tabpage_T *tp;
3916 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003917 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003918
3919 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3920 FOR_ALL_TAB_WINDOWS(tp, wp)
3921 {
3922 if (wp->w_buffer->b_fnum == bufnr)
3923 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003924 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003925 goto_tabpage_win(tp, wp);
3926 return;
3927 }
3928 }
3929
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003930 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003931
3932 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3933 && opt_item->li_tv.vval.v_dict != NULL)
3934 {
3935 dict_T *dict = opt_item->li_tv.vval.v_dict;
3936 char_u *p;
3937
Bram Moolenaar8f667172018-12-14 15:38:31 +01003938 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003939 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003940 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003941 if (p != NULL)
3942 {
3943 if (check_ff_value(p) == FAIL)
3944 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3945 else
3946 ea.force_ff = *p;
3947 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003948 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003949 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003950 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003951 if (p != NULL)
3952 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003953 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003954 if (ea.cmd != NULL)
3955 {
3956 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3957 ea.force_enc = 11;
3958 tofree = ea.cmd;
3959 }
3960 }
3961
Bram Moolenaar8f667172018-12-14 15:38:31 +01003962 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003963 if (p != NULL)
3964 get_bad_opt(p, &ea);
3965
3966 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3967 ea.force_bin = FORCE_BIN;
3968 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3969 ea.force_bin = FORCE_BIN;
3970 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3971 ea.force_bin = FORCE_NOBIN;
3972 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3973 ea.force_bin = FORCE_NOBIN;
3974 }
3975
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003976 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003977 if (ea.cmd == NULL)
3978 ea.cmd = (char_u *)"split";
3979 ea.arg = fname;
3980 ea.cmdidx = CMD_split;
3981 ex_splitview(&ea);
3982
3983 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003984}
3985
3986/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003987 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
3988 */
3989 static int
3990is_permitted_term_api(char_u *func, char_u *pat)
3991{
3992 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
3993}
3994
3995/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003996 * Handles a function call from the job running in a terminal.
3997 * "item" is the function name, "item->li_next" has the arguments.
3998 */
3999 static void
4000handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4001{
4002 char_u *func;
4003 typval_T argvars[2];
4004 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004005 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004006
4007 if (item->li_next == NULL)
4008 {
4009 ch_log(channel, "Missing function arguments for call");
4010 return;
4011 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004012 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004013
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004014 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004015 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004016 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004017 return;
4018 }
4019
4020 argvars[0].v_type = VAR_NUMBER;
4021 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4022 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004023 vim_memset(&funcexe, 0, sizeof(funcexe));
4024 funcexe.firstline = 1L;
4025 funcexe.lastline = 1L;
4026 funcexe.evaluate = TRUE;
4027 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004028 {
4029 clear_tv(&rettv);
4030 ch_log(channel, "Function %s called", func);
4031 }
4032 else
4033 ch_log(channel, "Calling function %s failed", func);
4034}
4035
4036/*
4037 * Called by libvterm when it cannot recognize an OSC sequence.
4038 * We recognize a terminal API command.
4039 */
4040 static int
4041parse_osc(const char *command, size_t cmdlen, void *user)
4042{
4043 term_T *term = (term_T *)user;
4044 js_read_T reader;
4045 typval_T tv;
4046 channel_T *channel = term->tl_job == NULL ? NULL
4047 : term->tl_job->jv_channel;
4048
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004049 // We recognize only OSC 5 1 ; {command}
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004050 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004051 return 0; // not handled
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004052
Bram Moolenaar878c96d2018-04-04 23:00:06 +02004053 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004054 if (reader.js_buf == NULL)
4055 return 1;
4056 reader.js_fill = NULL;
4057 reader.js_used = 0;
4058 if (json_decode(&reader, &tv, 0) == OK
4059 && tv.v_type == VAR_LIST
4060 && tv.vval.v_list != NULL)
4061 {
4062 listitem_T *item = tv.vval.v_list->lv_first;
4063
4064 if (item == NULL)
4065 ch_log(channel, "Missing command");
4066 else
4067 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004068 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004069
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004070 // Make sure an invoked command doesn't delete the buffer (and the
4071 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004072 ++term->tl_buffer->b_locked;
4073
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004074 item = item->li_next;
4075 if (item == NULL)
4076 ch_log(channel, "Missing argument for %s", cmd);
4077 else if (STRCMP(cmd, "drop") == 0)
4078 handle_drop_command(item);
4079 else if (STRCMP(cmd, "call") == 0)
4080 handle_call_command(term, channel, item);
4081 else
4082 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004083 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004084 }
4085 }
4086 else
4087 ch_log(channel, "Invalid JSON received");
4088
4089 vim_free(reader.js_buf);
4090 clear_tv(&tv);
4091 return 1;
4092}
4093
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004094/*
4095 * Called by libvterm when it cannot recognize a CSI sequence.
4096 * We recognize the window position report.
4097 */
4098 static int
4099parse_csi(
4100 const char *leader UNUSED,
4101 const long args[],
4102 int argcount,
4103 const char *intermed UNUSED,
4104 char command,
4105 void *user)
4106{
4107 term_T *term = (term_T *)user;
4108 char buf[100];
4109 int len;
4110 int x = 0;
4111 int y = 0;
4112 win_T *wp;
4113
4114 // We recognize only CSI 13 t
4115 if (command != 't' || argcount != 1 || args[0] != 13)
4116 return 0; // not handled
4117
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004118 // When getting the window position is not possible or it fails it results
4119 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004120#if defined(FEAT_GUI) \
4121 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4122 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004123 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004124#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004125
4126 FOR_ALL_WINDOWS(wp)
4127 if (wp->w_buffer == term->tl_buffer)
4128 break;
4129 if (wp != NULL)
4130 {
4131#ifdef FEAT_GUI
4132 if (gui.in_use)
4133 {
4134 x += wp->w_wincol * gui.char_width;
4135 y += W_WINROW(wp) * gui.char_height;
4136 }
4137 else
4138#endif
4139 {
4140 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004141 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004142 x += wp->w_wincol * 7;
4143 y += W_WINROW(wp) * 10;
4144 }
4145 }
4146
4147 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4148 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4149 (char_u *)buf, len, NULL);
4150 return 1;
4151}
4152
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004153static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004154 NULL, // text
4155 NULL, // control
4156 NULL, // escape
4157 parse_csi, // csi
4158 parse_osc, // osc
4159 NULL, // dcs
4160 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004161};
4162
4163/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004164 * Use Vim's allocation functions for vterm so profiling works.
4165 */
4166 static void *
4167vterm_malloc(size_t size, void *data UNUSED)
4168{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004169 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004170}
4171
4172 static void
4173vterm_memfree(void *ptr, void *data UNUSED)
4174{
4175 vim_free(ptr);
4176}
4177
4178static VTermAllocatorFunctions vterm_allocator = {
4179 &vterm_malloc,
4180 &vterm_memfree
4181};
4182
4183/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004184 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004185 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004186 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004187 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004188create_vterm(term_T *term, int rows, int cols)
4189{
4190 VTerm *vterm;
4191 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004192 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004193 VTermValue value;
4194
Bram Moolenaar756ef112018-04-10 12:04:27 +02004195 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004196 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004197 if (vterm == NULL)
4198 return FAIL;
4199
4200 // Allocate screen and state here, so we can bail out if that fails.
4201 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004202 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004203 if (state == NULL || screen == NULL)
4204 {
4205 vterm_free(vterm);
4206 return FAIL;
4207 }
4208
Bram Moolenaar52acb112018-03-18 19:20:22 +01004209 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004210 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004211 vterm_set_utf8(vterm, 1);
4212
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004213 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004214
4215 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004216 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004217 &term->tl_default_color.fg,
4218 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004219
Bram Moolenaar9e587872019-05-13 20:27:23 +02004220 if (t_colors < 16)
4221 // Less than 16 colors: assume that bold means using a bright color for
4222 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004223 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4224
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004225 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004226 vterm_screen_reset(screen, 1 /* hard */);
4227
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004228 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004229 vterm_screen_enable_altscreen(screen, 1);
4230
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004231 // For unix do not use a blinking cursor. In an xterm this causes the
4232 // cursor to blink if it's blinking in the xterm.
4233 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004234#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004235 if (GetCaretBlinkTime() == INFINITE)
4236 value.boolean = 0;
4237 else
4238 value.boolean = 1;
4239#else
4240 value.boolean = 0;
4241#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004242 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4243 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004244
4245 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004246}
4247
4248/*
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004249 * Called when 'wincolor' was set.
4250 */
4251 void
4252term_update_colors(void)
4253{
4254 term_T *term = curwin->w_buffer->b_term;
4255
4256 init_default_colors(term, curwin);
4257 vterm_state_set_default_colors(
4258 vterm_obtain_state(term->tl_vterm),
4259 &term->tl_default_color.fg,
4260 &term->tl_default_color.bg);
4261}
4262
4263/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004264 * Return the text to show for the buffer name and status.
4265 */
4266 char_u *
4267term_get_status_text(term_T *term)
4268{
4269 if (term->tl_status_text == NULL)
4270 {
4271 char_u *txt;
4272 size_t len;
4273
4274 if (term->tl_normal_mode)
4275 {
4276 if (term_job_running(term))
4277 txt = (char_u *)_("Terminal");
4278 else
4279 txt = (char_u *)_("Terminal-finished");
4280 }
4281 else if (term->tl_title != NULL)
4282 txt = term->tl_title;
4283 else if (term_none_open(term))
4284 txt = (char_u *)_("active");
4285 else if (term_job_running(term))
4286 txt = (char_u *)_("running");
4287 else
4288 txt = (char_u *)_("finished");
4289 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004290 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004291 if (term->tl_status_text != NULL)
4292 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4293 term->tl_buffer->b_fname, txt);
4294 }
4295 return term->tl_status_text;
4296}
4297
4298/*
4299 * Mark references in jobs of terminals.
4300 */
4301 int
4302set_ref_in_term(int copyID)
4303{
4304 int abort = FALSE;
4305 term_T *term;
4306 typval_T tv;
4307
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004308 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004309 if (term->tl_job != NULL)
4310 {
4311 tv.v_type = VAR_JOB;
4312 tv.vval.v_job = term->tl_job;
4313 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4314 }
4315 return abort;
4316}
4317
4318/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004319 * Cache "Terminal" highlight group colors.
4320 */
4321 void
4322set_terminal_default_colors(int cterm_fg, int cterm_bg)
4323{
4324 term_default_cterm_fg = cterm_fg - 1;
4325 term_default_cterm_bg = cterm_bg - 1;
4326}
4327
4328/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004329 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004330 * Returns NULL when the buffer is not for a terminal window and logs a message
4331 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004332 */
4333 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004334term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004335{
4336 buf_T *buf;
4337
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004338 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004339 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004340 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004341 --emsg_off;
4342 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004343 {
4344 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004345 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004346 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004347 return buf;
4348}
4349
Bram Moolenaard96ff162018-02-18 22:13:29 +01004350 static int
4351same_color(VTermColor *a, VTermColor *b)
4352{
4353 return a->red == b->red
4354 && a->green == b->green
4355 && a->blue == b->blue
4356 && a->ansi_index == b->ansi_index;
4357}
4358
4359 static void
4360dump_term_color(FILE *fd, VTermColor *color)
4361{
4362 fprintf(fd, "%02x%02x%02x%d",
4363 (int)color->red, (int)color->green, (int)color->blue,
4364 (int)color->ansi_index);
4365}
4366
4367/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004368 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004369 *
4370 * Each screen cell in full is:
4371 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4372 * {characters} is a space for an empty cell
4373 * For a double-width character "+" is changed to "*" and the next cell is
4374 * skipped.
4375 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4376 * when "&" use the same as the previous cell.
4377 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4378 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4379 * {color-idx} is a number from 0 to 255
4380 *
4381 * Screen cell with same width, attributes and color as the previous one:
4382 * |{characters}
4383 *
4384 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4385 *
4386 * Repeating the previous screen cell:
4387 * @{count}
4388 */
4389 void
4390f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4391{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004392 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004393 term_T *term;
4394 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004395 int max_height = 0;
4396 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004397 stat_T st;
4398 FILE *fd;
4399 VTermPos pos;
4400 VTermScreen *screen;
4401 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004402 VTermState *state;
4403 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004404
4405 if (check_restricted() || check_secure())
4406 return;
4407 if (buf == NULL)
4408 return;
4409 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004410 if (term->tl_vterm == NULL)
4411 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004412 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004413 return;
4414 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004415
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004416 if (argvars[2].v_type != VAR_UNKNOWN)
4417 {
4418 dict_T *d;
4419
4420 if (argvars[2].v_type != VAR_DICT)
4421 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004422 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004423 return;
4424 }
4425 d = argvars[2].vval.v_dict;
4426 if (d != NULL)
4427 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004428 max_height = dict_get_number(d, (char_u *)"rows");
4429 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004430 }
4431 }
4432
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004433 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004434 if (fname == NULL)
4435 return;
4436 if (mch_stat((char *)fname, &st) >= 0)
4437 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004438 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004439 return;
4440 }
4441
Bram Moolenaard96ff162018-02-18 22:13:29 +01004442 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4443 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004444 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004445 return;
4446 }
4447
4448 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4449
4450 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004451 state = vterm_obtain_state(term->tl_vterm);
4452 vterm_state_get_cursorpos(state, &cursor_pos);
4453
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004454 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4455 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004456 {
4457 int repeat = 0;
4458
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004459 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4460 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004461 {
4462 VTermScreenCell cell;
4463 int same_attr;
4464 int same_chars = TRUE;
4465 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004466 int is_cursor_pos = (pos.col == cursor_pos.col
4467 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004468
4469 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4470 vim_memset(&cell, 0, sizeof(cell));
4471
4472 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4473 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004474 int c = cell.chars[i];
4475 int pc = prev_cell.chars[i];
4476
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004477 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01004478 if (i == 0)
4479 {
4480 c = (c == NUL) ? ' ' : c;
4481 pc = (pc == NUL) ? ' ' : pc;
4482 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004483 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004484 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004485 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004486 break;
4487 }
4488 same_attr = vtermAttr2hl(cell.attrs)
4489 == vtermAttr2hl(prev_cell.attrs)
4490 && same_color(&cell.fg, &prev_cell.fg)
4491 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004492 if (same_chars && cell.width == prev_cell.width && same_attr
4493 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004494 {
4495 ++repeat;
4496 }
4497 else
4498 {
4499 if (repeat > 0)
4500 {
4501 fprintf(fd, "@%d", repeat);
4502 repeat = 0;
4503 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004504 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004505
4506 if (cell.chars[0] == NUL)
4507 fputs(" ", fd);
4508 else
4509 {
4510 char_u charbuf[10];
4511 int len;
4512
4513 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4514 && cell.chars[i] != NUL; ++i)
4515 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004516 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004517 fwrite(charbuf, len, 1, fd);
4518 }
4519 }
4520
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004521 // When only the characters differ we don't write anything, the
4522 // following "|", "@" or NL will indicate using the same
4523 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004524 if (cell.width != prev_cell.width || !same_attr)
4525 {
4526 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004527 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004528 else
4529 fputs("+", fd);
4530
4531 if (same_attr)
4532 {
4533 fputs("&", fd);
4534 }
4535 else
4536 {
4537 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4538 if (same_color(&cell.fg, &prev_cell.fg))
4539 fputs("&", fd);
4540 else
4541 {
4542 fputs("#", fd);
4543 dump_term_color(fd, &cell.fg);
4544 }
4545 if (same_color(&cell.bg, &prev_cell.bg))
4546 fputs("&", fd);
4547 else
4548 {
4549 fputs("#", fd);
4550 dump_term_color(fd, &cell.bg);
4551 }
4552 }
4553 }
4554
4555 prev_cell = cell;
4556 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004557
4558 if (cell.width == 2)
4559 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004560 }
4561 if (repeat > 0)
4562 fprintf(fd, "@%d", repeat);
4563 fputs("\n", fd);
4564 }
4565
4566 fclose(fd);
4567}
4568
4569/*
4570 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4571 */
4572 static void
4573dump_is_corrupt(garray_T *gap)
4574{
4575 ga_concat(gap, (char_u *)"CORRUPT");
4576}
4577
4578 static void
4579append_cell(garray_T *gap, cellattr_T *cell)
4580{
4581 if (ga_grow(gap, 1) == OK)
4582 {
4583 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4584 ++gap->ga_len;
4585 }
4586}
4587
4588/*
4589 * Read the dump file from "fd" and append lines to the current buffer.
4590 * Return the cell width of the longest line.
4591 */
4592 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004593read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004594{
4595 int c;
4596 garray_T ga_text;
4597 garray_T ga_cell;
4598 char_u *prev_char = NULL;
4599 int attr = 0;
4600 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004601 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004602 term_T *term = curbuf->b_term;
4603 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004604 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004605
4606 ga_init2(&ga_text, 1, 90);
4607 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4608 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004609 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004610 cursor_pos->row = -1;
4611 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004612
4613 c = fgetc(fd);
4614 for (;;)
4615 {
4616 if (c == EOF)
4617 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004618 if (c == '\r')
4619 {
4620 // DOS line endings? Ignore.
4621 c = fgetc(fd);
4622 }
4623 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004624 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004625 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004626 if (ga_text.ga_data == NULL)
4627 dump_is_corrupt(&ga_text);
4628 if (ga_grow(&term->tl_scrollback, 1) == OK)
4629 {
4630 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4631 + term->tl_scrollback.ga_len;
4632
4633 if (max_cells < ga_cell.ga_len)
4634 max_cells = ga_cell.ga_len;
4635 line->sb_cols = ga_cell.ga_len;
4636 line->sb_cells = ga_cell.ga_data;
4637 line->sb_fill_attr = term->tl_default_color;
4638 ++term->tl_scrollback.ga_len;
4639 ga_init(&ga_cell);
4640
4641 ga_append(&ga_text, NUL);
4642 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4643 ga_text.ga_len, FALSE);
4644 }
4645 else
4646 ga_clear(&ga_cell);
4647 ga_text.ga_len = 0;
4648
4649 c = fgetc(fd);
4650 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004651 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004652 {
4653 int prev_len = ga_text.ga_len;
4654
Bram Moolenaar9271d052018-02-25 21:39:46 +01004655 if (c == '>')
4656 {
4657 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004658 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004659 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4660 cursor_pos->col = ga_cell.ga_len;
4661 }
4662
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004663 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004664 c = fgetc(fd);
4665 if (c != EOF)
4666 ga_append(&ga_text, c);
4667 for (;;)
4668 {
4669 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004670 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004671 || c == EOF || c == '\n')
4672 break;
4673 ga_append(&ga_text, c);
4674 }
4675
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004676 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01004677 vim_free(prev_char);
4678 if (ga_text.ga_data != NULL)
4679 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4680 ga_text.ga_len - prev_len);
4681
Bram Moolenaar9271d052018-02-25 21:39:46 +01004682 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004683 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004684 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004685 }
4686 else if (c == '+' || c == '*')
4687 {
4688 int is_bg;
4689
4690 cell.width = c == '+' ? 1 : 2;
4691
4692 c = fgetc(fd);
4693 if (c == '&')
4694 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004695 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004696 c = fgetc(fd);
4697 }
4698 else if (isdigit(c))
4699 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004700 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01004701 attr = 0;
4702 while (isdigit(c))
4703 {
4704 attr = attr * 10 + (c - '0');
4705 c = fgetc(fd);
4706 }
4707 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004708
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004709 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004710 for (is_bg = 0; is_bg <= 1; ++is_bg)
4711 {
4712 if (c == '&')
4713 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004714 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004715 c = fgetc(fd);
4716 }
4717 else if (c == '#')
4718 {
4719 int red, green, blue, index = 0;
4720
4721 c = fgetc(fd);
4722 red = hex2nr(c);
4723 c = fgetc(fd);
4724 red = (red << 4) + hex2nr(c);
4725 c = fgetc(fd);
4726 green = hex2nr(c);
4727 c = fgetc(fd);
4728 green = (green << 4) + hex2nr(c);
4729 c = fgetc(fd);
4730 blue = hex2nr(c);
4731 c = fgetc(fd);
4732 blue = (blue << 4) + hex2nr(c);
4733 c = fgetc(fd);
4734 if (!isdigit(c))
4735 dump_is_corrupt(&ga_text);
4736 while (isdigit(c))
4737 {
4738 index = index * 10 + (c - '0');
4739 c = fgetc(fd);
4740 }
4741
4742 if (is_bg)
4743 {
4744 cell.bg.red = red;
4745 cell.bg.green = green;
4746 cell.bg.blue = blue;
4747 cell.bg.ansi_index = index;
4748 }
4749 else
4750 {
4751 cell.fg.red = red;
4752 cell.fg.green = green;
4753 cell.fg.blue = blue;
4754 cell.fg.ansi_index = index;
4755 }
4756 }
4757 else
4758 dump_is_corrupt(&ga_text);
4759 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004760 }
4761 else
4762 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004763 }
4764 else
4765 dump_is_corrupt(&ga_text);
4766
4767 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004768 if (cell.width == 2)
4769 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004770 }
4771 else if (c == '@')
4772 {
4773 if (prev_char == NULL)
4774 dump_is_corrupt(&ga_text);
4775 else
4776 {
4777 int count = 0;
4778
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004779 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01004780 for (;;)
4781 {
4782 c = fgetc(fd);
4783 if (!isdigit(c))
4784 break;
4785 count = count * 10 + (c - '0');
4786 }
4787
4788 while (count-- > 0)
4789 {
4790 ga_concat(&ga_text, prev_char);
4791 append_cell(&ga_cell, &cell);
4792 }
4793 }
4794 }
4795 else
4796 {
4797 dump_is_corrupt(&ga_text);
4798 c = fgetc(fd);
4799 }
4800 }
4801
4802 if (ga_text.ga_len > 0)
4803 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004804 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004805 dump_is_corrupt(&ga_text);
4806 ga_append(&ga_text, NUL);
4807 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4808 ga_text.ga_len, FALSE);
4809 }
4810
4811 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004812 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004813 vim_free(prev_char);
4814
4815 return max_cells;
4816}
4817
4818/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004819 * Return an allocated string with at least "text_width" "=" characters and
4820 * "fname" inserted in the middle.
4821 */
4822 static char_u *
4823get_separator(int text_width, char_u *fname)
4824{
4825 int width = MAX(text_width, curwin->w_width);
4826 char_u *textline;
4827 int fname_size;
4828 char_u *p = fname;
4829 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004830 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004831
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004832 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004833 if (textline == NULL)
4834 return NULL;
4835
4836 fname_size = vim_strsize(fname);
4837 if (fname_size < width - 8)
4838 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004839 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02004840 width = MAX(text_width, fname_size + 8);
4841 }
4842 else if (fname_size > width - 8)
4843 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004844 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02004845 p = gettail(fname);
4846 fname_size = vim_strsize(p);
4847 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004848 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02004849 while (fname_size > width - 8)
4850 {
4851 p += (*mb_ptr2len)(p);
4852 fname_size = vim_strsize(p);
4853 }
4854
4855 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4856 textline[i] = '=';
4857 textline[i++] = ' ';
4858
4859 STRCPY(textline + i, p);
4860 off = STRLEN(textline);
4861 textline[off] = ' ';
4862 for (i = 1; i < (width - fname_size) / 2; ++i)
4863 textline[off + i] = '=';
4864 textline[off + i] = NUL;
4865
4866 return textline;
4867}
4868
4869/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004870 * Common for "term_dumpdiff()" and "term_dumpload()".
4871 */
4872 static void
4873term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4874{
4875 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004876 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004877 char_u buf1[NUMBUFLEN];
4878 char_u buf2[NUMBUFLEN];
4879 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004880 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004881 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004882 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004883 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004884 char_u *textline = NULL;
4885
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004886 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004887 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004888 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004889 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004890 if (fname1 == NULL || (do_diff && fname2 == NULL))
4891 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004892 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004893 return;
4894 }
4895 fd1 = mch_fopen((char *)fname1, READBIN);
4896 if (fd1 == NULL)
4897 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004898 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004899 return;
4900 }
4901 if (do_diff)
4902 {
4903 fd2 = mch_fopen((char *)fname2, READBIN);
4904 if (fd2 == NULL)
4905 {
4906 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004907 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004908 return;
4909 }
4910 }
4911
4912 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004913 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4914 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4915 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4916 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4917 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004918
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004919 if (opt.jo_term_name == NULL)
4920 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004921 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004922
Bram Moolenaar51e14382019-05-25 20:21:28 +02004923 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004924 if (fname_tofree != NULL)
4925 {
4926 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4927 opt.jo_term_name = fname_tofree;
4928 }
4929 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004930
Bram Moolenaar87abab92019-06-03 21:14:59 +02004931 if (opt.jo_bufnr_buf != NULL)
4932 {
4933 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4934
4935 // With "bufnr" argument: enter the window with this buffer and make it
4936 // empty.
4937 if (wp == NULL)
4938 semsg(_(e_invarg2), "bufnr");
4939 else
4940 {
4941 buf = curbuf;
4942 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4943 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02004944 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02004945 redraw_later(NOT_VALID);
4946 }
4947 }
4948 else
4949 // Create a new terminal window.
4950 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4951
Bram Moolenaard96ff162018-02-18 22:13:29 +01004952 if (buf != NULL && buf->b_term != NULL)
4953 {
4954 int i;
4955 linenr_T bot_lnum;
4956 linenr_T lnum;
4957 term_T *term = buf->b_term;
4958 int width;
4959 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004960 VTermPos cursor_pos1;
4961 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004962
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004963 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004964
Bram Moolenaard96ff162018-02-18 22:13:29 +01004965 rettv->vval.v_number = buf->b_fnum;
4966
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004967 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01004968 width = read_dump_file(fd1, &cursor_pos1);
4969
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004970 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004971 if (cursor_pos1.row >= 0)
4972 {
4973 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4974 coladvance(cursor_pos1.col);
4975 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004976
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004977 // Delete the empty line that was in the empty buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004978 ml_delete(1, FALSE);
4979
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004980 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004981 if (!do_diff)
4982 goto theend;
4983
4984 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4985
Bram Moolenaar4a696342018-04-05 18:45:26 +02004986 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004987 if (textline == NULL)
4988 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004989 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4990 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4991 vim_free(textline);
4992
4993 textline = get_separator(width, fname2);
4994 if (textline == NULL)
4995 goto theend;
4996 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4997 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004998 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004999
5000 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005001 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005002 if (width2 > width)
5003 {
5004 vim_free(textline);
5005 textline = alloc(width2 + 1);
5006 if (textline == NULL)
5007 goto theend;
5008 width = width2;
5009 textline[width] = NUL;
5010 }
5011 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5012
5013 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5014 {
5015 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5016 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005017 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005018 for (i = 0; i < width; ++i)
5019 textline[i] = '-';
5020 }
5021 else
5022 {
5023 char_u *line1;
5024 char_u *line2;
5025 char_u *p1;
5026 char_u *p2;
5027 int col;
5028 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5029 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5030 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5031 ->sb_cells;
5032
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005033 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005034 line1 = vim_strsave(ml_get(lnum));
5035 if (line1 == NULL)
5036 break;
5037 p1 = line1;
5038
5039 line2 = ml_get(lnum + bot_lnum);
5040 p2 = line2;
5041 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5042 {
5043 int len1 = utfc_ptr2len(p1);
5044 int len2 = utfc_ptr2len(p2);
5045
5046 textline[col] = ' ';
5047 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005048 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005049 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005050 else if (lnum == cursor_pos1.row + 1
5051 && col == cursor_pos1.col
5052 && (cursor_pos1.row != cursor_pos2.row
5053 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005054 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005055 textline[col] = '>';
5056 else if (lnum == cursor_pos2.row + 1
5057 && col == cursor_pos2.col
5058 && (cursor_pos1.row != cursor_pos2.row
5059 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005060 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005061 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005062 else if (cellattr1 != NULL && cellattr2 != NULL)
5063 {
5064 if ((cellattr1 + col)->width
5065 != (cellattr2 + col)->width)
5066 textline[col] = 'w';
5067 else if (!same_color(&(cellattr1 + col)->fg,
5068 &(cellattr2 + col)->fg))
5069 textline[col] = 'f';
5070 else if (!same_color(&(cellattr1 + col)->bg,
5071 &(cellattr2 + col)->bg))
5072 textline[col] = 'b';
5073 else if (vtermAttr2hl((cellattr1 + col)->attrs)
5074 != vtermAttr2hl(((cellattr2 + col)->attrs)))
5075 textline[col] = 'a';
5076 }
5077 p1 += len1;
5078 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005079 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005080 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005081
5082 while (col < width)
5083 {
5084 if (*p1 == NUL && *p2 == NUL)
5085 textline[col] = '?';
5086 else if (*p1 == NUL)
5087 {
5088 textline[col] = '+';
5089 p2 += utfc_ptr2len(p2);
5090 }
5091 else
5092 {
5093 textline[col] = '-';
5094 p1 += utfc_ptr2len(p1);
5095 }
5096 ++col;
5097 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005098
5099 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005100 }
5101 if (add_empty_scrollback(term, &term->tl_default_color,
5102 term->tl_top_diff_rows) == OK)
5103 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5104 ++bot_lnum;
5105 }
5106
5107 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5108 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005109 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005110 for (i = 0; i < width; ++i)
5111 textline[i] = '+';
5112 if (add_empty_scrollback(term, &term->tl_default_color,
5113 term->tl_top_diff_rows) == OK)
5114 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5115 ++lnum;
5116 ++bot_lnum;
5117 }
5118
5119 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005120
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005121 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005122 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005123 }
5124
5125theend:
5126 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005127 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005128 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005129 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005130 fclose(fd2);
5131}
5132
5133/*
5134 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5135 * bottom files.
5136 * Return FAIL when this is not possible.
5137 */
5138 int
5139term_swap_diff()
5140{
5141 term_T *term = curbuf->b_term;
5142 linenr_T line_count;
5143 linenr_T top_rows;
5144 linenr_T bot_rows;
5145 linenr_T bot_start;
5146 linenr_T lnum;
5147 char_u *p;
5148 sb_line_T *sb_line;
5149
5150 if (term == NULL
5151 || !term_is_finished(curbuf)
5152 || term->tl_top_diff_rows == 0
5153 || term->tl_scrollback.ga_len == 0)
5154 return FAIL;
5155
5156 line_count = curbuf->b_ml.ml_line_count;
5157 top_rows = term->tl_top_diff_rows;
5158 bot_rows = term->tl_bot_diff_rows;
5159 bot_start = line_count - bot_rows;
5160 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5161
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005162 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005163 for (lnum = 1; lnum <= top_rows; ++lnum)
5164 {
5165 p = vim_strsave(ml_get(1));
5166 if (p == NULL)
5167 return OK;
5168 ml_append(bot_start, p, 0, FALSE);
5169 ml_delete(1, FALSE);
5170 vim_free(p);
5171 }
5172
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005173 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005174 for (lnum = 1; lnum <= bot_rows; ++lnum)
5175 {
5176 p = vim_strsave(ml_get(bot_start + lnum));
5177 if (p == NULL)
5178 return OK;
5179 ml_delete(bot_start + lnum, FALSE);
5180 ml_append(lnum - 1, p, 0, FALSE);
5181 vim_free(p);
5182 }
5183
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005184 // move top title to bottom
5185 p = vim_strsave(ml_get(bot_rows + 1));
5186 if (p == NULL)
5187 return OK;
5188 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5189 ml_delete(bot_rows + 1, FALSE);
5190 vim_free(p);
5191
5192 // move bottom title to top
5193 p = vim_strsave(ml_get(line_count - top_rows));
5194 if (p == NULL)
5195 return OK;
5196 ml_delete(line_count - top_rows, FALSE);
5197 ml_append(bot_rows, p, 0, FALSE);
5198 vim_free(p);
5199
Bram Moolenaard96ff162018-02-18 22:13:29 +01005200 if (top_rows == bot_rows)
5201 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005202 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005203 for (lnum = 0; lnum < top_rows; ++lnum)
5204 {
5205 sb_line_T temp;
5206
5207 temp = *(sb_line + lnum);
5208 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5209 *(sb_line + bot_start + lnum) = temp;
5210 }
5211 }
5212 else
5213 {
5214 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005215 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005216
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005217 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005218 if (temp != NULL)
5219 {
5220 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5221 mch_memmove(term->tl_scrollback.ga_data,
5222 temp + bot_start,
5223 sizeof(sb_line_T) * bot_rows);
5224 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5225 temp + top_rows,
5226 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5227 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5228 + line_count - top_rows,
5229 temp,
5230 sizeof(sb_line_T) * top_rows);
5231 vim_free(temp);
5232 }
5233 }
5234
5235 term->tl_top_diff_rows = bot_rows;
5236 term->tl_bot_diff_rows = top_rows;
5237
5238 update_screen(NOT_VALID);
5239 return OK;
5240}
5241
5242/*
5243 * "term_dumpdiff(filename, filename, options)" function
5244 */
5245 void
5246f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5247{
5248 term_load_dump(argvars, rettv, TRUE);
5249}
5250
5251/*
5252 * "term_dumpload(filename, options)" function
5253 */
5254 void
5255f_term_dumpload(typval_T *argvars, typval_T *rettv)
5256{
5257 term_load_dump(argvars, rettv, FALSE);
5258}
5259
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005260/*
5261 * "term_getaltscreen(buf)" function
5262 */
5263 void
5264f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5265{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005266 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005267
5268 if (buf == NULL)
5269 return;
5270 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5271}
5272
5273/*
5274 * "term_getattr(attr, name)" function
5275 */
5276 void
5277f_term_getattr(typval_T *argvars, typval_T *rettv)
5278{
5279 int attr;
5280 size_t i;
5281 char_u *name;
5282
5283 static struct {
5284 char *name;
5285 int attr;
5286 } attrs[] = {
5287 {"bold", HL_BOLD},
5288 {"italic", HL_ITALIC},
5289 {"underline", HL_UNDERLINE},
5290 {"strike", HL_STRIKETHROUGH},
5291 {"reverse", HL_INVERSE},
5292 };
5293
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005294 attr = tv_get_number(&argvars[0]);
5295 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005296 if (name == NULL)
5297 return;
5298
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005299 if (attr > HL_ALL)
5300 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005301 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5302 if (STRCMP(name, attrs[i].name) == 0)
5303 {
5304 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5305 break;
5306 }
5307}
5308
5309/*
5310 * "term_getcursor(buf)" function
5311 */
5312 void
5313f_term_getcursor(typval_T *argvars, typval_T *rettv)
5314{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005315 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005316 term_T *term;
5317 list_T *l;
5318 dict_T *d;
5319
5320 if (rettv_list_alloc(rettv) == FAIL)
5321 return;
5322 if (buf == NULL)
5323 return;
5324 term = buf->b_term;
5325
5326 l = rettv->vval.v_list;
5327 list_append_number(l, term->tl_cursor_pos.row + 1);
5328 list_append_number(l, term->tl_cursor_pos.col + 1);
5329
5330 d = dict_alloc();
5331 if (d != NULL)
5332 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005333 dict_add_number(d, "visible", term->tl_cursor_visible);
5334 dict_add_number(d, "blink", blink_state_is_inverted()
5335 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5336 dict_add_number(d, "shape", term->tl_cursor_shape);
5337 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005338 list_append_dict(l, d);
5339 }
5340}
5341
5342/*
5343 * "term_getjob(buf)" function
5344 */
5345 void
5346f_term_getjob(typval_T *argvars, typval_T *rettv)
5347{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005348 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005349
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005350 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005351 {
5352 rettv->v_type = VAR_SPECIAL;
5353 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005354 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005355 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005356
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005357 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005358 rettv->vval.v_job = buf->b_term->tl_job;
5359 if (rettv->vval.v_job != NULL)
5360 ++rettv->vval.v_job->jv_refcount;
5361}
5362
5363 static int
5364get_row_number(typval_T *tv, term_T *term)
5365{
5366 if (tv->v_type == VAR_STRING
5367 && tv->vval.v_string != NULL
5368 && STRCMP(tv->vval.v_string, ".") == 0)
5369 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005370 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005371}
5372
5373/*
5374 * "term_getline(buf, row)" function
5375 */
5376 void
5377f_term_getline(typval_T *argvars, typval_T *rettv)
5378{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005379 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005380 term_T *term;
5381 int row;
5382
5383 rettv->v_type = VAR_STRING;
5384 if (buf == NULL)
5385 return;
5386 term = buf->b_term;
5387 row = get_row_number(&argvars[1], term);
5388
5389 if (term->tl_vterm == NULL)
5390 {
5391 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5392
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005393 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005394 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5395 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5396 }
5397 else
5398 {
5399 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5400 VTermRect rect;
5401 int len;
5402 char_u *p;
5403
5404 if (row < 0 || row >= term->tl_rows)
5405 return;
5406 len = term->tl_cols * MB_MAXBYTES + 1;
5407 p = alloc(len);
5408 if (p == NULL)
5409 return;
5410 rettv->vval.v_string = p;
5411
5412 rect.start_col = 0;
5413 rect.end_col = term->tl_cols;
5414 rect.start_row = row;
5415 rect.end_row = row + 1;
5416 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5417 }
5418}
5419
5420/*
5421 * "term_getscrolled(buf)" function
5422 */
5423 void
5424f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5425{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005426 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005427
5428 if (buf == NULL)
5429 return;
5430 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5431}
5432
5433/*
5434 * "term_getsize(buf)" function
5435 */
5436 void
5437f_term_getsize(typval_T *argvars, typval_T *rettv)
5438{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005439 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005440 list_T *l;
5441
5442 if (rettv_list_alloc(rettv) == FAIL)
5443 return;
5444 if (buf == NULL)
5445 return;
5446
5447 l = rettv->vval.v_list;
5448 list_append_number(l, buf->b_term->tl_rows);
5449 list_append_number(l, buf->b_term->tl_cols);
5450}
5451
5452/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005453 * "term_setsize(buf, rows, cols)" function
5454 */
5455 void
5456f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5457{
5458 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5459 term_T *term;
5460 varnumber_T rows, cols;
5461
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005462 if (buf == NULL)
5463 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005464 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005465 return;
5466 }
5467 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005468 return;
5469 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005470 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005471 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005472 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005473 cols = cols <= 0 ? term->tl_cols : cols;
5474 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005475 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02005476
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005477 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02005478 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5479 term_report_winsize(term, term->tl_rows, term->tl_cols);
5480}
5481
5482/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005483 * "term_getstatus(buf)" function
5484 */
5485 void
5486f_term_getstatus(typval_T *argvars, typval_T *rettv)
5487{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005488 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005489 term_T *term;
5490 char_u val[100];
5491
5492 rettv->v_type = VAR_STRING;
5493 if (buf == NULL)
5494 return;
5495 term = buf->b_term;
5496
5497 if (term_job_running(term))
5498 STRCPY(val, "running");
5499 else
5500 STRCPY(val, "finished");
5501 if (term->tl_normal_mode)
5502 STRCAT(val, ",normal");
5503 rettv->vval.v_string = vim_strsave(val);
5504}
5505
5506/*
5507 * "term_gettitle(buf)" function
5508 */
5509 void
5510f_term_gettitle(typval_T *argvars, typval_T *rettv)
5511{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005512 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005513
5514 rettv->v_type = VAR_STRING;
5515 if (buf == NULL)
5516 return;
5517
5518 if (buf->b_term->tl_title != NULL)
5519 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5520}
5521
5522/*
5523 * "term_gettty(buf)" function
5524 */
5525 void
5526f_term_gettty(typval_T *argvars, typval_T *rettv)
5527{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005528 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005529 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005530 int num = 0;
5531
5532 rettv->v_type = VAR_STRING;
5533 if (buf == NULL)
5534 return;
5535 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005536 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005537
5538 switch (num)
5539 {
5540 case 0:
5541 if (buf->b_term->tl_job != NULL)
5542 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005543 break;
5544 case 1:
5545 if (buf->b_term->tl_job != NULL)
5546 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005547 break;
5548 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005549 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005550 return;
5551 }
5552 if (p != NULL)
5553 rettv->vval.v_string = vim_strsave(p);
5554}
5555
5556/*
5557 * "term_list()" function
5558 */
5559 void
5560f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5561{
5562 term_T *tp;
5563 list_T *l;
5564
5565 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5566 return;
5567
5568 l = rettv->vval.v_list;
5569 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5570 if (tp != NULL && tp->tl_buffer != NULL)
5571 if (list_append_number(l,
5572 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5573 return;
5574}
5575
5576/*
5577 * "term_scrape(buf, row)" function
5578 */
5579 void
5580f_term_scrape(typval_T *argvars, typval_T *rettv)
5581{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005582 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005583 VTermScreen *screen = NULL;
5584 VTermPos pos;
5585 list_T *l;
5586 term_T *term;
5587 char_u *p;
5588 sb_line_T *line;
5589
5590 if (rettv_list_alloc(rettv) == FAIL)
5591 return;
5592 if (buf == NULL)
5593 return;
5594 term = buf->b_term;
5595
5596 l = rettv->vval.v_list;
5597 pos.row = get_row_number(&argvars[1], term);
5598
5599 if (term->tl_vterm != NULL)
5600 {
5601 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005602 if (screen == NULL) // can't really happen
5603 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005604 p = NULL;
5605 line = NULL;
5606 }
5607 else
5608 {
5609 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5610
5611 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5612 return;
5613 p = ml_get_buf(buf, lnum + 1, FALSE);
5614 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5615 }
5616
5617 for (pos.col = 0; pos.col < term->tl_cols; )
5618 {
5619 dict_T *dcell;
5620 int width;
5621 VTermScreenCellAttrs attrs;
5622 VTermColor fg, bg;
5623 char_u rgb[8];
5624 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5625 int off = 0;
5626 int i;
5627
5628 if (screen == NULL)
5629 {
5630 cellattr_T *cellattr;
5631 int len;
5632
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005633 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005634 if (pos.col >= line->sb_cols)
5635 break;
5636 cellattr = line->sb_cells + pos.col;
5637 width = cellattr->width;
5638 attrs = cellattr->attrs;
5639 fg = cellattr->fg;
5640 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005641 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005642 mch_memmove(mbs, p, len);
5643 mbs[len] = NUL;
5644 p += len;
5645 }
5646 else
5647 {
5648 VTermScreenCell cell;
5649 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5650 break;
5651 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5652 {
5653 if (cell.chars[i] == 0)
5654 break;
5655 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5656 }
5657 mbs[off] = NUL;
5658 width = cell.width;
5659 attrs = cell.attrs;
5660 fg = cell.fg;
5661 bg = cell.bg;
5662 }
5663 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005664 if (dcell == NULL)
5665 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005666 list_append_dict(l, dcell);
5667
Bram Moolenaare0be1672018-07-08 16:50:37 +02005668 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005669
5670 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5671 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005672 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005673 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5674 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005675 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005676
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005677 dict_add_number(dcell, "attr", cell2attr(NULL, attrs, fg, bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02005678 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005679
5680 ++pos.col;
5681 if (width == 2)
5682 ++pos.col;
5683 }
5684}
5685
5686/*
5687 * "term_sendkeys(buf, keys)" function
5688 */
5689 void
5690f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5691{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005692 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005693 char_u *msg;
5694 term_T *term;
5695
5696 rettv->v_type = VAR_UNKNOWN;
5697 if (buf == NULL)
5698 return;
5699
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005700 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005701 if (msg == NULL)
5702 return;
5703 term = buf->b_term;
5704 if (term->tl_vterm == NULL)
5705 return;
5706
5707 while (*msg != NUL)
5708 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005709 int c;
5710
5711 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5712 {
5713 c = TO_SPECIAL(msg[1], msg[2]);
5714 msg += 3;
5715 }
5716 else
5717 {
5718 c = PTR2CHAR(msg);
5719 msg += MB_CPTR2LEN(msg);
5720 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005721 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005722 }
5723}
5724
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005725#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5726/*
5727 * "term_getansicolors(buf)" function
5728 */
5729 void
5730f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5731{
5732 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5733 term_T *term;
5734 VTermState *state;
5735 VTermColor color;
5736 char_u hexbuf[10];
5737 int index;
5738 list_T *list;
5739
5740 if (rettv_list_alloc(rettv) == FAIL)
5741 return;
5742
5743 if (buf == NULL)
5744 return;
5745 term = buf->b_term;
5746 if (term->tl_vterm == NULL)
5747 return;
5748
5749 list = rettv->vval.v_list;
5750 state = vterm_obtain_state(term->tl_vterm);
5751 for (index = 0; index < 16; index++)
5752 {
5753 vterm_state_get_palette_color(state, index, &color);
5754 sprintf((char *)hexbuf, "#%02x%02x%02x",
5755 color.red, color.green, color.blue);
5756 if (list_append_string(list, hexbuf, 7) == FAIL)
5757 return;
5758 }
5759}
5760
5761/*
5762 * "term_setansicolors(buf, list)" function
5763 */
5764 void
5765f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5766{
5767 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5768 term_T *term;
5769
5770 if (buf == NULL)
5771 return;
5772 term = buf->b_term;
5773 if (term->tl_vterm == NULL)
5774 return;
5775
5776 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5777 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005778 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005779 return;
5780 }
5781
5782 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005783 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005784}
5785#endif
5786
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005787/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005788 * "term_setapi(buf, api)" function
5789 */
5790 void
5791f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5792{
5793 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5794 term_T *term;
5795 char_u *api;
5796
5797 if (buf == NULL)
5798 return;
5799 term = buf->b_term;
5800 vim_free(term->tl_api);
5801 api = tv_get_string_chk(&argvars[1]);
5802 if (api != NULL)
5803 term->tl_api = vim_strsave(api);
5804 else
5805 term->tl_api = NULL;
5806}
5807
5808/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005809 * "term_setrestore(buf, command)" function
5810 */
5811 void
5812f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5813{
5814#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005815 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005816 term_T *term;
5817 char_u *cmd;
5818
5819 if (buf == NULL)
5820 return;
5821 term = buf->b_term;
5822 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005823 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005824 if (cmd != NULL)
5825 term->tl_command = vim_strsave(cmd);
5826 else
5827 term->tl_command = NULL;
5828#endif
5829}
5830
5831/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005832 * "term_setkill(buf, how)" function
5833 */
5834 void
5835f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5836{
5837 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5838 term_T *term;
5839 char_u *how;
5840
5841 if (buf == NULL)
5842 return;
5843 term = buf->b_term;
5844 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005845 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005846 if (how != NULL)
5847 term->tl_kill = vim_strsave(how);
5848 else
5849 term->tl_kill = NULL;
5850}
5851
5852/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005853 * "term_start(command, options)" function
5854 */
5855 void
5856f_term_start(typval_T *argvars, typval_T *rettv)
5857{
5858 jobopt_T opt;
5859 buf_T *buf;
5860
5861 init_job_options(&opt);
5862 if (argvars[1].v_type != VAR_UNKNOWN
5863 && get_job_options(&argvars[1], &opt,
5864 JO_TIMEOUT_ALL + JO_STOPONEXIT
5865 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5866 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5867 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5868 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005869 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005870 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005871 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005872 return;
5873
Bram Moolenaar13568252018-03-16 20:46:58 +01005874 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005875
5876 if (buf != NULL && buf->b_term != NULL)
5877 rettv->vval.v_number = buf->b_fnum;
5878}
5879
5880/*
5881 * "term_wait" function
5882 */
5883 void
5884f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5885{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005886 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005887
5888 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005889 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005890 if (buf->b_term->tl_job == NULL)
5891 {
5892 ch_log(NULL, "term_wait(): no job to wait for");
5893 return;
5894 }
5895 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005896 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005897 return;
5898
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005899 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01005900 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005901 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5902 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005903 // The job is dead, keep reading channel I/O until the channel is
5904 // closed. buf->b_term may become NULL if the terminal was closed while
5905 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005906 ch_log(NULL, "term_wait(): waiting for channel to close");
5907 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5908 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005909 term_flush_messages();
5910
Bram Moolenaard45aa552018-05-21 22:50:29 +02005911 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005912 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005913 // If the terminal is closed when the channel is closed the
5914 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01005915 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005916 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005917
5918 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005919 }
5920 else
5921 {
5922 long wait = 10L;
5923
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005924 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005925
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005926 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005927 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005928 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005929 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005930
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005931 // Flushing messages on channels is hopefully sufficient.
5932 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005933 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005934 }
5935}
5936
5937/*
5938 * Called when a channel has sent all the lines to a terminal.
5939 * Send a CTRL-D to mark the end of the text.
5940 */
5941 void
5942term_send_eof(channel_T *ch)
5943{
5944 term_T *term;
5945
5946 for (term = first_term; term != NULL; term = term->tl_next)
5947 if (term->tl_job == ch->ch_job)
5948 {
5949 if (term->tl_eof_chars != NULL)
5950 {
5951 channel_send(ch, PART_IN, term->tl_eof_chars,
5952 (int)STRLEN(term->tl_eof_chars), NULL);
5953 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5954 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005955# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005956 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005957 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005958 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5959# endif
5960 }
5961}
5962
Bram Moolenaar113e1072019-01-20 15:30:40 +01005963#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005964 job_T *
5965term_getjob(term_T *term)
5966{
5967 return term != NULL ? term->tl_job : NULL;
5968}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005969#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005970
Bram Moolenaar4f974752019-02-17 17:44:42 +01005971# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005972
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005973///////////////////////////////////////
5974// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005975#ifdef PROTO
5976typedef int COORD;
5977typedef int DWORD;
5978typedef int HANDLE;
5979typedef int *DWORD_PTR;
5980typedef int HPCON;
5981typedef int HRESULT;
5982typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005983typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005984typedef int PSIZE_T;
5985typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005986typedef int BOOL;
5987# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005988#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005989
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005990HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5991HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5992HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005993BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5994BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5995void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005996
5997 static int
5998dyn_conpty_init(int verbose)
5999{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006000 static HMODULE hKerneldll = NULL;
6001 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006002 static struct
6003 {
6004 char *name;
6005 FARPROC *ptr;
6006 } conpty_entry[] =
6007 {
6008 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6009 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6010 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6011 {"InitializeProcThreadAttributeList",
6012 (FARPROC*)&pInitializeProcThreadAttributeList},
6013 {"UpdateProcThreadAttribute",
6014 (FARPROC*)&pUpdateProcThreadAttribute},
6015 {"DeleteProcThreadAttributeList",
6016 (FARPROC*)&pDeleteProcThreadAttributeList},
6017 {NULL, NULL}
6018 };
6019
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006020 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006021 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006022 if (verbose)
6023 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006024 return FAIL;
6025 }
6026
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006027 // No need to initialize twice.
6028 if (hKerneldll)
6029 return OK;
6030
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006031 hKerneldll = vimLoadLib("kernel32.dll");
6032 for (i = 0; conpty_entry[i].name != NULL
6033 && conpty_entry[i].ptr != NULL; ++i)
6034 {
6035 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6036 conpty_entry[i].name)) == NULL)
6037 {
6038 if (verbose)
6039 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006040 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006041 return FAIL;
6042 }
6043 }
6044
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006045 return OK;
6046}
6047
6048 static int
6049conpty_term_and_job_init(
6050 term_T *term,
6051 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006052 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006053 jobopt_T *opt,
6054 jobopt_T *orig_opt)
6055{
6056 WCHAR *cmd_wchar = NULL;
6057 WCHAR *cmd_wchar_copy = NULL;
6058 WCHAR *cwd_wchar = NULL;
6059 WCHAR *env_wchar = NULL;
6060 channel_T *channel = NULL;
6061 job_T *job = NULL;
6062 HANDLE jo = NULL;
6063 garray_T ga_cmd, ga_env;
6064 char_u *cmd = NULL;
6065 HRESULT hr;
6066 COORD consize;
6067 SIZE_T breq;
6068 PROCESS_INFORMATION proc_info;
6069 HANDLE i_theirs = NULL;
6070 HANDLE o_theirs = NULL;
6071 HANDLE i_ours = NULL;
6072 HANDLE o_ours = NULL;
6073
6074 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6075 ga_init2(&ga_env, (int)sizeof(char*), 20);
6076
6077 if (argvar->v_type == VAR_STRING)
6078 {
6079 cmd = argvar->vval.v_string;
6080 }
6081 else if (argvar->v_type == VAR_LIST)
6082 {
6083 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6084 goto failed;
6085 cmd = ga_cmd.ga_data;
6086 }
6087 if (cmd == NULL || *cmd == NUL)
6088 {
6089 emsg(_(e_invarg));
6090 goto failed;
6091 }
6092
6093 term->tl_arg0_cmd = vim_strsave(cmd);
6094
6095 cmd_wchar = enc_to_utf16(cmd, NULL);
6096
6097 if (cmd_wchar != NULL)
6098 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006099 // Request by CreateProcessW
6100 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006101 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006102 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6103 }
6104
6105 ga_clear(&ga_cmd);
6106 if (cmd_wchar == NULL)
6107 goto failed;
6108 if (opt->jo_cwd != NULL)
6109 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6110
6111 win32_build_env(opt->jo_env, &ga_env, TRUE);
6112 env_wchar = ga_env.ga_data;
6113
6114 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6115 goto failed;
6116 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6117 goto failed;
6118
6119 consize.X = term->tl_cols;
6120 consize.Y = term->tl_rows;
6121 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6122 &term->tl_conpty);
6123 if (FAILED(hr))
6124 goto failed;
6125
6126 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6127
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006128 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006129 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006130 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006131 if (!term->tl_siex.lpAttributeList)
6132 goto failed;
6133 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6134 0, &breq))
6135 goto failed;
6136 if (!pUpdateProcThreadAttribute(
6137 term->tl_siex.lpAttributeList, 0,
6138 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6139 sizeof(HPCON), NULL, NULL))
6140 goto failed;
6141
6142 channel = add_channel();
6143 if (channel == NULL)
6144 goto failed;
6145
6146 job = job_alloc();
6147 if (job == NULL)
6148 goto failed;
6149 if (argvar->v_type == VAR_STRING)
6150 {
6151 int argc;
6152
6153 build_argv_from_string(cmd, &job->jv_argv, &argc);
6154 }
6155 else
6156 {
6157 int argc;
6158
6159 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6160 }
6161
6162 if (opt->jo_set & JO_IN_BUF)
6163 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6164
6165 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6166 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
6167 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
6168 | CREATE_DEFAULT_ERROR_MODE,
6169 env_wchar, cwd_wchar,
6170 &term->tl_siex.StartupInfo, &proc_info))
6171 goto failed;
6172
6173 CloseHandle(i_theirs);
6174 CloseHandle(o_theirs);
6175
6176 channel_set_pipes(channel,
6177 (sock_T)i_ours,
6178 (sock_T)o_ours,
6179 (sock_T)o_ours);
6180
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006181 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006182 channel->ch_write_text_mode = TRUE;
6183
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006184 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006185 channel->ch_anonymous_pipe = TRUE;
6186
6187 jo = CreateJobObject(NULL, NULL);
6188 if (jo == NULL)
6189 goto failed;
6190
6191 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6192 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006193 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006194 CloseHandle(jo);
6195 jo = NULL;
6196 }
6197
6198 ResumeThread(proc_info.hThread);
6199 CloseHandle(proc_info.hThread);
6200
6201 vim_free(cmd_wchar);
6202 vim_free(cmd_wchar_copy);
6203 vim_free(cwd_wchar);
6204 vim_free(env_wchar);
6205
6206 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6207 goto failed;
6208
6209#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6210 if (opt->jo_set2 & JO2_ANSI_COLORS)
6211 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6212 else
6213 init_vterm_ansi_colors(term->tl_vterm);
6214#endif
6215
6216 channel_set_job(channel, job, opt);
6217 job_set_options(job, opt);
6218
6219 job->jv_channel = channel;
6220 job->jv_proc_info = proc_info;
6221 job->jv_job_object = jo;
6222 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006223 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006224 ++job->jv_refcount;
6225 term->tl_job = job;
6226
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006227 // Redirecting stdout and stderr doesn't work at the job level. Instead
6228 // open the file here and handle it in. opt->jo_io was changed in
6229 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006230 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6231 {
6232 char_u *fname = opt->jo_io_name[PART_OUT];
6233
6234 ch_log(channel, "Opening output file %s", fname);
6235 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6236 if (term->tl_out_fd == NULL)
6237 semsg(_(e_notopen), fname);
6238 }
6239
6240 return OK;
6241
6242failed:
6243 ga_clear(&ga_cmd);
6244 ga_clear(&ga_env);
6245 vim_free(cmd_wchar);
6246 vim_free(cmd_wchar_copy);
6247 vim_free(cwd_wchar);
6248 if (channel != NULL)
6249 channel_clear(channel);
6250 if (job != NULL)
6251 {
6252 job->jv_channel = NULL;
6253 job_cleanup(job);
6254 }
6255 term->tl_job = NULL;
6256 if (jo != NULL)
6257 CloseHandle(jo);
6258
6259 if (term->tl_siex.lpAttributeList != NULL)
6260 {
6261 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6262 vim_free(term->tl_siex.lpAttributeList);
6263 }
6264 term->tl_siex.lpAttributeList = NULL;
6265 if (o_theirs != NULL)
6266 CloseHandle(o_theirs);
6267 if (o_ours != NULL)
6268 CloseHandle(o_ours);
6269 if (i_ours != NULL)
6270 CloseHandle(i_ours);
6271 if (i_theirs != NULL)
6272 CloseHandle(i_theirs);
6273 if (term->tl_conpty != NULL)
6274 pClosePseudoConsole(term->tl_conpty);
6275 term->tl_conpty = NULL;
6276 return FAIL;
6277}
6278
6279 static void
6280conpty_term_report_winsize(term_T *term, int rows, int cols)
6281{
6282 COORD consize;
6283
6284 consize.X = cols;
6285 consize.Y = rows;
6286 pResizePseudoConsole(term->tl_conpty, consize);
6287}
6288
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006289 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006290term_free_conpty(term_T *term)
6291{
6292 if (term->tl_siex.lpAttributeList != NULL)
6293 {
6294 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6295 vim_free(term->tl_siex.lpAttributeList);
6296 }
6297 term->tl_siex.lpAttributeList = NULL;
6298 if (term->tl_conpty != NULL)
6299 pClosePseudoConsole(term->tl_conpty);
6300 term->tl_conpty = NULL;
6301}
6302
6303 int
6304use_conpty(void)
6305{
6306 return has_conpty;
6307}
6308
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006309# ifndef PROTO
6310
6311#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6312#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006313#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006314
6315void* (*winpty_config_new)(UINT64, void*);
6316void* (*winpty_open)(void*, void*);
6317void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6318BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6319void (*winpty_config_set_mouse_mode)(void*, int);
6320void (*winpty_config_set_initial_size)(void*, int, int);
6321LPCWSTR (*winpty_conin_name)(void*);
6322LPCWSTR (*winpty_conout_name)(void*);
6323LPCWSTR (*winpty_conerr_name)(void*);
6324void (*winpty_free)(void*);
6325void (*winpty_config_free)(void*);
6326void (*winpty_spawn_config_free)(void*);
6327void (*winpty_error_free)(void*);
6328LPCWSTR (*winpty_error_msg)(void*);
6329BOOL (*winpty_set_size)(void*, int, int, void*);
6330HANDLE (*winpty_agent_process)(void*);
6331
6332#define WINPTY_DLL "winpty.dll"
6333
6334static HINSTANCE hWinPtyDLL = NULL;
6335# endif
6336
6337 static int
6338dyn_winpty_init(int verbose)
6339{
6340 int i;
6341 static struct
6342 {
6343 char *name;
6344 FARPROC *ptr;
6345 } winpty_entry[] =
6346 {
6347 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6348 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6349 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6350 {"winpty_config_set_mouse_mode",
6351 (FARPROC*)&winpty_config_set_mouse_mode},
6352 {"winpty_config_set_initial_size",
6353 (FARPROC*)&winpty_config_set_initial_size},
6354 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6355 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6356 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6357 {"winpty_free", (FARPROC*)&winpty_free},
6358 {"winpty_open", (FARPROC*)&winpty_open},
6359 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6360 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6361 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6362 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6363 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6364 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6365 {NULL, NULL}
6366 };
6367
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006368 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006369 if (hWinPtyDLL)
6370 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006371 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6372 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006373 if (*p_winptydll != NUL)
6374 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6375 if (!hWinPtyDLL)
6376 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6377 if (!hWinPtyDLL)
6378 {
6379 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006380 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006381 : (char_u *)WINPTY_DLL);
6382 return FAIL;
6383 }
6384 for (i = 0; winpty_entry[i].name != NULL
6385 && winpty_entry[i].ptr != NULL; ++i)
6386 {
6387 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6388 winpty_entry[i].name)) == NULL)
6389 {
6390 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006391 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006392 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006393 return FAIL;
6394 }
6395 }
6396
6397 return OK;
6398}
6399
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006400 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006401winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006402 term_T *term,
6403 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006404 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006405 jobopt_T *opt,
6406 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006407{
6408 WCHAR *cmd_wchar = NULL;
6409 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006410 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006411 channel_T *channel = NULL;
6412 job_T *job = NULL;
6413 DWORD error;
6414 HANDLE jo = NULL;
6415 HANDLE child_process_handle;
6416 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006417 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006418 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006419 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006420 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006421
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006422 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6423 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006424
6425 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006426 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006427 cmd = argvar->vval.v_string;
6428 }
6429 else if (argvar->v_type == VAR_LIST)
6430 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006431 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006432 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006433 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006434 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006435 if (cmd == NULL || *cmd == NUL)
6436 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006437 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006438 goto failed;
6439 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006440
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006441 term->tl_arg0_cmd = vim_strsave(cmd);
6442
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006443 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006444 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006445 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006446 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006447 if (opt->jo_cwd != NULL)
6448 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006449
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006450 win32_build_env(opt->jo_env, &ga_env, TRUE);
6451 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006452
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006453 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6454 if (term->tl_winpty_config == NULL)
6455 goto failed;
6456
6457 winpty_config_set_mouse_mode(term->tl_winpty_config,
6458 WINPTY_MOUSE_MODE_FORCE);
6459 winpty_config_set_initial_size(term->tl_winpty_config,
6460 term->tl_cols, term->tl_rows);
6461 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6462 if (term->tl_winpty == NULL)
6463 goto failed;
6464
6465 spawn_config = winpty_spawn_config_new(
6466 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6467 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6468 NULL,
6469 cmd_wchar,
6470 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006471 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006472 &winpty_err);
6473 if (spawn_config == NULL)
6474 goto failed;
6475
6476 channel = add_channel();
6477 if (channel == NULL)
6478 goto failed;
6479
6480 job = job_alloc();
6481 if (job == NULL)
6482 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006483 if (argvar->v_type == VAR_STRING)
6484 {
6485 int argc;
6486
6487 build_argv_from_string(cmd, &job->jv_argv, &argc);
6488 }
6489 else
6490 {
6491 int argc;
6492
6493 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6494 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006495
6496 if (opt->jo_set & JO_IN_BUF)
6497 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6498
6499 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6500 &child_thread_handle, &error, &winpty_err))
6501 goto failed;
6502
6503 channel_set_pipes(channel,
6504 (sock_T)CreateFileW(
6505 winpty_conin_name(term->tl_winpty),
6506 GENERIC_WRITE, 0, NULL,
6507 OPEN_EXISTING, 0, NULL),
6508 (sock_T)CreateFileW(
6509 winpty_conout_name(term->tl_winpty),
6510 GENERIC_READ, 0, NULL,
6511 OPEN_EXISTING, 0, NULL),
6512 (sock_T)CreateFileW(
6513 winpty_conerr_name(term->tl_winpty),
6514 GENERIC_READ, 0, NULL,
6515 OPEN_EXISTING, 0, NULL));
6516
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006517 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006518 channel->ch_write_text_mode = TRUE;
6519
6520 jo = CreateJobObject(NULL, NULL);
6521 if (jo == NULL)
6522 goto failed;
6523
6524 if (!AssignProcessToJobObject(jo, child_process_handle))
6525 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006526 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006527 CloseHandle(jo);
6528 jo = NULL;
6529 }
6530
6531 winpty_spawn_config_free(spawn_config);
6532 vim_free(cmd_wchar);
6533 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006534 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006535
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006536 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6537 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006538
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006539#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6540 if (opt->jo_set2 & JO2_ANSI_COLORS)
6541 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6542 else
6543 init_vterm_ansi_colors(term->tl_vterm);
6544#endif
6545
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006546 channel_set_job(channel, job, opt);
6547 job_set_options(job, opt);
6548
6549 job->jv_channel = channel;
6550 job->jv_proc_info.hProcess = child_process_handle;
6551 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6552 job->jv_job_object = jo;
6553 job->jv_status = JOB_STARTED;
6554 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006555 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006556 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006557 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006558 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006559 ++job->jv_refcount;
6560 term->tl_job = job;
6561
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006562 // Redirecting stdout and stderr doesn't work at the job level. Instead
6563 // open the file here and handle it in. opt->jo_io was changed in
6564 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006565 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6566 {
6567 char_u *fname = opt->jo_io_name[PART_OUT];
6568
6569 ch_log(channel, "Opening output file %s", fname);
6570 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6571 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006572 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006573 }
6574
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006575 return OK;
6576
6577failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006578 ga_clear(&ga_cmd);
6579 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006580 vim_free(cmd_wchar);
6581 vim_free(cwd_wchar);
6582 if (spawn_config != NULL)
6583 winpty_spawn_config_free(spawn_config);
6584 if (channel != NULL)
6585 channel_clear(channel);
6586 if (job != NULL)
6587 {
6588 job->jv_channel = NULL;
6589 job_cleanup(job);
6590 }
6591 term->tl_job = NULL;
6592 if (jo != NULL)
6593 CloseHandle(jo);
6594 if (term->tl_winpty != NULL)
6595 winpty_free(term->tl_winpty);
6596 term->tl_winpty = NULL;
6597 if (term->tl_winpty_config != NULL)
6598 winpty_config_free(term->tl_winpty_config);
6599 term->tl_winpty_config = NULL;
6600 if (winpty_err != NULL)
6601 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006602 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006603 (short_u *)winpty_error_msg(winpty_err), NULL);
6604
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006605 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006606 winpty_error_free(winpty_err);
6607 }
6608 return FAIL;
6609}
6610
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006611/*
6612 * Create a new terminal of "rows" by "cols" cells.
6613 * Store a reference in "term".
6614 * Return OK or FAIL.
6615 */
6616 static int
6617term_and_job_init(
6618 term_T *term,
6619 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01006620 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006621 jobopt_T *opt,
6622 jobopt_T *orig_opt)
6623{
6624 int use_winpty = FALSE;
6625 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006626 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006627
6628 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6629 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6630
6631 if (!has_winpty && !has_conpty)
6632 // If neither is available give the errors for winpty, since when
6633 // conpty is not available it can't be installed either.
6634 return dyn_winpty_init(TRUE);
6635
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006636 if (opt->jo_tty_type != NUL)
6637 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006638
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006639 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006640 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006641 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006642 use_conpty = TRUE;
6643 else if (has_winpty)
6644 use_winpty = TRUE;
6645 // else: error
6646 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006647 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006648 {
6649 if (has_winpty)
6650 use_winpty = TRUE;
6651 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006652 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006653 {
6654 if (has_conpty)
6655 use_conpty = TRUE;
6656 else
6657 return dyn_conpty_init(TRUE);
6658 }
6659
6660 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006661 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006662
6663 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006664 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006665
6666 // error
6667 return dyn_winpty_init(TRUE);
6668}
6669
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006670 static int
6671create_pty_only(term_T *term, jobopt_T *options)
6672{
6673 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6674 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6675 char in_name[80], out_name[80];
6676 channel_T *channel = NULL;
6677
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006678 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6679 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006680
6681 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6682 GetCurrentProcessId(),
6683 curbuf->b_fnum);
6684 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6685 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6686 PIPE_UNLIMITED_INSTANCES,
6687 0, 0, NMPWAIT_NOWAIT, NULL);
6688 if (hPipeIn == INVALID_HANDLE_VALUE)
6689 goto failed;
6690
6691 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6692 GetCurrentProcessId(),
6693 curbuf->b_fnum);
6694 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6695 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6696 PIPE_UNLIMITED_INSTANCES,
6697 0, 0, 0, NULL);
6698 if (hPipeOut == INVALID_HANDLE_VALUE)
6699 goto failed;
6700
6701 ConnectNamedPipe(hPipeIn, NULL);
6702 ConnectNamedPipe(hPipeOut, NULL);
6703
6704 term->tl_job = job_alloc();
6705 if (term->tl_job == NULL)
6706 goto failed;
6707 ++term->tl_job->jv_refcount;
6708
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006709 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006710 term->tl_job->jv_status = JOB_FINISHED;
6711
6712 channel = add_channel();
6713 if (channel == NULL)
6714 goto failed;
6715 term->tl_job->jv_channel = channel;
6716 channel->ch_keep_open = TRUE;
6717 channel->ch_named_pipe = TRUE;
6718
6719 channel_set_pipes(channel,
6720 (sock_T)hPipeIn,
6721 (sock_T)hPipeOut,
6722 (sock_T)hPipeOut);
6723 channel_set_job(channel, term->tl_job, options);
6724 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6725 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6726
6727 return OK;
6728
6729failed:
6730 if (hPipeIn != NULL)
6731 CloseHandle(hPipeIn);
6732 if (hPipeOut != NULL)
6733 CloseHandle(hPipeOut);
6734 return FAIL;
6735}
6736
6737/*
6738 * Free the terminal emulator part of "term".
6739 */
6740 static void
6741term_free_vterm(term_T *term)
6742{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006743 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006744 if (term->tl_winpty != NULL)
6745 winpty_free(term->tl_winpty);
6746 term->tl_winpty = NULL;
6747 if (term->tl_winpty_config != NULL)
6748 winpty_config_free(term->tl_winpty_config);
6749 term->tl_winpty_config = NULL;
6750 if (term->tl_vterm != NULL)
6751 vterm_free(term->tl_vterm);
6752 term->tl_vterm = NULL;
6753}
6754
6755/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006756 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006757 */
6758 static void
6759term_report_winsize(term_T *term, int rows, int cols)
6760{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006761 if (term->tl_conpty)
6762 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006763 if (term->tl_winpty)
6764 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6765}
6766
6767 int
6768terminal_enabled(void)
6769{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006770 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006771}
6772
6773# else
6774
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006775///////////////////////////////////////
6776// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006777
6778/*
6779 * Create a new terminal of "rows" by "cols" cells.
6780 * Start job for "cmd".
6781 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006782 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006783 * Return OK or FAIL.
6784 */
6785 static int
6786term_and_job_init(
6787 term_T *term,
6788 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006789 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006790 jobopt_T *opt,
6791 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006792{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006793 term->tl_arg0_cmd = NULL;
6794
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006795 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6796 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006797
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006798#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6799 if (opt->jo_set2 & JO2_ANSI_COLORS)
6800 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6801 else
6802 init_vterm_ansi_colors(term->tl_vterm);
6803#endif
6804
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006805 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01006806 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006807 if (term->tl_job != NULL)
6808 ++term->tl_job->jv_refcount;
6809
6810 return term->tl_job != NULL
6811 && term->tl_job->jv_channel != NULL
6812 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6813}
6814
6815 static int
6816create_pty_only(term_T *term, jobopt_T *opt)
6817{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006818 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6819 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006820
6821 term->tl_job = job_alloc();
6822 if (term->tl_job == NULL)
6823 return FAIL;
6824 ++term->tl_job->jv_refcount;
6825
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006826 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006827 term->tl_job->jv_status = JOB_FINISHED;
6828
6829 return mch_create_pty_channel(term->tl_job, opt);
6830}
6831
6832/*
6833 * Free the terminal emulator part of "term".
6834 */
6835 static void
6836term_free_vterm(term_T *term)
6837{
6838 if (term->tl_vterm != NULL)
6839 vterm_free(term->tl_vterm);
6840 term->tl_vterm = NULL;
6841}
6842
6843/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006844 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006845 */
6846 static void
6847term_report_winsize(term_T *term, int rows, int cols)
6848{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006849 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006850 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6851 {
6852 int fd = -1;
6853 int part;
6854
6855 for (part = PART_OUT; part < PART_COUNT; ++part)
6856 {
6857 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006858 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006859 break;
6860 }
6861 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6862 mch_signal_job(term->tl_job, (char_u *)"winch");
6863 }
6864}
6865
6866# endif
6867
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006868#endif // FEAT_TERMINAL