blob: 638c27ea65f4db2a9ba9f2bf63fb9321c63c19c3 [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 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100385 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100386
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100387 // Wiping out the buffer will also close the window and call
388 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100389 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
390}
391
392/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200393 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100394 * Use either "argvar" or "argv", the other must be NULL.
395 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
396 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200397 * Returns NULL when failed.
398 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100399 buf_T *
400term_start(
401 typval_T *argvar,
402 char **argv,
403 jobopt_T *opt,
404 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200405{
406 exarg_T split_ea;
407 win_T *old_curwin = curwin;
408 term_T *term;
409 buf_T *old_curbuf = NULL;
410 int res;
411 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100412 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200413 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200414
415 if (check_restricted() || check_secure())
416 return NULL;
417
418 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
419 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
420 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100421 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
422 || (argvar != NULL
423 && argvar->v_type == VAR_LIST
424 && argvar->vval.v_list != NULL
425 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200426 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100427 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 return NULL;
429 }
430
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200431 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200432 if (term == NULL)
433 return NULL;
434 term->tl_dirty_row_end = MAX_ROW;
435 term->tl_cursor_visible = TRUE;
436 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
437 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100438#ifdef FEAT_GUI
439 term->tl_system = (flags & TERM_START_SYSTEM);
440#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200441 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100442 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200443
444 vim_memset(&split_ea, 0, sizeof(split_ea));
445 if (opt->jo_curwin)
446 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100447 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100448 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200449 {
450 no_write_message();
451 vim_free(term);
452 return NULL;
453 }
454 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100455 ECMD_HIDE
456 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
457 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200458 {
459 vim_free(term);
460 return NULL;
461 }
462 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100463 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200464 {
465 buf_T *buf;
466
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100467 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100468 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200469 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
470 BLN_NEW | BLN_LISTED);
471 if (buf == NULL || ml_open(buf) == FAIL)
472 {
473 vim_free(term);
474 return NULL;
475 }
476 old_curbuf = curbuf;
477 --curbuf->b_nwindows;
478 curbuf = buf;
479 curwin->w_buffer = buf;
480 ++curbuf->b_nwindows;
481 }
482 else
483 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100484 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200485 split_ea.cmdidx = CMD_new;
486 split_ea.cmd = (char_u *)"new";
487 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100488 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200489 {
490 split_ea.line2 = opt->jo_term_rows;
491 split_ea.addr_count = 1;
492 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100493 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200494 {
495 split_ea.line2 = opt->jo_term_cols;
496 split_ea.addr_count = 1;
497 }
498
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100499 if (vertical)
500 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200501 ex_splitview(&split_ea);
502 if (curwin == old_curwin)
503 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100504 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200505 vim_free(term);
506 return NULL;
507 }
508 }
509 term->tl_buffer = curbuf;
510 curbuf->b_term = term;
511
512 if (!opt->jo_hidden)
513 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100514 // Only one size was taken care of with :new, do the other one. With
515 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100516 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200517 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100518 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200519 win_setwidth(opt->jo_term_cols);
520 }
521
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100522 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200523 term->tl_next = first_term;
524 first_term = term;
525
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100526 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
527
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200528 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100529 {
530 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200531 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100532 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100533 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100534 {
535 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100536 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100537 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200538 else
539 {
540 int i;
541 size_t len;
542 char_u *cmd, *p;
543
544 if (argvar->v_type == VAR_STRING)
545 {
546 cmd = argvar->vval.v_string;
547 if (cmd == NULL)
548 cmd = (char_u *)"";
549 else if (STRCMP(cmd, "NONE") == 0)
550 cmd = (char_u *)"pty";
551 }
552 else if (argvar->v_type != VAR_LIST
553 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100554 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100555 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200556 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
557 cmd = (char_u*)"";
558
559 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200560 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200561
562 for (i = 0; p != NULL; ++i)
563 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100564 // Prepend a ! to the command name to avoid the buffer name equals
565 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200566 if (i == 0)
567 vim_snprintf((char *)p, len, "!%s", cmd);
568 else
569 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
570 if (buflist_findname(p) == NULL)
571 {
572 vim_free(curbuf->b_ffname);
573 curbuf->b_ffname = p;
574 break;
575 }
576 }
577 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100578 vim_free(curbuf->b_sfname);
579 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200580 curbuf->b_fname = curbuf->b_ffname;
581
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100582 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
583
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200584 if (opt->jo_term_opencmd != NULL)
585 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
586
587 if (opt->jo_eof_chars != NULL)
588 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
589
590 set_string_option_direct((char_u *)"buftype", -1,
591 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200592 // Avoid that 'buftype' is reset when this buffer is entered.
593 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200594
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100595 // Mark the buffer as not modifiable. It can only be made modifiable after
596 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200597 curbuf->b_p_ma = FALSE;
598
599 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100600#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200601 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
602#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200603 setup_job_options(opt, term->tl_rows, term->tl_cols);
604
Bram Moolenaar13568252018-03-16 20:46:58 +0100605 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100606 return curbuf;
607
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100608#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100609 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100610 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100611 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100612 else if (argvar->v_type == VAR_STRING)
613 {
614 char_u *cmd = argvar->vval.v_string;
615
616 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
617 term->tl_command = vim_strsave(cmd);
618 }
619 else if (argvar->v_type == VAR_LIST
620 && argvar->vval.v_list != NULL
621 && argvar->vval.v_list->lv_len > 0)
622 {
623 garray_T ga;
624 listitem_T *item;
625
626 ga_init2(&ga, 1, 100);
627 for (item = argvar->vval.v_list->lv_first;
628 item != NULL; item = item->li_next)
629 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100630 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100631 char_u *p;
632
633 if (s == NULL)
634 break;
635 p = vim_strsave_fnameescape(s, FALSE);
636 if (p == NULL)
637 break;
638 ga_concat(&ga, p);
639 vim_free(p);
640 ga_append(&ga, ' ');
641 }
642 if (item == NULL)
643 {
644 ga_append(&ga, NUL);
645 term->tl_command = ga.ga_data;
646 }
647 else
648 ga_clear(&ga);
649 }
650#endif
651
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100652 if (opt->jo_term_kill != NULL)
653 {
654 char_u *p = skiptowhite(opt->jo_term_kill);
655
656 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
657 }
658
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200659 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100660 {
661 char_u *p = skiptowhite(opt->jo_term_api);
662
663 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
664 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200665 else
666 term->tl_api = vim_strsave((char_u *)"Tapi_");
667
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100668 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100669 if (argv == NULL
670 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200671 && argvar->vval.v_string != NULL
672 && STRCMP(argvar->vval.v_string, "NONE") == 0)
673 res = create_pty_only(term, opt);
674 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200675 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200676
677 newbuf = curbuf;
678 if (res == OK)
679 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100680 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200681 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
682 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100683#ifdef FEAT_GUI
684 if (term->tl_system)
685 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100686 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100687 term->tl_toprow = msg_row + 1;
688 term->tl_dirty_row_end = 0;
689 }
690#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200691
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100692 // Make sure we don't get stuck on sending keys to the job, it leads to
693 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200694 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
695
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200696 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200697 {
698 --curbuf->b_nwindows;
699 curbuf = old_curbuf;
700 curwin->w_buffer = curbuf;
701 ++curbuf->b_nwindows;
702 }
703 }
704 else
705 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100706 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200707 return NULL;
708 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100709
Bram Moolenaar13568252018-03-16 20:46:58 +0100710 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200711 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
712 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200713 return newbuf;
714}
715
716/*
717 * ":terminal": open a terminal window and execute a job in it.
718 */
719 void
720ex_terminal(exarg_T *eap)
721{
722 typval_T argvar[2];
723 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100724 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200725 char_u *cmd;
726 char_u *tofree = NULL;
727
728 init_job_options(&opt);
729
730 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100731 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200732 {
733 char_u *p, *ep;
734
735 cmd += 2;
736 p = skiptowhite(cmd);
737 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200738 if (ep != NULL)
739 {
740 if (ep < p)
741 p = ep;
742 else
743 ep = NULL;
744 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200745
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200746# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
747 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
748 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200749 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200750 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100751 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200752 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200753 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200754 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200755 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200756 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200757 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200758 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100759 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100760 else if (OPTARG_HAS("shell"))
761 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200762 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100763 {
764 opt.jo_set2 |= JO2_TERM_KILL;
765 opt.jo_term_kill = ep + 1;
766 p = skiptowhite(cmd);
767 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200768 else if (OPTARG_HAS("api"))
769 {
770 opt.jo_set2 |= JO2_TERM_API;
771 if (ep != NULL)
772 {
773 opt.jo_term_api = ep + 1;
774 p = skiptowhite(cmd);
775 }
776 else
777 opt.jo_term_api = NULL;
778 }
779 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200780 {
781 opt.jo_set2 |= JO2_TERM_ROWS;
782 opt.jo_term_rows = atoi((char *)ep + 1);
783 p = skiptowhite(cmd);
784 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200785 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200786 {
787 opt.jo_set2 |= JO2_TERM_COLS;
788 opt.jo_term_cols = atoi((char *)ep + 1);
789 p = skiptowhite(cmd);
790 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200791 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200792 {
793 char_u *buf = NULL;
794 char_u *keys;
795
Bram Moolenaar21109272020-01-30 16:27:20 +0100796 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200797 p = skiptowhite(cmd);
798 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200799 keys = replace_termcodes(ep + 1, &buf,
800 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200801 opt.jo_set2 |= JO2_EOF_CHARS;
802 opt.jo_eof_chars = vim_strsave(keys);
803 vim_free(buf);
804 *p = ' ';
805 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100806#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100807 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
808 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100809 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100810 int tty_type = NUL;
811
812 p = skiptowhite(cmd);
813 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
814 tty_type = 'w';
815 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
816 tty_type = 'c';
817 else
818 {
819 semsg(e_invargval, "type");
820 goto theend;
821 }
822 opt.jo_set2 |= JO2_TTY_TYPE;
823 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100824 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100825#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200826 else
827 {
828 if (*p)
829 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100830 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100831 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200832 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200833# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200834 cmd = skipwhite(p);
835 }
836 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100837 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100838 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200839 tofree = cmd = vim_strsave(p_sh);
840
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100841 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100842 if (opt.jo_term_finish == NUL)
843 opt.jo_term_finish = 'c';
844 }
845
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200846 if (eap->addr_count > 0)
847 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100848 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200849 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
850 opt.jo_io[PART_IN] = JIO_BUFFER;
851 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
852 opt.jo_in_top = eap->line1;
853 opt.jo_in_bot = eap->line2;
854 }
855
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100856 if (opt_shell && tofree == NULL)
857 {
858#ifdef UNIX
859 char **argv = NULL;
860 char_u *tofree1 = NULL;
861 char_u *tofree2 = NULL;
862
863 // :term ++shell command
864 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
865 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100866 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100867 vim_free(tofree1);
868 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100869 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100870#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100871# ifdef MSWIN
872 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
873 char_u *newcmd;
874
875 newcmd = alloc(cmdlen);
876 if (newcmd == NULL)
877 goto theend;
878 tofree = newcmd;
879 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
880 cmd = newcmd;
881# else
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100882 emsg(_("E279: Sorry, ++shell is not supported on this system"));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100883 goto theend;
884# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100885#endif
886 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100887 argvar[0].v_type = VAR_STRING;
888 argvar[0].vval.v_string = cmd;
889 argvar[1].v_type = VAR_UNKNOWN;
890 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100891
892theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100893 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200894 vim_free(opt.jo_eof_chars);
895}
896
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100897#if defined(FEAT_SESSION) || defined(PROTO)
898/*
899 * Write a :terminal command to the session file to restore the terminal in
900 * window "wp".
901 * Return FAIL if writing fails.
902 */
903 int
904term_write_session(FILE *fd, win_T *wp)
905{
906 term_T *term = wp->w_buffer->b_term;
907
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100908 // Create the terminal and run the command. This is not without
909 // risk, but let's assume the user only creates a session when this
910 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100911 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
912 term->tl_cols, term->tl_rows) < 0)
913 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100914#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100915 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
916 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100917#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100918 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
919 return FAIL;
920
921 return put_eol(fd);
922}
923
924/*
925 * Return TRUE if "buf" has a terminal that should be restored.
926 */
927 int
928term_should_restore(buf_T *buf)
929{
930 term_T *term = buf->b_term;
931
932 return term != NULL && (term->tl_command == NULL
933 || STRCMP(term->tl_command, "NONE") != 0);
934}
935#endif
936
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200937/*
938 * Free the scrollback buffer for "term".
939 */
940 static void
941free_scrollback(term_T *term)
942{
943 int i;
944
945 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
946 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
947 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100948 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
949 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
950 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200951}
952
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100953
954// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200955static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100956
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200957/*
958 * Free a terminal and everything it refers to.
959 * Kills the job if there is one.
960 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100961 * The actual terminal structure is freed later in free_unused_terminals(),
962 * because callbacks may wipe out a buffer while the terminal is still
963 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200964 */
965 void
966free_terminal(buf_T *buf)
967{
968 term_T *term = buf->b_term;
969 term_T *tp;
970
971 if (term == NULL)
972 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100973
974 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200975 if (first_term == term)
976 first_term = term->tl_next;
977 else
978 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
979 if (tp->tl_next == term)
980 {
981 tp->tl_next = term->tl_next;
982 break;
983 }
984
985 if (term->tl_job != NULL)
986 {
987 if (term->tl_job->jv_status != JOB_ENDED
988 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100989 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200990 job_stop(term->tl_job, NULL, "kill");
991 job_unref(term->tl_job);
992 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100993 term->tl_next = terminals_to_free;
994 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200995
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200996 buf->b_term = NULL;
997 if (in_terminal_loop == term)
998 in_terminal_loop = NULL;
999}
1000
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001001 void
1002free_unused_terminals()
1003{
1004 while (terminals_to_free != NULL)
1005 {
1006 term_T *term = terminals_to_free;
1007
1008 terminals_to_free = term->tl_next;
1009
1010 free_scrollback(term);
1011
1012 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001013 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001014 vim_free(term->tl_title);
1015#ifdef FEAT_SESSION
1016 vim_free(term->tl_command);
1017#endif
1018 vim_free(term->tl_kill);
1019 vim_free(term->tl_status_text);
1020 vim_free(term->tl_opencmd);
1021 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001022 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001023#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001024 if (term->tl_out_fd != NULL)
1025 fclose(term->tl_out_fd);
1026#endif
1027 vim_free(term->tl_cursor_color);
1028 vim_free(term);
1029 }
1030}
1031
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001032/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001033 * Get the part that is connected to the tty. Normally this is PART_IN, but
1034 * when writing buffer lines to the job it can be another. This makes it
1035 * possible to do "1,5term vim -".
1036 */
1037 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001038get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001039{
1040#ifdef UNIX
1041 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1042 int i;
1043
1044 for (i = 0; i < 3; ++i)
1045 {
1046 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1047
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001048 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001049 return parts[i];
1050 }
1051#endif
1052 return PART_IN;
1053}
1054
1055/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001056 * Write job output "msg[len]" to the vterm.
1057 */
1058 static void
1059term_write_job_output(term_T *term, char_u *msg, size_t len)
1060{
1061 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001062 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001063
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001064 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001065
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001066 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001067 if (prevlen != vterm_output_get_buffer_current(vterm))
1068 {
1069 char buf[KEY_BUF_LEN];
1070 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1071
1072 if (curlen > 0)
1073 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1074 (char_u *)buf, (int)curlen, NULL);
1075 }
1076
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001077 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001078 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1079}
1080
1081 static void
1082update_cursor(term_T *term, int redraw)
1083{
1084 if (term->tl_normal_mode)
1085 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001086#ifdef FEAT_GUI
1087 if (term->tl_system)
1088 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1089 term->tl_cursor_pos.col);
1090 else
1091#endif
1092 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001093 if (redraw)
1094 {
1095 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1096 cursor_on();
1097 out_flush();
1098#ifdef FEAT_GUI
1099 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001100 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001101 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001102 gui_mch_flush();
1103 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001104#endif
1105 }
1106}
1107
1108/*
1109 * Invoked when "msg" output from a job was received. Write it to the terminal
1110 * of "buffer".
1111 */
1112 void
1113write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1114{
1115 size_t len = STRLEN(msg);
1116 term_T *term = buffer->b_term;
1117
Bram Moolenaar4f974752019-02-17 17:44:42 +01001118#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001119 // Win32: Cannot redirect output of the job, intercept it here and write to
1120 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001121 if (term->tl_out_fd != NULL)
1122 {
1123 ch_log(channel, "Writing %d bytes to output file", (int)len);
1124 fwrite(msg, len, 1, term->tl_out_fd);
1125 return;
1126 }
1127#endif
1128
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001129 if (term->tl_vterm == NULL)
1130 {
1131 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1132 return;
1133 }
1134 ch_log(channel, "writing %d bytes to terminal", (int)len);
1135 term_write_job_output(term, msg, len);
1136
Bram Moolenaar13568252018-03-16 20:46:58 +01001137#ifdef FEAT_GUI
1138 if (term->tl_system)
1139 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001140 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001141 update_system_term(term);
1142 update_cursor(term, TRUE);
1143 }
1144 else
1145#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001146 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1147 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001148 if (!term->tl_normal_mode)
1149 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001150 // Don't use update_screen() when editing the command line, it gets
1151 // cleared.
1152 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001153 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001154 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001155 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001156 update_screen(VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001157 // update_screen() can be slow, check the terminal wasn't closed
1158 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001159 if (buffer == curbuf && curbuf->b_term != NULL)
1160 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001161 }
1162 else
1163 redraw_after_callback(TRUE);
1164 }
1165}
1166
1167/*
1168 * Send a mouse position and click to the vterm
1169 */
1170 static int
1171term_send_mouse(VTerm *vterm, int button, int pressed)
1172{
1173 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001174 int row = mouse_row - W_WINROW(curwin);
1175 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001176
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001177#ifdef FEAT_PROP_POPUP
1178 if (popup_is_popup(curwin))
1179 {
1180 row -= popup_top_extra(curwin);
1181 col -= popup_left_extra(curwin);
1182 }
1183#endif
1184 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001185 if (button != 0)
1186 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001187 return TRUE;
1188}
1189
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001190static int enter_mouse_col = -1;
1191static int enter_mouse_row = -1;
1192
1193/*
1194 * Handle a mouse click, drag or release.
1195 * Return TRUE when a mouse event is sent to the terminal.
1196 */
1197 static int
1198term_mouse_click(VTerm *vterm, int key)
1199{
1200#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001201 // For modeless selection mouse drag and release events are ignored, unless
1202 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001203 static int ignore_drag_release = TRUE;
1204 VTermMouseState mouse_state;
1205
1206 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1207 if (mouse_state.flags == 0)
1208 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001209 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001210 switch (key)
1211 {
1212 case K_LEFTDRAG:
1213 case K_LEFTRELEASE:
1214 case K_RIGHTDRAG:
1215 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001216 // Ignore drag and release events when the button-down wasn't
1217 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001218 if (ignore_drag_release)
1219 {
1220 int save_mouse_col, save_mouse_row;
1221
1222 if (enter_mouse_col < 0)
1223 break;
1224
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001225 // mouse click in the window gave us focus, handle that
1226 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001227 save_mouse_col = mouse_col;
1228 save_mouse_row = mouse_row;
1229 mouse_col = enter_mouse_col;
1230 mouse_row = enter_mouse_row;
1231 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1232 mouse_col = save_mouse_col;
1233 mouse_row = save_mouse_row;
1234 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001235 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001236 case K_LEFTMOUSE:
1237 case K_RIGHTMOUSE:
1238 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1239 ignore_drag_release = TRUE;
1240 else
1241 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001242 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001243 if (clip_star.available)
1244 {
1245 int button, is_click, is_drag;
1246
1247 button = get_mouse_button(KEY2TERMCAP1(key),
1248 &is_click, &is_drag);
1249 if (mouse_model_popup() && button == MOUSE_LEFT
1250 && (mod_mask & MOD_MASK_SHIFT))
1251 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001252 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001253 button = MOUSE_RIGHT;
1254 mod_mask &= ~MOD_MASK_SHIFT;
1255 }
1256 clip_modeless(button, is_click, is_drag);
1257 }
1258 break;
1259
1260 case K_MIDDLEMOUSE:
1261 if (clip_star.available)
1262 insert_reg('*', TRUE);
1263 break;
1264 }
1265 enter_mouse_col = -1;
1266 return FALSE;
1267 }
1268#endif
1269 enter_mouse_col = -1;
1270
1271 switch (key)
1272 {
1273 case K_LEFTMOUSE:
1274 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1275 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1276 case K_LEFTRELEASE:
1277 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1278 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1279 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1280 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1281 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1282 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1283 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1284 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1285 }
1286 return TRUE;
1287}
1288
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001289/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001290 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1291 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001292 * Return the number of bytes in "buf".
1293 */
1294 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001295term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001296{
1297 VTerm *vterm = term->tl_vterm;
1298 VTermKey key = VTERM_KEY_NONE;
1299 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001300 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001301
1302 switch (c)
1303 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001304 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001305
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001306 // don't use VTERM_KEY_BACKSPACE, it always
1307 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001308 case K_BS: c = term_backspace_char; break;
1309
1310 case ESC: key = VTERM_KEY_ESCAPE; break;
1311 case K_DEL: key = VTERM_KEY_DEL; break;
1312 case K_DOWN: key = VTERM_KEY_DOWN; break;
1313 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1314 key = VTERM_KEY_DOWN; break;
1315 case K_END: key = VTERM_KEY_END; break;
1316 case K_S_END: mod = VTERM_MOD_SHIFT;
1317 key = VTERM_KEY_END; break;
1318 case K_C_END: mod = VTERM_MOD_CTRL;
1319 key = VTERM_KEY_END; break;
1320 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1321 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1322 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1323 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1324 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1325 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1326 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1327 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1328 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1329 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1330 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1331 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1332 case K_HOME: key = VTERM_KEY_HOME; break;
1333 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1334 key = VTERM_KEY_HOME; break;
1335 case K_C_HOME: mod = VTERM_MOD_CTRL;
1336 key = VTERM_KEY_HOME; break;
1337 case K_INS: key = VTERM_KEY_INS; break;
1338 case K_K0: key = VTERM_KEY_KP_0; break;
1339 case K_K1: key = VTERM_KEY_KP_1; break;
1340 case K_K2: key = VTERM_KEY_KP_2; break;
1341 case K_K3: key = VTERM_KEY_KP_3; break;
1342 case K_K4: key = VTERM_KEY_KP_4; break;
1343 case K_K5: key = VTERM_KEY_KP_5; break;
1344 case K_K6: key = VTERM_KEY_KP_6; break;
1345 case K_K7: key = VTERM_KEY_KP_7; break;
1346 case K_K8: key = VTERM_KEY_KP_8; break;
1347 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001348 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001349 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001350 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001351 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001352 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1353 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001354 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1355 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001356 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1357 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001358 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1359 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1360 case K_LEFT: key = VTERM_KEY_LEFT; break;
1361 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1362 key = VTERM_KEY_LEFT; break;
1363 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1364 key = VTERM_KEY_LEFT; break;
1365 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1366 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1367 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1368 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1369 key = VTERM_KEY_RIGHT; break;
1370 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1371 key = VTERM_KEY_RIGHT; break;
1372 case K_UP: key = VTERM_KEY_UP; break;
1373 case K_S_UP: mod = VTERM_MOD_SHIFT;
1374 key = VTERM_KEY_UP; break;
1375 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001376 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1377 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001378
Bram Moolenaara42ad572017-11-16 13:08:04 +01001379 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1380 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001381 case K_MOUSELEFT: /* TODO */ return 0;
1382 case K_MOUSERIGHT: /* TODO */ return 0;
1383
1384 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001385 case K_LEFTMOUSE_NM:
1386 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001387 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001388 case K_LEFTRELEASE_NM:
1389 case K_MOUSEMOVE:
1390 case K_MIDDLEMOUSE:
1391 case K_MIDDLEDRAG:
1392 case K_MIDDLERELEASE:
1393 case K_RIGHTMOUSE:
1394 case K_RIGHTDRAG:
1395 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1396 return 0;
1397 other = TRUE;
1398 break;
1399
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001400 case K_X1MOUSE: /* TODO */ return 0;
1401 case K_X1DRAG: /* TODO */ return 0;
1402 case K_X1RELEASE: /* TODO */ return 0;
1403 case K_X2MOUSE: /* TODO */ return 0;
1404 case K_X2DRAG: /* TODO */ return 0;
1405 case K_X2RELEASE: /* TODO */ return 0;
1406
1407 case K_IGNORE: return 0;
1408 case K_NOP: return 0;
1409 case K_UNDO: return 0;
1410 case K_HELP: return 0;
1411 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1412 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1413 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1414 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1415 case K_SELECT: return 0;
1416#ifdef FEAT_GUI
1417 case K_VER_SCROLLBAR: return 0;
1418 case K_HOR_SCROLLBAR: return 0;
1419#endif
1420#ifdef FEAT_GUI_TABLINE
1421 case K_TABLINE: return 0;
1422 case K_TABMENU: return 0;
1423#endif
1424#ifdef FEAT_NETBEANS_INTG
1425 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1426#endif
1427#ifdef FEAT_DND
1428 case K_DROP: return 0;
1429#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001430 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001431 case K_PS: vterm_keyboard_start_paste(vterm);
1432 other = TRUE;
1433 break;
1434 case K_PE: vterm_keyboard_end_paste(vterm);
1435 other = TRUE;
1436 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001437 }
1438
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001439 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001440 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001441 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001442 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001443 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001444 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001445 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001446
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001447 /*
1448 * Convert special keys to vterm keys:
1449 * - Write keys to vterm: vterm_keyboard_key()
1450 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001451 */
1452 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001453 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001454 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001455 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001456 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001457 vterm_keyboard_unichar(vterm, c, mod);
1458
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001459 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001460 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1461}
1462
1463/*
1464 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001465 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001466 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001467 */
1468 static int
1469term_job_running_check(term_T *term, int check_job_status)
1470{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001471 // Also consider the job finished when the channel is closed, to avoid a
1472 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001473 if (term != NULL
1474 && term->tl_job != NULL
1475 && channel_is_open(term->tl_job->jv_channel))
1476 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001477 job_T *job = term->tl_job;
1478
1479 // Careful: Checking the job status may invoked callbacks, which close
1480 // the buffer and terminate "term". However, "job" will not be freed
1481 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001482 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001483 job_status(job);
1484 return (job->jv_status == JOB_STARTED
1485 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001486 }
1487 return FALSE;
1488}
1489
1490/*
1491 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001492 */
1493 int
1494term_job_running(term_T *term)
1495{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001496 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001497}
1498
1499/*
1500 * Return TRUE if "term" has an active channel and used ":term NONE".
1501 */
1502 int
1503term_none_open(term_T *term)
1504{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001505 // Also consider the job finished when the channel is closed, to avoid a
1506 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001507 return term != NULL
1508 && term->tl_job != NULL
1509 && channel_is_open(term->tl_job->jv_channel)
1510 && term->tl_job->jv_channel->ch_keep_open;
1511}
1512
1513/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001514 * Used when exiting: kill the job in "buf" if so desired.
1515 * Return OK when the job finished.
1516 * Return FAIL when the job is still running.
1517 */
1518 int
1519term_try_stop_job(buf_T *buf)
1520{
1521 int count;
1522 char *how = (char *)buf->b_term->tl_kill;
1523
1524#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1525 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1526 {
1527 char_u buff[DIALOG_MSG_SIZE];
1528 int ret;
1529
1530 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1531 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1532 if (ret == VIM_YES)
1533 how = "kill";
1534 else if (ret == VIM_CANCEL)
1535 return FAIL;
1536 }
1537#endif
1538 if (how == NULL || *how == NUL)
1539 return FAIL;
1540
1541 job_stop(buf->b_term->tl_job, NULL, how);
1542
Bram Moolenaar9172d232019-01-29 23:06:54 +01001543 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001544 for (count = 0; count < 100; ++count)
1545 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001546 job_T *job;
1547
1548 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001549 if (!buf_valid(buf)
1550 || buf->b_term == NULL
1551 || buf->b_term->tl_job == NULL)
1552 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001553 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001554
Bram Moolenaar9172d232019-01-29 23:06:54 +01001555 // Call job_status() to update jv_status. It may cause the job to be
1556 // cleaned up but it won't be freed.
1557 job_status(job);
1558 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001559 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001560
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001561 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001562 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001563 }
1564 return FAIL;
1565}
1566
1567/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001568 * Add the last line of the scrollback buffer to the buffer in the window.
1569 */
1570 static void
1571add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1572{
1573 buf_T *buf = term->tl_buffer;
1574 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1575 linenr_T lnum = buf->b_ml.ml_line_count;
1576
Bram Moolenaar4f974752019-02-17 17:44:42 +01001577#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001578 if (!enc_utf8 && enc_codepage > 0)
1579 {
1580 WCHAR *ret = NULL;
1581 int length = 0;
1582
1583 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1584 &ret, &length);
1585 if (ret != NULL)
1586 {
1587 WideCharToMultiByte_alloc(enc_codepage, 0,
1588 ret, length, (char **)&text, &len, 0, 0);
1589 vim_free(ret);
1590 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1591 vim_free(text);
1592 }
1593 }
1594 else
1595#endif
1596 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1597 if (empty)
1598 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001599 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001600 curbuf = buf;
1601 ml_delete(1, FALSE);
1602 curbuf = curwin->w_buffer;
1603 }
1604}
1605
1606 static void
1607cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1608{
1609 attr->width = cell->width;
1610 attr->attrs = cell->attrs;
1611 attr->fg = cell->fg;
1612 attr->bg = cell->bg;
1613}
1614
1615 static int
1616equal_celattr(cellattr_T *a, cellattr_T *b)
1617{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001618 // Comparing the colors should be sufficient.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001619 return a->fg.red == b->fg.red
1620 && a->fg.green == b->fg.green
1621 && a->fg.blue == b->fg.blue
1622 && a->bg.red == b->bg.red
1623 && a->bg.green == b->bg.green
1624 && a->bg.blue == b->bg.blue;
1625}
1626
Bram Moolenaard96ff162018-02-18 22:13:29 +01001627/*
1628 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1629 * line at this position. Otherwise at the end.
1630 */
1631 static int
1632add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1633{
1634 if (ga_grow(&term->tl_scrollback, 1) == OK)
1635 {
1636 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1637 + term->tl_scrollback.ga_len;
1638
1639 if (lnum > 0)
1640 {
1641 int i;
1642
1643 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1644 {
1645 *line = *(line - 1);
1646 --line;
1647 }
1648 }
1649 line->sb_cols = 0;
1650 line->sb_cells = NULL;
1651 line->sb_fill_attr = *fill_attr;
1652 ++term->tl_scrollback.ga_len;
1653 return OK;
1654 }
1655 return FALSE;
1656}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001657
1658/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001659 * Remove the terminal contents from the scrollback and the buffer.
1660 * Used before adding a new scrollback line or updating the buffer for lines
1661 * displayed in the terminal.
1662 */
1663 static void
1664cleanup_scrollback(term_T *term)
1665{
1666 sb_line_T *line;
1667 garray_T *gap;
1668
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001669 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001670 gap = &term->tl_scrollback;
1671 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1672 && gap->ga_len > 0)
1673 {
1674 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1675 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1676 vim_free(line->sb_cells);
1677 --gap->ga_len;
1678 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001679 curbuf = curwin->w_buffer;
1680 if (curbuf == term->tl_buffer)
1681 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001682}
1683
1684/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001685 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001686 */
1687 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001688update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001689{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001690 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001691 int len;
1692 int lines_skipped = 0;
1693 VTermPos pos;
1694 VTermScreenCell cell;
1695 cellattr_T fill_attr, new_fill_attr;
1696 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001697
1698 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1699 "Adding terminal window snapshot to buffer");
1700
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001701 // First remove the lines that were appended before, they might be
1702 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001703 cleanup_scrollback(term);
1704
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001705 screen = vterm_obtain_screen(term->tl_vterm);
1706 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001707 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1708 {
1709 len = 0;
1710 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1711 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1712 && cell.chars[0] != NUL)
1713 {
1714 len = pos.col + 1;
1715 new_fill_attr = term->tl_default_color;
1716 }
1717 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001718 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001719 cell2cellattr(&cell, &new_fill_attr);
1720
1721 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1722 ++lines_skipped;
1723 else
1724 {
1725 while (lines_skipped > 0)
1726 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001727 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001728 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001729 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001730 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001731 }
1732
1733 if (len == 0)
1734 p = NULL;
1735 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001736 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001737 if ((p != NULL || len == 0)
1738 && ga_grow(&term->tl_scrollback, 1) == OK)
1739 {
1740 garray_T ga;
1741 int width;
1742 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1743 + term->tl_scrollback.ga_len;
1744
1745 ga_init2(&ga, 1, 100);
1746 for (pos.col = 0; pos.col < len; pos.col += width)
1747 {
1748 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1749 {
1750 width = 1;
1751 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1752 if (ga_grow(&ga, 1) == OK)
1753 ga.ga_len += utf_char2bytes(' ',
1754 (char_u *)ga.ga_data + ga.ga_len);
1755 }
1756 else
1757 {
1758 width = cell.width;
1759
1760 cell2cellattr(&cell, &p[pos.col]);
1761
Bram Moolenaara79fd562018-12-20 20:47:32 +01001762 // Each character can be up to 6 bytes.
1763 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001764 {
1765 int i;
1766 int c;
1767
1768 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1769 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1770 (char_u *)ga.ga_data + ga.ga_len);
1771 }
1772 }
1773 }
1774 line->sb_cols = len;
1775 line->sb_cells = p;
1776 line->sb_fill_attr = new_fill_attr;
1777 fill_attr = new_fill_attr;
1778 ++term->tl_scrollback.ga_len;
1779
1780 if (ga_grow(&ga, 1) == FAIL)
1781 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1782 else
1783 {
1784 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1785 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1786 }
1787 ga_clear(&ga);
1788 }
1789 else
1790 vim_free(p);
1791 }
1792 }
1793
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001794 // Add trailing empty lines.
1795 for (pos.row = term->tl_scrollback.ga_len;
1796 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1797 ++pos.row)
1798 {
1799 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1800 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1801 }
1802
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001803 term->tl_dirty_snapshot = FALSE;
1804#ifdef FEAT_TIMERS
1805 term->tl_timer_set = FALSE;
1806#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001807}
1808
1809/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001810 * Loop over all windows in the current tab, and also curwin, which is not
1811 * encountered when using a terminal in a popup window.
1812 * Return TRUE if "*wp" was set to the next window.
1813 */
1814 static int
1815for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1816{
1817 if (*wp == NULL)
1818 *wp = firstwin;
1819 else if ((*wp)->w_next != NULL)
1820 *wp = (*wp)->w_next;
1821 else if (!*did_curwin)
1822 *wp = curwin;
1823 else
1824 return FALSE;
1825 if (*wp == curwin)
1826 *did_curwin = TRUE;
1827 return TRUE;
1828}
1829
1830/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001831 * If needed, add the current lines of the terminal to scrollback and to the
1832 * buffer. Called after the job has ended and when switching to
1833 * Terminal-Normal mode.
1834 * When "redraw" is TRUE redraw the windows that show the terminal.
1835 */
1836 static void
1837may_move_terminal_to_buffer(term_T *term, int redraw)
1838{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001839 if (term->tl_vterm == NULL)
1840 return;
1841
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001842 // Update the snapshot only if something changes or the buffer does not
1843 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001844 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1845 <= term->tl_scrollback_scrolled)
1846 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001847
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001848 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001849 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1850 &term->tl_default_color.fg, &term->tl_default_color.bg);
1851
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001852 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001853 {
1854 win_T *wp = NULL;
1855 int did_curwin = FALSE;
1856
1857 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001858 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001859 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001860 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001861 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1862 wp->w_cursor.col = 0;
1863 wp->w_valid = 0;
1864 if (wp->w_cursor.lnum >= wp->w_height)
1865 {
1866 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001867
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001868 if (wp->w_topline < min_topline)
1869 wp->w_topline = min_topline;
1870 }
1871 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001872 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001873 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001874 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875}
1876
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001877#if defined(FEAT_TIMERS) || defined(PROTO)
1878/*
1879 * Check if any terminal timer expired. If so, copy text from the terminal to
1880 * the buffer.
1881 * Return the time until the next timer will expire.
1882 */
1883 int
1884term_check_timers(int next_due_arg, proftime_T *now)
1885{
1886 term_T *term;
1887 int next_due = next_due_arg;
1888
1889 for (term = first_term; term != NULL; term = term->tl_next)
1890 {
1891 if (term->tl_timer_set && !term->tl_normal_mode)
1892 {
1893 long this_due = proftime_time_left(&term->tl_timer_due, now);
1894
1895 if (this_due <= 1)
1896 {
1897 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001898 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001899 }
1900 else if (next_due == -1 || next_due > this_due)
1901 next_due = this_due;
1902 }
1903 }
1904
1905 return next_due;
1906}
1907#endif
1908
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001909/*
1910 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1911 * otherwise end it.
1912 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913 static void
1914set_terminal_mode(term_T *term, int normal_mode)
1915{
1916 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001917 if (!normal_mode)
1918 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001919 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001920 if (term->tl_buffer == curbuf)
1921 maketitle();
1922}
1923
1924/*
1925 * Called after the job if finished and Terminal mode is not active:
1926 * Move the vterm contents into the scrollback buffer and free the vterm.
1927 */
1928 static void
1929cleanup_vterm(term_T *term)
1930{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001931 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001932 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001933 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001934 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001935}
1936
1937/*
1938 * Switch from Terminal-Job mode to Terminal-Normal mode.
1939 * Suspends updating the terminal window.
1940 */
1941 static void
1942term_enter_normal_mode(void)
1943{
1944 term_T *term = curbuf->b_term;
1945
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001946 set_terminal_mode(term, TRUE);
1947
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001948 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001949 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001950
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001951 // Move the window cursor to the position of the cursor in the
1952 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001953 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1954 + term->tl_cursor_pos.row + 1;
1955 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001956 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1957 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001958 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001959
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001960 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001961 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1962}
1963
1964/*
1965 * Returns TRUE if the current window contains a terminal and we are in
1966 * Terminal-Normal mode.
1967 */
1968 int
1969term_in_normal_mode(void)
1970{
1971 term_T *term = curbuf->b_term;
1972
1973 return term != NULL && term->tl_normal_mode;
1974}
1975
1976/*
1977 * Switch from Terminal-Normal mode to Terminal-Job mode.
1978 * Restores updating the terminal window.
1979 */
1980 void
1981term_enter_job_mode()
1982{
1983 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001984
1985 set_terminal_mode(term, FALSE);
1986
1987 if (term->tl_channel_closed)
1988 cleanup_vterm(term);
1989 redraw_buf_and_status_later(curbuf, NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001990#ifdef FEAT_PROP_POPUP
1991 if (WIN_IS_POPUP(curwin))
Bram Moolenaard5bc32d2020-03-22 19:25:50 +01001992 redraw_later(NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001993#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001994}
1995
1996/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001997 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001998 * Note: while waiting a terminal may be closed and freed if the channel is
1999 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002000 */
2001 static int
2002term_vgetc()
2003{
2004 int c;
2005 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002006 int modify_other_keys =
2007 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002008
2009 State = TERMINAL;
2010 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002011#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002012 ctrl_break_was_pressed = FALSE;
2013#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002014 if (modify_other_keys)
2015 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016 c = vgetc();
2017 got_int = FALSE;
2018 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002019 if (modify_other_keys)
2020 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002021 return c;
2022}
2023
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002024static int mouse_was_outside = FALSE;
2025
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002026/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002027 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 * Return FAIL when the key needs to be handled in Normal mode.
2029 * Return OK when the key was dropped or sent to the terminal.
2030 */
2031 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002032send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002033{
2034 char msg[KEY_BUF_LEN];
2035 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002036 int dragging_outside = FALSE;
2037
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002038 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002039 switch (c)
2040 {
2041 case NUL:
2042 case K_ZERO:
2043 if (typed)
2044 stuffcharReadbuff(c);
2045 return FAIL;
2046
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002047 case K_TABLINE:
2048 stuffcharReadbuff(c);
2049 return FAIL;
2050
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002051 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002052 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002053 return FAIL;
2054
2055 case K_LEFTDRAG:
2056 case K_MIDDLEDRAG:
2057 case K_RIGHTDRAG:
2058 case K_X1DRAG:
2059 case K_X2DRAG:
2060 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002061 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002062 case K_LEFTMOUSE:
2063 case K_LEFTMOUSE_NM:
2064 case K_LEFTRELEASE:
2065 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002066 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002067 case K_MIDDLEMOUSE:
2068 case K_MIDDLERELEASE:
2069 case K_RIGHTMOUSE:
2070 case K_RIGHTRELEASE:
2071 case K_X1MOUSE:
2072 case K_X1RELEASE:
2073 case K_X2MOUSE:
2074 case K_X2RELEASE:
2075
2076 case K_MOUSEUP:
2077 case K_MOUSEDOWN:
2078 case K_MOUSELEFT:
2079 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002080 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002081 int row = mouse_row;
2082 int col = mouse_col;
2083
2084#ifdef FEAT_PROP_POPUP
2085 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002086 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002087 row -= popup_top_extra(curwin);
2088 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002089 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002090#endif
2091 if (row < W_WINROW(curwin)
2092 || row >= (W_WINROW(curwin) + curwin->w_height)
2093 || col < curwin->w_wincol
2094 || col >= W_ENDCOL(curwin)
2095 || dragging_outside)
2096 {
2097 // click or scroll outside the current window or on status
2098 // line or vertical separator
2099 if (typed)
2100 {
2101 stuffcharReadbuff(c);
2102 mouse_was_outside = TRUE;
2103 }
2104 return FAIL;
2105 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002106 }
2107 }
2108 if (typed)
2109 mouse_was_outside = FALSE;
2110
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002111 // Convert the typed key to a sequence of bytes for the job.
2112 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002113 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002114 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002115 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2116 (char_u *)msg, (int)len, NULL);
2117
2118 return OK;
2119}
2120
2121 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002122position_cursor(win_T *wp, VTermPos *pos, int add_off UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002123{
2124 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2125 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002126#ifdef FEAT_PROP_POPUP
2127 if (add_off && popup_is_popup(curwin))
2128 {
2129 wp->w_wrow += popup_top_extra(curwin);
2130 wp->w_wcol += popup_left_extra(curwin);
2131 }
2132#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002133 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2134}
2135
2136/*
2137 * Handle CTRL-W "": send register contents to the job.
2138 */
2139 static void
2140term_paste_register(int prev_c UNUSED)
2141{
2142 int c;
2143 list_T *l;
2144 listitem_T *item;
2145 long reglen = 0;
2146 int type;
2147
2148#ifdef FEAT_CMDL_INFO
2149 if (add_to_showcmd(prev_c))
2150 if (add_to_showcmd('"'))
2151 out_flush();
2152#endif
2153 c = term_vgetc();
2154#ifdef FEAT_CMDL_INFO
2155 clear_showcmd();
2156#endif
2157 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002158 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002159 return;
2160
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002161 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002162 if (c == '=' && get_expr_register() != '=')
2163 return;
2164 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002165 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166 return;
2167
2168 l = (list_T *)get_reg_contents(c, GREG_LIST);
2169 if (l != NULL)
2170 {
2171 type = get_reg_type(c, &reglen);
2172 for (item = l->lv_first; item != NULL; item = item->li_next)
2173 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002174 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002175#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002176 char_u *tmp = s;
2177
2178 if (!enc_utf8 && enc_codepage > 0)
2179 {
2180 WCHAR *ret = NULL;
2181 int length = 0;
2182
2183 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2184 (int)STRLEN(s), &ret, &length);
2185 if (ret != NULL)
2186 {
2187 WideCharToMultiByte_alloc(CP_UTF8, 0,
2188 ret, length, (char **)&s, &length, 0, 0);
2189 vim_free(ret);
2190 }
2191 }
2192#endif
2193 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2194 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002195#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002196 if (tmp != s)
2197 vim_free(s);
2198#endif
2199
2200 if (item->li_next != NULL || type == MLINE)
2201 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2202 (char_u *)"\r", 1, NULL);
2203 }
2204 list_free(l);
2205 }
2206}
2207
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002208/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002209 * Return TRUE when waiting for a character in the terminal, the cursor of the
2210 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002211 */
2212 int
2213terminal_is_active()
2214{
2215 return in_terminal_loop != NULL;
2216}
2217
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002218#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002219 cursorentry_T *
2220term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2221{
2222 term_T *term = in_terminal_loop;
2223 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002224 int id;
2225 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002226
2227 vim_memset(&entry, 0, sizeof(entry));
2228 entry.shape = entry.mshape =
2229 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2230 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2231 SHAPE_BLOCK;
2232 entry.percentage = 20;
2233 if (term->tl_cursor_blink)
2234 {
2235 entry.blinkwait = 700;
2236 entry.blinkon = 400;
2237 entry.blinkoff = 250;
2238 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002239
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002240 // The "Terminal" highlight group overrules the defaults.
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002241 id = syn_name2id((char_u *)"Terminal");
2242 if (id != 0)
2243 {
2244 syn_id2colors(id, &term_fg, &term_bg);
2245 *fg = term_bg;
2246 }
2247 else
2248 *fg = gui.back_pixel;
2249
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002250 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002251 {
2252 if (id != 0)
2253 *bg = term_fg;
2254 else
2255 *bg = gui.norm_pixel;
2256 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002257 else
2258 *bg = color_name2handle(term->tl_cursor_color);
2259 entry.name = "n";
2260 entry.used_for = SHAPE_CURSOR;
2261
2262 return &entry;
2263}
2264#endif
2265
Bram Moolenaard317b382018-02-08 22:33:31 +01002266 static void
2267may_output_cursor_props(void)
2268{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002269 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002270 || last_set_cursor_shape != desired_cursor_shape
2271 || last_set_cursor_blink != desired_cursor_blink)
2272 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002273 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002274 last_set_cursor_shape = desired_cursor_shape;
2275 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002276 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002277 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002278 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002279 ui_cursor_shape_forced(TRUE);
2280 else
2281 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2282 }
2283}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002284
Bram Moolenaard317b382018-02-08 22:33:31 +01002285/*
2286 * Set the cursor color and shape, if not last set to these.
2287 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002288 static void
2289may_set_cursor_props(term_T *term)
2290{
2291#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002292 // For the GUI the cursor properties are obtained with
2293 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002294 if (gui.in_use)
2295 return;
2296#endif
2297 if (in_terminal_loop == term)
2298 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002299 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002300 desired_cursor_shape = term->tl_cursor_shape;
2301 desired_cursor_blink = term->tl_cursor_blink;
2302 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002303 }
2304}
2305
Bram Moolenaard317b382018-02-08 22:33:31 +01002306/*
2307 * Reset the desired cursor properties and restore them when needed.
2308 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002309 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002310prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002311{
2312#ifdef FEAT_GUI
2313 if (gui.in_use)
2314 return;
2315#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002316 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002317 desired_cursor_shape = -1;
2318 desired_cursor_blink = -1;
2319 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002320}
2321
2322/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002323 * Returns TRUE if the current window contains a terminal and we are sending
2324 * keys to the job.
2325 * If "check_job_status" is TRUE update the job status.
2326 */
2327 static int
2328term_use_loop_check(int check_job_status)
2329{
2330 term_T *term = curbuf->b_term;
2331
2332 return term != NULL
2333 && !term->tl_normal_mode
2334 && term->tl_vterm != NULL
2335 && term_job_running_check(term, check_job_status);
2336}
2337
2338/*
2339 * Returns TRUE if the current window contains a terminal and we are sending
2340 * keys to the job.
2341 */
2342 int
2343term_use_loop(void)
2344{
2345 return term_use_loop_check(FALSE);
2346}
2347
2348/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002349 * Called when entering a window with the mouse. If this is a terminal window
2350 * we may want to change state.
2351 */
2352 void
2353term_win_entered()
2354{
2355 term_T *term = curbuf->b_term;
2356
2357 if (term != NULL)
2358 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002359 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002360 {
2361 reset_VIsual_and_resel();
2362 if (State & INSERT)
2363 stop_insert_mode = TRUE;
2364 }
2365 mouse_was_outside = FALSE;
2366 enter_mouse_col = mouse_col;
2367 enter_mouse_row = mouse_row;
2368 }
2369}
2370
2371/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002372 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2373 * Return the Ctrl-key value in that case.
2374 */
2375 static int
2376raw_c_to_ctrl(int c)
2377{
2378 if ((mod_mask & MOD_MASK_CTRL)
2379 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2380 return c & 0x1f;
2381 return c;
2382}
2383
2384/*
2385 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2386 * May set "mod_mask".
2387 */
2388 static int
2389ctrl_to_raw_c(int c)
2390{
2391 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2392 {
2393 mod_mask |= MOD_MASK_CTRL;
2394 return c + '@';
2395 }
2396 return c;
2397}
2398
2399/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002400 * Wait for input and send it to the job.
2401 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2402 * when there is no more typahead.
2403 * Return when the start of a CTRL-W command is typed or anything else that
2404 * should be handled as a Normal mode command.
2405 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2406 * the terminal was closed.
2407 */
2408 int
2409terminal_loop(int blocking)
2410{
2411 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002412 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002413 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002414 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002415#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002416 int tty_fd = curbuf->b_term->tl_job->jv_channel
2417 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002418#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002419 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002420
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002421 // Remember the terminal we are sending keys to. However, the terminal
2422 // might be closed while waiting for a character, e.g. typing "exit" in a
2423 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2424 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002425 in_terminal_loop = curbuf->b_term;
2426
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002427 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002428 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002429 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002430 if (termwinkey == Ctrl_W)
2431 termwinkey = 0;
2432 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002433 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002434 may_set_cursor_props(curbuf->b_term);
2435
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002436 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002437 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002438#ifdef FEAT_GUI
2439 if (!curbuf->b_term->tl_system)
2440#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002441 // TODO: skip screen update when handling a sequence of keys.
2442 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002443 while (must_redraw != 0)
2444 if (update_screen(0) == FAIL)
2445 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002446 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002447 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002448 break;
2449
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002450 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002451 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002452
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002453 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002454 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002455 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002456 // Job finished while waiting for a character. Push back the
2457 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002458 if (raw_c != K_IGNORE)
2459 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002460 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002461 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002462 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002463 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002464 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002465
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002466#ifdef UNIX
2467 /*
2468 * The shell or another program may change the tty settings. Getting
2469 * them for every typed character is a bit of overhead, but it's needed
2470 * for the first character typed, e.g. when Vim starts in a shell.
2471 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002472 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002473 {
2474 ttyinfo_T info;
2475
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002476 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002477 if (get_tty_info(tty_fd, &info) == OK)
2478 term_backspace_char = info.backspace;
2479 }
2480#endif
2481
Bram Moolenaar4f974752019-02-17 17:44:42 +01002482#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002483 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2484 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002485 if (ctrl_break_was_pressed)
2486 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2487#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002488 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2489 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002490 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002491#ifdef FEAT_GUI
2492 && !curbuf->b_term->tl_system
2493#endif
2494 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002495 {
2496 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002497 int prev_raw_c = raw_c;
2498 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002499
2500#ifdef FEAT_CMDL_INFO
2501 if (add_to_showcmd(c))
2502 out_flush();
2503#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002504 raw_c = term_vgetc();
2505 c = raw_c_to_ctrl(raw_c);
2506
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002507#ifdef FEAT_CMDL_INFO
2508 clear_showcmd();
2509#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002510 if (!term_use_loop_check(TRUE)
2511 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002512 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002513 break;
2514
2515 if (prev_c == Ctrl_BSL)
2516 {
2517 if (c == Ctrl_N)
2518 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002519 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002520 term_enter_normal_mode();
2521 ret = FAIL;
2522 goto theend;
2523 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002524 // Send both keys to the terminal, first one here, second one
2525 // below.
2526 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2527 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002528 }
2529 else if (c == Ctrl_C)
2530 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002531 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002532 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2533 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002534 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002535 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002536 // "CTRL-W .": send CTRL-W to the job
2537 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002538 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002540 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002541 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002542 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002543 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002544 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002545 else if (c == 'N')
2546 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002547 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002548 term_enter_normal_mode();
2549 ret = FAIL;
2550 goto theend;
2551 }
2552 else if (c == '"')
2553 {
2554 term_paste_register(prev_c);
2555 continue;
2556 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002557 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002558 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002559 char_u buf[MB_MAXBYTES + 2];
2560
2561 // Put the command into the typeahead buffer, when using the
2562 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2563 buf[0] = Ctrl_W;
2564 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2565 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002566 ret = OK;
2567 goto theend;
2568 }
2569 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002570# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002571 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002572 {
2573 WCHAR wc;
2574 char_u mb[3];
2575
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002576 mb[0] = (unsigned)raw_c >> 8;
2577 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002578 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002579 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002580 }
2581# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002582 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002583 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002584 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002585 // We are sure to come back here, don't reset the cursor color
2586 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002587 restore_cursor = FALSE;
2588
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002589 ret = OK;
2590 goto theend;
2591 }
2592 }
2593 ret = FAIL;
2594
2595theend:
2596 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002597 if (restore_cursor)
2598 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002599
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002600 // Move a snapshot of the screen contents to the buffer, so that completion
2601 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002602 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2603 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002604
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002605 return ret;
2606}
2607
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002608 static void
2609may_toggle_cursor(term_T *term)
2610{
2611 if (in_terminal_loop == term)
2612 {
2613 if (term->tl_cursor_visible)
2614 cursor_on();
2615 else
2616 cursor_off();
2617 }
2618}
2619
2620/*
2621 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002622 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002623 */
2624 static int
2625color2index(VTermColor *color, int fg, int *boldp)
2626{
2627 int red = color->red;
2628 int blue = color->blue;
2629 int green = color->green;
2630
Bram Moolenaar46359e12017-11-29 22:33:38 +01002631 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002632 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002633 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002634 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002635 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002636 case 0: return 0;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002637 case 1: return lookup_color( 0, fg, boldp) + 1; // black
2638 case 2: return lookup_color( 4, fg, boldp) + 1; // dark red
2639 case 3: return lookup_color( 2, fg, boldp) + 1; // dark green
2640 case 4: return lookup_color( 6, fg, boldp) + 1; // brown
2641 case 5: return lookup_color( 1, fg, boldp) + 1; // dark blue
2642 case 6: return lookup_color( 5, fg, boldp) + 1; // dark magenta
2643 case 7: return lookup_color( 3, fg, boldp) + 1; // dark cyan
2644 case 8: return lookup_color( 8, fg, boldp) + 1; // light grey
2645 case 9: return lookup_color(12, fg, boldp) + 1; // dark grey
2646 case 10: return lookup_color(20, fg, boldp) + 1; // red
2647 case 11: return lookup_color(16, fg, boldp) + 1; // green
2648 case 12: return lookup_color(24, fg, boldp) + 1; // yellow
2649 case 13: return lookup_color(14, fg, boldp) + 1; // blue
2650 case 14: return lookup_color(22, fg, boldp) + 1; // magenta
2651 case 15: return lookup_color(18, fg, boldp) + 1; // cyan
2652 case 16: return lookup_color(26, fg, boldp) + 1; // white
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002653 }
2654 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002655
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002656 if (t_colors >= 256)
2657 {
2658 if (red == blue && red == green)
2659 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002660 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002661 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002662 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2663 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2664 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002665 int i;
2666
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002667 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002668 return 17; // 00/00/00
2669 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002670 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002671 for (i = 0; i < 23; ++i)
2672 if (red < cutoff[i])
2673 return i + 233;
2674 return 256;
2675 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002676 {
2677 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2678 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002679
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002680 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002681 for (ri = 0; ri < 5; ++ri)
2682 if (red < cutoff[ri])
2683 break;
2684 for (gi = 0; gi < 5; ++gi)
2685 if (green < cutoff[gi])
2686 break;
2687 for (bi = 0; bi < 5; ++bi)
2688 if (blue < cutoff[bi])
2689 break;
2690 return 17 + ri * 36 + gi * 6 + bi;
2691 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002692 }
2693 return 0;
2694}
2695
2696/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002697 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002698 */
2699 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002700vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002701{
2702 int attr = 0;
2703
2704 if (cellattrs.bold)
2705 attr |= HL_BOLD;
2706 if (cellattrs.underline)
2707 attr |= HL_UNDERLINE;
2708 if (cellattrs.italic)
2709 attr |= HL_ITALIC;
2710 if (cellattrs.strike)
2711 attr |= HL_STRIKETHROUGH;
2712 if (cellattrs.reverse)
2713 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002714 return attr;
2715}
2716
2717/*
2718 * Store Vterm attributes in "cell" from highlight flags.
2719 */
2720 static void
2721hl2vtermAttr(int attr, cellattr_T *cell)
2722{
2723 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2724 if (attr & HL_BOLD)
2725 cell->attrs.bold = 1;
2726 if (attr & HL_UNDERLINE)
2727 cell->attrs.underline = 1;
2728 if (attr & HL_ITALIC)
2729 cell->attrs.italic = 1;
2730 if (attr & HL_STRIKETHROUGH)
2731 cell->attrs.strike = 1;
2732 if (attr & HL_INVERSE)
2733 cell->attrs.reverse = 1;
2734}
2735
2736/*
2737 * Convert the attributes of a vterm cell into an attribute index.
2738 */
2739 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002740cell2attr(
2741 win_T *wp,
2742 VTermScreenCellAttrs cellattrs,
2743 VTermColor cellfg,
2744 VTermColor cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002745{
2746 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002747
2748#ifdef FEAT_GUI
2749 if (gui.in_use)
2750 {
2751 guicolor_T fg, bg;
2752
2753 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2754 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2755 return get_gui_attr_idx(attr, fg, bg);
2756 }
2757 else
2758#endif
2759#ifdef FEAT_TERMGUICOLORS
2760 if (p_tgc)
2761 {
2762 guicolor_T fg, bg;
2763
2764 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2765 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2766
2767 return get_tgc_attr_idx(attr, fg, bg);
2768 }
2769 else
2770#endif
2771 {
2772 int bold = MAYBE;
2773 int fg = color2index(&cellfg, TRUE, &bold);
2774 int bg = color2index(&cellbg, FALSE, &bold);
2775
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002776 // Use the 'wincolor' or "Terminal" highlighting for the default
2777 // colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002778 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002779 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002780 int wincolor_fg = -1;
2781 int wincolor_bg = -1;
2782
2783 if (wp != NULL && *wp->w_p_wcr != NUL)
2784 {
2785 int id = syn_name2id(curwin->w_p_wcr);
2786
2787 // Get the 'wincolor' group colors.
2788 if (id > 0)
2789 syn_id2cterm_bg(id, &wincolor_fg, &wincolor_bg);
2790 }
2791 if (fg == 0)
2792 {
2793 if (wincolor_fg >= 0)
2794 fg = wincolor_fg + 1;
2795 else if (term_default_cterm_fg >= 0)
2796 fg = term_default_cterm_fg + 1;
2797 }
2798 if (bg == 0)
2799 {
2800 if (wincolor_bg >= 0)
2801 bg = wincolor_bg + 1;
2802 else if (term_default_cterm_bg >= 0)
2803 bg = term_default_cterm_bg + 1;
2804 }
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002805 }
2806
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002807 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002808 if (bold == TRUE)
2809 attr |= HL_BOLD;
2810 return get_cterm_attr_idx(attr, fg, bg);
2811 }
2812 return 0;
2813}
2814
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002815 static void
2816set_dirty_snapshot(term_T *term)
2817{
2818 term->tl_dirty_snapshot = TRUE;
2819#ifdef FEAT_TIMERS
2820 if (!term->tl_normal_mode)
2821 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002822 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002823 profile_setlimit(100L, &term->tl_timer_due);
2824 term->tl_timer_set = TRUE;
2825 }
2826#endif
2827}
2828
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002829 static int
2830handle_damage(VTermRect rect, void *user)
2831{
2832 term_T *term = (term_T *)user;
2833
2834 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2835 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002836 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002837 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002838 return 1;
2839}
2840
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002841 static void
2842term_scroll_up(term_T *term, int start_row, int count)
2843{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002844 win_T *wp = NULL;
2845 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002846 VTermColor fg, bg;
2847 VTermScreenCellAttrs attr;
2848 int clear_attr;
2849
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002850 vim_memset(&attr, 0, sizeof(attr));
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002851
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002852 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002853 {
2854 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002855 {
2856 // Set the color to clear lines with.
2857 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2858 &fg, &bg);
2859 clear_attr = cell2attr(wp, attr, fg, bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002860 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002861 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002862 }
2863}
2864
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002865 static int
2866handle_moverect(VTermRect dest, VTermRect src, void *user)
2867{
2868 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002869 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002870
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002871 // Scrolling up is done much more efficiently by deleting lines instead of
2872 // redrawing the text. But avoid doing this multiple times, postpone until
2873 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002874 if (dest.start_col == src.start_col
2875 && dest.end_col == src.end_col
2876 && dest.start_row < src.start_row)
2877 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002878 if (dest.start_row == 0)
2879 term->tl_postponed_scroll += count;
2880 else
2881 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002882 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002883
2884 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2885 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002886 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002887
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002888 // Note sure if the scrolling will work correctly, let's do a complete
2889 // redraw later.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002890 redraw_buf_later(term->tl_buffer, NOT_VALID);
2891 return 1;
2892}
2893
2894 static int
2895handle_movecursor(
2896 VTermPos pos,
2897 VTermPos oldpos UNUSED,
2898 int visible,
2899 void *user)
2900{
2901 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002902 win_T *wp = NULL;
2903 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002904
2905 term->tl_cursor_pos = pos;
2906 term->tl_cursor_visible = visible;
2907
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002908 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002909 {
2910 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002911 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002912 }
2913 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2914 {
2915 may_toggle_cursor(term);
2916 update_cursor(term, term->tl_cursor_visible);
2917 }
2918
2919 return 1;
2920}
2921
2922 static int
2923handle_settermprop(
2924 VTermProp prop,
2925 VTermValue *value,
2926 void *user)
2927{
2928 term_T *term = (term_T *)user;
2929
2930 switch (prop)
2931 {
2932 case VTERM_PROP_TITLE:
2933 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002934 // a blank title isn't useful, make it empty, so that "running" is
2935 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002936 if (*skipwhite((char_u *)value->string) == NUL)
2937 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002938 // Same as blank
2939 else if (term->tl_arg0_cmd != NULL
2940 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2941 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2942 term->tl_title = NULL;
2943 // Empty corrupted data of winpty
2944 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2945 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002946#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002947 else if (!enc_utf8 && enc_codepage > 0)
2948 {
2949 WCHAR *ret = NULL;
2950 int length = 0;
2951
2952 MultiByteToWideChar_alloc(CP_UTF8, 0,
2953 (char*)value->string, (int)STRLEN(value->string),
2954 &ret, &length);
2955 if (ret != NULL)
2956 {
2957 WideCharToMultiByte_alloc(enc_codepage, 0,
2958 ret, length, (char**)&term->tl_title,
2959 &length, 0, 0);
2960 vim_free(ret);
2961 }
2962 }
2963#endif
2964 else
2965 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002966 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002967 if (term == curbuf->b_term)
2968 maketitle();
2969 break;
2970
2971 case VTERM_PROP_CURSORVISIBLE:
2972 term->tl_cursor_visible = value->boolean;
2973 may_toggle_cursor(term);
2974 out_flush();
2975 break;
2976
2977 case VTERM_PROP_CURSORBLINK:
2978 term->tl_cursor_blink = value->boolean;
2979 may_set_cursor_props(term);
2980 break;
2981
2982 case VTERM_PROP_CURSORSHAPE:
2983 term->tl_cursor_shape = value->number;
2984 may_set_cursor_props(term);
2985 break;
2986
2987 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002988 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002989 may_set_cursor_props(term);
2990 break;
2991
2992 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002993 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002994 term->tl_using_altscreen = value->boolean;
2995 break;
2996
2997 default:
2998 break;
2999 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003000 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003001 return 1;
3002}
3003
3004/*
3005 * The job running in the terminal resized the terminal.
3006 */
3007 static int
3008handle_resize(int rows, int cols, void *user)
3009{
3010 term_T *term = (term_T *)user;
3011 win_T *wp;
3012
3013 term->tl_rows = rows;
3014 term->tl_cols = cols;
3015 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003016 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003017 term->tl_vterm_size_changed = FALSE;
3018 else
3019 {
3020 FOR_ALL_WINDOWS(wp)
3021 {
3022 if (wp->w_buffer == term->tl_buffer)
3023 {
3024 win_setheight_win(rows, wp);
3025 win_setwidth_win(cols, wp);
3026 }
3027 }
3028 redraw_buf_later(term->tl_buffer, NOT_VALID);
3029 }
3030 return 1;
3031}
3032
3033/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003034 * If the number of lines that are stored goes over 'termscrollback' then
3035 * delete the first 10%.
3036 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3037 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003038 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003039 static void
3040limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003041{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003042 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003043 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003044 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003045 int i;
3046
3047 curbuf = term->tl_buffer;
3048 for (i = 0; i < todo; ++i)
3049 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003050 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3051 if (update_buffer)
3052 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003053 }
3054 curbuf = curwin->w_buffer;
3055
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003056 gap->ga_len -= todo;
3057 mch_memmove(gap->ga_data,
3058 (sb_line_T *)gap->ga_data + todo,
3059 sizeof(sb_line_T) * gap->ga_len);
3060 if (update_buffer)
3061 term->tl_scrollback_scrolled -= todo;
3062 }
3063}
3064
3065/*
3066 * Handle a line that is pushed off the top of the screen.
3067 */
3068 static int
3069handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3070{
3071 term_T *term = (term_T *)user;
3072 garray_T *gap;
3073 int update_buffer;
3074
3075 if (term->tl_normal_mode)
3076 {
3077 // In Terminal-Normal mode the user interacts with the buffer, thus we
3078 // must not change it. Postpone adding the scrollback lines.
3079 gap = &term->tl_scrollback_postponed;
3080 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003081 }
3082 else
3083 {
3084 // First remove the lines that were appended before, the pushed line
3085 // goes above it.
3086 cleanup_scrollback(term);
3087 gap = &term->tl_scrollback;
3088 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003089 }
3090
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003091 limit_scrollback(term, gap, update_buffer);
3092
3093 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003094 {
3095 cellattr_T *p = NULL;
3096 int len = 0;
3097 int i;
3098 int c;
3099 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003100 int text_len;
3101 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003102 sb_line_T *line;
3103 garray_T ga;
3104 cellattr_T fill_attr = term->tl_default_color;
3105
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003106 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003107 for (i = 0; i < cols; ++i)
3108 if (cells[i].chars[0] != 0)
3109 len = i + 1;
3110 else
3111 cell2cellattr(&cells[i], &fill_attr);
3112
3113 ga_init2(&ga, 1, 100);
3114 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003115 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003116 if (p != NULL)
3117 {
3118 for (col = 0; col < len; col += cells[col].width)
3119 {
3120 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3121 {
3122 ga.ga_len = 0;
3123 break;
3124 }
3125 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3126 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3127 (char_u *)ga.ga_data + ga.ga_len);
3128 cell2cellattr(&cells[col], &p[col]);
3129 }
3130 }
3131 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003132 {
3133 if (update_buffer)
3134 text = (char_u *)"";
3135 else
3136 text = vim_strsave((char_u *)"");
3137 text_len = 0;
3138 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003139 else
3140 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003141 text = ga.ga_data;
3142 text_len = ga.ga_len;
3143 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003144 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003145 if (update_buffer)
3146 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003147
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003148 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003149 line->sb_cols = len;
3150 line->sb_cells = p;
3151 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003152 if (update_buffer)
3153 {
3154 line->sb_text = NULL;
3155 ++term->tl_scrollback_scrolled;
3156 ga_clear(&ga); // free the text
3157 }
3158 else
3159 {
3160 line->sb_text = text;
3161 ga_init(&ga); // text is kept in tl_scrollback_postponed
3162 }
3163 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003164 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003165 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003166}
3167
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003168/*
3169 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3170 * received and stored in tl_scrollback_postponed.
3171 */
3172 static void
3173handle_postponed_scrollback(term_T *term)
3174{
3175 int i;
3176
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003177 if (term->tl_scrollback_postponed.ga_len == 0)
3178 return;
3179 ch_log(NULL, "Moving postponed scrollback to scrollback");
3180
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003181 // First remove the lines that were appended before, the pushed lines go
3182 // above it.
3183 cleanup_scrollback(term);
3184
3185 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3186 {
3187 char_u *text;
3188 sb_line_T *pp_line;
3189 sb_line_T *line;
3190
3191 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3192 break;
3193 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3194
3195 text = pp_line->sb_text;
3196 if (text == NULL)
3197 text = (char_u *)"";
3198 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3199 vim_free(pp_line->sb_text);
3200
3201 line = (sb_line_T *)term->tl_scrollback.ga_data
3202 + term->tl_scrollback.ga_len;
3203 line->sb_cols = pp_line->sb_cols;
3204 line->sb_cells = pp_line->sb_cells;
3205 line->sb_fill_attr = pp_line->sb_fill_attr;
3206 line->sb_text = NULL;
3207 ++term->tl_scrollback_scrolled;
3208 ++term->tl_scrollback.ga_len;
3209 }
3210
3211 ga_clear(&term->tl_scrollback_postponed);
3212 limit_scrollback(term, &term->tl_scrollback, TRUE);
3213}
3214
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003215static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003216 handle_damage, // damage
3217 handle_moverect, // moverect
3218 handle_movecursor, // movecursor
3219 handle_settermprop, // settermprop
3220 NULL, // bell
3221 handle_resize, // resize
3222 handle_pushline, // sb_pushline
3223 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003224};
3225
3226/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003227 * Do the work after the channel of a terminal was closed.
3228 * Must be called only when updating_screen is FALSE.
3229 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3230 */
3231 static int
3232term_after_channel_closed(term_T *term)
3233{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003234 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003235 if (!term->tl_normal_mode)
3236 {
3237 int fnum = term->tl_buffer->b_fnum;
3238
3239 cleanup_vterm(term);
3240
3241 if (term->tl_finish == TL_FINISH_CLOSE)
3242 {
3243 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003244 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003245#ifdef FEAT_PROP_POPUP
3246 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003247
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003248 // If this was a terminal in a popup window, go back to the
3249 // previous window.
3250 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3251 {
3252 pwin = curwin;
3253 if (win_valid(prevwin))
3254 win_enter(prevwin, FALSE);
3255 }
3256 else
3257#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003258 // If this is the last normal window: exit Vim.
3259 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3260 {
3261 exarg_T ea;
3262
3263 vim_memset(&ea, 0, sizeof(ea));
3264 ex_quit(&ea);
3265 return TRUE;
3266 }
3267
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003268 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003269 ch_log(NULL, "terminal job finished, closing window");
3270 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003271 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003272 if (curwin == aucmd_win)
3273 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003274 if (do_set_w_closing)
3275 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003276 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003277 if (do_set_w_closing)
3278 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003279 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003280#ifdef FEAT_PROP_POPUP
3281 if (pwin != NULL)
3282 popup_close_with_retval(pwin, 0);
3283#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003284 return TRUE;
3285 }
3286 if (term->tl_finish == TL_FINISH_OPEN
3287 && term->tl_buffer->b_nwindows == 0)
3288 {
3289 char buf[50];
3290
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003291 // TODO: use term_opencmd
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003292 ch_log(NULL, "terminal job finished, opening window");
3293 vim_snprintf(buf, sizeof(buf),
3294 term->tl_opencmd == NULL
3295 ? "botright sbuf %d"
3296 : (char *)term->tl_opencmd, fnum);
3297 do_cmdline_cmd((char_u *)buf);
3298 }
3299 else
3300 ch_log(NULL, "terminal job finished");
3301 }
3302
3303 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3304 return FALSE;
3305}
3306
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003307#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3308/*
3309 * If the current window is a terminal in a popup window and the job has
3310 * finished, close the popup window and to back to the previous window.
3311 * Otherwise return FAIL.
3312 */
3313 int
3314may_close_term_popup(void)
3315{
3316 if (popup_is_popup(curwin) && curbuf->b_term != NULL
3317 && !term_job_running(curbuf->b_term))
3318 {
3319 win_T *pwin = curwin;
3320
3321 if (win_valid(prevwin))
3322 win_enter(prevwin, FALSE);
3323 popup_close_with_retval(pwin, 0);
3324 return OK;
3325 }
3326 return FAIL;
3327}
3328#endif
3329
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003330/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003331 * Called when a channel has been closed.
3332 * If this was a channel for a terminal window then finish it up.
3333 */
3334 void
3335term_channel_closed(channel_T *ch)
3336{
3337 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003338 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003339 int did_one = FALSE;
3340
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003341 for (term = first_term; term != NULL; term = next_term)
3342 {
3343 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003344 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003345 {
3346 term->tl_channel_closed = TRUE;
3347 did_one = TRUE;
3348
Bram Moolenaard23a8232018-02-10 18:45:26 +01003349 VIM_CLEAR(term->tl_title);
3350 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003351#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003352 if (term->tl_out_fd != NULL)
3353 {
3354 fclose(term->tl_out_fd);
3355 term->tl_out_fd = NULL;
3356 }
3357#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003358
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003359 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003360 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003361 // Cannot open or close windows now. Can happen when
3362 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003363 term->tl_channel_recently_closed = TRUE;
3364 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003365 }
3366
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003367 if (term_after_channel_closed(term))
3368 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003369 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003370 }
3371
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003372 if (did_one)
3373 {
3374 redraw_statuslines();
3375
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003376 // Need to break out of vgetc().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003377 ins_char_typebuf(K_IGNORE);
3378 typebuf_was_filled = TRUE;
3379
3380 term = curbuf->b_term;
3381 if (term != NULL)
3382 {
3383 if (term->tl_job == ch->ch_job)
3384 maketitle();
3385 update_cursor(term, term->tl_cursor_visible);
3386 }
3387 }
3388}
3389
3390/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003391 * To be called after resetting updating_screen: handle any terminal where the
3392 * channel was closed.
3393 */
3394 void
3395term_check_channel_closed_recently()
3396{
3397 term_T *term;
3398 term_T *next_term;
3399
3400 for (term = first_term; term != NULL; term = next_term)
3401 {
3402 next_term = term->tl_next;
3403 if (term->tl_channel_recently_closed)
3404 {
3405 term->tl_channel_recently_closed = FALSE;
3406 if (term_after_channel_closed(term))
3407 // start over, the list may have changed
3408 next_term = first_term;
3409 }
3410 }
3411}
3412
3413/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003414 * Fill one screen line from a line of the terminal.
3415 * Advances "pos" to past the last column.
3416 */
3417 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003418term_line2screenline(
3419 win_T *wp,
3420 VTermScreen *screen,
3421 VTermPos *pos,
3422 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003423{
3424 int off = screen_get_current_line_off();
3425
3426 for (pos->col = 0; pos->col < max_col; )
3427 {
3428 VTermScreenCell cell;
3429 int c;
3430
3431 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3432 vim_memset(&cell, 0, sizeof(cell));
3433
3434 c = cell.chars[0];
3435 if (c == NUL)
3436 {
3437 ScreenLines[off] = ' ';
3438 if (enc_utf8)
3439 ScreenLinesUC[off] = NUL;
3440 }
3441 else
3442 {
3443 if (enc_utf8)
3444 {
3445 int i;
3446
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003447 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003448 for (i = 0; i < Screen_mco
3449 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3450 {
3451 ScreenLinesC[i][off] = cell.chars[i + 1];
3452 if (cell.chars[i + 1] == 0)
3453 break;
3454 }
3455 if (c >= 0x80 || (Screen_mco > 0
3456 && ScreenLinesC[0][off] != 0))
3457 {
3458 ScreenLines[off] = ' ';
3459 ScreenLinesUC[off] = c;
3460 }
3461 else
3462 {
3463 ScreenLines[off] = c;
3464 ScreenLinesUC[off] = NUL;
3465 }
3466 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003467#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003468 else if (has_mbyte && c >= 0x80)
3469 {
3470 char_u mb[MB_MAXBYTES+1];
3471 WCHAR wc = c;
3472
3473 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3474 (char*)mb, 2, 0, 0) > 1)
3475 {
3476 ScreenLines[off] = mb[0];
3477 ScreenLines[off + 1] = mb[1];
3478 cell.width = mb_ptr2cells(mb);
3479 }
3480 else
3481 ScreenLines[off] = c;
3482 }
3483#endif
3484 else
3485 ScreenLines[off] = c;
3486 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003487 ScreenAttrs[off] = cell2attr(wp, cell.attrs, cell.fg, cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003488
3489 ++pos->col;
3490 ++off;
3491 if (cell.width == 2)
3492 {
3493 if (enc_utf8)
3494 ScreenLinesUC[off] = NUL;
3495
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003496 // don't set the second byte to NUL for a DBCS encoding, it
3497 // has been set above
Bram Moolenaar13568252018-03-16 20:46:58 +01003498 if (enc_utf8 || !has_mbyte)
3499 ScreenLines[off] = NUL;
3500
3501 ++pos->col;
3502 ++off;
3503 }
3504 }
3505}
3506
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003507#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003508 static void
3509update_system_term(term_T *term)
3510{
3511 VTermPos pos;
3512 VTermScreen *screen;
3513
3514 if (term->tl_vterm == NULL)
3515 return;
3516 screen = vterm_obtain_screen(term->tl_vterm);
3517
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003518 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003519 while (term->tl_toprow > 0
3520 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3521 {
3522 int save_p_more = p_more;
3523
3524 p_more = FALSE;
3525 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003526 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003527 p_more = save_p_more;
3528 --term->tl_toprow;
3529 }
3530
3531 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3532 && pos.row < Rows; ++pos.row)
3533 {
3534 if (pos.row < term->tl_rows)
3535 {
3536 int max_col = MIN(Columns, term->tl_cols);
3537
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003538 term_line2screenline(NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003539 }
3540 else
3541 pos.col = 0;
3542
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003543 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003544 }
3545
3546 term->tl_dirty_row_start = MAX_ROW;
3547 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003548}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003549#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003550
3551/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003552 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3553 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003554 * Terminal-Normal mode.
3555 */
3556 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003557term_do_update_window(win_T *wp)
3558{
3559 term_T *term = wp->w_buffer->b_term;
3560
3561 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3562}
3563
3564/*
3565 * Called to update a window that contains an active terminal.
3566 */
3567 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003568term_update_window(win_T *wp)
3569{
3570 term_T *term = wp->w_buffer->b_term;
3571 VTerm *vterm;
3572 VTermScreen *screen;
3573 VTermState *state;
3574 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003575 int rows, cols;
3576 int newrows, newcols;
3577 int minsize;
3578 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003579
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003580 vterm = term->tl_vterm;
3581 screen = vterm_obtain_screen(vterm);
3582 state = vterm_obtain_state(vterm);
3583
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003584 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3585 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003586 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003587 {
3588 term->tl_dirty_row_start = 0;
3589 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003590
3591 if (term->tl_postponed_scroll > 0
3592 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003593 // Scrolling is usually faster than redrawing, when there are only
3594 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003595 term_scroll_up(term, 0, term->tl_postponed_scroll);
3596 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003597 }
3598
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003599 /*
3600 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003601 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003602 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003603 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003604
Bram Moolenaar498c2562018-04-15 23:45:15 +02003605 newrows = 99999;
3606 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003607 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003608 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003609 // Always use curwin, it may be a popup window.
3610 win_T *wwp = twp == NULL ? curwin : twp;
3611
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003612 // When more than one window shows the same terminal, use the
3613 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003614 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003615 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003616 newrows = MIN(newrows, wwp->w_height);
3617 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003618 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003619 if (twp == NULL)
3620 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003621 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003622 if (newrows == 99999 || newcols == 99999)
3623 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003624 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3625 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3626
3627 if (term->tl_rows != newrows || term->tl_cols != newcols)
3628 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003629 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003630 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003631 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003632 newrows);
3633 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003634
3635 // Updating the terminal size will cause the snapshot to be cleared.
3636 // When not in terminal_loop() we need to restore it.
3637 if (term != in_terminal_loop)
3638 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003639 }
3640
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003641 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003642 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003643 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003644
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003645 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3646 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003647 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003648 if (pos.row < term->tl_rows)
3649 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003650 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003651
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003652 term_line2screenline(wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003653 }
3654 else
3655 pos.col = 0;
3656
Bram Moolenaarf118d482018-03-13 13:14:00 +01003657 screen_line(wp->w_winrow + pos.row
3658#ifdef FEAT_MENU
3659 + winbar_height(wp)
3660#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003661 , wp->w_wincol, pos.col, wp->w_width,
3662#ifdef FEAT_PROP_POPUP
3663 popup_is_popup(wp) ? SLF_POPUP :
3664#endif
3665 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003666 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003667 term->tl_dirty_row_start = MAX_ROW;
3668 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003669}
3670
3671/*
3672 * Return TRUE if "wp" is a terminal window where the job has finished.
3673 */
3674 int
3675term_is_finished(buf_T *buf)
3676{
3677 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3678}
3679
3680/*
3681 * Return TRUE if "wp" is a terminal window where the job has finished or we
3682 * are in Terminal-Normal mode, thus we show the buffer contents.
3683 */
3684 int
3685term_show_buffer(buf_T *buf)
3686{
3687 term_T *term = buf->b_term;
3688
3689 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3690}
3691
3692/*
3693 * The current buffer is going to be changed. If there is terminal
3694 * highlighting remove it now.
3695 */
3696 void
3697term_change_in_curbuf(void)
3698{
3699 term_T *term = curbuf->b_term;
3700
3701 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3702 {
3703 free_scrollback(term);
3704 redraw_buf_later(term->tl_buffer, NOT_VALID);
3705
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003706 // The buffer is now like a normal buffer, it cannot be easily
3707 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003708 set_string_option_direct((char_u *)"buftype", -1,
3709 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3710 }
3711}
3712
3713/*
3714 * Get the screen attribute for a position in the buffer.
3715 * Use a negative "col" to get the filler background color.
3716 */
3717 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003718term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003719{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003720 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003721 term_T *term = buf->b_term;
3722 sb_line_T *line;
3723 cellattr_T *cellattr;
3724
3725 if (lnum > term->tl_scrollback.ga_len)
3726 cellattr = &term->tl_default_color;
3727 else
3728 {
3729 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3730 if (col < 0 || col >= line->sb_cols)
3731 cellattr = &line->sb_fill_attr;
3732 else
3733 cellattr = line->sb_cells + col;
3734 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003735 return cell2attr(wp, cellattr->attrs, cellattr->fg, cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003736}
3737
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003738/*
3739 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003740 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003741 */
3742 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003743cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003744{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003745 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003746}
3747
3748/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003749 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003750 */
3751 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003752init_default_colors(term_T *term, win_T *wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003753{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003754 VTermColor *fg, *bg;
3755 int fgval, bgval;
3756 int id;
3757
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003758 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3759 term->tl_default_color.width = 1;
3760 fg = &term->tl_default_color.fg;
3761 bg = &term->tl_default_color.bg;
3762
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003763 // Vterm uses a default black background. Set it to white when
3764 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003765 if (*p_bg == 'l')
3766 {
3767 fgval = 0;
3768 bgval = 255;
3769 }
3770 else
3771 {
3772 fgval = 255;
3773 bgval = 0;
3774 }
3775 fg->red = fg->green = fg->blue = fgval;
3776 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003777 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003778
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003779 // The 'wincolor' or "Terminal" highlight group overrules the defaults.
3780 if (wp != NULL && *wp->w_p_wcr != NUL)
3781 id = syn_name2id(wp->w_p_wcr);
3782 else
3783 id = syn_name2id((char_u *)"Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003784
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003785 // Use the actual color for the GUI and when 'termguicolors' is set.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003786#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3787 if (0
3788# ifdef FEAT_GUI
3789 || gui.in_use
3790# endif
3791# ifdef FEAT_TERMGUICOLORS
3792 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003793# ifdef FEAT_VTP
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003794 // Finally get INVALCOLOR on this execution path
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003795 || (!p_tgc && t_colors >= 256)
3796# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003797# endif
3798 )
3799 {
3800 guicolor_T fg_rgb = INVALCOLOR;
3801 guicolor_T bg_rgb = INVALCOLOR;
3802
3803 if (id != 0)
3804 syn_id2colors(id, &fg_rgb, &bg_rgb);
3805
3806# ifdef FEAT_GUI
3807 if (gui.in_use)
3808 {
3809 if (fg_rgb == INVALCOLOR)
3810 fg_rgb = gui.norm_pixel;
3811 if (bg_rgb == INVALCOLOR)
3812 bg_rgb = gui.back_pixel;
3813 }
3814# ifdef FEAT_TERMGUICOLORS
3815 else
3816# endif
3817# endif
3818# ifdef FEAT_TERMGUICOLORS
3819 {
3820 if (fg_rgb == INVALCOLOR)
3821 fg_rgb = cterm_normal_fg_gui_color;
3822 if (bg_rgb == INVALCOLOR)
3823 bg_rgb = cterm_normal_bg_gui_color;
3824 }
3825# endif
3826 if (fg_rgb != INVALCOLOR)
3827 {
3828 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3829
3830 fg->red = (unsigned)(rgb >> 16);
3831 fg->green = (unsigned)(rgb >> 8) & 255;
3832 fg->blue = (unsigned)rgb & 255;
3833 }
3834 if (bg_rgb != INVALCOLOR)
3835 {
3836 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3837
3838 bg->red = (unsigned)(rgb >> 16);
3839 bg->green = (unsigned)(rgb >> 8) & 255;
3840 bg->blue = (unsigned)rgb & 255;
3841 }
3842 }
3843 else
3844#endif
3845 if (id != 0 && t_colors >= 16)
3846 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003847 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003848 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003849 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003850 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003851 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003852 else
3853 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003854#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003855 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003856#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003857
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003858 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003859 if (cterm_normal_fg_color > 0)
3860 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003861 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003862# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3863# ifdef VIMDLL
3864 if (!gui.in_use)
3865# endif
3866 {
3867 tmp = fg->red;
3868 fg->red = fg->blue;
3869 fg->blue = tmp;
3870 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003871# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003872 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003873# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003874 else
3875 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003876# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003877
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003878 if (cterm_normal_bg_color > 0)
3879 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003880 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003881# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3882# ifdef VIMDLL
3883 if (!gui.in_use)
3884# endif
3885 {
3886 tmp = fg->red;
3887 fg->red = fg->blue;
3888 fg->blue = tmp;
3889 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003890# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003891 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003892# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003893 else
3894 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003895# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003896 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003897}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003898
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003899#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3900/*
3901 * Set the 16 ANSI colors from array of RGB values
3902 */
3903 static void
3904set_vterm_palette(VTerm *vterm, long_u *rgb)
3905{
3906 int index = 0;
3907 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003908
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003909 for (; index < 16; index++)
3910 {
3911 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003912
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003913 color.red = (unsigned)(rgb[index] >> 16);
3914 color.green = (unsigned)(rgb[index] >> 8) & 255;
3915 color.blue = (unsigned)rgb[index] & 255;
3916 vterm_state_set_palette_color(state, index, &color);
3917 }
3918}
3919
3920/*
3921 * Set the ANSI color palette from a list of colors
3922 */
3923 static int
3924set_ansi_colors_list(VTerm *vterm, list_T *list)
3925{
3926 int n = 0;
3927 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01003928 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003929
Bram Moolenaarb0992022020-01-30 14:55:42 +01003930 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003931 {
3932 char_u *color_name;
3933 guicolor_T guicolor;
3934
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003935 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003936 if (color_name == NULL)
3937 return FAIL;
3938
3939 guicolor = GUI_GET_COLOR(color_name);
3940 if (guicolor == INVALCOLOR)
3941 return FAIL;
3942
3943 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3944 }
3945
3946 if (n != 16 || li != NULL)
3947 return FAIL;
3948
3949 set_vterm_palette(vterm, rgb);
3950
3951 return OK;
3952}
3953
3954/*
3955 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3956 */
3957 static void
3958init_vterm_ansi_colors(VTerm *vterm)
3959{
3960 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3961
3962 if (var != NULL
3963 && (var->di_tv.v_type != VAR_LIST
3964 || var->di_tv.vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +01003965 || var->di_tv.vval.v_list->lv_first == &range_list_item
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003966 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003967 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003968}
3969#endif
3970
Bram Moolenaar52acb112018-03-18 19:20:22 +01003971/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003972 * Handles a "drop" command from the job in the terminal.
3973 * "item" is the file name, "item->li_next" may have options.
3974 */
3975 static void
3976handle_drop_command(listitem_T *item)
3977{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003978 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003979 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003980 int bufnr;
3981 win_T *wp;
3982 tabpage_T *tp;
3983 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003984 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003985
3986 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3987 FOR_ALL_TAB_WINDOWS(tp, wp)
3988 {
3989 if (wp->w_buffer->b_fnum == bufnr)
3990 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003991 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003992 goto_tabpage_win(tp, wp);
3993 return;
3994 }
3995 }
3996
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003997 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003998
3999 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4000 && opt_item->li_tv.vval.v_dict != NULL)
4001 {
4002 dict_T *dict = opt_item->li_tv.vval.v_dict;
4003 char_u *p;
4004
Bram Moolenaar8f667172018-12-14 15:38:31 +01004005 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004006 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004007 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004008 if (p != NULL)
4009 {
4010 if (check_ff_value(p) == FAIL)
4011 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4012 else
4013 ea.force_ff = *p;
4014 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01004015 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004016 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004017 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004018 if (p != NULL)
4019 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004020 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004021 if (ea.cmd != NULL)
4022 {
4023 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4024 ea.force_enc = 11;
4025 tofree = ea.cmd;
4026 }
4027 }
4028
Bram Moolenaar8f667172018-12-14 15:38:31 +01004029 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004030 if (p != NULL)
4031 get_bad_opt(p, &ea);
4032
4033 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
4034 ea.force_bin = FORCE_BIN;
4035 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
4036 ea.force_bin = FORCE_BIN;
4037 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
4038 ea.force_bin = FORCE_NOBIN;
4039 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
4040 ea.force_bin = FORCE_NOBIN;
4041 }
4042
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004043 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004044 if (ea.cmd == NULL)
4045 ea.cmd = (char_u *)"split";
4046 ea.arg = fname;
4047 ea.cmdidx = CMD_split;
4048 ex_splitview(&ea);
4049
4050 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004051}
4052
4053/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004054 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4055 */
4056 static int
4057is_permitted_term_api(char_u *func, char_u *pat)
4058{
4059 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4060}
4061
4062/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004063 * Handles a function call from the job running in a terminal.
4064 * "item" is the function name, "item->li_next" has the arguments.
4065 */
4066 static void
4067handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4068{
4069 char_u *func;
4070 typval_T argvars[2];
4071 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004072 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004073
4074 if (item->li_next == NULL)
4075 {
4076 ch_log(channel, "Missing function arguments for call");
4077 return;
4078 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004079 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004080
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004081 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004082 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004083 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004084 return;
4085 }
4086
4087 argvars[0].v_type = VAR_NUMBER;
4088 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4089 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004090 vim_memset(&funcexe, 0, sizeof(funcexe));
4091 funcexe.firstline = 1L;
4092 funcexe.lastline = 1L;
4093 funcexe.evaluate = TRUE;
4094 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004095 {
4096 clear_tv(&rettv);
4097 ch_log(channel, "Function %s called", func);
4098 }
4099 else
4100 ch_log(channel, "Calling function %s failed", func);
4101}
4102
4103/*
4104 * Called by libvterm when it cannot recognize an OSC sequence.
4105 * We recognize a terminal API command.
4106 */
4107 static int
4108parse_osc(const char *command, size_t cmdlen, void *user)
4109{
4110 term_T *term = (term_T *)user;
4111 js_read_T reader;
4112 typval_T tv;
4113 channel_T *channel = term->tl_job == NULL ? NULL
4114 : term->tl_job->jv_channel;
4115
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004116 // We recognize only OSC 5 1 ; {command}
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004117 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004118 return 0; // not handled
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004119
Bram Moolenaar878c96d2018-04-04 23:00:06 +02004120 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004121 if (reader.js_buf == NULL)
4122 return 1;
4123 reader.js_fill = NULL;
4124 reader.js_used = 0;
4125 if (json_decode(&reader, &tv, 0) == OK
4126 && tv.v_type == VAR_LIST
4127 && tv.vval.v_list != NULL)
4128 {
4129 listitem_T *item = tv.vval.v_list->lv_first;
4130
4131 if (item == NULL)
4132 ch_log(channel, "Missing command");
4133 else
4134 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004135 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004136
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004137 // Make sure an invoked command doesn't delete the buffer (and the
4138 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004139 ++term->tl_buffer->b_locked;
4140
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004141 item = item->li_next;
4142 if (item == NULL)
4143 ch_log(channel, "Missing argument for %s", cmd);
4144 else if (STRCMP(cmd, "drop") == 0)
4145 handle_drop_command(item);
4146 else if (STRCMP(cmd, "call") == 0)
4147 handle_call_command(term, channel, item);
4148 else
4149 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004150 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004151 }
4152 }
4153 else
4154 ch_log(channel, "Invalid JSON received");
4155
4156 vim_free(reader.js_buf);
4157 clear_tv(&tv);
4158 return 1;
4159}
4160
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004161/*
4162 * Called by libvterm when it cannot recognize a CSI sequence.
4163 * We recognize the window position report.
4164 */
4165 static int
4166parse_csi(
4167 const char *leader UNUSED,
4168 const long args[],
4169 int argcount,
4170 const char *intermed UNUSED,
4171 char command,
4172 void *user)
4173{
4174 term_T *term = (term_T *)user;
4175 char buf[100];
4176 int len;
4177 int x = 0;
4178 int y = 0;
4179 win_T *wp;
4180
4181 // We recognize only CSI 13 t
4182 if (command != 't' || argcount != 1 || args[0] != 13)
4183 return 0; // not handled
4184
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004185 // When getting the window position is not possible or it fails it results
4186 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004187#if defined(FEAT_GUI) \
4188 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4189 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004190 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004191#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004192
4193 FOR_ALL_WINDOWS(wp)
4194 if (wp->w_buffer == term->tl_buffer)
4195 break;
4196 if (wp != NULL)
4197 {
4198#ifdef FEAT_GUI
4199 if (gui.in_use)
4200 {
4201 x += wp->w_wincol * gui.char_width;
4202 y += W_WINROW(wp) * gui.char_height;
4203 }
4204 else
4205#endif
4206 {
4207 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004208 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004209 x += wp->w_wincol * 7;
4210 y += W_WINROW(wp) * 10;
4211 }
4212 }
4213
4214 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4215 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4216 (char_u *)buf, len, NULL);
4217 return 1;
4218}
4219
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004220static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004221 NULL, // text
4222 NULL, // control
4223 NULL, // escape
4224 parse_csi, // csi
4225 parse_osc, // osc
4226 NULL, // dcs
4227 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004228};
4229
4230/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004231 * Use Vim's allocation functions for vterm so profiling works.
4232 */
4233 static void *
4234vterm_malloc(size_t size, void *data UNUSED)
4235{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004236 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004237}
4238
4239 static void
4240vterm_memfree(void *ptr, void *data UNUSED)
4241{
4242 vim_free(ptr);
4243}
4244
4245static VTermAllocatorFunctions vterm_allocator = {
4246 &vterm_malloc,
4247 &vterm_memfree
4248};
4249
4250/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004251 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004252 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004253 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004254 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004255create_vterm(term_T *term, int rows, int cols)
4256{
4257 VTerm *vterm;
4258 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004259 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004260 VTermValue value;
4261
Bram Moolenaar756ef112018-04-10 12:04:27 +02004262 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004263 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004264 if (vterm == NULL)
4265 return FAIL;
4266
4267 // Allocate screen and state here, so we can bail out if that fails.
4268 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004269 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004270 if (state == NULL || screen == NULL)
4271 {
4272 vterm_free(vterm);
4273 return FAIL;
4274 }
4275
Bram Moolenaar52acb112018-03-18 19:20:22 +01004276 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004277 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004278 vterm_set_utf8(vterm, 1);
4279
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004280 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004281
4282 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004283 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004284 &term->tl_default_color.fg,
4285 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004286
Bram Moolenaar9e587872019-05-13 20:27:23 +02004287 if (t_colors < 16)
4288 // Less than 16 colors: assume that bold means using a bright color for
4289 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004290 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4291
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004292 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004293 vterm_screen_reset(screen, 1 /* hard */);
4294
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004295 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004296 vterm_screen_enable_altscreen(screen, 1);
4297
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004298 // For unix do not use a blinking cursor. In an xterm this causes the
4299 // cursor to blink if it's blinking in the xterm.
4300 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004301#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004302 if (GetCaretBlinkTime() == INFINITE)
4303 value.boolean = 0;
4304 else
4305 value.boolean = 1;
4306#else
4307 value.boolean = 0;
4308#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004309 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4310 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004311
4312 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004313}
4314
4315/*
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004316 * Called when 'wincolor' was set.
4317 */
4318 void
4319term_update_colors(void)
4320{
4321 term_T *term = curwin->w_buffer->b_term;
4322
Bram Moolenaar7ba3b912020-02-10 20:34:04 +01004323 if (term->tl_vterm == NULL)
4324 return;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004325 init_default_colors(term, curwin);
4326 vterm_state_set_default_colors(
4327 vterm_obtain_state(term->tl_vterm),
4328 &term->tl_default_color.fg,
4329 &term->tl_default_color.bg);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +01004330
4331 redraw_later(NOT_VALID);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004332}
4333
4334/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004335 * Return the text to show for the buffer name and status.
4336 */
4337 char_u *
4338term_get_status_text(term_T *term)
4339{
4340 if (term->tl_status_text == NULL)
4341 {
4342 char_u *txt;
4343 size_t len;
4344
4345 if (term->tl_normal_mode)
4346 {
4347 if (term_job_running(term))
4348 txt = (char_u *)_("Terminal");
4349 else
4350 txt = (char_u *)_("Terminal-finished");
4351 }
4352 else if (term->tl_title != NULL)
4353 txt = term->tl_title;
4354 else if (term_none_open(term))
4355 txt = (char_u *)_("active");
4356 else if (term_job_running(term))
4357 txt = (char_u *)_("running");
4358 else
4359 txt = (char_u *)_("finished");
4360 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004361 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004362 if (term->tl_status_text != NULL)
4363 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4364 term->tl_buffer->b_fname, txt);
4365 }
4366 return term->tl_status_text;
4367}
4368
4369/*
4370 * Mark references in jobs of terminals.
4371 */
4372 int
4373set_ref_in_term(int copyID)
4374{
4375 int abort = FALSE;
4376 term_T *term;
4377 typval_T tv;
4378
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004379 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004380 if (term->tl_job != NULL)
4381 {
4382 tv.v_type = VAR_JOB;
4383 tv.vval.v_job = term->tl_job;
4384 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4385 }
4386 return abort;
4387}
4388
4389/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004390 * Cache "Terminal" highlight group colors.
4391 */
4392 void
4393set_terminal_default_colors(int cterm_fg, int cterm_bg)
4394{
4395 term_default_cterm_fg = cterm_fg - 1;
4396 term_default_cterm_bg = cterm_bg - 1;
4397}
4398
4399/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004400 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004401 * Returns NULL when the buffer is not for a terminal window and logs a message
4402 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004403 */
4404 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004405term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004406{
4407 buf_T *buf;
4408
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004409 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004410 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004411 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004412 --emsg_off;
4413 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004414 {
4415 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004416 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004417 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004418 return buf;
4419}
4420
Bram Moolenaard96ff162018-02-18 22:13:29 +01004421 static int
4422same_color(VTermColor *a, VTermColor *b)
4423{
4424 return a->red == b->red
4425 && a->green == b->green
4426 && a->blue == b->blue
4427 && a->ansi_index == b->ansi_index;
4428}
4429
4430 static void
4431dump_term_color(FILE *fd, VTermColor *color)
4432{
4433 fprintf(fd, "%02x%02x%02x%d",
4434 (int)color->red, (int)color->green, (int)color->blue,
4435 (int)color->ansi_index);
4436}
4437
4438/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004439 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004440 *
4441 * Each screen cell in full is:
4442 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4443 * {characters} is a space for an empty cell
4444 * For a double-width character "+" is changed to "*" and the next cell is
4445 * skipped.
4446 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4447 * when "&" use the same as the previous cell.
4448 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4449 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4450 * {color-idx} is a number from 0 to 255
4451 *
4452 * Screen cell with same width, attributes and color as the previous one:
4453 * |{characters}
4454 *
4455 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4456 *
4457 * Repeating the previous screen cell:
4458 * @{count}
4459 */
4460 void
4461f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4462{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004463 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004464 term_T *term;
4465 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004466 int max_height = 0;
4467 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004468 stat_T st;
4469 FILE *fd;
4470 VTermPos pos;
4471 VTermScreen *screen;
4472 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004473 VTermState *state;
4474 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004475
4476 if (check_restricted() || check_secure())
4477 return;
4478 if (buf == NULL)
4479 return;
4480 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004481 if (term->tl_vterm == NULL)
4482 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004483 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004484 return;
4485 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004486
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004487 if (argvars[2].v_type != VAR_UNKNOWN)
4488 {
4489 dict_T *d;
4490
4491 if (argvars[2].v_type != VAR_DICT)
4492 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004493 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004494 return;
4495 }
4496 d = argvars[2].vval.v_dict;
4497 if (d != NULL)
4498 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004499 max_height = dict_get_number(d, (char_u *)"rows");
4500 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004501 }
4502 }
4503
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004504 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004505 if (fname == NULL)
4506 return;
4507 if (mch_stat((char *)fname, &st) >= 0)
4508 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004509 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004510 return;
4511 }
4512
Bram Moolenaard96ff162018-02-18 22:13:29 +01004513 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4514 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004515 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004516 return;
4517 }
4518
4519 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4520
4521 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004522 state = vterm_obtain_state(term->tl_vterm);
4523 vterm_state_get_cursorpos(state, &cursor_pos);
4524
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004525 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4526 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004527 {
4528 int repeat = 0;
4529
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004530 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4531 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004532 {
4533 VTermScreenCell cell;
4534 int same_attr;
4535 int same_chars = TRUE;
4536 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004537 int is_cursor_pos = (pos.col == cursor_pos.col
4538 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004539
4540 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4541 vim_memset(&cell, 0, sizeof(cell));
4542
4543 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4544 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004545 int c = cell.chars[i];
4546 int pc = prev_cell.chars[i];
4547
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004548 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01004549 if (i == 0)
4550 {
4551 c = (c == NUL) ? ' ' : c;
4552 pc = (pc == NUL) ? ' ' : pc;
4553 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004554 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004555 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004556 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004557 break;
4558 }
4559 same_attr = vtermAttr2hl(cell.attrs)
4560 == vtermAttr2hl(prev_cell.attrs)
4561 && same_color(&cell.fg, &prev_cell.fg)
4562 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004563 if (same_chars && cell.width == prev_cell.width && same_attr
4564 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004565 {
4566 ++repeat;
4567 }
4568 else
4569 {
4570 if (repeat > 0)
4571 {
4572 fprintf(fd, "@%d", repeat);
4573 repeat = 0;
4574 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004575 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004576
4577 if (cell.chars[0] == NUL)
4578 fputs(" ", fd);
4579 else
4580 {
4581 char_u charbuf[10];
4582 int len;
4583
4584 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4585 && cell.chars[i] != NUL; ++i)
4586 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004587 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004588 fwrite(charbuf, len, 1, fd);
4589 }
4590 }
4591
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004592 // When only the characters differ we don't write anything, the
4593 // following "|", "@" or NL will indicate using the same
4594 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004595 if (cell.width != prev_cell.width || !same_attr)
4596 {
4597 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004598 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004599 else
4600 fputs("+", fd);
4601
4602 if (same_attr)
4603 {
4604 fputs("&", fd);
4605 }
4606 else
4607 {
4608 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4609 if (same_color(&cell.fg, &prev_cell.fg))
4610 fputs("&", fd);
4611 else
4612 {
4613 fputs("#", fd);
4614 dump_term_color(fd, &cell.fg);
4615 }
4616 if (same_color(&cell.bg, &prev_cell.bg))
4617 fputs("&", fd);
4618 else
4619 {
4620 fputs("#", fd);
4621 dump_term_color(fd, &cell.bg);
4622 }
4623 }
4624 }
4625
4626 prev_cell = cell;
4627 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004628
4629 if (cell.width == 2)
4630 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004631 }
4632 if (repeat > 0)
4633 fprintf(fd, "@%d", repeat);
4634 fputs("\n", fd);
4635 }
4636
4637 fclose(fd);
4638}
4639
4640/*
4641 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4642 */
4643 static void
4644dump_is_corrupt(garray_T *gap)
4645{
4646 ga_concat(gap, (char_u *)"CORRUPT");
4647}
4648
4649 static void
4650append_cell(garray_T *gap, cellattr_T *cell)
4651{
4652 if (ga_grow(gap, 1) == OK)
4653 {
4654 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4655 ++gap->ga_len;
4656 }
4657}
4658
4659/*
4660 * Read the dump file from "fd" and append lines to the current buffer.
4661 * Return the cell width of the longest line.
4662 */
4663 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004664read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004665{
4666 int c;
4667 garray_T ga_text;
4668 garray_T ga_cell;
4669 char_u *prev_char = NULL;
4670 int attr = 0;
4671 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004672 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004673 term_T *term = curbuf->b_term;
4674 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004675 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004676
4677 ga_init2(&ga_text, 1, 90);
4678 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4679 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004680 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004681 cursor_pos->row = -1;
4682 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004683
4684 c = fgetc(fd);
4685 for (;;)
4686 {
4687 if (c == EOF)
4688 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004689 if (c == '\r')
4690 {
4691 // DOS line endings? Ignore.
4692 c = fgetc(fd);
4693 }
4694 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004695 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004696 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004697 if (ga_text.ga_data == NULL)
4698 dump_is_corrupt(&ga_text);
4699 if (ga_grow(&term->tl_scrollback, 1) == OK)
4700 {
4701 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4702 + term->tl_scrollback.ga_len;
4703
4704 if (max_cells < ga_cell.ga_len)
4705 max_cells = ga_cell.ga_len;
4706 line->sb_cols = ga_cell.ga_len;
4707 line->sb_cells = ga_cell.ga_data;
4708 line->sb_fill_attr = term->tl_default_color;
4709 ++term->tl_scrollback.ga_len;
4710 ga_init(&ga_cell);
4711
4712 ga_append(&ga_text, NUL);
4713 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4714 ga_text.ga_len, FALSE);
4715 }
4716 else
4717 ga_clear(&ga_cell);
4718 ga_text.ga_len = 0;
4719
4720 c = fgetc(fd);
4721 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004722 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004723 {
4724 int prev_len = ga_text.ga_len;
4725
Bram Moolenaar9271d052018-02-25 21:39:46 +01004726 if (c == '>')
4727 {
4728 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004729 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004730 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4731 cursor_pos->col = ga_cell.ga_len;
4732 }
4733
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004734 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004735 c = fgetc(fd);
4736 if (c != EOF)
4737 ga_append(&ga_text, c);
4738 for (;;)
4739 {
4740 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004741 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004742 || c == EOF || c == '\n')
4743 break;
4744 ga_append(&ga_text, c);
4745 }
4746
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004747 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01004748 vim_free(prev_char);
4749 if (ga_text.ga_data != NULL)
4750 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4751 ga_text.ga_len - prev_len);
4752
Bram Moolenaar9271d052018-02-25 21:39:46 +01004753 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004754 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004755 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004756 }
4757 else if (c == '+' || c == '*')
4758 {
4759 int is_bg;
4760
4761 cell.width = c == '+' ? 1 : 2;
4762
4763 c = fgetc(fd);
4764 if (c == '&')
4765 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004766 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004767 c = fgetc(fd);
4768 }
4769 else if (isdigit(c))
4770 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004771 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01004772 attr = 0;
4773 while (isdigit(c))
4774 {
4775 attr = attr * 10 + (c - '0');
4776 c = fgetc(fd);
4777 }
4778 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004779
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004780 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004781 for (is_bg = 0; is_bg <= 1; ++is_bg)
4782 {
4783 if (c == '&')
4784 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004785 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004786 c = fgetc(fd);
4787 }
4788 else if (c == '#')
4789 {
4790 int red, green, blue, index = 0;
4791
4792 c = fgetc(fd);
4793 red = hex2nr(c);
4794 c = fgetc(fd);
4795 red = (red << 4) + hex2nr(c);
4796 c = fgetc(fd);
4797 green = hex2nr(c);
4798 c = fgetc(fd);
4799 green = (green << 4) + hex2nr(c);
4800 c = fgetc(fd);
4801 blue = hex2nr(c);
4802 c = fgetc(fd);
4803 blue = (blue << 4) + hex2nr(c);
4804 c = fgetc(fd);
4805 if (!isdigit(c))
4806 dump_is_corrupt(&ga_text);
4807 while (isdigit(c))
4808 {
4809 index = index * 10 + (c - '0');
4810 c = fgetc(fd);
4811 }
4812
4813 if (is_bg)
4814 {
4815 cell.bg.red = red;
4816 cell.bg.green = green;
4817 cell.bg.blue = blue;
4818 cell.bg.ansi_index = index;
4819 }
4820 else
4821 {
4822 cell.fg.red = red;
4823 cell.fg.green = green;
4824 cell.fg.blue = blue;
4825 cell.fg.ansi_index = index;
4826 }
4827 }
4828 else
4829 dump_is_corrupt(&ga_text);
4830 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004831 }
4832 else
4833 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004834 }
4835 else
4836 dump_is_corrupt(&ga_text);
4837
4838 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004839 if (cell.width == 2)
4840 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004841 }
4842 else if (c == '@')
4843 {
4844 if (prev_char == NULL)
4845 dump_is_corrupt(&ga_text);
4846 else
4847 {
4848 int count = 0;
4849
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004850 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01004851 for (;;)
4852 {
4853 c = fgetc(fd);
4854 if (!isdigit(c))
4855 break;
4856 count = count * 10 + (c - '0');
4857 }
4858
4859 while (count-- > 0)
4860 {
4861 ga_concat(&ga_text, prev_char);
4862 append_cell(&ga_cell, &cell);
4863 }
4864 }
4865 }
4866 else
4867 {
4868 dump_is_corrupt(&ga_text);
4869 c = fgetc(fd);
4870 }
4871 }
4872
4873 if (ga_text.ga_len > 0)
4874 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004875 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004876 dump_is_corrupt(&ga_text);
4877 ga_append(&ga_text, NUL);
4878 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4879 ga_text.ga_len, FALSE);
4880 }
4881
4882 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004883 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004884 vim_free(prev_char);
4885
4886 return max_cells;
4887}
4888
4889/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004890 * Return an allocated string with at least "text_width" "=" characters and
4891 * "fname" inserted in the middle.
4892 */
4893 static char_u *
4894get_separator(int text_width, char_u *fname)
4895{
4896 int width = MAX(text_width, curwin->w_width);
4897 char_u *textline;
4898 int fname_size;
4899 char_u *p = fname;
4900 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004901 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004902
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004903 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004904 if (textline == NULL)
4905 return NULL;
4906
4907 fname_size = vim_strsize(fname);
4908 if (fname_size < width - 8)
4909 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004910 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02004911 width = MAX(text_width, fname_size + 8);
4912 }
4913 else if (fname_size > width - 8)
4914 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004915 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02004916 p = gettail(fname);
4917 fname_size = vim_strsize(p);
4918 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004919 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02004920 while (fname_size > width - 8)
4921 {
4922 p += (*mb_ptr2len)(p);
4923 fname_size = vim_strsize(p);
4924 }
4925
4926 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4927 textline[i] = '=';
4928 textline[i++] = ' ';
4929
4930 STRCPY(textline + i, p);
4931 off = STRLEN(textline);
4932 textline[off] = ' ';
4933 for (i = 1; i < (width - fname_size) / 2; ++i)
4934 textline[off + i] = '=';
4935 textline[off + i] = NUL;
4936
4937 return textline;
4938}
4939
4940/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004941 * Common for "term_dumpdiff()" and "term_dumpload()".
4942 */
4943 static void
4944term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4945{
4946 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004947 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004948 char_u buf1[NUMBUFLEN];
4949 char_u buf2[NUMBUFLEN];
4950 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004951 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004952 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004953 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004954 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004955 char_u *textline = NULL;
4956
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004957 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004958 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004959 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004960 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004961 if (fname1 == NULL || (do_diff && fname2 == NULL))
4962 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004963 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004964 return;
4965 }
4966 fd1 = mch_fopen((char *)fname1, READBIN);
4967 if (fd1 == NULL)
4968 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004969 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004970 return;
4971 }
4972 if (do_diff)
4973 {
4974 fd2 = mch_fopen((char *)fname2, READBIN);
4975 if (fd2 == NULL)
4976 {
4977 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004978 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004979 return;
4980 }
4981 }
4982
4983 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004984 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4985 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4986 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4987 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4988 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004989
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004990 if (opt.jo_term_name == NULL)
4991 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004992 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004993
Bram Moolenaar51e14382019-05-25 20:21:28 +02004994 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004995 if (fname_tofree != NULL)
4996 {
4997 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4998 opt.jo_term_name = fname_tofree;
4999 }
5000 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005001
Bram Moolenaar87abab92019-06-03 21:14:59 +02005002 if (opt.jo_bufnr_buf != NULL)
5003 {
5004 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5005
5006 // With "bufnr" argument: enter the window with this buffer and make it
5007 // empty.
5008 if (wp == NULL)
5009 semsg(_(e_invarg2), "bufnr");
5010 else
5011 {
5012 buf = curbuf;
5013 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
5014 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02005015 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005016 redraw_later(NOT_VALID);
5017 }
5018 }
5019 else
5020 // Create a new terminal window.
5021 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5022
Bram Moolenaard96ff162018-02-18 22:13:29 +01005023 if (buf != NULL && buf->b_term != NULL)
5024 {
5025 int i;
5026 linenr_T bot_lnum;
5027 linenr_T lnum;
5028 term_T *term = buf->b_term;
5029 int width;
5030 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005031 VTermPos cursor_pos1;
5032 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005033
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005034 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005035
Bram Moolenaard96ff162018-02-18 22:13:29 +01005036 rettv->vval.v_number = buf->b_fnum;
5037
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005038 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005039 width = read_dump_file(fd1, &cursor_pos1);
5040
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005041 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005042 if (cursor_pos1.row >= 0)
5043 {
5044 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5045 coladvance(cursor_pos1.col);
5046 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005047
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005048 // Delete the empty line that was in the empty buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005049 ml_delete(1, FALSE);
5050
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005051 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005052 if (!do_diff)
5053 goto theend;
5054
5055 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5056
Bram Moolenaar4a696342018-04-05 18:45:26 +02005057 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005058 if (textline == NULL)
5059 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005060 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5061 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5062 vim_free(textline);
5063
5064 textline = get_separator(width, fname2);
5065 if (textline == NULL)
5066 goto theend;
5067 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5068 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005069 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005070
5071 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005072 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005073 if (width2 > width)
5074 {
5075 vim_free(textline);
5076 textline = alloc(width2 + 1);
5077 if (textline == NULL)
5078 goto theend;
5079 width = width2;
5080 textline[width] = NUL;
5081 }
5082 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5083
5084 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5085 {
5086 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5087 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005088 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005089 for (i = 0; i < width; ++i)
5090 textline[i] = '-';
5091 }
5092 else
5093 {
5094 char_u *line1;
5095 char_u *line2;
5096 char_u *p1;
5097 char_u *p2;
5098 int col;
5099 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5100 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5101 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5102 ->sb_cells;
5103
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005104 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005105 line1 = vim_strsave(ml_get(lnum));
5106 if (line1 == NULL)
5107 break;
5108 p1 = line1;
5109
5110 line2 = ml_get(lnum + bot_lnum);
5111 p2 = line2;
5112 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5113 {
5114 int len1 = utfc_ptr2len(p1);
5115 int len2 = utfc_ptr2len(p2);
5116
5117 textline[col] = ' ';
5118 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005119 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005120 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005121 else if (lnum == cursor_pos1.row + 1
5122 && col == cursor_pos1.col
5123 && (cursor_pos1.row != cursor_pos2.row
5124 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005125 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005126 textline[col] = '>';
5127 else if (lnum == cursor_pos2.row + 1
5128 && col == cursor_pos2.col
5129 && (cursor_pos1.row != cursor_pos2.row
5130 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005131 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005132 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005133 else if (cellattr1 != NULL && cellattr2 != NULL)
5134 {
5135 if ((cellattr1 + col)->width
5136 != (cellattr2 + col)->width)
5137 textline[col] = 'w';
5138 else if (!same_color(&(cellattr1 + col)->fg,
5139 &(cellattr2 + col)->fg))
5140 textline[col] = 'f';
5141 else if (!same_color(&(cellattr1 + col)->bg,
5142 &(cellattr2 + col)->bg))
5143 textline[col] = 'b';
5144 else if (vtermAttr2hl((cellattr1 + col)->attrs)
5145 != vtermAttr2hl(((cellattr2 + col)->attrs)))
5146 textline[col] = 'a';
5147 }
5148 p1 += len1;
5149 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005150 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005151 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005152
5153 while (col < width)
5154 {
5155 if (*p1 == NUL && *p2 == NUL)
5156 textline[col] = '?';
5157 else if (*p1 == NUL)
5158 {
5159 textline[col] = '+';
5160 p2 += utfc_ptr2len(p2);
5161 }
5162 else
5163 {
5164 textline[col] = '-';
5165 p1 += utfc_ptr2len(p1);
5166 }
5167 ++col;
5168 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005169
5170 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005171 }
5172 if (add_empty_scrollback(term, &term->tl_default_color,
5173 term->tl_top_diff_rows) == OK)
5174 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5175 ++bot_lnum;
5176 }
5177
5178 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5179 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005180 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005181 for (i = 0; i < width; ++i)
5182 textline[i] = '+';
5183 if (add_empty_scrollback(term, &term->tl_default_color,
5184 term->tl_top_diff_rows) == OK)
5185 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5186 ++lnum;
5187 ++bot_lnum;
5188 }
5189
5190 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005191
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005192 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005193 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005194 }
5195
5196theend:
5197 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005198 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005199 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005200 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005201 fclose(fd2);
5202}
5203
5204/*
5205 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5206 * bottom files.
5207 * Return FAIL when this is not possible.
5208 */
5209 int
5210term_swap_diff()
5211{
5212 term_T *term = curbuf->b_term;
5213 linenr_T line_count;
5214 linenr_T top_rows;
5215 linenr_T bot_rows;
5216 linenr_T bot_start;
5217 linenr_T lnum;
5218 char_u *p;
5219 sb_line_T *sb_line;
5220
5221 if (term == NULL
5222 || !term_is_finished(curbuf)
5223 || term->tl_top_diff_rows == 0
5224 || term->tl_scrollback.ga_len == 0)
5225 return FAIL;
5226
5227 line_count = curbuf->b_ml.ml_line_count;
5228 top_rows = term->tl_top_diff_rows;
5229 bot_rows = term->tl_bot_diff_rows;
5230 bot_start = line_count - bot_rows;
5231 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5232
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005233 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005234 for (lnum = 1; lnum <= top_rows; ++lnum)
5235 {
5236 p = vim_strsave(ml_get(1));
5237 if (p == NULL)
5238 return OK;
5239 ml_append(bot_start, p, 0, FALSE);
5240 ml_delete(1, FALSE);
5241 vim_free(p);
5242 }
5243
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005244 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005245 for (lnum = 1; lnum <= bot_rows; ++lnum)
5246 {
5247 p = vim_strsave(ml_get(bot_start + lnum));
5248 if (p == NULL)
5249 return OK;
5250 ml_delete(bot_start + lnum, FALSE);
5251 ml_append(lnum - 1, p, 0, FALSE);
5252 vim_free(p);
5253 }
5254
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005255 // move top title to bottom
5256 p = vim_strsave(ml_get(bot_rows + 1));
5257 if (p == NULL)
5258 return OK;
5259 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5260 ml_delete(bot_rows + 1, FALSE);
5261 vim_free(p);
5262
5263 // move bottom title to top
5264 p = vim_strsave(ml_get(line_count - top_rows));
5265 if (p == NULL)
5266 return OK;
5267 ml_delete(line_count - top_rows, FALSE);
5268 ml_append(bot_rows, p, 0, FALSE);
5269 vim_free(p);
5270
Bram Moolenaard96ff162018-02-18 22:13:29 +01005271 if (top_rows == bot_rows)
5272 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005273 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005274 for (lnum = 0; lnum < top_rows; ++lnum)
5275 {
5276 sb_line_T temp;
5277
5278 temp = *(sb_line + lnum);
5279 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5280 *(sb_line + bot_start + lnum) = temp;
5281 }
5282 }
5283 else
5284 {
5285 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005286 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005287
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005288 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005289 if (temp != NULL)
5290 {
5291 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5292 mch_memmove(term->tl_scrollback.ga_data,
5293 temp + bot_start,
5294 sizeof(sb_line_T) * bot_rows);
5295 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5296 temp + top_rows,
5297 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5298 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5299 + line_count - top_rows,
5300 temp,
5301 sizeof(sb_line_T) * top_rows);
5302 vim_free(temp);
5303 }
5304 }
5305
5306 term->tl_top_diff_rows = bot_rows;
5307 term->tl_bot_diff_rows = top_rows;
5308
5309 update_screen(NOT_VALID);
5310 return OK;
5311}
5312
5313/*
5314 * "term_dumpdiff(filename, filename, options)" function
5315 */
5316 void
5317f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5318{
5319 term_load_dump(argvars, rettv, TRUE);
5320}
5321
5322/*
5323 * "term_dumpload(filename, options)" function
5324 */
5325 void
5326f_term_dumpload(typval_T *argvars, typval_T *rettv)
5327{
5328 term_load_dump(argvars, rettv, FALSE);
5329}
5330
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005331/*
5332 * "term_getaltscreen(buf)" function
5333 */
5334 void
5335f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5336{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005337 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005338
5339 if (buf == NULL)
5340 return;
5341 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5342}
5343
5344/*
5345 * "term_getattr(attr, name)" function
5346 */
5347 void
5348f_term_getattr(typval_T *argvars, typval_T *rettv)
5349{
5350 int attr;
5351 size_t i;
5352 char_u *name;
5353
5354 static struct {
5355 char *name;
5356 int attr;
5357 } attrs[] = {
5358 {"bold", HL_BOLD},
5359 {"italic", HL_ITALIC},
5360 {"underline", HL_UNDERLINE},
5361 {"strike", HL_STRIKETHROUGH},
5362 {"reverse", HL_INVERSE},
5363 };
5364
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005365 attr = tv_get_number(&argvars[0]);
5366 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005367 if (name == NULL)
5368 return;
5369
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005370 if (attr > HL_ALL)
5371 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005372 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5373 if (STRCMP(name, attrs[i].name) == 0)
5374 {
5375 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5376 break;
5377 }
5378}
5379
5380/*
5381 * "term_getcursor(buf)" function
5382 */
5383 void
5384f_term_getcursor(typval_T *argvars, typval_T *rettv)
5385{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005386 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005387 term_T *term;
5388 list_T *l;
5389 dict_T *d;
5390
5391 if (rettv_list_alloc(rettv) == FAIL)
5392 return;
5393 if (buf == NULL)
5394 return;
5395 term = buf->b_term;
5396
5397 l = rettv->vval.v_list;
5398 list_append_number(l, term->tl_cursor_pos.row + 1);
5399 list_append_number(l, term->tl_cursor_pos.col + 1);
5400
5401 d = dict_alloc();
5402 if (d != NULL)
5403 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005404 dict_add_number(d, "visible", term->tl_cursor_visible);
5405 dict_add_number(d, "blink", blink_state_is_inverted()
5406 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5407 dict_add_number(d, "shape", term->tl_cursor_shape);
5408 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005409 list_append_dict(l, d);
5410 }
5411}
5412
5413/*
5414 * "term_getjob(buf)" function
5415 */
5416 void
5417f_term_getjob(typval_T *argvars, typval_T *rettv)
5418{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005419 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005420
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005421 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005422 {
5423 rettv->v_type = VAR_SPECIAL;
5424 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005425 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005426 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005427
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005428 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005429 rettv->vval.v_job = buf->b_term->tl_job;
5430 if (rettv->vval.v_job != NULL)
5431 ++rettv->vval.v_job->jv_refcount;
5432}
5433
5434 static int
5435get_row_number(typval_T *tv, term_T *term)
5436{
5437 if (tv->v_type == VAR_STRING
5438 && tv->vval.v_string != NULL
5439 && STRCMP(tv->vval.v_string, ".") == 0)
5440 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005441 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005442}
5443
5444/*
5445 * "term_getline(buf, row)" function
5446 */
5447 void
5448f_term_getline(typval_T *argvars, typval_T *rettv)
5449{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005450 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005451 term_T *term;
5452 int row;
5453
5454 rettv->v_type = VAR_STRING;
5455 if (buf == NULL)
5456 return;
5457 term = buf->b_term;
5458 row = get_row_number(&argvars[1], term);
5459
5460 if (term->tl_vterm == NULL)
5461 {
5462 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5463
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005464 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005465 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5466 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5467 }
5468 else
5469 {
5470 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5471 VTermRect rect;
5472 int len;
5473 char_u *p;
5474
5475 if (row < 0 || row >= term->tl_rows)
5476 return;
5477 len = term->tl_cols * MB_MAXBYTES + 1;
5478 p = alloc(len);
5479 if (p == NULL)
5480 return;
5481 rettv->vval.v_string = p;
5482
5483 rect.start_col = 0;
5484 rect.end_col = term->tl_cols;
5485 rect.start_row = row;
5486 rect.end_row = row + 1;
5487 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5488 }
5489}
5490
5491/*
5492 * "term_getscrolled(buf)" function
5493 */
5494 void
5495f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5496{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005497 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005498
5499 if (buf == NULL)
5500 return;
5501 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5502}
5503
5504/*
5505 * "term_getsize(buf)" function
5506 */
5507 void
5508f_term_getsize(typval_T *argvars, typval_T *rettv)
5509{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005510 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005511 list_T *l;
5512
5513 if (rettv_list_alloc(rettv) == FAIL)
5514 return;
5515 if (buf == NULL)
5516 return;
5517
5518 l = rettv->vval.v_list;
5519 list_append_number(l, buf->b_term->tl_rows);
5520 list_append_number(l, buf->b_term->tl_cols);
5521}
5522
5523/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005524 * "term_setsize(buf, rows, cols)" function
5525 */
5526 void
5527f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5528{
5529 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5530 term_T *term;
5531 varnumber_T rows, cols;
5532
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005533 if (buf == NULL)
5534 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005535 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005536 return;
5537 }
5538 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005539 return;
5540 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005541 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005542 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005543 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005544 cols = cols <= 0 ? term->tl_cols : cols;
5545 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005546 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02005547
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005548 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02005549 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5550 term_report_winsize(term, term->tl_rows, term->tl_cols);
5551}
5552
5553/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005554 * "term_getstatus(buf)" function
5555 */
5556 void
5557f_term_getstatus(typval_T *argvars, typval_T *rettv)
5558{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005559 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005560 term_T *term;
5561 char_u val[100];
5562
5563 rettv->v_type = VAR_STRING;
5564 if (buf == NULL)
5565 return;
5566 term = buf->b_term;
5567
5568 if (term_job_running(term))
5569 STRCPY(val, "running");
5570 else
5571 STRCPY(val, "finished");
5572 if (term->tl_normal_mode)
5573 STRCAT(val, ",normal");
5574 rettv->vval.v_string = vim_strsave(val);
5575}
5576
5577/*
5578 * "term_gettitle(buf)" function
5579 */
5580 void
5581f_term_gettitle(typval_T *argvars, typval_T *rettv)
5582{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005583 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005584
5585 rettv->v_type = VAR_STRING;
5586 if (buf == NULL)
5587 return;
5588
5589 if (buf->b_term->tl_title != NULL)
5590 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5591}
5592
5593/*
5594 * "term_gettty(buf)" function
5595 */
5596 void
5597f_term_gettty(typval_T *argvars, typval_T *rettv)
5598{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005599 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005600 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005601 int num = 0;
5602
5603 rettv->v_type = VAR_STRING;
5604 if (buf == NULL)
5605 return;
5606 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005607 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005608
5609 switch (num)
5610 {
5611 case 0:
5612 if (buf->b_term->tl_job != NULL)
5613 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005614 break;
5615 case 1:
5616 if (buf->b_term->tl_job != NULL)
5617 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005618 break;
5619 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005620 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005621 return;
5622 }
5623 if (p != NULL)
5624 rettv->vval.v_string = vim_strsave(p);
5625}
5626
5627/*
5628 * "term_list()" function
5629 */
5630 void
5631f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5632{
5633 term_T *tp;
5634 list_T *l;
5635
5636 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5637 return;
5638
5639 l = rettv->vval.v_list;
5640 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5641 if (tp != NULL && tp->tl_buffer != NULL)
5642 if (list_append_number(l,
5643 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5644 return;
5645}
5646
5647/*
5648 * "term_scrape(buf, row)" function
5649 */
5650 void
5651f_term_scrape(typval_T *argvars, typval_T *rettv)
5652{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005653 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005654 VTermScreen *screen = NULL;
5655 VTermPos pos;
5656 list_T *l;
5657 term_T *term;
5658 char_u *p;
5659 sb_line_T *line;
5660
5661 if (rettv_list_alloc(rettv) == FAIL)
5662 return;
5663 if (buf == NULL)
5664 return;
5665 term = buf->b_term;
5666
5667 l = rettv->vval.v_list;
5668 pos.row = get_row_number(&argvars[1], term);
5669
5670 if (term->tl_vterm != NULL)
5671 {
5672 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005673 if (screen == NULL) // can't really happen
5674 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005675 p = NULL;
5676 line = NULL;
5677 }
5678 else
5679 {
5680 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5681
5682 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5683 return;
5684 p = ml_get_buf(buf, lnum + 1, FALSE);
5685 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5686 }
5687
5688 for (pos.col = 0; pos.col < term->tl_cols; )
5689 {
5690 dict_T *dcell;
5691 int width;
5692 VTermScreenCellAttrs attrs;
5693 VTermColor fg, bg;
5694 char_u rgb[8];
5695 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5696 int off = 0;
5697 int i;
5698
5699 if (screen == NULL)
5700 {
5701 cellattr_T *cellattr;
5702 int len;
5703
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005704 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005705 if (pos.col >= line->sb_cols)
5706 break;
5707 cellattr = line->sb_cells + pos.col;
5708 width = cellattr->width;
5709 attrs = cellattr->attrs;
5710 fg = cellattr->fg;
5711 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005712 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005713 mch_memmove(mbs, p, len);
5714 mbs[len] = NUL;
5715 p += len;
5716 }
5717 else
5718 {
5719 VTermScreenCell cell;
5720 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5721 break;
5722 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5723 {
5724 if (cell.chars[i] == 0)
5725 break;
5726 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5727 }
5728 mbs[off] = NUL;
5729 width = cell.width;
5730 attrs = cell.attrs;
5731 fg = cell.fg;
5732 bg = cell.bg;
5733 }
5734 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005735 if (dcell == NULL)
5736 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005737 list_append_dict(l, dcell);
5738
Bram Moolenaare0be1672018-07-08 16:50:37 +02005739 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005740
5741 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5742 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005743 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005744 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5745 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005746 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005747
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005748 dict_add_number(dcell, "attr", cell2attr(NULL, attrs, fg, bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02005749 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005750
5751 ++pos.col;
5752 if (width == 2)
5753 ++pos.col;
5754 }
5755}
5756
5757/*
5758 * "term_sendkeys(buf, keys)" function
5759 */
5760 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01005761f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005762{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005763 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005764 char_u *msg;
5765 term_T *term;
5766
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005767 if (buf == NULL)
5768 return;
5769
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005770 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005771 if (msg == NULL)
5772 return;
5773 term = buf->b_term;
5774 if (term->tl_vterm == NULL)
5775 return;
5776
5777 while (*msg != NUL)
5778 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005779 int c;
5780
5781 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5782 {
5783 c = TO_SPECIAL(msg[1], msg[2]);
5784 msg += 3;
5785 }
5786 else
5787 {
5788 c = PTR2CHAR(msg);
5789 msg += MB_CPTR2LEN(msg);
5790 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005791 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005792 }
5793}
5794
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005795#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5796/*
5797 * "term_getansicolors(buf)" function
5798 */
5799 void
5800f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5801{
5802 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5803 term_T *term;
5804 VTermState *state;
5805 VTermColor color;
5806 char_u hexbuf[10];
5807 int index;
5808 list_T *list;
5809
5810 if (rettv_list_alloc(rettv) == FAIL)
5811 return;
5812
5813 if (buf == NULL)
5814 return;
5815 term = buf->b_term;
5816 if (term->tl_vterm == NULL)
5817 return;
5818
5819 list = rettv->vval.v_list;
5820 state = vterm_obtain_state(term->tl_vterm);
5821 for (index = 0; index < 16; index++)
5822 {
5823 vterm_state_get_palette_color(state, index, &color);
5824 sprintf((char *)hexbuf, "#%02x%02x%02x",
5825 color.red, color.green, color.blue);
5826 if (list_append_string(list, hexbuf, 7) == FAIL)
5827 return;
5828 }
5829}
5830
5831/*
5832 * "term_setansicolors(buf, list)" function
5833 */
5834 void
5835f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5836{
5837 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5838 term_T *term;
5839
5840 if (buf == NULL)
5841 return;
5842 term = buf->b_term;
5843 if (term->tl_vterm == NULL)
5844 return;
5845
5846 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5847 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005848 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005849 return;
5850 }
5851
5852 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005853 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005854}
5855#endif
5856
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005857/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005858 * "term_setapi(buf, api)" function
5859 */
5860 void
5861f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5862{
5863 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5864 term_T *term;
5865 char_u *api;
5866
5867 if (buf == NULL)
5868 return;
5869 term = buf->b_term;
5870 vim_free(term->tl_api);
5871 api = tv_get_string_chk(&argvars[1]);
5872 if (api != NULL)
5873 term->tl_api = vim_strsave(api);
5874 else
5875 term->tl_api = NULL;
5876}
5877
5878/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005879 * "term_setrestore(buf, command)" function
5880 */
5881 void
5882f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5883{
5884#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005885 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005886 term_T *term;
5887 char_u *cmd;
5888
5889 if (buf == NULL)
5890 return;
5891 term = buf->b_term;
5892 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005893 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005894 if (cmd != NULL)
5895 term->tl_command = vim_strsave(cmd);
5896 else
5897 term->tl_command = NULL;
5898#endif
5899}
5900
5901/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005902 * "term_setkill(buf, how)" function
5903 */
5904 void
5905f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5906{
5907 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5908 term_T *term;
5909 char_u *how;
5910
5911 if (buf == NULL)
5912 return;
5913 term = buf->b_term;
5914 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005915 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005916 if (how != NULL)
5917 term->tl_kill = vim_strsave(how);
5918 else
5919 term->tl_kill = NULL;
5920}
5921
5922/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005923 * "term_start(command, options)" function
5924 */
5925 void
5926f_term_start(typval_T *argvars, typval_T *rettv)
5927{
5928 jobopt_T opt;
5929 buf_T *buf;
5930
5931 init_job_options(&opt);
5932 if (argvars[1].v_type != VAR_UNKNOWN
5933 && get_job_options(&argvars[1], &opt,
5934 JO_TIMEOUT_ALL + JO_STOPONEXIT
5935 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5936 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5937 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5938 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005939 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005940 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005941 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005942 return;
5943
Bram Moolenaar13568252018-03-16 20:46:58 +01005944 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005945
5946 if (buf != NULL && buf->b_term != NULL)
5947 rettv->vval.v_number = buf->b_fnum;
5948}
5949
5950/*
5951 * "term_wait" function
5952 */
5953 void
5954f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5955{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005956 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005957
5958 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005959 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005960 if (buf->b_term->tl_job == NULL)
5961 {
5962 ch_log(NULL, "term_wait(): no job to wait for");
5963 return;
5964 }
5965 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005966 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005967 return;
5968
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005969 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01005970 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005971 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5972 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005973 // The job is dead, keep reading channel I/O until the channel is
5974 // closed. buf->b_term may become NULL if the terminal was closed while
5975 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005976 ch_log(NULL, "term_wait(): waiting for channel to close");
5977 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5978 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005979 term_flush_messages();
5980
Bram Moolenaard45aa552018-05-21 22:50:29 +02005981 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005982 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005983 // If the terminal is closed when the channel is closed the
5984 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01005985 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005986 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005987
5988 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005989 }
5990 else
5991 {
5992 long wait = 10L;
5993
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005994 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005995
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005996 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005997 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005998 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005999 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006000
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006001 // Flushing messages on channels is hopefully sufficient.
6002 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006003 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006004 }
6005}
6006
6007/*
6008 * Called when a channel has sent all the lines to a terminal.
6009 * Send a CTRL-D to mark the end of the text.
6010 */
6011 void
6012term_send_eof(channel_T *ch)
6013{
6014 term_T *term;
6015
6016 for (term = first_term; term != NULL; term = term->tl_next)
6017 if (term->tl_job == ch->ch_job)
6018 {
6019 if (term->tl_eof_chars != NULL)
6020 {
6021 channel_send(ch, PART_IN, term->tl_eof_chars,
6022 (int)STRLEN(term->tl_eof_chars), NULL);
6023 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6024 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006025# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006026 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006027 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006028 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6029# endif
6030 }
6031}
6032
Bram Moolenaar113e1072019-01-20 15:30:40 +01006033#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006034 job_T *
6035term_getjob(term_T *term)
6036{
6037 return term != NULL ? term->tl_job : NULL;
6038}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006039#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006040
Bram Moolenaar4f974752019-02-17 17:44:42 +01006041# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006042
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006043///////////////////////////////////////
6044// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006045#ifdef PROTO
6046typedef int COORD;
6047typedef int DWORD;
6048typedef int HANDLE;
6049typedef int *DWORD_PTR;
6050typedef int HPCON;
6051typedef int HRESULT;
6052typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006053typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006054typedef int PSIZE_T;
6055typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006056typedef int BOOL;
6057# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006058#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006059
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006060HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6061HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6062HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006063BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6064BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6065void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006066
6067 static int
6068dyn_conpty_init(int verbose)
6069{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006070 static HMODULE hKerneldll = NULL;
6071 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006072 static struct
6073 {
6074 char *name;
6075 FARPROC *ptr;
6076 } conpty_entry[] =
6077 {
6078 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6079 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6080 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6081 {"InitializeProcThreadAttributeList",
6082 (FARPROC*)&pInitializeProcThreadAttributeList},
6083 {"UpdateProcThreadAttribute",
6084 (FARPROC*)&pUpdateProcThreadAttribute},
6085 {"DeleteProcThreadAttributeList",
6086 (FARPROC*)&pDeleteProcThreadAttributeList},
6087 {NULL, NULL}
6088 };
6089
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006090 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006091 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006092 if (verbose)
6093 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006094 return FAIL;
6095 }
6096
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006097 // No need to initialize twice.
6098 if (hKerneldll)
6099 return OK;
6100
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006101 hKerneldll = vimLoadLib("kernel32.dll");
6102 for (i = 0; conpty_entry[i].name != NULL
6103 && conpty_entry[i].ptr != NULL; ++i)
6104 {
6105 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6106 conpty_entry[i].name)) == NULL)
6107 {
6108 if (verbose)
6109 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006110 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006111 return FAIL;
6112 }
6113 }
6114
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006115 return OK;
6116}
6117
6118 static int
6119conpty_term_and_job_init(
6120 term_T *term,
6121 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006122 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006123 jobopt_T *opt,
6124 jobopt_T *orig_opt)
6125{
6126 WCHAR *cmd_wchar = NULL;
6127 WCHAR *cmd_wchar_copy = NULL;
6128 WCHAR *cwd_wchar = NULL;
6129 WCHAR *env_wchar = NULL;
6130 channel_T *channel = NULL;
6131 job_T *job = NULL;
6132 HANDLE jo = NULL;
6133 garray_T ga_cmd, ga_env;
6134 char_u *cmd = NULL;
6135 HRESULT hr;
6136 COORD consize;
6137 SIZE_T breq;
6138 PROCESS_INFORMATION proc_info;
6139 HANDLE i_theirs = NULL;
6140 HANDLE o_theirs = NULL;
6141 HANDLE i_ours = NULL;
6142 HANDLE o_ours = NULL;
6143
6144 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6145 ga_init2(&ga_env, (int)sizeof(char*), 20);
6146
6147 if (argvar->v_type == VAR_STRING)
6148 {
6149 cmd = argvar->vval.v_string;
6150 }
6151 else if (argvar->v_type == VAR_LIST)
6152 {
6153 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6154 goto failed;
6155 cmd = ga_cmd.ga_data;
6156 }
6157 if (cmd == NULL || *cmd == NUL)
6158 {
6159 emsg(_(e_invarg));
6160 goto failed;
6161 }
6162
6163 term->tl_arg0_cmd = vim_strsave(cmd);
6164
6165 cmd_wchar = enc_to_utf16(cmd, NULL);
6166
6167 if (cmd_wchar != NULL)
6168 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006169 // Request by CreateProcessW
6170 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006171 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006172 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6173 }
6174
6175 ga_clear(&ga_cmd);
6176 if (cmd_wchar == NULL)
6177 goto failed;
6178 if (opt->jo_cwd != NULL)
6179 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6180
6181 win32_build_env(opt->jo_env, &ga_env, TRUE);
6182 env_wchar = ga_env.ga_data;
6183
6184 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6185 goto failed;
6186 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6187 goto failed;
6188
6189 consize.X = term->tl_cols;
6190 consize.Y = term->tl_rows;
6191 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6192 &term->tl_conpty);
6193 if (FAILED(hr))
6194 goto failed;
6195
6196 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6197
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006198 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006199 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006200 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006201 if (!term->tl_siex.lpAttributeList)
6202 goto failed;
6203 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6204 0, &breq))
6205 goto failed;
6206 if (!pUpdateProcThreadAttribute(
6207 term->tl_siex.lpAttributeList, 0,
6208 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6209 sizeof(HPCON), NULL, NULL))
6210 goto failed;
6211
6212 channel = add_channel();
6213 if (channel == NULL)
6214 goto failed;
6215
6216 job = job_alloc();
6217 if (job == NULL)
6218 goto failed;
6219 if (argvar->v_type == VAR_STRING)
6220 {
6221 int argc;
6222
6223 build_argv_from_string(cmd, &job->jv_argv, &argc);
6224 }
6225 else
6226 {
6227 int argc;
6228
6229 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6230 }
6231
6232 if (opt->jo_set & JO_IN_BUF)
6233 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6234
6235 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6236 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
6237 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
6238 | CREATE_DEFAULT_ERROR_MODE,
6239 env_wchar, cwd_wchar,
6240 &term->tl_siex.StartupInfo, &proc_info))
6241 goto failed;
6242
6243 CloseHandle(i_theirs);
6244 CloseHandle(o_theirs);
6245
6246 channel_set_pipes(channel,
6247 (sock_T)i_ours,
6248 (sock_T)o_ours,
6249 (sock_T)o_ours);
6250
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006251 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006252 channel->ch_write_text_mode = TRUE;
6253
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006254 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006255 channel->ch_anonymous_pipe = TRUE;
6256
6257 jo = CreateJobObject(NULL, NULL);
6258 if (jo == NULL)
6259 goto failed;
6260
6261 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6262 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006263 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006264 CloseHandle(jo);
6265 jo = NULL;
6266 }
6267
6268 ResumeThread(proc_info.hThread);
6269 CloseHandle(proc_info.hThread);
6270
6271 vim_free(cmd_wchar);
6272 vim_free(cmd_wchar_copy);
6273 vim_free(cwd_wchar);
6274 vim_free(env_wchar);
6275
6276 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6277 goto failed;
6278
6279#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6280 if (opt->jo_set2 & JO2_ANSI_COLORS)
6281 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6282 else
6283 init_vterm_ansi_colors(term->tl_vterm);
6284#endif
6285
6286 channel_set_job(channel, job, opt);
6287 job_set_options(job, opt);
6288
6289 job->jv_channel = channel;
6290 job->jv_proc_info = proc_info;
6291 job->jv_job_object = jo;
6292 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006293 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006294 ++job->jv_refcount;
6295 term->tl_job = job;
6296
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006297 // Redirecting stdout and stderr doesn't work at the job level. Instead
6298 // open the file here and handle it in. opt->jo_io was changed in
6299 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006300 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6301 {
6302 char_u *fname = opt->jo_io_name[PART_OUT];
6303
6304 ch_log(channel, "Opening output file %s", fname);
6305 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6306 if (term->tl_out_fd == NULL)
6307 semsg(_(e_notopen), fname);
6308 }
6309
6310 return OK;
6311
6312failed:
6313 ga_clear(&ga_cmd);
6314 ga_clear(&ga_env);
6315 vim_free(cmd_wchar);
6316 vim_free(cmd_wchar_copy);
6317 vim_free(cwd_wchar);
6318 if (channel != NULL)
6319 channel_clear(channel);
6320 if (job != NULL)
6321 {
6322 job->jv_channel = NULL;
6323 job_cleanup(job);
6324 }
6325 term->tl_job = NULL;
6326 if (jo != NULL)
6327 CloseHandle(jo);
6328
6329 if (term->tl_siex.lpAttributeList != NULL)
6330 {
6331 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6332 vim_free(term->tl_siex.lpAttributeList);
6333 }
6334 term->tl_siex.lpAttributeList = NULL;
6335 if (o_theirs != NULL)
6336 CloseHandle(o_theirs);
6337 if (o_ours != NULL)
6338 CloseHandle(o_ours);
6339 if (i_ours != NULL)
6340 CloseHandle(i_ours);
6341 if (i_theirs != NULL)
6342 CloseHandle(i_theirs);
6343 if (term->tl_conpty != NULL)
6344 pClosePseudoConsole(term->tl_conpty);
6345 term->tl_conpty = NULL;
6346 return FAIL;
6347}
6348
6349 static void
6350conpty_term_report_winsize(term_T *term, int rows, int cols)
6351{
6352 COORD consize;
6353
6354 consize.X = cols;
6355 consize.Y = rows;
6356 pResizePseudoConsole(term->tl_conpty, consize);
6357}
6358
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006359 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006360term_free_conpty(term_T *term)
6361{
6362 if (term->tl_siex.lpAttributeList != NULL)
6363 {
6364 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6365 vim_free(term->tl_siex.lpAttributeList);
6366 }
6367 term->tl_siex.lpAttributeList = NULL;
6368 if (term->tl_conpty != NULL)
6369 pClosePseudoConsole(term->tl_conpty);
6370 term->tl_conpty = NULL;
6371}
6372
6373 int
6374use_conpty(void)
6375{
6376 return has_conpty;
6377}
6378
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006379# ifndef PROTO
6380
6381#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6382#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006383#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006384
6385void* (*winpty_config_new)(UINT64, void*);
6386void* (*winpty_open)(void*, void*);
6387void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6388BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6389void (*winpty_config_set_mouse_mode)(void*, int);
6390void (*winpty_config_set_initial_size)(void*, int, int);
6391LPCWSTR (*winpty_conin_name)(void*);
6392LPCWSTR (*winpty_conout_name)(void*);
6393LPCWSTR (*winpty_conerr_name)(void*);
6394void (*winpty_free)(void*);
6395void (*winpty_config_free)(void*);
6396void (*winpty_spawn_config_free)(void*);
6397void (*winpty_error_free)(void*);
6398LPCWSTR (*winpty_error_msg)(void*);
6399BOOL (*winpty_set_size)(void*, int, int, void*);
6400HANDLE (*winpty_agent_process)(void*);
6401
6402#define WINPTY_DLL "winpty.dll"
6403
6404static HINSTANCE hWinPtyDLL = NULL;
6405# endif
6406
6407 static int
6408dyn_winpty_init(int verbose)
6409{
6410 int i;
6411 static struct
6412 {
6413 char *name;
6414 FARPROC *ptr;
6415 } winpty_entry[] =
6416 {
6417 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6418 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6419 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6420 {"winpty_config_set_mouse_mode",
6421 (FARPROC*)&winpty_config_set_mouse_mode},
6422 {"winpty_config_set_initial_size",
6423 (FARPROC*)&winpty_config_set_initial_size},
6424 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6425 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6426 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6427 {"winpty_free", (FARPROC*)&winpty_free},
6428 {"winpty_open", (FARPROC*)&winpty_open},
6429 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6430 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6431 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6432 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6433 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6434 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6435 {NULL, NULL}
6436 };
6437
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006438 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006439 if (hWinPtyDLL)
6440 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006441 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6442 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006443 if (*p_winptydll != NUL)
6444 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6445 if (!hWinPtyDLL)
6446 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6447 if (!hWinPtyDLL)
6448 {
6449 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006450 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006451 : (char_u *)WINPTY_DLL);
6452 return FAIL;
6453 }
6454 for (i = 0; winpty_entry[i].name != NULL
6455 && winpty_entry[i].ptr != NULL; ++i)
6456 {
6457 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6458 winpty_entry[i].name)) == NULL)
6459 {
6460 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006461 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006462 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006463 return FAIL;
6464 }
6465 }
6466
6467 return OK;
6468}
6469
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006470 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006471winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006472 term_T *term,
6473 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006474 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006475 jobopt_T *opt,
6476 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006477{
6478 WCHAR *cmd_wchar = NULL;
6479 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006480 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006481 channel_T *channel = NULL;
6482 job_T *job = NULL;
6483 DWORD error;
6484 HANDLE jo = NULL;
6485 HANDLE child_process_handle;
6486 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006487 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006488 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006489 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006490 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006491
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006492 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6493 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006494
6495 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006496 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006497 cmd = argvar->vval.v_string;
6498 }
6499 else if (argvar->v_type == VAR_LIST)
6500 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006501 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006502 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006503 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006504 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006505 if (cmd == NULL || *cmd == NUL)
6506 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006507 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006508 goto failed;
6509 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006510
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006511 term->tl_arg0_cmd = vim_strsave(cmd);
6512
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006513 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006514 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006515 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006516 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006517 if (opt->jo_cwd != NULL)
6518 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006519
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006520 win32_build_env(opt->jo_env, &ga_env, TRUE);
6521 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006522
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006523 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6524 if (term->tl_winpty_config == NULL)
6525 goto failed;
6526
6527 winpty_config_set_mouse_mode(term->tl_winpty_config,
6528 WINPTY_MOUSE_MODE_FORCE);
6529 winpty_config_set_initial_size(term->tl_winpty_config,
6530 term->tl_cols, term->tl_rows);
6531 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6532 if (term->tl_winpty == NULL)
6533 goto failed;
6534
6535 spawn_config = winpty_spawn_config_new(
6536 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6537 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6538 NULL,
6539 cmd_wchar,
6540 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006541 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006542 &winpty_err);
6543 if (spawn_config == NULL)
6544 goto failed;
6545
6546 channel = add_channel();
6547 if (channel == NULL)
6548 goto failed;
6549
6550 job = job_alloc();
6551 if (job == NULL)
6552 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006553 if (argvar->v_type == VAR_STRING)
6554 {
6555 int argc;
6556
6557 build_argv_from_string(cmd, &job->jv_argv, &argc);
6558 }
6559 else
6560 {
6561 int argc;
6562
6563 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6564 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006565
6566 if (opt->jo_set & JO_IN_BUF)
6567 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6568
6569 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6570 &child_thread_handle, &error, &winpty_err))
6571 goto failed;
6572
6573 channel_set_pipes(channel,
6574 (sock_T)CreateFileW(
6575 winpty_conin_name(term->tl_winpty),
6576 GENERIC_WRITE, 0, NULL,
6577 OPEN_EXISTING, 0, NULL),
6578 (sock_T)CreateFileW(
6579 winpty_conout_name(term->tl_winpty),
6580 GENERIC_READ, 0, NULL,
6581 OPEN_EXISTING, 0, NULL),
6582 (sock_T)CreateFileW(
6583 winpty_conerr_name(term->tl_winpty),
6584 GENERIC_READ, 0, NULL,
6585 OPEN_EXISTING, 0, NULL));
6586
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006587 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006588 channel->ch_write_text_mode = TRUE;
6589
6590 jo = CreateJobObject(NULL, NULL);
6591 if (jo == NULL)
6592 goto failed;
6593
6594 if (!AssignProcessToJobObject(jo, child_process_handle))
6595 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006596 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006597 CloseHandle(jo);
6598 jo = NULL;
6599 }
6600
6601 winpty_spawn_config_free(spawn_config);
6602 vim_free(cmd_wchar);
6603 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006604 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006605
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006606 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6607 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006608
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006609#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6610 if (opt->jo_set2 & JO2_ANSI_COLORS)
6611 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6612 else
6613 init_vterm_ansi_colors(term->tl_vterm);
6614#endif
6615
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006616 channel_set_job(channel, job, opt);
6617 job_set_options(job, opt);
6618
6619 job->jv_channel = channel;
6620 job->jv_proc_info.hProcess = child_process_handle;
6621 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6622 job->jv_job_object = jo;
6623 job->jv_status = JOB_STARTED;
6624 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006625 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006626 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006627 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006628 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006629 ++job->jv_refcount;
6630 term->tl_job = job;
6631
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006632 // Redirecting stdout and stderr doesn't work at the job level. Instead
6633 // open the file here and handle it in. opt->jo_io was changed in
6634 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006635 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6636 {
6637 char_u *fname = opt->jo_io_name[PART_OUT];
6638
6639 ch_log(channel, "Opening output file %s", fname);
6640 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6641 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006642 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006643 }
6644
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006645 return OK;
6646
6647failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006648 ga_clear(&ga_cmd);
6649 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006650 vim_free(cmd_wchar);
6651 vim_free(cwd_wchar);
6652 if (spawn_config != NULL)
6653 winpty_spawn_config_free(spawn_config);
6654 if (channel != NULL)
6655 channel_clear(channel);
6656 if (job != NULL)
6657 {
6658 job->jv_channel = NULL;
6659 job_cleanup(job);
6660 }
6661 term->tl_job = NULL;
6662 if (jo != NULL)
6663 CloseHandle(jo);
6664 if (term->tl_winpty != NULL)
6665 winpty_free(term->tl_winpty);
6666 term->tl_winpty = NULL;
6667 if (term->tl_winpty_config != NULL)
6668 winpty_config_free(term->tl_winpty_config);
6669 term->tl_winpty_config = NULL;
6670 if (winpty_err != NULL)
6671 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006672 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006673 (short_u *)winpty_error_msg(winpty_err), NULL);
6674
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006675 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006676 winpty_error_free(winpty_err);
6677 }
6678 return FAIL;
6679}
6680
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006681/*
6682 * Create a new terminal of "rows" by "cols" cells.
6683 * Store a reference in "term".
6684 * Return OK or FAIL.
6685 */
6686 static int
6687term_and_job_init(
6688 term_T *term,
6689 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01006690 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006691 jobopt_T *opt,
6692 jobopt_T *orig_opt)
6693{
6694 int use_winpty = FALSE;
6695 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006696 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006697
6698 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6699 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6700
6701 if (!has_winpty && !has_conpty)
6702 // If neither is available give the errors for winpty, since when
6703 // conpty is not available it can't be installed either.
6704 return dyn_winpty_init(TRUE);
6705
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006706 if (opt->jo_tty_type != NUL)
6707 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006708
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006709 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006710 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006711 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006712 use_conpty = TRUE;
6713 else if (has_winpty)
6714 use_winpty = TRUE;
6715 // else: error
6716 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006717 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006718 {
6719 if (has_winpty)
6720 use_winpty = TRUE;
6721 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006722 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006723 {
6724 if (has_conpty)
6725 use_conpty = TRUE;
6726 else
6727 return dyn_conpty_init(TRUE);
6728 }
6729
6730 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006731 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006732
6733 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006734 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006735
6736 // error
6737 return dyn_winpty_init(TRUE);
6738}
6739
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006740 static int
6741create_pty_only(term_T *term, jobopt_T *options)
6742{
6743 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6744 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6745 char in_name[80], out_name[80];
6746 channel_T *channel = NULL;
6747
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006748 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6749 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006750
6751 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6752 GetCurrentProcessId(),
6753 curbuf->b_fnum);
6754 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6755 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6756 PIPE_UNLIMITED_INSTANCES,
6757 0, 0, NMPWAIT_NOWAIT, NULL);
6758 if (hPipeIn == INVALID_HANDLE_VALUE)
6759 goto failed;
6760
6761 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6762 GetCurrentProcessId(),
6763 curbuf->b_fnum);
6764 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6765 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6766 PIPE_UNLIMITED_INSTANCES,
6767 0, 0, 0, NULL);
6768 if (hPipeOut == INVALID_HANDLE_VALUE)
6769 goto failed;
6770
6771 ConnectNamedPipe(hPipeIn, NULL);
6772 ConnectNamedPipe(hPipeOut, NULL);
6773
6774 term->tl_job = job_alloc();
6775 if (term->tl_job == NULL)
6776 goto failed;
6777 ++term->tl_job->jv_refcount;
6778
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006779 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006780 term->tl_job->jv_status = JOB_FINISHED;
6781
6782 channel = add_channel();
6783 if (channel == NULL)
6784 goto failed;
6785 term->tl_job->jv_channel = channel;
6786 channel->ch_keep_open = TRUE;
6787 channel->ch_named_pipe = TRUE;
6788
6789 channel_set_pipes(channel,
6790 (sock_T)hPipeIn,
6791 (sock_T)hPipeOut,
6792 (sock_T)hPipeOut);
6793 channel_set_job(channel, term->tl_job, options);
6794 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6795 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6796
6797 return OK;
6798
6799failed:
6800 if (hPipeIn != NULL)
6801 CloseHandle(hPipeIn);
6802 if (hPipeOut != NULL)
6803 CloseHandle(hPipeOut);
6804 return FAIL;
6805}
6806
6807/*
6808 * Free the terminal emulator part of "term".
6809 */
6810 static void
6811term_free_vterm(term_T *term)
6812{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006813 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006814 if (term->tl_winpty != NULL)
6815 winpty_free(term->tl_winpty);
6816 term->tl_winpty = NULL;
6817 if (term->tl_winpty_config != NULL)
6818 winpty_config_free(term->tl_winpty_config);
6819 term->tl_winpty_config = NULL;
6820 if (term->tl_vterm != NULL)
6821 vterm_free(term->tl_vterm);
6822 term->tl_vterm = NULL;
6823}
6824
6825/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006826 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006827 */
6828 static void
6829term_report_winsize(term_T *term, int rows, int cols)
6830{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006831 if (term->tl_conpty)
6832 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006833 if (term->tl_winpty)
6834 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6835}
6836
6837 int
6838terminal_enabled(void)
6839{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006840 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006841}
6842
6843# else
6844
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006845///////////////////////////////////////
6846// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006847
6848/*
6849 * Create a new terminal of "rows" by "cols" cells.
6850 * Start job for "cmd".
6851 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006852 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006853 * Return OK or FAIL.
6854 */
6855 static int
6856term_and_job_init(
6857 term_T *term,
6858 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006859 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006860 jobopt_T *opt,
6861 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006862{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006863 term->tl_arg0_cmd = NULL;
6864
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006865 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6866 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006867
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006868#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6869 if (opt->jo_set2 & JO2_ANSI_COLORS)
6870 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6871 else
6872 init_vterm_ansi_colors(term->tl_vterm);
6873#endif
6874
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006875 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01006876 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006877 if (term->tl_job != NULL)
6878 ++term->tl_job->jv_refcount;
6879
6880 return term->tl_job != NULL
6881 && term->tl_job->jv_channel != NULL
6882 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6883}
6884
6885 static int
6886create_pty_only(term_T *term, jobopt_T *opt)
6887{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006888 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6889 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006890
6891 term->tl_job = job_alloc();
6892 if (term->tl_job == NULL)
6893 return FAIL;
6894 ++term->tl_job->jv_refcount;
6895
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006896 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006897 term->tl_job->jv_status = JOB_FINISHED;
6898
6899 return mch_create_pty_channel(term->tl_job, opt);
6900}
6901
6902/*
6903 * Free the terminal emulator part of "term".
6904 */
6905 static void
6906term_free_vterm(term_T *term)
6907{
6908 if (term->tl_vterm != NULL)
6909 vterm_free(term->tl_vterm);
6910 term->tl_vterm = NULL;
6911}
6912
6913/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006914 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006915 */
6916 static void
6917term_report_winsize(term_T *term, int rows, int cols)
6918{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006919 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006920 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6921 {
6922 int fd = -1;
6923 int part;
6924
6925 for (part = PART_OUT; part < PART_COUNT; ++part)
6926 {
6927 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006928 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006929 break;
6930 }
6931 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6932 mch_signal_job(term->tl_job, (char_u *)"winch");
6933 }
6934}
6935
6936# endif
6937
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006938#endif // FEAT_TERMINAL