blob: cbf8fe0799159ee7194590a47b59c54b41f564ed [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020039 */
40
41#include "vim.h"
42
43#if defined(FEAT_TERMINAL) || defined(PROTO)
44
45#ifndef MIN
46# define MIN(x,y) ((x) < (y) ? (x) : (y))
47#endif
48#ifndef MAX
49# define MAX(x,y) ((x) > (y) ? (x) : (y))
50#endif
51
52#include "libvterm/include/vterm.h"
53
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010054// This is VTermScreenCell without the characters, thus much smaller.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055typedef struct {
56 VTermScreenCellAttrs attrs;
57 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010058 VTermColor fg;
59 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060} cellattr_T;
61
62typedef struct sb_line_S {
Bram Moolenaar29ae2232019-02-14 21:22:01 +010063 int sb_cols; // can differ per line
64 cellattr_T *sb_cells; // allocated
65 cellattr_T sb_fill_attr; // for short line
66 char_u *sb_text; // for tl_scrollback_postponed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067} sb_line_T;
68
Bram Moolenaar4f974752019-02-17 17:44:42 +010069#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010070# ifndef HPCON
71# define HPCON VOID*
72# endif
73# ifndef EXTENDED_STARTUPINFO_PRESENT
74# define EXTENDED_STARTUPINFO_PRESENT 0x00080000
75# endif
76# ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
77# define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE 0x00020016
78# endif
79typedef struct _DYN_STARTUPINFOEXW
80{
81 STARTUPINFOW StartupInfo;
82 LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
83} DYN_STARTUPINFOEXW, *PDYN_STARTUPINFOEXW;
84#endif
85
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010086// typedef term_T in structs.h
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020087struct terminal_S {
88 term_T *tl_next;
89
90 VTerm *tl_vterm;
91 job_T *tl_job;
92 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010093#if defined(FEAT_GUI)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010094 int tl_system; // when non-zero used for :!cmd output
95 int tl_toprow; // row with first line of system terminal
Bram Moolenaar13568252018-03-16 20:46:58 +010096#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010098 // Set when setting the size of a vterm, reset after redrawing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020099 int tl_vterm_size_changed;
100
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100101 int tl_normal_mode; // TRUE: Terminal-Normal mode
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200102 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200103 int tl_channel_recently_closed; // still need to handle tl_finish
104
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100105 int tl_finish;
106#define TL_FINISH_UNSET NUL
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100107#define TL_FINISH_CLOSE 'c' // ++close or :terminal without argument
108#define TL_FINISH_NOCLOSE 'n' // ++noclose
109#define TL_FINISH_OPEN 'o' // ++open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200110 char_u *tl_opencmd;
111 char_u *tl_eof_chars;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200112 char_u *tl_api; // prefix for terminal API function
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200113
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100114 char_u *tl_arg0_cmd; // To format the status bar
115
Bram Moolenaar4f974752019-02-17 17:44:42 +0100116#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200117 void *tl_winpty_config;
118 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200119
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100120 HPCON tl_conpty;
121 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
122
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200123 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200124#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100125#if defined(FEAT_SESSION)
126 char_u *tl_command;
127#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100128 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200129
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100130 // last known vterm size
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200131 int tl_rows;
132 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200133
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100134 char_u *tl_title; // NULL or allocated
135 char_u *tl_status_text; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200136
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100137 // Range of screen rows to update. Zero based.
138 int tl_dirty_row_start; // MAX_ROW if nothing dirty
139 int tl_dirty_row_end; // row below last one to update
140 int tl_dirty_snapshot; // text updated after making snapshot
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200141#ifdef FEAT_TIMERS
142 int tl_timer_set;
143 proftime_T tl_timer_due;
144#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100145 int tl_postponed_scroll; // to be scrolled up
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200146
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200147 garray_T tl_scrollback;
148 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100149 garray_T tl_scrollback_postponed;
150
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200151 cellattr_T tl_default_color;
152
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100153 linenr_T tl_top_diff_rows; // rows of top diff file or zero
154 linenr_T tl_bot_diff_rows; // rows of bottom diff file
Bram Moolenaard96ff162018-02-18 22:13:29 +0100155
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200156 VTermPos tl_cursor_pos;
157 int tl_cursor_visible;
158 int tl_cursor_blink;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100159 int tl_cursor_shape; // 1: block, 2: underline, 3: bar
160 char_u *tl_cursor_color; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200161
162 int tl_using_altscreen;
163};
164
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100165#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
166#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167
168/*
169 * List of all active terminals.
170 */
171static term_T *first_term = NULL;
172
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100173// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200174static term_T *in_terminal_loop = NULL;
175
Bram Moolenaar4f974752019-02-17 17:44:42 +0100176#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100177static BOOL has_winpty = FALSE;
178static BOOL has_conpty = FALSE;
179#endif
180
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100181#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200182#define KEY_BUF_LEN 200
183
184/*
185 * Functions with separate implementation for MS-Windows and Unix-like systems.
186 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200187static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188static int create_pty_only(term_T *term, jobopt_T *opt);
189static void term_report_winsize(term_T *term, int rows, int cols);
190static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100191#ifdef FEAT_GUI
192static void update_system_term(term_T *term);
193#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200194
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100195static void handle_postponed_scrollback(term_T *term);
196
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100197// The character that we know (or assume) that the terminal expects for the
198// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200199static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200200
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100201// "Terminal" highlight group colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100202static int term_default_cterm_fg = -1;
203static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200204
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100205// Store the last set and the desired cursor properties, so that we only update
206// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200207static char_u *last_set_cursor_color = NULL;
208static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100209static int last_set_cursor_shape = -1;
210static int desired_cursor_shape = -1;
211static int last_set_cursor_blink = -1;
212static int desired_cursor_blink = -1;
213
214
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100215///////////////////////////////////////
216// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200217
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200218 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200219cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
220{
221 if (lhs_color != NULL && rhs_color != NULL)
222 return STRCMP(lhs_color, rhs_color) == 0;
223 return lhs_color == NULL && rhs_color == NULL;
224}
225
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200226 static void
227cursor_color_copy(char_u **to_color, char_u *from_color)
228{
229 // Avoid a free & alloc if the value is already right.
230 if (cursor_color_equal(*to_color, from_color))
231 return;
232 vim_free(*to_color);
233 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
234}
235
236 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200237cursor_color_get(char_u *color)
238{
239 return (color == NULL) ? (char_u *)"" : color;
240}
241
242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200243/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200244 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200245 * current window.
246 * Sets "rows" and/or "cols" to zero when it should follow the window size.
247 * Return TRUE if the size is the minimum size: "24*80".
248 */
249 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200250parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200251{
252 int minsize = FALSE;
253
254 *rows = 0;
255 *cols = 0;
256
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200257 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200258 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200259 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200260
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100261 // Syntax of value was already checked when it's set.
Bram Moolenaar498c2562018-04-15 23:45:15 +0200262 if (p == NULL)
263 {
264 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200265 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200266 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200267 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200268 *cols = atoi((char *)p + 1);
269 }
270 return minsize;
271}
272
273/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200274 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200275 */
276 static void
277set_term_and_win_size(term_T *term)
278{
Bram Moolenaar13568252018-03-16 20:46:58 +0100279#ifdef FEAT_GUI
280 if (term->tl_system)
281 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100282 // Use the whole screen for the system command. However, it will start
283 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100284 term->tl_rows = Rows;
285 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200286 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100287 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100288#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200289 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200290 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200291 if (term->tl_rows != 0)
292 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
293 if (term->tl_cols != 0)
294 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200295 }
296 if (term->tl_rows == 0)
297 term->tl_rows = curwin->w_height;
298 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200299 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 if (term->tl_cols == 0)
301 term->tl_cols = curwin->w_width;
302 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200303 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200304}
305
306/*
307 * Initialize job options for a terminal job.
308 * Caller may overrule some of them.
309 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100310 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311init_job_options(jobopt_T *opt)
312{
313 clear_job_options(opt);
314
315 opt->jo_mode = MODE_RAW;
316 opt->jo_out_mode = MODE_RAW;
317 opt->jo_err_mode = MODE_RAW;
318 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
319}
320
321/*
322 * Set job options mandatory for a terminal job.
323 */
324 static void
325setup_job_options(jobopt_T *opt, int rows, int cols)
326{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100327#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100328 // Win32: Redirecting the job output won't work, thus always connect stdout
329 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200330 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200331#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200332 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100333 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200334 opt->jo_io[PART_OUT] = JIO_BUFFER;
335 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
336 opt->jo_modifiable[PART_OUT] = 0;
337 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
338 }
339
Bram Moolenaar4f974752019-02-17 17:44:42 +0100340#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100341 // Win32: Redirecting the job output won't work, thus always connect stderr
342 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200343 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200344#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200345 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100346 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200347 opt->jo_io[PART_ERR] = JIO_BUFFER;
348 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
349 opt->jo_modifiable[PART_ERR] = 0;
350 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
351 }
352
353 opt->jo_pty = TRUE;
354 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
355 opt->jo_term_rows = rows;
356 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
357 opt->jo_term_cols = cols;
358}
359
360/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200361 * Flush messages on channels.
362 */
363 static void
364term_flush_messages()
365{
366 mch_check_messages();
367 parse_queued_messages();
368}
369
370/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100371 * Close a terminal buffer (and its window). Used when creating the terminal
372 * fails.
373 */
374 static void
375term_close_buffer(buf_T *buf, buf_T *old_curbuf)
376{
377 free_terminal(buf);
378 if (old_curbuf != NULL)
379 {
380 --curbuf->b_nwindows;
381 curbuf = old_curbuf;
382 curwin->w_buffer = curbuf;
383 ++curbuf->b_nwindows;
384 }
385
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100386 // Wiping out the buffer will also close the window and call
387 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100388 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
389}
390
391/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200392 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100393 * Use either "argvar" or "argv", the other must be NULL.
394 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
395 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200396 * Returns NULL when failed.
397 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100398 buf_T *
399term_start(
400 typval_T *argvar,
401 char **argv,
402 jobopt_T *opt,
403 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200404{
405 exarg_T split_ea;
406 win_T *old_curwin = curwin;
407 term_T *term;
408 buf_T *old_curbuf = NULL;
409 int res;
410 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100411 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200412 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200413
414 if (check_restricted() || check_secure())
415 return NULL;
416
417 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
418 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
419 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100420 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
421 || (argvar != NULL
422 && argvar->v_type == VAR_LIST
423 && argvar->vval.v_list != NULL
424 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200425 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100426 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200427 return NULL;
428 }
429
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200430 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200431 if (term == NULL)
432 return NULL;
433 term->tl_dirty_row_end = MAX_ROW;
434 term->tl_cursor_visible = TRUE;
435 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
436 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100437#ifdef FEAT_GUI
438 term->tl_system = (flags & TERM_START_SYSTEM);
439#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200440 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100441 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200442
443 vim_memset(&split_ea, 0, sizeof(split_ea));
444 if (opt->jo_curwin)
445 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100446 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100447 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200448 {
449 no_write_message();
450 vim_free(term);
451 return NULL;
452 }
453 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100454 ECMD_HIDE
455 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
456 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200457 {
458 vim_free(term);
459 return NULL;
460 }
461 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100462 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200463 {
464 buf_T *buf;
465
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100466 // Create a new buffer without a window. Make it the current buffer for
467 // a moment to be able to do the initialisations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200468 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
469 BLN_NEW | BLN_LISTED);
470 if (buf == NULL || ml_open(buf) == FAIL)
471 {
472 vim_free(term);
473 return NULL;
474 }
475 old_curbuf = curbuf;
476 --curbuf->b_nwindows;
477 curbuf = buf;
478 curwin->w_buffer = buf;
479 ++curbuf->b_nwindows;
480 }
481 else
482 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100483 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200484 split_ea.cmdidx = CMD_new;
485 split_ea.cmd = (char_u *)"new";
486 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100487 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200488 {
489 split_ea.line2 = opt->jo_term_rows;
490 split_ea.addr_count = 1;
491 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100492 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200493 {
494 split_ea.line2 = opt->jo_term_cols;
495 split_ea.addr_count = 1;
496 }
497
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100498 if (vertical)
499 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200500 ex_splitview(&split_ea);
501 if (curwin == old_curwin)
502 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100503 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200504 vim_free(term);
505 return NULL;
506 }
507 }
508 term->tl_buffer = curbuf;
509 curbuf->b_term = term;
510
511 if (!opt->jo_hidden)
512 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100513 // Only one size was taken care of with :new, do the other one. With
514 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100515 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200516 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100517 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200518 win_setwidth(opt->jo_term_cols);
519 }
520
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100521 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200522 term->tl_next = first_term;
523 first_term = term;
524
525 if (opt->jo_term_name != NULL)
526 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100527 else if (argv != NULL)
528 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200529 else
530 {
531 int i;
532 size_t len;
533 char_u *cmd, *p;
534
535 if (argvar->v_type == VAR_STRING)
536 {
537 cmd = argvar->vval.v_string;
538 if (cmd == NULL)
539 cmd = (char_u *)"";
540 else if (STRCMP(cmd, "NONE") == 0)
541 cmd = (char_u *)"pty";
542 }
543 else if (argvar->v_type != VAR_LIST
544 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100545 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100546 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200547 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
548 cmd = (char_u*)"";
549
550 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200551 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200552
553 for (i = 0; p != NULL; ++i)
554 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100555 // Prepend a ! to the command name to avoid the buffer name equals
556 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200557 if (i == 0)
558 vim_snprintf((char *)p, len, "!%s", cmd);
559 else
560 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
561 if (buflist_findname(p) == NULL)
562 {
563 vim_free(curbuf->b_ffname);
564 curbuf->b_ffname = p;
565 break;
566 }
567 }
568 }
569 curbuf->b_fname = curbuf->b_ffname;
570
571 if (opt->jo_term_opencmd != NULL)
572 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
573
574 if (opt->jo_eof_chars != NULL)
575 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
576
577 set_string_option_direct((char_u *)"buftype", -1,
578 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200579 // Avoid that 'buftype' is reset when this buffer is entered.
580 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200581
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100582 // Mark the buffer as not modifiable. It can only be made modifiable after
583 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200584 curbuf->b_p_ma = FALSE;
585
586 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100587#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200588 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
589#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200590 setup_job_options(opt, term->tl_rows, term->tl_cols);
591
Bram Moolenaar13568252018-03-16 20:46:58 +0100592 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100593 return curbuf;
594
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100595#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100596 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100597 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100598 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100599 else if (argvar->v_type == VAR_STRING)
600 {
601 char_u *cmd = argvar->vval.v_string;
602
603 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
604 term->tl_command = vim_strsave(cmd);
605 }
606 else if (argvar->v_type == VAR_LIST
607 && argvar->vval.v_list != NULL
608 && argvar->vval.v_list->lv_len > 0)
609 {
610 garray_T ga;
611 listitem_T *item;
612
613 ga_init2(&ga, 1, 100);
614 for (item = argvar->vval.v_list->lv_first;
615 item != NULL; item = item->li_next)
616 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100617 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100618 char_u *p;
619
620 if (s == NULL)
621 break;
622 p = vim_strsave_fnameescape(s, FALSE);
623 if (p == NULL)
624 break;
625 ga_concat(&ga, p);
626 vim_free(p);
627 ga_append(&ga, ' ');
628 }
629 if (item == NULL)
630 {
631 ga_append(&ga, NUL);
632 term->tl_command = ga.ga_data;
633 }
634 else
635 ga_clear(&ga);
636 }
637#endif
638
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100639 if (opt->jo_term_kill != NULL)
640 {
641 char_u *p = skiptowhite(opt->jo_term_kill);
642
643 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
644 }
645
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200646 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100647 {
648 char_u *p = skiptowhite(opt->jo_term_api);
649
650 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
651 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200652 else
653 term->tl_api = vim_strsave((char_u *)"Tapi_");
654
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100655 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100656 if (argv == NULL
657 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200658 && argvar->vval.v_string != NULL
659 && STRCMP(argvar->vval.v_string, "NONE") == 0)
660 res = create_pty_only(term, opt);
661 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200662 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200663
664 newbuf = curbuf;
665 if (res == OK)
666 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100667 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200668 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
669 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100670#ifdef FEAT_GUI
671 if (term->tl_system)
672 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100673 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100674 term->tl_toprow = msg_row + 1;
675 term->tl_dirty_row_end = 0;
676 }
677#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200678
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100679 // Make sure we don't get stuck on sending keys to the job, it leads to
680 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200681 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
682
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200683 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200684 {
685 --curbuf->b_nwindows;
686 curbuf = old_curbuf;
687 curwin->w_buffer = curbuf;
688 ++curbuf->b_nwindows;
689 }
690 }
691 else
692 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100693 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200694 return NULL;
695 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100696
Bram Moolenaar13568252018-03-16 20:46:58 +0100697 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200698 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
699 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200700 return newbuf;
701}
702
703/*
704 * ":terminal": open a terminal window and execute a job in it.
705 */
706 void
707ex_terminal(exarg_T *eap)
708{
709 typval_T argvar[2];
710 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100711 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200712 char_u *cmd;
713 char_u *tofree = NULL;
714
715 init_job_options(&opt);
716
717 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100718 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200719 {
720 char_u *p, *ep;
721
722 cmd += 2;
723 p = skiptowhite(cmd);
724 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200725 if (ep != NULL)
726 {
727 if (ep < p)
728 p = ep;
729 else
730 ep = NULL;
731 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200732
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200733# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
734 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
735 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200736 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200737 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100738 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200739 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200740 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200741 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200742 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200743 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200744 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200745 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100746 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100747 else if (OPTARG_HAS("shell"))
748 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200749 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100750 {
751 opt.jo_set2 |= JO2_TERM_KILL;
752 opt.jo_term_kill = ep + 1;
753 p = skiptowhite(cmd);
754 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200755 else if (OPTARG_HAS("api"))
756 {
757 opt.jo_set2 |= JO2_TERM_API;
758 if (ep != NULL)
759 {
760 opt.jo_term_api = ep + 1;
761 p = skiptowhite(cmd);
762 }
763 else
764 opt.jo_term_api = NULL;
765 }
766 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200767 {
768 opt.jo_set2 |= JO2_TERM_ROWS;
769 opt.jo_term_rows = atoi((char *)ep + 1);
770 p = skiptowhite(cmd);
771 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200772 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200773 {
774 opt.jo_set2 |= JO2_TERM_COLS;
775 opt.jo_term_cols = atoi((char *)ep + 1);
776 p = skiptowhite(cmd);
777 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200778 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200779 {
780 char_u *buf = NULL;
781 char_u *keys;
782
Bram Moolenaar21109272020-01-30 16:27:20 +0100783 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200784 p = skiptowhite(cmd);
785 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200786 keys = replace_termcodes(ep + 1, &buf,
787 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788 opt.jo_set2 |= JO2_EOF_CHARS;
789 opt.jo_eof_chars = vim_strsave(keys);
790 vim_free(buf);
791 *p = ' ';
792 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100793#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100794 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
795 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100796 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100797 int tty_type = NUL;
798
799 p = skiptowhite(cmd);
800 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
801 tty_type = 'w';
802 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
803 tty_type = 'c';
804 else
805 {
806 semsg(e_invargval, "type");
807 goto theend;
808 }
809 opt.jo_set2 |= JO2_TTY_TYPE;
810 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100811 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100812#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200813 else
814 {
815 if (*p)
816 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100817 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100818 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200819 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200820# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200821 cmd = skipwhite(p);
822 }
823 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100824 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100825 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200826 tofree = cmd = vim_strsave(p_sh);
827
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100828 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100829 if (opt.jo_term_finish == NUL)
830 opt.jo_term_finish = 'c';
831 }
832
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200833 if (eap->addr_count > 0)
834 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100835 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200836 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
837 opt.jo_io[PART_IN] = JIO_BUFFER;
838 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
839 opt.jo_in_top = eap->line1;
840 opt.jo_in_bot = eap->line2;
841 }
842
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100843 if (opt_shell && tofree == NULL)
844 {
845#ifdef UNIX
846 char **argv = NULL;
847 char_u *tofree1 = NULL;
848 char_u *tofree2 = NULL;
849
850 // :term ++shell command
851 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
852 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100853 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100854 vim_free(tofree1);
855 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100856 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100857#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100858# ifdef MSWIN
859 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
860 char_u *newcmd;
861
862 newcmd = alloc(cmdlen);
863 if (newcmd == NULL)
864 goto theend;
865 tofree = newcmd;
866 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
867 cmd = newcmd;
868# else
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100869 emsg(_("E279: Sorry, ++shell is not supported on this system"));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100870 goto theend;
871# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100872#endif
873 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100874 argvar[0].v_type = VAR_STRING;
875 argvar[0].vval.v_string = cmd;
876 argvar[1].v_type = VAR_UNKNOWN;
877 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100878
879theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100880 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200881 vim_free(opt.jo_eof_chars);
882}
883
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100884#if defined(FEAT_SESSION) || defined(PROTO)
885/*
886 * Write a :terminal command to the session file to restore the terminal in
887 * window "wp".
888 * Return FAIL if writing fails.
889 */
890 int
891term_write_session(FILE *fd, win_T *wp)
892{
893 term_T *term = wp->w_buffer->b_term;
894
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100895 // Create the terminal and run the command. This is not without
896 // risk, but let's assume the user only creates a session when this
897 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100898 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
899 term->tl_cols, term->tl_rows) < 0)
900 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100901#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100902 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
903 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100904#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100905 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
906 return FAIL;
907
908 return put_eol(fd);
909}
910
911/*
912 * Return TRUE if "buf" has a terminal that should be restored.
913 */
914 int
915term_should_restore(buf_T *buf)
916{
917 term_T *term = buf->b_term;
918
919 return term != NULL && (term->tl_command == NULL
920 || STRCMP(term->tl_command, "NONE") != 0);
921}
922#endif
923
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200924/*
925 * Free the scrollback buffer for "term".
926 */
927 static void
928free_scrollback(term_T *term)
929{
930 int i;
931
932 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
933 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
934 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100935 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
936 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
937 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200938}
939
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100940
941// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200942static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100943
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200944/*
945 * Free a terminal and everything it refers to.
946 * Kills the job if there is one.
947 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100948 * The actual terminal structure is freed later in free_unused_terminals(),
949 * because callbacks may wipe out a buffer while the terminal is still
950 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200951 */
952 void
953free_terminal(buf_T *buf)
954{
955 term_T *term = buf->b_term;
956 term_T *tp;
957
958 if (term == NULL)
959 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100960
961 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200962 if (first_term == term)
963 first_term = term->tl_next;
964 else
965 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
966 if (tp->tl_next == term)
967 {
968 tp->tl_next = term->tl_next;
969 break;
970 }
971
972 if (term->tl_job != NULL)
973 {
974 if (term->tl_job->jv_status != JOB_ENDED
975 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100976 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200977 job_stop(term->tl_job, NULL, "kill");
978 job_unref(term->tl_job);
979 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100980 term->tl_next = terminals_to_free;
981 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200982
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200983 buf->b_term = NULL;
984 if (in_terminal_loop == term)
985 in_terminal_loop = NULL;
986}
987
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100988 void
989free_unused_terminals()
990{
991 while (terminals_to_free != NULL)
992 {
993 term_T *term = terminals_to_free;
994
995 terminals_to_free = term->tl_next;
996
997 free_scrollback(term);
998
999 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001000 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001001 vim_free(term->tl_title);
1002#ifdef FEAT_SESSION
1003 vim_free(term->tl_command);
1004#endif
1005 vim_free(term->tl_kill);
1006 vim_free(term->tl_status_text);
1007 vim_free(term->tl_opencmd);
1008 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001009 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001010#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001011 if (term->tl_out_fd != NULL)
1012 fclose(term->tl_out_fd);
1013#endif
1014 vim_free(term->tl_cursor_color);
1015 vim_free(term);
1016 }
1017}
1018
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001019/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001020 * Get the part that is connected to the tty. Normally this is PART_IN, but
1021 * when writing buffer lines to the job it can be another. This makes it
1022 * possible to do "1,5term vim -".
1023 */
1024 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001025get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001026{
1027#ifdef UNIX
1028 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1029 int i;
1030
1031 for (i = 0; i < 3; ++i)
1032 {
1033 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1034
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001035 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001036 return parts[i];
1037 }
1038#endif
1039 return PART_IN;
1040}
1041
1042/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001043 * Write job output "msg[len]" to the vterm.
1044 */
1045 static void
1046term_write_job_output(term_T *term, char_u *msg, size_t len)
1047{
1048 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001049 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001050
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001051 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001052
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001053 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001054 if (prevlen != vterm_output_get_buffer_current(vterm))
1055 {
1056 char buf[KEY_BUF_LEN];
1057 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1058
1059 if (curlen > 0)
1060 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1061 (char_u *)buf, (int)curlen, NULL);
1062 }
1063
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001064 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001065 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1066}
1067
1068 static void
1069update_cursor(term_T *term, int redraw)
1070{
1071 if (term->tl_normal_mode)
1072 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001073#ifdef FEAT_GUI
1074 if (term->tl_system)
1075 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1076 term->tl_cursor_pos.col);
1077 else
1078#endif
1079 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001080 if (redraw)
1081 {
1082 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1083 cursor_on();
1084 out_flush();
1085#ifdef FEAT_GUI
1086 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001087 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001088 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001089 gui_mch_flush();
1090 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001091#endif
1092 }
1093}
1094
1095/*
1096 * Invoked when "msg" output from a job was received. Write it to the terminal
1097 * of "buffer".
1098 */
1099 void
1100write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1101{
1102 size_t len = STRLEN(msg);
1103 term_T *term = buffer->b_term;
1104
Bram Moolenaar4f974752019-02-17 17:44:42 +01001105#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001106 // Win32: Cannot redirect output of the job, intercept it here and write to
1107 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001108 if (term->tl_out_fd != NULL)
1109 {
1110 ch_log(channel, "Writing %d bytes to output file", (int)len);
1111 fwrite(msg, len, 1, term->tl_out_fd);
1112 return;
1113 }
1114#endif
1115
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001116 if (term->tl_vterm == NULL)
1117 {
1118 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1119 return;
1120 }
1121 ch_log(channel, "writing %d bytes to terminal", (int)len);
1122 term_write_job_output(term, msg, len);
1123
Bram Moolenaar13568252018-03-16 20:46:58 +01001124#ifdef FEAT_GUI
1125 if (term->tl_system)
1126 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001127 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001128 update_system_term(term);
1129 update_cursor(term, TRUE);
1130 }
1131 else
1132#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001133 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1134 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001135 if (!term->tl_normal_mode)
1136 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001137 // Don't use update_screen() when editing the command line, it gets
1138 // cleared.
1139 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001140 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001141 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001142 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001143 update_screen(VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001144 // update_screen() can be slow, check the terminal wasn't closed
1145 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001146 if (buffer == curbuf && curbuf->b_term != NULL)
1147 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001148 }
1149 else
1150 redraw_after_callback(TRUE);
1151 }
1152}
1153
1154/*
1155 * Send a mouse position and click to the vterm
1156 */
1157 static int
1158term_send_mouse(VTerm *vterm, int button, int pressed)
1159{
1160 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001161 int row = mouse_row - W_WINROW(curwin);
1162 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001163
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001164#ifdef FEAT_PROP_POPUP
1165 if (popup_is_popup(curwin))
1166 {
1167 row -= popup_top_extra(curwin);
1168 col -= popup_left_extra(curwin);
1169 }
1170#endif
1171 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001172 if (button != 0)
1173 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001174 return TRUE;
1175}
1176
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001177static int enter_mouse_col = -1;
1178static int enter_mouse_row = -1;
1179
1180/*
1181 * Handle a mouse click, drag or release.
1182 * Return TRUE when a mouse event is sent to the terminal.
1183 */
1184 static int
1185term_mouse_click(VTerm *vterm, int key)
1186{
1187#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001188 // For modeless selection mouse drag and release events are ignored, unless
1189 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001190 static int ignore_drag_release = TRUE;
1191 VTermMouseState mouse_state;
1192
1193 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1194 if (mouse_state.flags == 0)
1195 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001196 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001197 switch (key)
1198 {
1199 case K_LEFTDRAG:
1200 case K_LEFTRELEASE:
1201 case K_RIGHTDRAG:
1202 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001203 // Ignore drag and release events when the button-down wasn't
1204 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001205 if (ignore_drag_release)
1206 {
1207 int save_mouse_col, save_mouse_row;
1208
1209 if (enter_mouse_col < 0)
1210 break;
1211
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001212 // mouse click in the window gave us focus, handle that
1213 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001214 save_mouse_col = mouse_col;
1215 save_mouse_row = mouse_row;
1216 mouse_col = enter_mouse_col;
1217 mouse_row = enter_mouse_row;
1218 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1219 mouse_col = save_mouse_col;
1220 mouse_row = save_mouse_row;
1221 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001222 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001223 case K_LEFTMOUSE:
1224 case K_RIGHTMOUSE:
1225 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1226 ignore_drag_release = TRUE;
1227 else
1228 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001229 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001230 if (clip_star.available)
1231 {
1232 int button, is_click, is_drag;
1233
1234 button = get_mouse_button(KEY2TERMCAP1(key),
1235 &is_click, &is_drag);
1236 if (mouse_model_popup() && button == MOUSE_LEFT
1237 && (mod_mask & MOD_MASK_SHIFT))
1238 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001239 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001240 button = MOUSE_RIGHT;
1241 mod_mask &= ~MOD_MASK_SHIFT;
1242 }
1243 clip_modeless(button, is_click, is_drag);
1244 }
1245 break;
1246
1247 case K_MIDDLEMOUSE:
1248 if (clip_star.available)
1249 insert_reg('*', TRUE);
1250 break;
1251 }
1252 enter_mouse_col = -1;
1253 return FALSE;
1254 }
1255#endif
1256 enter_mouse_col = -1;
1257
1258 switch (key)
1259 {
1260 case K_LEFTMOUSE:
1261 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1262 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1263 case K_LEFTRELEASE:
1264 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1265 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1266 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1267 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1268 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1269 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1270 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1271 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1272 }
1273 return TRUE;
1274}
1275
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001276/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001277 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1278 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001279 * Return the number of bytes in "buf".
1280 */
1281 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001282term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001283{
1284 VTerm *vterm = term->tl_vterm;
1285 VTermKey key = VTERM_KEY_NONE;
1286 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001287 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001288
1289 switch (c)
1290 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001291 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001292
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001293 // don't use VTERM_KEY_BACKSPACE, it always
1294 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001295 case K_BS: c = term_backspace_char; break;
1296
1297 case ESC: key = VTERM_KEY_ESCAPE; break;
1298 case K_DEL: key = VTERM_KEY_DEL; break;
1299 case K_DOWN: key = VTERM_KEY_DOWN; break;
1300 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1301 key = VTERM_KEY_DOWN; break;
1302 case K_END: key = VTERM_KEY_END; break;
1303 case K_S_END: mod = VTERM_MOD_SHIFT;
1304 key = VTERM_KEY_END; break;
1305 case K_C_END: mod = VTERM_MOD_CTRL;
1306 key = VTERM_KEY_END; break;
1307 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1308 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1309 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1310 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1311 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1312 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1313 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1314 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1315 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1316 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1317 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1318 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1319 case K_HOME: key = VTERM_KEY_HOME; break;
1320 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1321 key = VTERM_KEY_HOME; break;
1322 case K_C_HOME: mod = VTERM_MOD_CTRL;
1323 key = VTERM_KEY_HOME; break;
1324 case K_INS: key = VTERM_KEY_INS; break;
1325 case K_K0: key = VTERM_KEY_KP_0; break;
1326 case K_K1: key = VTERM_KEY_KP_1; break;
1327 case K_K2: key = VTERM_KEY_KP_2; break;
1328 case K_K3: key = VTERM_KEY_KP_3; break;
1329 case K_K4: key = VTERM_KEY_KP_4; break;
1330 case K_K5: key = VTERM_KEY_KP_5; break;
1331 case K_K6: key = VTERM_KEY_KP_6; break;
1332 case K_K7: key = VTERM_KEY_KP_7; break;
1333 case K_K8: key = VTERM_KEY_KP_8; break;
1334 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001335 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001336 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001337 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001338 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001339 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1340 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001341 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1342 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001343 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1344 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001345 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1346 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1347 case K_LEFT: key = VTERM_KEY_LEFT; break;
1348 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1349 key = VTERM_KEY_LEFT; break;
1350 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1351 key = VTERM_KEY_LEFT; break;
1352 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1353 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1354 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1355 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1356 key = VTERM_KEY_RIGHT; break;
1357 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1358 key = VTERM_KEY_RIGHT; break;
1359 case K_UP: key = VTERM_KEY_UP; break;
1360 case K_S_UP: mod = VTERM_MOD_SHIFT;
1361 key = VTERM_KEY_UP; break;
1362 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001363 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1364 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001365
Bram Moolenaara42ad572017-11-16 13:08:04 +01001366 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1367 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001368 case K_MOUSELEFT: /* TODO */ return 0;
1369 case K_MOUSERIGHT: /* TODO */ return 0;
1370
1371 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001372 case K_LEFTMOUSE_NM:
1373 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001374 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001375 case K_LEFTRELEASE_NM:
1376 case K_MOUSEMOVE:
1377 case K_MIDDLEMOUSE:
1378 case K_MIDDLEDRAG:
1379 case K_MIDDLERELEASE:
1380 case K_RIGHTMOUSE:
1381 case K_RIGHTDRAG:
1382 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1383 return 0;
1384 other = TRUE;
1385 break;
1386
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001387 case K_X1MOUSE: /* TODO */ return 0;
1388 case K_X1DRAG: /* TODO */ return 0;
1389 case K_X1RELEASE: /* TODO */ return 0;
1390 case K_X2MOUSE: /* TODO */ return 0;
1391 case K_X2DRAG: /* TODO */ return 0;
1392 case K_X2RELEASE: /* TODO */ return 0;
1393
1394 case K_IGNORE: return 0;
1395 case K_NOP: return 0;
1396 case K_UNDO: return 0;
1397 case K_HELP: return 0;
1398 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1399 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1400 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1401 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1402 case K_SELECT: return 0;
1403#ifdef FEAT_GUI
1404 case K_VER_SCROLLBAR: return 0;
1405 case K_HOR_SCROLLBAR: return 0;
1406#endif
1407#ifdef FEAT_GUI_TABLINE
1408 case K_TABLINE: return 0;
1409 case K_TABMENU: return 0;
1410#endif
1411#ifdef FEAT_NETBEANS_INTG
1412 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1413#endif
1414#ifdef FEAT_DND
1415 case K_DROP: return 0;
1416#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001417 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001418 case K_PS: vterm_keyboard_start_paste(vterm);
1419 other = TRUE;
1420 break;
1421 case K_PE: vterm_keyboard_end_paste(vterm);
1422 other = TRUE;
1423 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001424 }
1425
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001426 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001427 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001428 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001429 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001430 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001431 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001432 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001433
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001434 /*
1435 * Convert special keys to vterm keys:
1436 * - Write keys to vterm: vterm_keyboard_key()
1437 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001438 */
1439 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001440 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001441 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001442 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001443 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001444 vterm_keyboard_unichar(vterm, c, mod);
1445
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001446 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001447 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1448}
1449
1450/*
1451 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001452 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001453 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001454 */
1455 static int
1456term_job_running_check(term_T *term, int check_job_status)
1457{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001458 // Also consider the job finished when the channel is closed, to avoid a
1459 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001460 if (term != NULL
1461 && term->tl_job != NULL
1462 && channel_is_open(term->tl_job->jv_channel))
1463 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001464 job_T *job = term->tl_job;
1465
1466 // Careful: Checking the job status may invoked callbacks, which close
1467 // the buffer and terminate "term". However, "job" will not be freed
1468 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001469 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001470 job_status(job);
1471 return (job->jv_status == JOB_STARTED
1472 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001473 }
1474 return FALSE;
1475}
1476
1477/*
1478 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001479 */
1480 int
1481term_job_running(term_T *term)
1482{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001483 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001484}
1485
1486/*
1487 * Return TRUE if "term" has an active channel and used ":term NONE".
1488 */
1489 int
1490term_none_open(term_T *term)
1491{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001492 // Also consider the job finished when the channel is closed, to avoid a
1493 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001494 return term != NULL
1495 && term->tl_job != NULL
1496 && channel_is_open(term->tl_job->jv_channel)
1497 && term->tl_job->jv_channel->ch_keep_open;
1498}
1499
1500/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001501 * Used when exiting: kill the job in "buf" if so desired.
1502 * Return OK when the job finished.
1503 * Return FAIL when the job is still running.
1504 */
1505 int
1506term_try_stop_job(buf_T *buf)
1507{
1508 int count;
1509 char *how = (char *)buf->b_term->tl_kill;
1510
1511#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1512 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1513 {
1514 char_u buff[DIALOG_MSG_SIZE];
1515 int ret;
1516
1517 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1518 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1519 if (ret == VIM_YES)
1520 how = "kill";
1521 else if (ret == VIM_CANCEL)
1522 return FAIL;
1523 }
1524#endif
1525 if (how == NULL || *how == NUL)
1526 return FAIL;
1527
1528 job_stop(buf->b_term->tl_job, NULL, how);
1529
Bram Moolenaar9172d232019-01-29 23:06:54 +01001530 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001531 for (count = 0; count < 100; ++count)
1532 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001533 job_T *job;
1534
1535 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001536 if (!buf_valid(buf)
1537 || buf->b_term == NULL
1538 || buf->b_term->tl_job == NULL)
1539 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001540 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001541
Bram Moolenaar9172d232019-01-29 23:06:54 +01001542 // Call job_status() to update jv_status. It may cause the job to be
1543 // cleaned up but it won't be freed.
1544 job_status(job);
1545 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001546 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001547
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001548 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001549 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001550 }
1551 return FAIL;
1552}
1553
1554/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001555 * Add the last line of the scrollback buffer to the buffer in the window.
1556 */
1557 static void
1558add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1559{
1560 buf_T *buf = term->tl_buffer;
1561 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1562 linenr_T lnum = buf->b_ml.ml_line_count;
1563
Bram Moolenaar4f974752019-02-17 17:44:42 +01001564#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001565 if (!enc_utf8 && enc_codepage > 0)
1566 {
1567 WCHAR *ret = NULL;
1568 int length = 0;
1569
1570 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1571 &ret, &length);
1572 if (ret != NULL)
1573 {
1574 WideCharToMultiByte_alloc(enc_codepage, 0,
1575 ret, length, (char **)&text, &len, 0, 0);
1576 vim_free(ret);
1577 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1578 vim_free(text);
1579 }
1580 }
1581 else
1582#endif
1583 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1584 if (empty)
1585 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001586 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001587 curbuf = buf;
1588 ml_delete(1, FALSE);
1589 curbuf = curwin->w_buffer;
1590 }
1591}
1592
1593 static void
1594cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1595{
1596 attr->width = cell->width;
1597 attr->attrs = cell->attrs;
1598 attr->fg = cell->fg;
1599 attr->bg = cell->bg;
1600}
1601
1602 static int
1603equal_celattr(cellattr_T *a, cellattr_T *b)
1604{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001605 // Comparing the colors should be sufficient.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001606 return a->fg.red == b->fg.red
1607 && a->fg.green == b->fg.green
1608 && a->fg.blue == b->fg.blue
1609 && a->bg.red == b->bg.red
1610 && a->bg.green == b->bg.green
1611 && a->bg.blue == b->bg.blue;
1612}
1613
Bram Moolenaard96ff162018-02-18 22:13:29 +01001614/*
1615 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1616 * line at this position. Otherwise at the end.
1617 */
1618 static int
1619add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1620{
1621 if (ga_grow(&term->tl_scrollback, 1) == OK)
1622 {
1623 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1624 + term->tl_scrollback.ga_len;
1625
1626 if (lnum > 0)
1627 {
1628 int i;
1629
1630 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1631 {
1632 *line = *(line - 1);
1633 --line;
1634 }
1635 }
1636 line->sb_cols = 0;
1637 line->sb_cells = NULL;
1638 line->sb_fill_attr = *fill_attr;
1639 ++term->tl_scrollback.ga_len;
1640 return OK;
1641 }
1642 return FALSE;
1643}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001644
1645/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001646 * Remove the terminal contents from the scrollback and the buffer.
1647 * Used before adding a new scrollback line or updating the buffer for lines
1648 * displayed in the terminal.
1649 */
1650 static void
1651cleanup_scrollback(term_T *term)
1652{
1653 sb_line_T *line;
1654 garray_T *gap;
1655
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001656 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001657 gap = &term->tl_scrollback;
1658 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1659 && gap->ga_len > 0)
1660 {
1661 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1662 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1663 vim_free(line->sb_cells);
1664 --gap->ga_len;
1665 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001666 curbuf = curwin->w_buffer;
1667 if (curbuf == term->tl_buffer)
1668 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001669}
1670
1671/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001672 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001673 */
1674 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001675update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001676{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001677 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001678 int len;
1679 int lines_skipped = 0;
1680 VTermPos pos;
1681 VTermScreenCell cell;
1682 cellattr_T fill_attr, new_fill_attr;
1683 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001684
1685 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1686 "Adding terminal window snapshot to buffer");
1687
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001688 // First remove the lines that were appended before, they might be
1689 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001690 cleanup_scrollback(term);
1691
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001692 screen = vterm_obtain_screen(term->tl_vterm);
1693 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001694 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1695 {
1696 len = 0;
1697 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1698 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1699 && cell.chars[0] != NUL)
1700 {
1701 len = pos.col + 1;
1702 new_fill_attr = term->tl_default_color;
1703 }
1704 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001705 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001706 cell2cellattr(&cell, &new_fill_attr);
1707
1708 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1709 ++lines_skipped;
1710 else
1711 {
1712 while (lines_skipped > 0)
1713 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001714 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001715 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001716 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001717 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001718 }
1719
1720 if (len == 0)
1721 p = NULL;
1722 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001723 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001724 if ((p != NULL || len == 0)
1725 && ga_grow(&term->tl_scrollback, 1) == OK)
1726 {
1727 garray_T ga;
1728 int width;
1729 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1730 + term->tl_scrollback.ga_len;
1731
1732 ga_init2(&ga, 1, 100);
1733 for (pos.col = 0; pos.col < len; pos.col += width)
1734 {
1735 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1736 {
1737 width = 1;
1738 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1739 if (ga_grow(&ga, 1) == OK)
1740 ga.ga_len += utf_char2bytes(' ',
1741 (char_u *)ga.ga_data + ga.ga_len);
1742 }
1743 else
1744 {
1745 width = cell.width;
1746
1747 cell2cellattr(&cell, &p[pos.col]);
1748
Bram Moolenaara79fd562018-12-20 20:47:32 +01001749 // Each character can be up to 6 bytes.
1750 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001751 {
1752 int i;
1753 int c;
1754
1755 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1756 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1757 (char_u *)ga.ga_data + ga.ga_len);
1758 }
1759 }
1760 }
1761 line->sb_cols = len;
1762 line->sb_cells = p;
1763 line->sb_fill_attr = new_fill_attr;
1764 fill_attr = new_fill_attr;
1765 ++term->tl_scrollback.ga_len;
1766
1767 if (ga_grow(&ga, 1) == FAIL)
1768 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1769 else
1770 {
1771 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1772 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1773 }
1774 ga_clear(&ga);
1775 }
1776 else
1777 vim_free(p);
1778 }
1779 }
1780
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001781 // Add trailing empty lines.
1782 for (pos.row = term->tl_scrollback.ga_len;
1783 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1784 ++pos.row)
1785 {
1786 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1787 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1788 }
1789
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001790 term->tl_dirty_snapshot = FALSE;
1791#ifdef FEAT_TIMERS
1792 term->tl_timer_set = FALSE;
1793#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001794}
1795
1796/*
1797 * If needed, add the current lines of the terminal to scrollback and to the
1798 * buffer. Called after the job has ended and when switching to
1799 * Terminal-Normal mode.
1800 * When "redraw" is TRUE redraw the windows that show the terminal.
1801 */
1802 static void
1803may_move_terminal_to_buffer(term_T *term, int redraw)
1804{
1805 win_T *wp;
1806
1807 if (term->tl_vterm == NULL)
1808 return;
1809
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001810 // Update the snapshot only if something changes or the buffer does not
1811 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001812 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1813 <= term->tl_scrollback_scrolled)
1814 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001815
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001816 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001817 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1818 &term->tl_default_color.fg, &term->tl_default_color.bg);
1819
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001820 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001821 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001822 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001823 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001825 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1826 wp->w_cursor.col = 0;
1827 wp->w_valid = 0;
1828 if (wp->w_cursor.lnum >= wp->w_height)
1829 {
1830 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001831
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001832 if (wp->w_topline < min_topline)
1833 wp->w_topline = min_topline;
1834 }
1835 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001836 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001837 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001838}
1839
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001840#if defined(FEAT_TIMERS) || defined(PROTO)
1841/*
1842 * Check if any terminal timer expired. If so, copy text from the terminal to
1843 * the buffer.
1844 * Return the time until the next timer will expire.
1845 */
1846 int
1847term_check_timers(int next_due_arg, proftime_T *now)
1848{
1849 term_T *term;
1850 int next_due = next_due_arg;
1851
1852 for (term = first_term; term != NULL; term = term->tl_next)
1853 {
1854 if (term->tl_timer_set && !term->tl_normal_mode)
1855 {
1856 long this_due = proftime_time_left(&term->tl_timer_due, now);
1857
1858 if (this_due <= 1)
1859 {
1860 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001861 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001862 }
1863 else if (next_due == -1 || next_due > this_due)
1864 next_due = this_due;
1865 }
1866 }
1867
1868 return next_due;
1869}
1870#endif
1871
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001872/*
1873 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1874 * otherwise end it.
1875 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001876 static void
1877set_terminal_mode(term_T *term, int normal_mode)
1878{
1879 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001880 if (!normal_mode)
1881 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001882 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001883 if (term->tl_buffer == curbuf)
1884 maketitle();
1885}
1886
1887/*
1888 * Called after the job if finished and Terminal mode is not active:
1889 * Move the vterm contents into the scrollback buffer and free the vterm.
1890 */
1891 static void
1892cleanup_vterm(term_T *term)
1893{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001894 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001895 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001896 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001898}
1899
1900/*
1901 * Switch from Terminal-Job mode to Terminal-Normal mode.
1902 * Suspends updating the terminal window.
1903 */
1904 static void
1905term_enter_normal_mode(void)
1906{
1907 term_T *term = curbuf->b_term;
1908
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001909 set_terminal_mode(term, TRUE);
1910
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001911 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001912 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001914 // Move the window cursor to the position of the cursor in the
1915 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001916 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1917 + term->tl_cursor_pos.row + 1;
1918 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001919 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1920 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001921
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001922 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001923 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1924}
1925
1926/*
1927 * Returns TRUE if the current window contains a terminal and we are in
1928 * Terminal-Normal mode.
1929 */
1930 int
1931term_in_normal_mode(void)
1932{
1933 term_T *term = curbuf->b_term;
1934
1935 return term != NULL && term->tl_normal_mode;
1936}
1937
1938/*
1939 * Switch from Terminal-Normal mode to Terminal-Job mode.
1940 * Restores updating the terminal window.
1941 */
1942 void
1943term_enter_job_mode()
1944{
1945 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001946
1947 set_terminal_mode(term, FALSE);
1948
1949 if (term->tl_channel_closed)
1950 cleanup_vterm(term);
1951 redraw_buf_and_status_later(curbuf, NOT_VALID);
1952}
1953
1954/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001955 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001956 * Note: while waiting a terminal may be closed and freed if the channel is
1957 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001958 */
1959 static int
1960term_vgetc()
1961{
1962 int c;
1963 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001964 int modify_other_keys =
1965 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001966
1967 State = TERMINAL;
1968 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001969#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001970 ctrl_break_was_pressed = FALSE;
1971#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001972 if (modify_other_keys)
1973 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001974 c = vgetc();
1975 got_int = FALSE;
1976 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001977 if (modify_other_keys)
1978 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001979 return c;
1980}
1981
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001982static int mouse_was_outside = FALSE;
1983
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001984/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001985 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001986 * Return FAIL when the key needs to be handled in Normal mode.
1987 * Return OK when the key was dropped or sent to the terminal.
1988 */
1989 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001990send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001991{
1992 char msg[KEY_BUF_LEN];
1993 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001994 int dragging_outside = FALSE;
1995
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001996 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001997 switch (c)
1998 {
1999 case NUL:
2000 case K_ZERO:
2001 if (typed)
2002 stuffcharReadbuff(c);
2003 return FAIL;
2004
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002005 case K_TABLINE:
2006 stuffcharReadbuff(c);
2007 return FAIL;
2008
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002009 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002010 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 return FAIL;
2012
2013 case K_LEFTDRAG:
2014 case K_MIDDLEDRAG:
2015 case K_RIGHTDRAG:
2016 case K_X1DRAG:
2017 case K_X2DRAG:
2018 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002019 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002020 case K_LEFTMOUSE:
2021 case K_LEFTMOUSE_NM:
2022 case K_LEFTRELEASE:
2023 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002024 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002025 case K_MIDDLEMOUSE:
2026 case K_MIDDLERELEASE:
2027 case K_RIGHTMOUSE:
2028 case K_RIGHTRELEASE:
2029 case K_X1MOUSE:
2030 case K_X1RELEASE:
2031 case K_X2MOUSE:
2032 case K_X2RELEASE:
2033
2034 case K_MOUSEUP:
2035 case K_MOUSEDOWN:
2036 case K_MOUSELEFT:
2037 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002038 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002039 int row = mouse_row;
2040 int col = mouse_col;
2041
2042#ifdef FEAT_PROP_POPUP
2043 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002044 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002045 row -= popup_top_extra(curwin);
2046 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002047 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002048#endif
2049 if (row < W_WINROW(curwin)
2050 || row >= (W_WINROW(curwin) + curwin->w_height)
2051 || col < curwin->w_wincol
2052 || col >= W_ENDCOL(curwin)
2053 || dragging_outside)
2054 {
2055 // click or scroll outside the current window or on status
2056 // line or vertical separator
2057 if (typed)
2058 {
2059 stuffcharReadbuff(c);
2060 mouse_was_outside = TRUE;
2061 }
2062 return FAIL;
2063 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002064 }
2065 }
2066 if (typed)
2067 mouse_was_outside = FALSE;
2068
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002069 // Convert the typed key to a sequence of bytes for the job.
2070 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002071 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002072 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002073 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2074 (char_u *)msg, (int)len, NULL);
2075
2076 return OK;
2077}
2078
2079 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002080position_cursor(win_T *wp, VTermPos *pos, int add_off UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002081{
2082 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2083 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002084#ifdef FEAT_PROP_POPUP
2085 if (add_off && popup_is_popup(curwin))
2086 {
2087 wp->w_wrow += popup_top_extra(curwin);
2088 wp->w_wcol += popup_left_extra(curwin);
2089 }
2090#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002091 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2092}
2093
2094/*
2095 * Handle CTRL-W "": send register contents to the job.
2096 */
2097 static void
2098term_paste_register(int prev_c UNUSED)
2099{
2100 int c;
2101 list_T *l;
2102 listitem_T *item;
2103 long reglen = 0;
2104 int type;
2105
2106#ifdef FEAT_CMDL_INFO
2107 if (add_to_showcmd(prev_c))
2108 if (add_to_showcmd('"'))
2109 out_flush();
2110#endif
2111 c = term_vgetc();
2112#ifdef FEAT_CMDL_INFO
2113 clear_showcmd();
2114#endif
2115 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002116 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002117 return;
2118
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002119 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002120 if (c == '=' && get_expr_register() != '=')
2121 return;
2122 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002123 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002124 return;
2125
2126 l = (list_T *)get_reg_contents(c, GREG_LIST);
2127 if (l != NULL)
2128 {
2129 type = get_reg_type(c, &reglen);
2130 for (item = l->lv_first; item != NULL; item = item->li_next)
2131 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002132 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002133#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002134 char_u *tmp = s;
2135
2136 if (!enc_utf8 && enc_codepage > 0)
2137 {
2138 WCHAR *ret = NULL;
2139 int length = 0;
2140
2141 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2142 (int)STRLEN(s), &ret, &length);
2143 if (ret != NULL)
2144 {
2145 WideCharToMultiByte_alloc(CP_UTF8, 0,
2146 ret, length, (char **)&s, &length, 0, 0);
2147 vim_free(ret);
2148 }
2149 }
2150#endif
2151 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2152 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002153#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002154 if (tmp != s)
2155 vim_free(s);
2156#endif
2157
2158 if (item->li_next != NULL || type == MLINE)
2159 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2160 (char_u *)"\r", 1, NULL);
2161 }
2162 list_free(l);
2163 }
2164}
2165
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002167 * Return TRUE when waiting for a character in the terminal, the cursor of the
2168 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002169 */
2170 int
2171terminal_is_active()
2172{
2173 return in_terminal_loop != NULL;
2174}
2175
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002176#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002177 cursorentry_T *
2178term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2179{
2180 term_T *term = in_terminal_loop;
2181 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002182 int id;
2183 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002184
2185 vim_memset(&entry, 0, sizeof(entry));
2186 entry.shape = entry.mshape =
2187 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2188 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2189 SHAPE_BLOCK;
2190 entry.percentage = 20;
2191 if (term->tl_cursor_blink)
2192 {
2193 entry.blinkwait = 700;
2194 entry.blinkon = 400;
2195 entry.blinkoff = 250;
2196 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002197
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002198 // The "Terminal" highlight group overrules the defaults.
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002199 id = syn_name2id((char_u *)"Terminal");
2200 if (id != 0)
2201 {
2202 syn_id2colors(id, &term_fg, &term_bg);
2203 *fg = term_bg;
2204 }
2205 else
2206 *fg = gui.back_pixel;
2207
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002208 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002209 {
2210 if (id != 0)
2211 *bg = term_fg;
2212 else
2213 *bg = gui.norm_pixel;
2214 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002215 else
2216 *bg = color_name2handle(term->tl_cursor_color);
2217 entry.name = "n";
2218 entry.used_for = SHAPE_CURSOR;
2219
2220 return &entry;
2221}
2222#endif
2223
Bram Moolenaard317b382018-02-08 22:33:31 +01002224 static void
2225may_output_cursor_props(void)
2226{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002227 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002228 || last_set_cursor_shape != desired_cursor_shape
2229 || last_set_cursor_blink != desired_cursor_blink)
2230 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002231 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002232 last_set_cursor_shape = desired_cursor_shape;
2233 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002234 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002235 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002236 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002237 ui_cursor_shape_forced(TRUE);
2238 else
2239 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2240 }
2241}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002242
Bram Moolenaard317b382018-02-08 22:33:31 +01002243/*
2244 * Set the cursor color and shape, if not last set to these.
2245 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002246 static void
2247may_set_cursor_props(term_T *term)
2248{
2249#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002250 // For the GUI the cursor properties are obtained with
2251 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002252 if (gui.in_use)
2253 return;
2254#endif
2255 if (in_terminal_loop == term)
2256 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002257 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002258 desired_cursor_shape = term->tl_cursor_shape;
2259 desired_cursor_blink = term->tl_cursor_blink;
2260 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002261 }
2262}
2263
Bram Moolenaard317b382018-02-08 22:33:31 +01002264/*
2265 * Reset the desired cursor properties and restore them when needed.
2266 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002267 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002268prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002269{
2270#ifdef FEAT_GUI
2271 if (gui.in_use)
2272 return;
2273#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002274 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002275 desired_cursor_shape = -1;
2276 desired_cursor_blink = -1;
2277 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002278}
2279
2280/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002281 * Returns TRUE if the current window contains a terminal and we are sending
2282 * keys to the job.
2283 * If "check_job_status" is TRUE update the job status.
2284 */
2285 static int
2286term_use_loop_check(int check_job_status)
2287{
2288 term_T *term = curbuf->b_term;
2289
2290 return term != NULL
2291 && !term->tl_normal_mode
2292 && term->tl_vterm != NULL
2293 && term_job_running_check(term, check_job_status);
2294}
2295
2296/*
2297 * Returns TRUE if the current window contains a terminal and we are sending
2298 * keys to the job.
2299 */
2300 int
2301term_use_loop(void)
2302{
2303 return term_use_loop_check(FALSE);
2304}
2305
2306/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002307 * Called when entering a window with the mouse. If this is a terminal window
2308 * we may want to change state.
2309 */
2310 void
2311term_win_entered()
2312{
2313 term_T *term = curbuf->b_term;
2314
2315 if (term != NULL)
2316 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002317 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002318 {
2319 reset_VIsual_and_resel();
2320 if (State & INSERT)
2321 stop_insert_mode = TRUE;
2322 }
2323 mouse_was_outside = FALSE;
2324 enter_mouse_col = mouse_col;
2325 enter_mouse_row = mouse_row;
2326 }
2327}
2328
2329/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002330 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2331 * Return the Ctrl-key value in that case.
2332 */
2333 static int
2334raw_c_to_ctrl(int c)
2335{
2336 if ((mod_mask & MOD_MASK_CTRL)
2337 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2338 return c & 0x1f;
2339 return c;
2340}
2341
2342/*
2343 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2344 * May set "mod_mask".
2345 */
2346 static int
2347ctrl_to_raw_c(int c)
2348{
2349 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2350 {
2351 mod_mask |= MOD_MASK_CTRL;
2352 return c + '@';
2353 }
2354 return c;
2355}
2356
2357/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358 * Wait for input and send it to the job.
2359 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2360 * when there is no more typahead.
2361 * Return when the start of a CTRL-W command is typed or anything else that
2362 * should be handled as a Normal mode command.
2363 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2364 * the terminal was closed.
2365 */
2366 int
2367terminal_loop(int blocking)
2368{
2369 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002370 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002371 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002372 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002373#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002374 int tty_fd = curbuf->b_term->tl_job->jv_channel
2375 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002376#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002377 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002378
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002379 // Remember the terminal we are sending keys to. However, the terminal
2380 // might be closed while waiting for a character, e.g. typing "exit" in a
2381 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2382 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002383 in_terminal_loop = curbuf->b_term;
2384
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002385 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002386 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002387 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002388 if (termwinkey == Ctrl_W)
2389 termwinkey = 0;
2390 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002391 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002392 may_set_cursor_props(curbuf->b_term);
2393
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002394 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002395 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002396#ifdef FEAT_GUI
2397 if (!curbuf->b_term->tl_system)
2398#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002399 // TODO: skip screen update when handling a sequence of keys.
2400 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002401 while (must_redraw != 0)
2402 if (update_screen(0) == FAIL)
2403 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002404 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002405 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002406 break;
2407
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002408 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002409 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002410
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002411 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002412 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002413 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002414 // Job finished while waiting for a character. Push back the
2415 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002416 if (raw_c != K_IGNORE)
2417 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002418 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002419 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002420 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002421 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002422 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002423
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002424#ifdef UNIX
2425 /*
2426 * The shell or another program may change the tty settings. Getting
2427 * them for every typed character is a bit of overhead, but it's needed
2428 * for the first character typed, e.g. when Vim starts in a shell.
2429 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002430 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002431 {
2432 ttyinfo_T info;
2433
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002434 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002435 if (get_tty_info(tty_fd, &info) == OK)
2436 term_backspace_char = info.backspace;
2437 }
2438#endif
2439
Bram Moolenaar4f974752019-02-17 17:44:42 +01002440#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002441 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2442 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002443 if (ctrl_break_was_pressed)
2444 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2445#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002446 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2447 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002448 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002449#ifdef FEAT_GUI
2450 && !curbuf->b_term->tl_system
2451#endif
2452 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002453 {
2454 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002455 int prev_raw_c = raw_c;
2456 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002457
2458#ifdef FEAT_CMDL_INFO
2459 if (add_to_showcmd(c))
2460 out_flush();
2461#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002462 raw_c = term_vgetc();
2463 c = raw_c_to_ctrl(raw_c);
2464
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002465#ifdef FEAT_CMDL_INFO
2466 clear_showcmd();
2467#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002468 if (!term_use_loop_check(TRUE)
2469 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002470 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002471 break;
2472
2473 if (prev_c == Ctrl_BSL)
2474 {
2475 if (c == Ctrl_N)
2476 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002477 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002478 term_enter_normal_mode();
2479 ret = FAIL;
2480 goto theend;
2481 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002482 // Send both keys to the terminal, first one here, second one
2483 // below.
2484 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2485 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002486 }
2487 else if (c == Ctrl_C)
2488 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002489 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002490 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2491 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002492 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002493 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002494 // "CTRL-W .": send CTRL-W to the job
2495 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002496 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002497 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002498 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002499 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002500 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002501 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002502 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 else if (c == 'N')
2504 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002505 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002506 term_enter_normal_mode();
2507 ret = FAIL;
2508 goto theend;
2509 }
2510 else if (c == '"')
2511 {
2512 term_paste_register(prev_c);
2513 continue;
2514 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002515 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002516 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002517 char_u buf[MB_MAXBYTES + 2];
2518
2519 // Put the command into the typeahead buffer, when using the
2520 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2521 buf[0] = Ctrl_W;
2522 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2523 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002524 ret = OK;
2525 goto theend;
2526 }
2527 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002528# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002529 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002530 {
2531 WCHAR wc;
2532 char_u mb[3];
2533
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002534 mb[0] = (unsigned)raw_c >> 8;
2535 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002536 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002537 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002538 }
2539# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002540 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002541 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002542 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002543 // We are sure to come back here, don't reset the cursor color
2544 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002545 restore_cursor = FALSE;
2546
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002547 ret = OK;
2548 goto theend;
2549 }
2550 }
2551 ret = FAIL;
2552
2553theend:
2554 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002555 if (restore_cursor)
2556 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002557
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002558 // Move a snapshot of the screen contents to the buffer, so that completion
2559 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002560 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2561 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002562
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002563 return ret;
2564}
2565
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002566 static void
2567may_toggle_cursor(term_T *term)
2568{
2569 if (in_terminal_loop == term)
2570 {
2571 if (term->tl_cursor_visible)
2572 cursor_on();
2573 else
2574 cursor_off();
2575 }
2576}
2577
2578/*
2579 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002580 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002581 */
2582 static int
2583color2index(VTermColor *color, int fg, int *boldp)
2584{
2585 int red = color->red;
2586 int blue = color->blue;
2587 int green = color->green;
2588
Bram Moolenaar46359e12017-11-29 22:33:38 +01002589 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002590 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002591 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002592 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002594 case 0: return 0;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002595 case 1: return lookup_color( 0, fg, boldp) + 1; // black
2596 case 2: return lookup_color( 4, fg, boldp) + 1; // dark red
2597 case 3: return lookup_color( 2, fg, boldp) + 1; // dark green
2598 case 4: return lookup_color( 6, fg, boldp) + 1; // brown
2599 case 5: return lookup_color( 1, fg, boldp) + 1; // dark blue
2600 case 6: return lookup_color( 5, fg, boldp) + 1; // dark magenta
2601 case 7: return lookup_color( 3, fg, boldp) + 1; // dark cyan
2602 case 8: return lookup_color( 8, fg, boldp) + 1; // light grey
2603 case 9: return lookup_color(12, fg, boldp) + 1; // dark grey
2604 case 10: return lookup_color(20, fg, boldp) + 1; // red
2605 case 11: return lookup_color(16, fg, boldp) + 1; // green
2606 case 12: return lookup_color(24, fg, boldp) + 1; // yellow
2607 case 13: return lookup_color(14, fg, boldp) + 1; // blue
2608 case 14: return lookup_color(22, fg, boldp) + 1; // magenta
2609 case 15: return lookup_color(18, fg, boldp) + 1; // cyan
2610 case 16: return lookup_color(26, fg, boldp) + 1; // white
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002611 }
2612 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002613
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002614 if (t_colors >= 256)
2615 {
2616 if (red == blue && red == green)
2617 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002618 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002619 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002620 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2621 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2622 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002623 int i;
2624
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002625 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002626 return 17; // 00/00/00
2627 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002628 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002629 for (i = 0; i < 23; ++i)
2630 if (red < cutoff[i])
2631 return i + 233;
2632 return 256;
2633 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002634 {
2635 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2636 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002637
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002638 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002639 for (ri = 0; ri < 5; ++ri)
2640 if (red < cutoff[ri])
2641 break;
2642 for (gi = 0; gi < 5; ++gi)
2643 if (green < cutoff[gi])
2644 break;
2645 for (bi = 0; bi < 5; ++bi)
2646 if (blue < cutoff[bi])
2647 break;
2648 return 17 + ri * 36 + gi * 6 + bi;
2649 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002650 }
2651 return 0;
2652}
2653
2654/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002655 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002656 */
2657 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002658vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002659{
2660 int attr = 0;
2661
2662 if (cellattrs.bold)
2663 attr |= HL_BOLD;
2664 if (cellattrs.underline)
2665 attr |= HL_UNDERLINE;
2666 if (cellattrs.italic)
2667 attr |= HL_ITALIC;
2668 if (cellattrs.strike)
2669 attr |= HL_STRIKETHROUGH;
2670 if (cellattrs.reverse)
2671 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002672 return attr;
2673}
2674
2675/*
2676 * Store Vterm attributes in "cell" from highlight flags.
2677 */
2678 static void
2679hl2vtermAttr(int attr, cellattr_T *cell)
2680{
2681 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2682 if (attr & HL_BOLD)
2683 cell->attrs.bold = 1;
2684 if (attr & HL_UNDERLINE)
2685 cell->attrs.underline = 1;
2686 if (attr & HL_ITALIC)
2687 cell->attrs.italic = 1;
2688 if (attr & HL_STRIKETHROUGH)
2689 cell->attrs.strike = 1;
2690 if (attr & HL_INVERSE)
2691 cell->attrs.reverse = 1;
2692}
2693
2694/*
2695 * Convert the attributes of a vterm cell into an attribute index.
2696 */
2697 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002698cell2attr(
2699 win_T *wp,
2700 VTermScreenCellAttrs cellattrs,
2701 VTermColor cellfg,
2702 VTermColor cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002703{
2704 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002705
2706#ifdef FEAT_GUI
2707 if (gui.in_use)
2708 {
2709 guicolor_T fg, bg;
2710
2711 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2712 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2713 return get_gui_attr_idx(attr, fg, bg);
2714 }
2715 else
2716#endif
2717#ifdef FEAT_TERMGUICOLORS
2718 if (p_tgc)
2719 {
2720 guicolor_T fg, bg;
2721
2722 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2723 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2724
2725 return get_tgc_attr_idx(attr, fg, bg);
2726 }
2727 else
2728#endif
2729 {
2730 int bold = MAYBE;
2731 int fg = color2index(&cellfg, TRUE, &bold);
2732 int bg = color2index(&cellbg, FALSE, &bold);
2733
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002734 // Use the 'wincolor' or "Terminal" highlighting for the default
2735 // colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002736 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002737 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002738 int wincolor_fg = -1;
2739 int wincolor_bg = -1;
2740
2741 if (wp != NULL && *wp->w_p_wcr != NUL)
2742 {
2743 int id = syn_name2id(curwin->w_p_wcr);
2744
2745 // Get the 'wincolor' group colors.
2746 if (id > 0)
2747 syn_id2cterm_bg(id, &wincolor_fg, &wincolor_bg);
2748 }
2749 if (fg == 0)
2750 {
2751 if (wincolor_fg >= 0)
2752 fg = wincolor_fg + 1;
2753 else if (term_default_cterm_fg >= 0)
2754 fg = term_default_cterm_fg + 1;
2755 }
2756 if (bg == 0)
2757 {
2758 if (wincolor_bg >= 0)
2759 bg = wincolor_bg + 1;
2760 else if (term_default_cterm_bg >= 0)
2761 bg = term_default_cterm_bg + 1;
2762 }
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002763 }
2764
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002765 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002766 if (bold == TRUE)
2767 attr |= HL_BOLD;
2768 return get_cterm_attr_idx(attr, fg, bg);
2769 }
2770 return 0;
2771}
2772
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002773 static void
2774set_dirty_snapshot(term_T *term)
2775{
2776 term->tl_dirty_snapshot = TRUE;
2777#ifdef FEAT_TIMERS
2778 if (!term->tl_normal_mode)
2779 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002780 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002781 profile_setlimit(100L, &term->tl_timer_due);
2782 term->tl_timer_set = TRUE;
2783 }
2784#endif
2785}
2786
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002787 static int
2788handle_damage(VTermRect rect, void *user)
2789{
2790 term_T *term = (term_T *)user;
2791
2792 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2793 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002794 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002795 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002796 return 1;
2797}
2798
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002799 static void
2800term_scroll_up(term_T *term, int start_row, int count)
2801{
2802 win_T *wp;
2803 VTermColor fg, bg;
2804 VTermScreenCellAttrs attr;
2805 int clear_attr;
2806
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002807 vim_memset(&attr, 0, sizeof(attr));
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002808
2809 FOR_ALL_WINDOWS(wp)
2810 {
2811 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002812 {
2813 // Set the color to clear lines with.
2814 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2815 &fg, &bg);
2816 clear_attr = cell2attr(wp, attr, fg, bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002817 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002818 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002819 }
2820}
2821
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002822 static int
2823handle_moverect(VTermRect dest, VTermRect src, void *user)
2824{
2825 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002826 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002827
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002828 // Scrolling up is done much more efficiently by deleting lines instead of
2829 // redrawing the text. But avoid doing this multiple times, postpone until
2830 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002831 if (dest.start_col == src.start_col
2832 && dest.end_col == src.end_col
2833 && dest.start_row < src.start_row)
2834 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002835 if (dest.start_row == 0)
2836 term->tl_postponed_scroll += count;
2837 else
2838 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002839 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002840
2841 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2842 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002843 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002844
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002845 // Note sure if the scrolling will work correctly, let's do a complete
2846 // redraw later.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002847 redraw_buf_later(term->tl_buffer, NOT_VALID);
2848 return 1;
2849}
2850
2851 static int
2852handle_movecursor(
2853 VTermPos pos,
2854 VTermPos oldpos UNUSED,
2855 int visible,
2856 void *user)
2857{
2858 term_T *term = (term_T *)user;
2859 win_T *wp;
2860
2861 term->tl_cursor_pos = pos;
2862 term->tl_cursor_visible = visible;
2863
2864 FOR_ALL_WINDOWS(wp)
2865 {
2866 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002867 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002868 }
2869 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2870 {
2871 may_toggle_cursor(term);
2872 update_cursor(term, term->tl_cursor_visible);
2873 }
2874
2875 return 1;
2876}
2877
2878 static int
2879handle_settermprop(
2880 VTermProp prop,
2881 VTermValue *value,
2882 void *user)
2883{
2884 term_T *term = (term_T *)user;
2885
2886 switch (prop)
2887 {
2888 case VTERM_PROP_TITLE:
2889 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002890 // a blank title isn't useful, make it empty, so that "running" is
2891 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002892 if (*skipwhite((char_u *)value->string) == NUL)
2893 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002894 // Same as blank
2895 else if (term->tl_arg0_cmd != NULL
2896 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2897 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2898 term->tl_title = NULL;
2899 // Empty corrupted data of winpty
2900 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2901 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002902#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002903 else if (!enc_utf8 && enc_codepage > 0)
2904 {
2905 WCHAR *ret = NULL;
2906 int length = 0;
2907
2908 MultiByteToWideChar_alloc(CP_UTF8, 0,
2909 (char*)value->string, (int)STRLEN(value->string),
2910 &ret, &length);
2911 if (ret != NULL)
2912 {
2913 WideCharToMultiByte_alloc(enc_codepage, 0,
2914 ret, length, (char**)&term->tl_title,
2915 &length, 0, 0);
2916 vim_free(ret);
2917 }
2918 }
2919#endif
2920 else
2921 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002922 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002923 if (term == curbuf->b_term)
2924 maketitle();
2925 break;
2926
2927 case VTERM_PROP_CURSORVISIBLE:
2928 term->tl_cursor_visible = value->boolean;
2929 may_toggle_cursor(term);
2930 out_flush();
2931 break;
2932
2933 case VTERM_PROP_CURSORBLINK:
2934 term->tl_cursor_blink = value->boolean;
2935 may_set_cursor_props(term);
2936 break;
2937
2938 case VTERM_PROP_CURSORSHAPE:
2939 term->tl_cursor_shape = value->number;
2940 may_set_cursor_props(term);
2941 break;
2942
2943 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002944 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002945 may_set_cursor_props(term);
2946 break;
2947
2948 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002949 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002950 term->tl_using_altscreen = value->boolean;
2951 break;
2952
2953 default:
2954 break;
2955 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002956 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002957 return 1;
2958}
2959
2960/*
2961 * The job running in the terminal resized the terminal.
2962 */
2963 static int
2964handle_resize(int rows, int cols, void *user)
2965{
2966 term_T *term = (term_T *)user;
2967 win_T *wp;
2968
2969 term->tl_rows = rows;
2970 term->tl_cols = cols;
2971 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002972 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002973 term->tl_vterm_size_changed = FALSE;
2974 else
2975 {
2976 FOR_ALL_WINDOWS(wp)
2977 {
2978 if (wp->w_buffer == term->tl_buffer)
2979 {
2980 win_setheight_win(rows, wp);
2981 win_setwidth_win(cols, wp);
2982 }
2983 }
2984 redraw_buf_later(term->tl_buffer, NOT_VALID);
2985 }
2986 return 1;
2987}
2988
2989/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002990 * If the number of lines that are stored goes over 'termscrollback' then
2991 * delete the first 10%.
2992 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2993 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002994 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002995 static void
2996limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002997{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002998 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002999 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003000 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003001 int i;
3002
3003 curbuf = term->tl_buffer;
3004 for (i = 0; i < todo; ++i)
3005 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003006 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3007 if (update_buffer)
3008 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003009 }
3010 curbuf = curwin->w_buffer;
3011
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003012 gap->ga_len -= todo;
3013 mch_memmove(gap->ga_data,
3014 (sb_line_T *)gap->ga_data + todo,
3015 sizeof(sb_line_T) * gap->ga_len);
3016 if (update_buffer)
3017 term->tl_scrollback_scrolled -= todo;
3018 }
3019}
3020
3021/*
3022 * Handle a line that is pushed off the top of the screen.
3023 */
3024 static int
3025handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3026{
3027 term_T *term = (term_T *)user;
3028 garray_T *gap;
3029 int update_buffer;
3030
3031 if (term->tl_normal_mode)
3032 {
3033 // In Terminal-Normal mode the user interacts with the buffer, thus we
3034 // must not change it. Postpone adding the scrollback lines.
3035 gap = &term->tl_scrollback_postponed;
3036 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003037 }
3038 else
3039 {
3040 // First remove the lines that were appended before, the pushed line
3041 // goes above it.
3042 cleanup_scrollback(term);
3043 gap = &term->tl_scrollback;
3044 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003045 }
3046
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003047 limit_scrollback(term, gap, update_buffer);
3048
3049 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003050 {
3051 cellattr_T *p = NULL;
3052 int len = 0;
3053 int i;
3054 int c;
3055 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003056 int text_len;
3057 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003058 sb_line_T *line;
3059 garray_T ga;
3060 cellattr_T fill_attr = term->tl_default_color;
3061
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003062 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003063 for (i = 0; i < cols; ++i)
3064 if (cells[i].chars[0] != 0)
3065 len = i + 1;
3066 else
3067 cell2cellattr(&cells[i], &fill_attr);
3068
3069 ga_init2(&ga, 1, 100);
3070 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003071 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003072 if (p != NULL)
3073 {
3074 for (col = 0; col < len; col += cells[col].width)
3075 {
3076 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3077 {
3078 ga.ga_len = 0;
3079 break;
3080 }
3081 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3082 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3083 (char_u *)ga.ga_data + ga.ga_len);
3084 cell2cellattr(&cells[col], &p[col]);
3085 }
3086 }
3087 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003088 {
3089 if (update_buffer)
3090 text = (char_u *)"";
3091 else
3092 text = vim_strsave((char_u *)"");
3093 text_len = 0;
3094 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 else
3096 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003097 text = ga.ga_data;
3098 text_len = ga.ga_len;
3099 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003100 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003101 if (update_buffer)
3102 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003103
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003104 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003105 line->sb_cols = len;
3106 line->sb_cells = p;
3107 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003108 if (update_buffer)
3109 {
3110 line->sb_text = NULL;
3111 ++term->tl_scrollback_scrolled;
3112 ga_clear(&ga); // free the text
3113 }
3114 else
3115 {
3116 line->sb_text = text;
3117 ga_init(&ga); // text is kept in tl_scrollback_postponed
3118 }
3119 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003120 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003121 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003122}
3123
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003124/*
3125 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3126 * received and stored in tl_scrollback_postponed.
3127 */
3128 static void
3129handle_postponed_scrollback(term_T *term)
3130{
3131 int i;
3132
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003133 if (term->tl_scrollback_postponed.ga_len == 0)
3134 return;
3135 ch_log(NULL, "Moving postponed scrollback to scrollback");
3136
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003137 // First remove the lines that were appended before, the pushed lines go
3138 // above it.
3139 cleanup_scrollback(term);
3140
3141 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3142 {
3143 char_u *text;
3144 sb_line_T *pp_line;
3145 sb_line_T *line;
3146
3147 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3148 break;
3149 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3150
3151 text = pp_line->sb_text;
3152 if (text == NULL)
3153 text = (char_u *)"";
3154 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3155 vim_free(pp_line->sb_text);
3156
3157 line = (sb_line_T *)term->tl_scrollback.ga_data
3158 + term->tl_scrollback.ga_len;
3159 line->sb_cols = pp_line->sb_cols;
3160 line->sb_cells = pp_line->sb_cells;
3161 line->sb_fill_attr = pp_line->sb_fill_attr;
3162 line->sb_text = NULL;
3163 ++term->tl_scrollback_scrolled;
3164 ++term->tl_scrollback.ga_len;
3165 }
3166
3167 ga_clear(&term->tl_scrollback_postponed);
3168 limit_scrollback(term, &term->tl_scrollback, TRUE);
3169}
3170
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003171static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003172 handle_damage, // damage
3173 handle_moverect, // moverect
3174 handle_movecursor, // movecursor
3175 handle_settermprop, // settermprop
3176 NULL, // bell
3177 handle_resize, // resize
3178 handle_pushline, // sb_pushline
3179 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003180};
3181
3182/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003183 * Do the work after the channel of a terminal was closed.
3184 * Must be called only when updating_screen is FALSE.
3185 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3186 */
3187 static int
3188term_after_channel_closed(term_T *term)
3189{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003190 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003191 if (!term->tl_normal_mode)
3192 {
3193 int fnum = term->tl_buffer->b_fnum;
3194
3195 cleanup_vterm(term);
3196
3197 if (term->tl_finish == TL_FINISH_CLOSE)
3198 {
3199 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003200 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003201#ifdef FEAT_PROP_POPUP
3202 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003203
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003204 // If this was a terminal in a popup window, go back to the
3205 // previous window.
3206 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3207 {
3208 pwin = curwin;
3209 if (win_valid(prevwin))
3210 win_enter(prevwin, FALSE);
3211 }
3212 else
3213#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003214 // If this is the last normal window: exit Vim.
3215 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3216 {
3217 exarg_T ea;
3218
3219 vim_memset(&ea, 0, sizeof(ea));
3220 ex_quit(&ea);
3221 return TRUE;
3222 }
3223
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003224 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003225 ch_log(NULL, "terminal job finished, closing window");
3226 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003227 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003228 if (curwin == aucmd_win)
3229 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003230 if (do_set_w_closing)
3231 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003232 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003233 if (do_set_w_closing)
3234 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003235 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003236#ifdef FEAT_PROP_POPUP
3237 if (pwin != NULL)
3238 popup_close_with_retval(pwin, 0);
3239#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003240 return TRUE;
3241 }
3242 if (term->tl_finish == TL_FINISH_OPEN
3243 && term->tl_buffer->b_nwindows == 0)
3244 {
3245 char buf[50];
3246
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003247 // TODO: use term_opencmd
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003248 ch_log(NULL, "terminal job finished, opening window");
3249 vim_snprintf(buf, sizeof(buf),
3250 term->tl_opencmd == NULL
3251 ? "botright sbuf %d"
3252 : (char *)term->tl_opencmd, fnum);
3253 do_cmdline_cmd((char_u *)buf);
3254 }
3255 else
3256 ch_log(NULL, "terminal job finished");
3257 }
3258
3259 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3260 return FALSE;
3261}
3262
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003263#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3264/*
3265 * If the current window is a terminal in a popup window and the job has
3266 * finished, close the popup window and to back to the previous window.
3267 * Otherwise return FAIL.
3268 */
3269 int
3270may_close_term_popup(void)
3271{
3272 if (popup_is_popup(curwin) && curbuf->b_term != NULL
3273 && !term_job_running(curbuf->b_term))
3274 {
3275 win_T *pwin = curwin;
3276
3277 if (win_valid(prevwin))
3278 win_enter(prevwin, FALSE);
3279 popup_close_with_retval(pwin, 0);
3280 return OK;
3281 }
3282 return FAIL;
3283}
3284#endif
3285
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003286/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003287 * Called when a channel has been closed.
3288 * If this was a channel for a terminal window then finish it up.
3289 */
3290 void
3291term_channel_closed(channel_T *ch)
3292{
3293 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003294 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003295 int did_one = FALSE;
3296
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003297 for (term = first_term; term != NULL; term = next_term)
3298 {
3299 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003300 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003301 {
3302 term->tl_channel_closed = TRUE;
3303 did_one = TRUE;
3304
Bram Moolenaard23a8232018-02-10 18:45:26 +01003305 VIM_CLEAR(term->tl_title);
3306 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003307#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003308 if (term->tl_out_fd != NULL)
3309 {
3310 fclose(term->tl_out_fd);
3311 term->tl_out_fd = NULL;
3312 }
3313#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003314
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003315 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003316 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003317 // Cannot open or close windows now. Can happen when
3318 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003319 term->tl_channel_recently_closed = TRUE;
3320 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003321 }
3322
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003323 if (term_after_channel_closed(term))
3324 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003325 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003326 }
3327
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003328 if (did_one)
3329 {
3330 redraw_statuslines();
3331
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003332 // Need to break out of vgetc().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003333 ins_char_typebuf(K_IGNORE);
3334 typebuf_was_filled = TRUE;
3335
3336 term = curbuf->b_term;
3337 if (term != NULL)
3338 {
3339 if (term->tl_job == ch->ch_job)
3340 maketitle();
3341 update_cursor(term, term->tl_cursor_visible);
3342 }
3343 }
3344}
3345
3346/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003347 * To be called after resetting updating_screen: handle any terminal where the
3348 * channel was closed.
3349 */
3350 void
3351term_check_channel_closed_recently()
3352{
3353 term_T *term;
3354 term_T *next_term;
3355
3356 for (term = first_term; term != NULL; term = next_term)
3357 {
3358 next_term = term->tl_next;
3359 if (term->tl_channel_recently_closed)
3360 {
3361 term->tl_channel_recently_closed = FALSE;
3362 if (term_after_channel_closed(term))
3363 // start over, the list may have changed
3364 next_term = first_term;
3365 }
3366 }
3367}
3368
3369/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003370 * Fill one screen line from a line of the terminal.
3371 * Advances "pos" to past the last column.
3372 */
3373 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003374term_line2screenline(
3375 win_T *wp,
3376 VTermScreen *screen,
3377 VTermPos *pos,
3378 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003379{
3380 int off = screen_get_current_line_off();
3381
3382 for (pos->col = 0; pos->col < max_col; )
3383 {
3384 VTermScreenCell cell;
3385 int c;
3386
3387 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3388 vim_memset(&cell, 0, sizeof(cell));
3389
3390 c = cell.chars[0];
3391 if (c == NUL)
3392 {
3393 ScreenLines[off] = ' ';
3394 if (enc_utf8)
3395 ScreenLinesUC[off] = NUL;
3396 }
3397 else
3398 {
3399 if (enc_utf8)
3400 {
3401 int i;
3402
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003403 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003404 for (i = 0; i < Screen_mco
3405 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3406 {
3407 ScreenLinesC[i][off] = cell.chars[i + 1];
3408 if (cell.chars[i + 1] == 0)
3409 break;
3410 }
3411 if (c >= 0x80 || (Screen_mco > 0
3412 && ScreenLinesC[0][off] != 0))
3413 {
3414 ScreenLines[off] = ' ';
3415 ScreenLinesUC[off] = c;
3416 }
3417 else
3418 {
3419 ScreenLines[off] = c;
3420 ScreenLinesUC[off] = NUL;
3421 }
3422 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003423#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003424 else if (has_mbyte && c >= 0x80)
3425 {
3426 char_u mb[MB_MAXBYTES+1];
3427 WCHAR wc = c;
3428
3429 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3430 (char*)mb, 2, 0, 0) > 1)
3431 {
3432 ScreenLines[off] = mb[0];
3433 ScreenLines[off + 1] = mb[1];
3434 cell.width = mb_ptr2cells(mb);
3435 }
3436 else
3437 ScreenLines[off] = c;
3438 }
3439#endif
3440 else
3441 ScreenLines[off] = c;
3442 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003443 ScreenAttrs[off] = cell2attr(wp, cell.attrs, cell.fg, cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003444
3445 ++pos->col;
3446 ++off;
3447 if (cell.width == 2)
3448 {
3449 if (enc_utf8)
3450 ScreenLinesUC[off] = NUL;
3451
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003452 // don't set the second byte to NUL for a DBCS encoding, it
3453 // has been set above
Bram Moolenaar13568252018-03-16 20:46:58 +01003454 if (enc_utf8 || !has_mbyte)
3455 ScreenLines[off] = NUL;
3456
3457 ++pos->col;
3458 ++off;
3459 }
3460 }
3461}
3462
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003463#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003464 static void
3465update_system_term(term_T *term)
3466{
3467 VTermPos pos;
3468 VTermScreen *screen;
3469
3470 if (term->tl_vterm == NULL)
3471 return;
3472 screen = vterm_obtain_screen(term->tl_vterm);
3473
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003474 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003475 while (term->tl_toprow > 0
3476 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3477 {
3478 int save_p_more = p_more;
3479
3480 p_more = FALSE;
3481 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003482 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003483 p_more = save_p_more;
3484 --term->tl_toprow;
3485 }
3486
3487 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3488 && pos.row < Rows; ++pos.row)
3489 {
3490 if (pos.row < term->tl_rows)
3491 {
3492 int max_col = MIN(Columns, term->tl_cols);
3493
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003494 term_line2screenline(NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003495 }
3496 else
3497 pos.col = 0;
3498
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003499 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003500 }
3501
3502 term->tl_dirty_row_start = MAX_ROW;
3503 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003504}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003505#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003506
3507/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003508 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3509 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003510 * Terminal-Normal mode.
3511 */
3512 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003513term_do_update_window(win_T *wp)
3514{
3515 term_T *term = wp->w_buffer->b_term;
3516
3517 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3518}
3519
3520/*
3521 * Called to update a window that contains an active terminal.
3522 */
3523 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003524term_update_window(win_T *wp)
3525{
3526 term_T *term = wp->w_buffer->b_term;
3527 VTerm *vterm;
3528 VTermScreen *screen;
3529 VTermState *state;
3530 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003531 int rows, cols;
3532 int newrows, newcols;
3533 int minsize;
3534 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003535
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003536 vterm = term->tl_vterm;
3537 screen = vterm_obtain_screen(vterm);
3538 state = vterm_obtain_state(vterm);
3539
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003540 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3541 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003542 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003543 {
3544 term->tl_dirty_row_start = 0;
3545 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003546
3547 if (term->tl_postponed_scroll > 0
3548 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003549 // Scrolling is usually faster than redrawing, when there are only
3550 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003551 term_scroll_up(term, 0, term->tl_postponed_scroll);
3552 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003553 }
3554
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003555 /*
3556 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003557 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003558 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003559 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003560
Bram Moolenaar498c2562018-04-15 23:45:15 +02003561 newrows = 99999;
3562 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003563 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003564 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003565 // Always use curwin, it may be a popup window.
3566 win_T *wwp = twp == NULL ? curwin : twp;
3567
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003568 // When more than one window shows the same terminal, use the
3569 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003570 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003571 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003572 newrows = MIN(newrows, wwp->w_height);
3573 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003574 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003575 if (twp == NULL)
3576 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003577 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003578 if (newrows == 99999 || newcols == 99999)
3579 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003580 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3581 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3582
3583 if (term->tl_rows != newrows || term->tl_cols != newcols)
3584 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003585 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003586 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003587 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003588 newrows);
3589 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003590
3591 // Updating the terminal size will cause the snapshot to be cleared.
3592 // When not in terminal_loop() we need to restore it.
3593 if (term != in_terminal_loop)
3594 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003595 }
3596
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003597 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003598 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003599 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003600
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003601 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3602 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003603 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003604 if (pos.row < term->tl_rows)
3605 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003606 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003607
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003608 term_line2screenline(wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003609 }
3610 else
3611 pos.col = 0;
3612
Bram Moolenaarf118d482018-03-13 13:14:00 +01003613 screen_line(wp->w_winrow + pos.row
3614#ifdef FEAT_MENU
3615 + winbar_height(wp)
3616#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003617 , wp->w_wincol, pos.col, wp->w_width,
3618#ifdef FEAT_PROP_POPUP
3619 popup_is_popup(wp) ? SLF_POPUP :
3620#endif
3621 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003622 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003623 term->tl_dirty_row_start = MAX_ROW;
3624 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003625}
3626
3627/*
3628 * Return TRUE if "wp" is a terminal window where the job has finished.
3629 */
3630 int
3631term_is_finished(buf_T *buf)
3632{
3633 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3634}
3635
3636/*
3637 * Return TRUE if "wp" is a terminal window where the job has finished or we
3638 * are in Terminal-Normal mode, thus we show the buffer contents.
3639 */
3640 int
3641term_show_buffer(buf_T *buf)
3642{
3643 term_T *term = buf->b_term;
3644
3645 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3646}
3647
3648/*
3649 * The current buffer is going to be changed. If there is terminal
3650 * highlighting remove it now.
3651 */
3652 void
3653term_change_in_curbuf(void)
3654{
3655 term_T *term = curbuf->b_term;
3656
3657 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3658 {
3659 free_scrollback(term);
3660 redraw_buf_later(term->tl_buffer, NOT_VALID);
3661
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003662 // The buffer is now like a normal buffer, it cannot be easily
3663 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003664 set_string_option_direct((char_u *)"buftype", -1,
3665 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3666 }
3667}
3668
3669/*
3670 * Get the screen attribute for a position in the buffer.
3671 * Use a negative "col" to get the filler background color.
3672 */
3673 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003674term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003675{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003676 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003677 term_T *term = buf->b_term;
3678 sb_line_T *line;
3679 cellattr_T *cellattr;
3680
3681 if (lnum > term->tl_scrollback.ga_len)
3682 cellattr = &term->tl_default_color;
3683 else
3684 {
3685 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3686 if (col < 0 || col >= line->sb_cols)
3687 cellattr = &line->sb_fill_attr;
3688 else
3689 cellattr = line->sb_cells + col;
3690 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003691 return cell2attr(wp, cellattr->attrs, cellattr->fg, cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003692}
3693
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003694/*
3695 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003696 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003697 */
3698 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003699cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003700{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003701 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003702}
3703
3704/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003705 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003706 */
3707 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003708init_default_colors(term_T *term, win_T *wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003709{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003710 VTermColor *fg, *bg;
3711 int fgval, bgval;
3712 int id;
3713
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003714 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3715 term->tl_default_color.width = 1;
3716 fg = &term->tl_default_color.fg;
3717 bg = &term->tl_default_color.bg;
3718
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003719 // Vterm uses a default black background. Set it to white when
3720 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003721 if (*p_bg == 'l')
3722 {
3723 fgval = 0;
3724 bgval = 255;
3725 }
3726 else
3727 {
3728 fgval = 255;
3729 bgval = 0;
3730 }
3731 fg->red = fg->green = fg->blue = fgval;
3732 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003733 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003734
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003735 // The 'wincolor' or "Terminal" highlight group overrules the defaults.
3736 if (wp != NULL && *wp->w_p_wcr != NUL)
3737 id = syn_name2id(wp->w_p_wcr);
3738 else
3739 id = syn_name2id((char_u *)"Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003740
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003741 // Use the actual color for the GUI and when 'termguicolors' is set.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003742#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3743 if (0
3744# ifdef FEAT_GUI
3745 || gui.in_use
3746# endif
3747# ifdef FEAT_TERMGUICOLORS
3748 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003749# ifdef FEAT_VTP
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003750 // Finally get INVALCOLOR on this execution path
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003751 || (!p_tgc && t_colors >= 256)
3752# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003753# endif
3754 )
3755 {
3756 guicolor_T fg_rgb = INVALCOLOR;
3757 guicolor_T bg_rgb = INVALCOLOR;
3758
3759 if (id != 0)
3760 syn_id2colors(id, &fg_rgb, &bg_rgb);
3761
3762# ifdef FEAT_GUI
3763 if (gui.in_use)
3764 {
3765 if (fg_rgb == INVALCOLOR)
3766 fg_rgb = gui.norm_pixel;
3767 if (bg_rgb == INVALCOLOR)
3768 bg_rgb = gui.back_pixel;
3769 }
3770# ifdef FEAT_TERMGUICOLORS
3771 else
3772# endif
3773# endif
3774# ifdef FEAT_TERMGUICOLORS
3775 {
3776 if (fg_rgb == INVALCOLOR)
3777 fg_rgb = cterm_normal_fg_gui_color;
3778 if (bg_rgb == INVALCOLOR)
3779 bg_rgb = cterm_normal_bg_gui_color;
3780 }
3781# endif
3782 if (fg_rgb != INVALCOLOR)
3783 {
3784 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3785
3786 fg->red = (unsigned)(rgb >> 16);
3787 fg->green = (unsigned)(rgb >> 8) & 255;
3788 fg->blue = (unsigned)rgb & 255;
3789 }
3790 if (bg_rgb != INVALCOLOR)
3791 {
3792 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3793
3794 bg->red = (unsigned)(rgb >> 16);
3795 bg->green = (unsigned)(rgb >> 8) & 255;
3796 bg->blue = (unsigned)rgb & 255;
3797 }
3798 }
3799 else
3800#endif
3801 if (id != 0 && t_colors >= 16)
3802 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003803 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003804 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003805 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003806 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003807 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003808 else
3809 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003810#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003811 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003812#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003813
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003814 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003815 if (cterm_normal_fg_color > 0)
3816 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003817 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003818# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3819# ifdef VIMDLL
3820 if (!gui.in_use)
3821# endif
3822 {
3823 tmp = fg->red;
3824 fg->red = fg->blue;
3825 fg->blue = tmp;
3826 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003827# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003828 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003829# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003830 else
3831 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003832# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003833
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003834 if (cterm_normal_bg_color > 0)
3835 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003836 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003837# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3838# ifdef VIMDLL
3839 if (!gui.in_use)
3840# endif
3841 {
3842 tmp = fg->red;
3843 fg->red = fg->blue;
3844 fg->blue = tmp;
3845 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003846# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003847 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003848# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003849 else
3850 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003851# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003852 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003853}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003854
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003855#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3856/*
3857 * Set the 16 ANSI colors from array of RGB values
3858 */
3859 static void
3860set_vterm_palette(VTerm *vterm, long_u *rgb)
3861{
3862 int index = 0;
3863 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003864
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003865 for (; index < 16; index++)
3866 {
3867 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003868
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003869 color.red = (unsigned)(rgb[index] >> 16);
3870 color.green = (unsigned)(rgb[index] >> 8) & 255;
3871 color.blue = (unsigned)rgb[index] & 255;
3872 vterm_state_set_palette_color(state, index, &color);
3873 }
3874}
3875
3876/*
3877 * Set the ANSI color palette from a list of colors
3878 */
3879 static int
3880set_ansi_colors_list(VTerm *vterm, list_T *list)
3881{
3882 int n = 0;
3883 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01003884 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003885
Bram Moolenaarb0992022020-01-30 14:55:42 +01003886 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003887 {
3888 char_u *color_name;
3889 guicolor_T guicolor;
3890
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003891 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003892 if (color_name == NULL)
3893 return FAIL;
3894
3895 guicolor = GUI_GET_COLOR(color_name);
3896 if (guicolor == INVALCOLOR)
3897 return FAIL;
3898
3899 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3900 }
3901
3902 if (n != 16 || li != NULL)
3903 return FAIL;
3904
3905 set_vterm_palette(vterm, rgb);
3906
3907 return OK;
3908}
3909
3910/*
3911 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3912 */
3913 static void
3914init_vterm_ansi_colors(VTerm *vterm)
3915{
3916 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3917
3918 if (var != NULL
3919 && (var->di_tv.v_type != VAR_LIST
3920 || var->di_tv.vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +01003921 || var->di_tv.vval.v_list->lv_first == &range_list_item
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003922 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003923 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003924}
3925#endif
3926
Bram Moolenaar52acb112018-03-18 19:20:22 +01003927/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003928 * Handles a "drop" command from the job in the terminal.
3929 * "item" is the file name, "item->li_next" may have options.
3930 */
3931 static void
3932handle_drop_command(listitem_T *item)
3933{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003934 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003935 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003936 int bufnr;
3937 win_T *wp;
3938 tabpage_T *tp;
3939 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003940 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003941
3942 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3943 FOR_ALL_TAB_WINDOWS(tp, wp)
3944 {
3945 if (wp->w_buffer->b_fnum == bufnr)
3946 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003947 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003948 goto_tabpage_win(tp, wp);
3949 return;
3950 }
3951 }
3952
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003953 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003954
3955 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3956 && opt_item->li_tv.vval.v_dict != NULL)
3957 {
3958 dict_T *dict = opt_item->li_tv.vval.v_dict;
3959 char_u *p;
3960
Bram Moolenaar8f667172018-12-14 15:38:31 +01003961 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003962 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003963 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003964 if (p != NULL)
3965 {
3966 if (check_ff_value(p) == FAIL)
3967 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3968 else
3969 ea.force_ff = *p;
3970 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003971 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003972 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003973 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003974 if (p != NULL)
3975 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003976 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003977 if (ea.cmd != NULL)
3978 {
3979 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3980 ea.force_enc = 11;
3981 tofree = ea.cmd;
3982 }
3983 }
3984
Bram Moolenaar8f667172018-12-14 15:38:31 +01003985 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003986 if (p != NULL)
3987 get_bad_opt(p, &ea);
3988
3989 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3990 ea.force_bin = FORCE_BIN;
3991 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3992 ea.force_bin = FORCE_BIN;
3993 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3994 ea.force_bin = FORCE_NOBIN;
3995 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3996 ea.force_bin = FORCE_NOBIN;
3997 }
3998
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003999 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004000 if (ea.cmd == NULL)
4001 ea.cmd = (char_u *)"split";
4002 ea.arg = fname;
4003 ea.cmdidx = CMD_split;
4004 ex_splitview(&ea);
4005
4006 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004007}
4008
4009/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004010 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4011 */
4012 static int
4013is_permitted_term_api(char_u *func, char_u *pat)
4014{
4015 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4016}
4017
4018/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004019 * Handles a function call from the job running in a terminal.
4020 * "item" is the function name, "item->li_next" has the arguments.
4021 */
4022 static void
4023handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4024{
4025 char_u *func;
4026 typval_T argvars[2];
4027 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004028 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004029
4030 if (item->li_next == NULL)
4031 {
4032 ch_log(channel, "Missing function arguments for call");
4033 return;
4034 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004035 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004036
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004037 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004038 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004039 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004040 return;
4041 }
4042
4043 argvars[0].v_type = VAR_NUMBER;
4044 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4045 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004046 vim_memset(&funcexe, 0, sizeof(funcexe));
4047 funcexe.firstline = 1L;
4048 funcexe.lastline = 1L;
4049 funcexe.evaluate = TRUE;
4050 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004051 {
4052 clear_tv(&rettv);
4053 ch_log(channel, "Function %s called", func);
4054 }
4055 else
4056 ch_log(channel, "Calling function %s failed", func);
4057}
4058
4059/*
4060 * Called by libvterm when it cannot recognize an OSC sequence.
4061 * We recognize a terminal API command.
4062 */
4063 static int
4064parse_osc(const char *command, size_t cmdlen, void *user)
4065{
4066 term_T *term = (term_T *)user;
4067 js_read_T reader;
4068 typval_T tv;
4069 channel_T *channel = term->tl_job == NULL ? NULL
4070 : term->tl_job->jv_channel;
4071
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004072 // We recognize only OSC 5 1 ; {command}
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004073 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004074 return 0; // not handled
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004075
Bram Moolenaar878c96d2018-04-04 23:00:06 +02004076 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004077 if (reader.js_buf == NULL)
4078 return 1;
4079 reader.js_fill = NULL;
4080 reader.js_used = 0;
4081 if (json_decode(&reader, &tv, 0) == OK
4082 && tv.v_type == VAR_LIST
4083 && tv.vval.v_list != NULL)
4084 {
4085 listitem_T *item = tv.vval.v_list->lv_first;
4086
4087 if (item == NULL)
4088 ch_log(channel, "Missing command");
4089 else
4090 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004091 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004092
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004093 // Make sure an invoked command doesn't delete the buffer (and the
4094 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004095 ++term->tl_buffer->b_locked;
4096
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004097 item = item->li_next;
4098 if (item == NULL)
4099 ch_log(channel, "Missing argument for %s", cmd);
4100 else if (STRCMP(cmd, "drop") == 0)
4101 handle_drop_command(item);
4102 else if (STRCMP(cmd, "call") == 0)
4103 handle_call_command(term, channel, item);
4104 else
4105 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004106 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004107 }
4108 }
4109 else
4110 ch_log(channel, "Invalid JSON received");
4111
4112 vim_free(reader.js_buf);
4113 clear_tv(&tv);
4114 return 1;
4115}
4116
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004117/*
4118 * Called by libvterm when it cannot recognize a CSI sequence.
4119 * We recognize the window position report.
4120 */
4121 static int
4122parse_csi(
4123 const char *leader UNUSED,
4124 const long args[],
4125 int argcount,
4126 const char *intermed UNUSED,
4127 char command,
4128 void *user)
4129{
4130 term_T *term = (term_T *)user;
4131 char buf[100];
4132 int len;
4133 int x = 0;
4134 int y = 0;
4135 win_T *wp;
4136
4137 // We recognize only CSI 13 t
4138 if (command != 't' || argcount != 1 || args[0] != 13)
4139 return 0; // not handled
4140
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004141 // When getting the window position is not possible or it fails it results
4142 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004143#if defined(FEAT_GUI) \
4144 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4145 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004146 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004147#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004148
4149 FOR_ALL_WINDOWS(wp)
4150 if (wp->w_buffer == term->tl_buffer)
4151 break;
4152 if (wp != NULL)
4153 {
4154#ifdef FEAT_GUI
4155 if (gui.in_use)
4156 {
4157 x += wp->w_wincol * gui.char_width;
4158 y += W_WINROW(wp) * gui.char_height;
4159 }
4160 else
4161#endif
4162 {
4163 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004164 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004165 x += wp->w_wincol * 7;
4166 y += W_WINROW(wp) * 10;
4167 }
4168 }
4169
4170 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4171 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4172 (char_u *)buf, len, NULL);
4173 return 1;
4174}
4175
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004176static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004177 NULL, // text
4178 NULL, // control
4179 NULL, // escape
4180 parse_csi, // csi
4181 parse_osc, // osc
4182 NULL, // dcs
4183 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004184};
4185
4186/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004187 * Use Vim's allocation functions for vterm so profiling works.
4188 */
4189 static void *
4190vterm_malloc(size_t size, void *data UNUSED)
4191{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004192 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004193}
4194
4195 static void
4196vterm_memfree(void *ptr, void *data UNUSED)
4197{
4198 vim_free(ptr);
4199}
4200
4201static VTermAllocatorFunctions vterm_allocator = {
4202 &vterm_malloc,
4203 &vterm_memfree
4204};
4205
4206/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004207 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004208 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004209 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004210 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004211create_vterm(term_T *term, int rows, int cols)
4212{
4213 VTerm *vterm;
4214 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004215 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004216 VTermValue value;
4217
Bram Moolenaar756ef112018-04-10 12:04:27 +02004218 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004219 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004220 if (vterm == NULL)
4221 return FAIL;
4222
4223 // Allocate screen and state here, so we can bail out if that fails.
4224 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004225 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004226 if (state == NULL || screen == NULL)
4227 {
4228 vterm_free(vterm);
4229 return FAIL;
4230 }
4231
Bram Moolenaar52acb112018-03-18 19:20:22 +01004232 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004233 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004234 vterm_set_utf8(vterm, 1);
4235
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004236 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004237
4238 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004239 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004240 &term->tl_default_color.fg,
4241 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004242
Bram Moolenaar9e587872019-05-13 20:27:23 +02004243 if (t_colors < 16)
4244 // Less than 16 colors: assume that bold means using a bright color for
4245 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004246 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4247
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004248 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004249 vterm_screen_reset(screen, 1 /* hard */);
4250
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004251 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004252 vterm_screen_enable_altscreen(screen, 1);
4253
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004254 // For unix do not use a blinking cursor. In an xterm this causes the
4255 // cursor to blink if it's blinking in the xterm.
4256 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004257#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004258 if (GetCaretBlinkTime() == INFINITE)
4259 value.boolean = 0;
4260 else
4261 value.boolean = 1;
4262#else
4263 value.boolean = 0;
4264#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004265 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4266 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004267
4268 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004269}
4270
4271/*
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004272 * Called when 'wincolor' was set.
4273 */
4274 void
4275term_update_colors(void)
4276{
4277 term_T *term = curwin->w_buffer->b_term;
4278
4279 init_default_colors(term, curwin);
4280 vterm_state_set_default_colors(
4281 vterm_obtain_state(term->tl_vterm),
4282 &term->tl_default_color.fg,
4283 &term->tl_default_color.bg);
4284}
4285
4286/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004287 * Return the text to show for the buffer name and status.
4288 */
4289 char_u *
4290term_get_status_text(term_T *term)
4291{
4292 if (term->tl_status_text == NULL)
4293 {
4294 char_u *txt;
4295 size_t len;
4296
4297 if (term->tl_normal_mode)
4298 {
4299 if (term_job_running(term))
4300 txt = (char_u *)_("Terminal");
4301 else
4302 txt = (char_u *)_("Terminal-finished");
4303 }
4304 else if (term->tl_title != NULL)
4305 txt = term->tl_title;
4306 else if (term_none_open(term))
4307 txt = (char_u *)_("active");
4308 else if (term_job_running(term))
4309 txt = (char_u *)_("running");
4310 else
4311 txt = (char_u *)_("finished");
4312 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004313 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004314 if (term->tl_status_text != NULL)
4315 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4316 term->tl_buffer->b_fname, txt);
4317 }
4318 return term->tl_status_text;
4319}
4320
4321/*
4322 * Mark references in jobs of terminals.
4323 */
4324 int
4325set_ref_in_term(int copyID)
4326{
4327 int abort = FALSE;
4328 term_T *term;
4329 typval_T tv;
4330
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004331 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004332 if (term->tl_job != NULL)
4333 {
4334 tv.v_type = VAR_JOB;
4335 tv.vval.v_job = term->tl_job;
4336 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4337 }
4338 return abort;
4339}
4340
4341/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004342 * Cache "Terminal" highlight group colors.
4343 */
4344 void
4345set_terminal_default_colors(int cterm_fg, int cterm_bg)
4346{
4347 term_default_cterm_fg = cterm_fg - 1;
4348 term_default_cterm_bg = cterm_bg - 1;
4349}
4350
4351/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004352 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004353 * Returns NULL when the buffer is not for a terminal window and logs a message
4354 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004355 */
4356 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004357term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004358{
4359 buf_T *buf;
4360
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004361 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004362 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004363 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004364 --emsg_off;
4365 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004366 {
4367 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004368 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004369 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004370 return buf;
4371}
4372
Bram Moolenaard96ff162018-02-18 22:13:29 +01004373 static int
4374same_color(VTermColor *a, VTermColor *b)
4375{
4376 return a->red == b->red
4377 && a->green == b->green
4378 && a->blue == b->blue
4379 && a->ansi_index == b->ansi_index;
4380}
4381
4382 static void
4383dump_term_color(FILE *fd, VTermColor *color)
4384{
4385 fprintf(fd, "%02x%02x%02x%d",
4386 (int)color->red, (int)color->green, (int)color->blue,
4387 (int)color->ansi_index);
4388}
4389
4390/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004391 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004392 *
4393 * Each screen cell in full is:
4394 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4395 * {characters} is a space for an empty cell
4396 * For a double-width character "+" is changed to "*" and the next cell is
4397 * skipped.
4398 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4399 * when "&" use the same as the previous cell.
4400 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4401 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4402 * {color-idx} is a number from 0 to 255
4403 *
4404 * Screen cell with same width, attributes and color as the previous one:
4405 * |{characters}
4406 *
4407 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4408 *
4409 * Repeating the previous screen cell:
4410 * @{count}
4411 */
4412 void
4413f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4414{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004415 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004416 term_T *term;
4417 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004418 int max_height = 0;
4419 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004420 stat_T st;
4421 FILE *fd;
4422 VTermPos pos;
4423 VTermScreen *screen;
4424 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004425 VTermState *state;
4426 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004427
4428 if (check_restricted() || check_secure())
4429 return;
4430 if (buf == NULL)
4431 return;
4432 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004433 if (term->tl_vterm == NULL)
4434 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004435 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004436 return;
4437 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004438
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004439 if (argvars[2].v_type != VAR_UNKNOWN)
4440 {
4441 dict_T *d;
4442
4443 if (argvars[2].v_type != VAR_DICT)
4444 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004445 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004446 return;
4447 }
4448 d = argvars[2].vval.v_dict;
4449 if (d != NULL)
4450 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004451 max_height = dict_get_number(d, (char_u *)"rows");
4452 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004453 }
4454 }
4455
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004456 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004457 if (fname == NULL)
4458 return;
4459 if (mch_stat((char *)fname, &st) >= 0)
4460 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004461 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004462 return;
4463 }
4464
Bram Moolenaard96ff162018-02-18 22:13:29 +01004465 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4466 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004467 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004468 return;
4469 }
4470
4471 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4472
4473 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004474 state = vterm_obtain_state(term->tl_vterm);
4475 vterm_state_get_cursorpos(state, &cursor_pos);
4476
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004477 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4478 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004479 {
4480 int repeat = 0;
4481
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004482 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4483 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004484 {
4485 VTermScreenCell cell;
4486 int same_attr;
4487 int same_chars = TRUE;
4488 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004489 int is_cursor_pos = (pos.col == cursor_pos.col
4490 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004491
4492 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4493 vim_memset(&cell, 0, sizeof(cell));
4494
4495 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4496 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004497 int c = cell.chars[i];
4498 int pc = prev_cell.chars[i];
4499
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004500 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01004501 if (i == 0)
4502 {
4503 c = (c == NUL) ? ' ' : c;
4504 pc = (pc == NUL) ? ' ' : pc;
4505 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004506 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004507 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004508 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004509 break;
4510 }
4511 same_attr = vtermAttr2hl(cell.attrs)
4512 == vtermAttr2hl(prev_cell.attrs)
4513 && same_color(&cell.fg, &prev_cell.fg)
4514 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004515 if (same_chars && cell.width == prev_cell.width && same_attr
4516 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004517 {
4518 ++repeat;
4519 }
4520 else
4521 {
4522 if (repeat > 0)
4523 {
4524 fprintf(fd, "@%d", repeat);
4525 repeat = 0;
4526 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004527 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004528
4529 if (cell.chars[0] == NUL)
4530 fputs(" ", fd);
4531 else
4532 {
4533 char_u charbuf[10];
4534 int len;
4535
4536 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4537 && cell.chars[i] != NUL; ++i)
4538 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004539 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004540 fwrite(charbuf, len, 1, fd);
4541 }
4542 }
4543
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004544 // When only the characters differ we don't write anything, the
4545 // following "|", "@" or NL will indicate using the same
4546 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004547 if (cell.width != prev_cell.width || !same_attr)
4548 {
4549 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004550 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004551 else
4552 fputs("+", fd);
4553
4554 if (same_attr)
4555 {
4556 fputs("&", fd);
4557 }
4558 else
4559 {
4560 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4561 if (same_color(&cell.fg, &prev_cell.fg))
4562 fputs("&", fd);
4563 else
4564 {
4565 fputs("#", fd);
4566 dump_term_color(fd, &cell.fg);
4567 }
4568 if (same_color(&cell.bg, &prev_cell.bg))
4569 fputs("&", fd);
4570 else
4571 {
4572 fputs("#", fd);
4573 dump_term_color(fd, &cell.bg);
4574 }
4575 }
4576 }
4577
4578 prev_cell = cell;
4579 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004580
4581 if (cell.width == 2)
4582 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004583 }
4584 if (repeat > 0)
4585 fprintf(fd, "@%d", repeat);
4586 fputs("\n", fd);
4587 }
4588
4589 fclose(fd);
4590}
4591
4592/*
4593 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4594 */
4595 static void
4596dump_is_corrupt(garray_T *gap)
4597{
4598 ga_concat(gap, (char_u *)"CORRUPT");
4599}
4600
4601 static void
4602append_cell(garray_T *gap, cellattr_T *cell)
4603{
4604 if (ga_grow(gap, 1) == OK)
4605 {
4606 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4607 ++gap->ga_len;
4608 }
4609}
4610
4611/*
4612 * Read the dump file from "fd" and append lines to the current buffer.
4613 * Return the cell width of the longest line.
4614 */
4615 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004616read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004617{
4618 int c;
4619 garray_T ga_text;
4620 garray_T ga_cell;
4621 char_u *prev_char = NULL;
4622 int attr = 0;
4623 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004624 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004625 term_T *term = curbuf->b_term;
4626 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004627 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004628
4629 ga_init2(&ga_text, 1, 90);
4630 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4631 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004632 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004633 cursor_pos->row = -1;
4634 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004635
4636 c = fgetc(fd);
4637 for (;;)
4638 {
4639 if (c == EOF)
4640 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004641 if (c == '\r')
4642 {
4643 // DOS line endings? Ignore.
4644 c = fgetc(fd);
4645 }
4646 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004647 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004648 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004649 if (ga_text.ga_data == NULL)
4650 dump_is_corrupt(&ga_text);
4651 if (ga_grow(&term->tl_scrollback, 1) == OK)
4652 {
4653 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4654 + term->tl_scrollback.ga_len;
4655
4656 if (max_cells < ga_cell.ga_len)
4657 max_cells = ga_cell.ga_len;
4658 line->sb_cols = ga_cell.ga_len;
4659 line->sb_cells = ga_cell.ga_data;
4660 line->sb_fill_attr = term->tl_default_color;
4661 ++term->tl_scrollback.ga_len;
4662 ga_init(&ga_cell);
4663
4664 ga_append(&ga_text, NUL);
4665 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4666 ga_text.ga_len, FALSE);
4667 }
4668 else
4669 ga_clear(&ga_cell);
4670 ga_text.ga_len = 0;
4671
4672 c = fgetc(fd);
4673 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004674 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004675 {
4676 int prev_len = ga_text.ga_len;
4677
Bram Moolenaar9271d052018-02-25 21:39:46 +01004678 if (c == '>')
4679 {
4680 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004681 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004682 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4683 cursor_pos->col = ga_cell.ga_len;
4684 }
4685
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004686 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004687 c = fgetc(fd);
4688 if (c != EOF)
4689 ga_append(&ga_text, c);
4690 for (;;)
4691 {
4692 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004693 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004694 || c == EOF || c == '\n')
4695 break;
4696 ga_append(&ga_text, c);
4697 }
4698
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004699 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01004700 vim_free(prev_char);
4701 if (ga_text.ga_data != NULL)
4702 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4703 ga_text.ga_len - prev_len);
4704
Bram Moolenaar9271d052018-02-25 21:39:46 +01004705 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004706 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004707 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004708 }
4709 else if (c == '+' || c == '*')
4710 {
4711 int is_bg;
4712
4713 cell.width = c == '+' ? 1 : 2;
4714
4715 c = fgetc(fd);
4716 if (c == '&')
4717 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004718 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004719 c = fgetc(fd);
4720 }
4721 else if (isdigit(c))
4722 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004723 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01004724 attr = 0;
4725 while (isdigit(c))
4726 {
4727 attr = attr * 10 + (c - '0');
4728 c = fgetc(fd);
4729 }
4730 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004731
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004732 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004733 for (is_bg = 0; is_bg <= 1; ++is_bg)
4734 {
4735 if (c == '&')
4736 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004737 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004738 c = fgetc(fd);
4739 }
4740 else if (c == '#')
4741 {
4742 int red, green, blue, index = 0;
4743
4744 c = fgetc(fd);
4745 red = hex2nr(c);
4746 c = fgetc(fd);
4747 red = (red << 4) + hex2nr(c);
4748 c = fgetc(fd);
4749 green = hex2nr(c);
4750 c = fgetc(fd);
4751 green = (green << 4) + hex2nr(c);
4752 c = fgetc(fd);
4753 blue = hex2nr(c);
4754 c = fgetc(fd);
4755 blue = (blue << 4) + hex2nr(c);
4756 c = fgetc(fd);
4757 if (!isdigit(c))
4758 dump_is_corrupt(&ga_text);
4759 while (isdigit(c))
4760 {
4761 index = index * 10 + (c - '0');
4762 c = fgetc(fd);
4763 }
4764
4765 if (is_bg)
4766 {
4767 cell.bg.red = red;
4768 cell.bg.green = green;
4769 cell.bg.blue = blue;
4770 cell.bg.ansi_index = index;
4771 }
4772 else
4773 {
4774 cell.fg.red = red;
4775 cell.fg.green = green;
4776 cell.fg.blue = blue;
4777 cell.fg.ansi_index = index;
4778 }
4779 }
4780 else
4781 dump_is_corrupt(&ga_text);
4782 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004783 }
4784 else
4785 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004786 }
4787 else
4788 dump_is_corrupt(&ga_text);
4789
4790 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004791 if (cell.width == 2)
4792 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004793 }
4794 else if (c == '@')
4795 {
4796 if (prev_char == NULL)
4797 dump_is_corrupt(&ga_text);
4798 else
4799 {
4800 int count = 0;
4801
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004802 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01004803 for (;;)
4804 {
4805 c = fgetc(fd);
4806 if (!isdigit(c))
4807 break;
4808 count = count * 10 + (c - '0');
4809 }
4810
4811 while (count-- > 0)
4812 {
4813 ga_concat(&ga_text, prev_char);
4814 append_cell(&ga_cell, &cell);
4815 }
4816 }
4817 }
4818 else
4819 {
4820 dump_is_corrupt(&ga_text);
4821 c = fgetc(fd);
4822 }
4823 }
4824
4825 if (ga_text.ga_len > 0)
4826 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004827 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004828 dump_is_corrupt(&ga_text);
4829 ga_append(&ga_text, NUL);
4830 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4831 ga_text.ga_len, FALSE);
4832 }
4833
4834 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004835 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004836 vim_free(prev_char);
4837
4838 return max_cells;
4839}
4840
4841/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004842 * Return an allocated string with at least "text_width" "=" characters and
4843 * "fname" inserted in the middle.
4844 */
4845 static char_u *
4846get_separator(int text_width, char_u *fname)
4847{
4848 int width = MAX(text_width, curwin->w_width);
4849 char_u *textline;
4850 int fname_size;
4851 char_u *p = fname;
4852 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004853 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004854
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004855 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004856 if (textline == NULL)
4857 return NULL;
4858
4859 fname_size = vim_strsize(fname);
4860 if (fname_size < width - 8)
4861 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004862 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02004863 width = MAX(text_width, fname_size + 8);
4864 }
4865 else if (fname_size > width - 8)
4866 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004867 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02004868 p = gettail(fname);
4869 fname_size = vim_strsize(p);
4870 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004871 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02004872 while (fname_size > width - 8)
4873 {
4874 p += (*mb_ptr2len)(p);
4875 fname_size = vim_strsize(p);
4876 }
4877
4878 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4879 textline[i] = '=';
4880 textline[i++] = ' ';
4881
4882 STRCPY(textline + i, p);
4883 off = STRLEN(textline);
4884 textline[off] = ' ';
4885 for (i = 1; i < (width - fname_size) / 2; ++i)
4886 textline[off + i] = '=';
4887 textline[off + i] = NUL;
4888
4889 return textline;
4890}
4891
4892/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004893 * Common for "term_dumpdiff()" and "term_dumpload()".
4894 */
4895 static void
4896term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4897{
4898 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004899 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004900 char_u buf1[NUMBUFLEN];
4901 char_u buf2[NUMBUFLEN];
4902 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004903 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004904 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004905 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004906 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004907 char_u *textline = NULL;
4908
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004909 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004910 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004911 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004912 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004913 if (fname1 == NULL || (do_diff && fname2 == NULL))
4914 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004915 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004916 return;
4917 }
4918 fd1 = mch_fopen((char *)fname1, READBIN);
4919 if (fd1 == NULL)
4920 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004921 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004922 return;
4923 }
4924 if (do_diff)
4925 {
4926 fd2 = mch_fopen((char *)fname2, READBIN);
4927 if (fd2 == NULL)
4928 {
4929 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004930 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004931 return;
4932 }
4933 }
4934
4935 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004936 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4937 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4938 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4939 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4940 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004941
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004942 if (opt.jo_term_name == NULL)
4943 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004944 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004945
Bram Moolenaar51e14382019-05-25 20:21:28 +02004946 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004947 if (fname_tofree != NULL)
4948 {
4949 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4950 opt.jo_term_name = fname_tofree;
4951 }
4952 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004953
Bram Moolenaar87abab92019-06-03 21:14:59 +02004954 if (opt.jo_bufnr_buf != NULL)
4955 {
4956 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4957
4958 // With "bufnr" argument: enter the window with this buffer and make it
4959 // empty.
4960 if (wp == NULL)
4961 semsg(_(e_invarg2), "bufnr");
4962 else
4963 {
4964 buf = curbuf;
4965 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4966 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02004967 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02004968 redraw_later(NOT_VALID);
4969 }
4970 }
4971 else
4972 // Create a new terminal window.
4973 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4974
Bram Moolenaard96ff162018-02-18 22:13:29 +01004975 if (buf != NULL && buf->b_term != NULL)
4976 {
4977 int i;
4978 linenr_T bot_lnum;
4979 linenr_T lnum;
4980 term_T *term = buf->b_term;
4981 int width;
4982 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004983 VTermPos cursor_pos1;
4984 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004985
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004986 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004987
Bram Moolenaard96ff162018-02-18 22:13:29 +01004988 rettv->vval.v_number = buf->b_fnum;
4989
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004990 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01004991 width = read_dump_file(fd1, &cursor_pos1);
4992
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004993 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004994 if (cursor_pos1.row >= 0)
4995 {
4996 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4997 coladvance(cursor_pos1.col);
4998 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004999
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005000 // Delete the empty line that was in the empty buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005001 ml_delete(1, FALSE);
5002
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005003 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005004 if (!do_diff)
5005 goto theend;
5006
5007 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5008
Bram Moolenaar4a696342018-04-05 18:45:26 +02005009 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005010 if (textline == NULL)
5011 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005012 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5013 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5014 vim_free(textline);
5015
5016 textline = get_separator(width, fname2);
5017 if (textline == NULL)
5018 goto theend;
5019 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5020 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005021 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005022
5023 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005024 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005025 if (width2 > width)
5026 {
5027 vim_free(textline);
5028 textline = alloc(width2 + 1);
5029 if (textline == NULL)
5030 goto theend;
5031 width = width2;
5032 textline[width] = NUL;
5033 }
5034 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5035
5036 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5037 {
5038 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5039 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005040 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005041 for (i = 0; i < width; ++i)
5042 textline[i] = '-';
5043 }
5044 else
5045 {
5046 char_u *line1;
5047 char_u *line2;
5048 char_u *p1;
5049 char_u *p2;
5050 int col;
5051 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5052 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5053 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5054 ->sb_cells;
5055
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005056 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005057 line1 = vim_strsave(ml_get(lnum));
5058 if (line1 == NULL)
5059 break;
5060 p1 = line1;
5061
5062 line2 = ml_get(lnum + bot_lnum);
5063 p2 = line2;
5064 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5065 {
5066 int len1 = utfc_ptr2len(p1);
5067 int len2 = utfc_ptr2len(p2);
5068
5069 textline[col] = ' ';
5070 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005071 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005072 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005073 else if (lnum == cursor_pos1.row + 1
5074 && col == cursor_pos1.col
5075 && (cursor_pos1.row != cursor_pos2.row
5076 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005077 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005078 textline[col] = '>';
5079 else if (lnum == cursor_pos2.row + 1
5080 && col == cursor_pos2.col
5081 && (cursor_pos1.row != cursor_pos2.row
5082 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005083 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005084 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005085 else if (cellattr1 != NULL && cellattr2 != NULL)
5086 {
5087 if ((cellattr1 + col)->width
5088 != (cellattr2 + col)->width)
5089 textline[col] = 'w';
5090 else if (!same_color(&(cellattr1 + col)->fg,
5091 &(cellattr2 + col)->fg))
5092 textline[col] = 'f';
5093 else if (!same_color(&(cellattr1 + col)->bg,
5094 &(cellattr2 + col)->bg))
5095 textline[col] = 'b';
5096 else if (vtermAttr2hl((cellattr1 + col)->attrs)
5097 != vtermAttr2hl(((cellattr2 + col)->attrs)))
5098 textline[col] = 'a';
5099 }
5100 p1 += len1;
5101 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005102 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005103 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005104
5105 while (col < width)
5106 {
5107 if (*p1 == NUL && *p2 == NUL)
5108 textline[col] = '?';
5109 else if (*p1 == NUL)
5110 {
5111 textline[col] = '+';
5112 p2 += utfc_ptr2len(p2);
5113 }
5114 else
5115 {
5116 textline[col] = '-';
5117 p1 += utfc_ptr2len(p1);
5118 }
5119 ++col;
5120 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005121
5122 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005123 }
5124 if (add_empty_scrollback(term, &term->tl_default_color,
5125 term->tl_top_diff_rows) == OK)
5126 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5127 ++bot_lnum;
5128 }
5129
5130 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5131 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005132 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005133 for (i = 0; i < width; ++i)
5134 textline[i] = '+';
5135 if (add_empty_scrollback(term, &term->tl_default_color,
5136 term->tl_top_diff_rows) == OK)
5137 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5138 ++lnum;
5139 ++bot_lnum;
5140 }
5141
5142 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005143
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005144 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005145 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005146 }
5147
5148theend:
5149 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005150 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005151 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005152 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005153 fclose(fd2);
5154}
5155
5156/*
5157 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5158 * bottom files.
5159 * Return FAIL when this is not possible.
5160 */
5161 int
5162term_swap_diff()
5163{
5164 term_T *term = curbuf->b_term;
5165 linenr_T line_count;
5166 linenr_T top_rows;
5167 linenr_T bot_rows;
5168 linenr_T bot_start;
5169 linenr_T lnum;
5170 char_u *p;
5171 sb_line_T *sb_line;
5172
5173 if (term == NULL
5174 || !term_is_finished(curbuf)
5175 || term->tl_top_diff_rows == 0
5176 || term->tl_scrollback.ga_len == 0)
5177 return FAIL;
5178
5179 line_count = curbuf->b_ml.ml_line_count;
5180 top_rows = term->tl_top_diff_rows;
5181 bot_rows = term->tl_bot_diff_rows;
5182 bot_start = line_count - bot_rows;
5183 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5184
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005185 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005186 for (lnum = 1; lnum <= top_rows; ++lnum)
5187 {
5188 p = vim_strsave(ml_get(1));
5189 if (p == NULL)
5190 return OK;
5191 ml_append(bot_start, p, 0, FALSE);
5192 ml_delete(1, FALSE);
5193 vim_free(p);
5194 }
5195
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005196 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005197 for (lnum = 1; lnum <= bot_rows; ++lnum)
5198 {
5199 p = vim_strsave(ml_get(bot_start + lnum));
5200 if (p == NULL)
5201 return OK;
5202 ml_delete(bot_start + lnum, FALSE);
5203 ml_append(lnum - 1, p, 0, FALSE);
5204 vim_free(p);
5205 }
5206
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005207 // move top title to bottom
5208 p = vim_strsave(ml_get(bot_rows + 1));
5209 if (p == NULL)
5210 return OK;
5211 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5212 ml_delete(bot_rows + 1, FALSE);
5213 vim_free(p);
5214
5215 // move bottom title to top
5216 p = vim_strsave(ml_get(line_count - top_rows));
5217 if (p == NULL)
5218 return OK;
5219 ml_delete(line_count - top_rows, FALSE);
5220 ml_append(bot_rows, p, 0, FALSE);
5221 vim_free(p);
5222
Bram Moolenaard96ff162018-02-18 22:13:29 +01005223 if (top_rows == bot_rows)
5224 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005225 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005226 for (lnum = 0; lnum < top_rows; ++lnum)
5227 {
5228 sb_line_T temp;
5229
5230 temp = *(sb_line + lnum);
5231 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5232 *(sb_line + bot_start + lnum) = temp;
5233 }
5234 }
5235 else
5236 {
5237 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005238 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005239
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005240 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005241 if (temp != NULL)
5242 {
5243 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5244 mch_memmove(term->tl_scrollback.ga_data,
5245 temp + bot_start,
5246 sizeof(sb_line_T) * bot_rows);
5247 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5248 temp + top_rows,
5249 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5250 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5251 + line_count - top_rows,
5252 temp,
5253 sizeof(sb_line_T) * top_rows);
5254 vim_free(temp);
5255 }
5256 }
5257
5258 term->tl_top_diff_rows = bot_rows;
5259 term->tl_bot_diff_rows = top_rows;
5260
5261 update_screen(NOT_VALID);
5262 return OK;
5263}
5264
5265/*
5266 * "term_dumpdiff(filename, filename, options)" function
5267 */
5268 void
5269f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5270{
5271 term_load_dump(argvars, rettv, TRUE);
5272}
5273
5274/*
5275 * "term_dumpload(filename, options)" function
5276 */
5277 void
5278f_term_dumpload(typval_T *argvars, typval_T *rettv)
5279{
5280 term_load_dump(argvars, rettv, FALSE);
5281}
5282
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005283/*
5284 * "term_getaltscreen(buf)" function
5285 */
5286 void
5287f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5288{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005289 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005290
5291 if (buf == NULL)
5292 return;
5293 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5294}
5295
5296/*
5297 * "term_getattr(attr, name)" function
5298 */
5299 void
5300f_term_getattr(typval_T *argvars, typval_T *rettv)
5301{
5302 int attr;
5303 size_t i;
5304 char_u *name;
5305
5306 static struct {
5307 char *name;
5308 int attr;
5309 } attrs[] = {
5310 {"bold", HL_BOLD},
5311 {"italic", HL_ITALIC},
5312 {"underline", HL_UNDERLINE},
5313 {"strike", HL_STRIKETHROUGH},
5314 {"reverse", HL_INVERSE},
5315 };
5316
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005317 attr = tv_get_number(&argvars[0]);
5318 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005319 if (name == NULL)
5320 return;
5321
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005322 if (attr > HL_ALL)
5323 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005324 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5325 if (STRCMP(name, attrs[i].name) == 0)
5326 {
5327 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5328 break;
5329 }
5330}
5331
5332/*
5333 * "term_getcursor(buf)" function
5334 */
5335 void
5336f_term_getcursor(typval_T *argvars, typval_T *rettv)
5337{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005338 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005339 term_T *term;
5340 list_T *l;
5341 dict_T *d;
5342
5343 if (rettv_list_alloc(rettv) == FAIL)
5344 return;
5345 if (buf == NULL)
5346 return;
5347 term = buf->b_term;
5348
5349 l = rettv->vval.v_list;
5350 list_append_number(l, term->tl_cursor_pos.row + 1);
5351 list_append_number(l, term->tl_cursor_pos.col + 1);
5352
5353 d = dict_alloc();
5354 if (d != NULL)
5355 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005356 dict_add_number(d, "visible", term->tl_cursor_visible);
5357 dict_add_number(d, "blink", blink_state_is_inverted()
5358 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5359 dict_add_number(d, "shape", term->tl_cursor_shape);
5360 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005361 list_append_dict(l, d);
5362 }
5363}
5364
5365/*
5366 * "term_getjob(buf)" function
5367 */
5368 void
5369f_term_getjob(typval_T *argvars, typval_T *rettv)
5370{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005371 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005372
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005373 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005374 {
5375 rettv->v_type = VAR_SPECIAL;
5376 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005377 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005378 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005379
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005380 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005381 rettv->vval.v_job = buf->b_term->tl_job;
5382 if (rettv->vval.v_job != NULL)
5383 ++rettv->vval.v_job->jv_refcount;
5384}
5385
5386 static int
5387get_row_number(typval_T *tv, term_T *term)
5388{
5389 if (tv->v_type == VAR_STRING
5390 && tv->vval.v_string != NULL
5391 && STRCMP(tv->vval.v_string, ".") == 0)
5392 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005393 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005394}
5395
5396/*
5397 * "term_getline(buf, row)" function
5398 */
5399 void
5400f_term_getline(typval_T *argvars, typval_T *rettv)
5401{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005402 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005403 term_T *term;
5404 int row;
5405
5406 rettv->v_type = VAR_STRING;
5407 if (buf == NULL)
5408 return;
5409 term = buf->b_term;
5410 row = get_row_number(&argvars[1], term);
5411
5412 if (term->tl_vterm == NULL)
5413 {
5414 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5415
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005416 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005417 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5418 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5419 }
5420 else
5421 {
5422 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5423 VTermRect rect;
5424 int len;
5425 char_u *p;
5426
5427 if (row < 0 || row >= term->tl_rows)
5428 return;
5429 len = term->tl_cols * MB_MAXBYTES + 1;
5430 p = alloc(len);
5431 if (p == NULL)
5432 return;
5433 rettv->vval.v_string = p;
5434
5435 rect.start_col = 0;
5436 rect.end_col = term->tl_cols;
5437 rect.start_row = row;
5438 rect.end_row = row + 1;
5439 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5440 }
5441}
5442
5443/*
5444 * "term_getscrolled(buf)" function
5445 */
5446 void
5447f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5448{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005449 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005450
5451 if (buf == NULL)
5452 return;
5453 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5454}
5455
5456/*
5457 * "term_getsize(buf)" function
5458 */
5459 void
5460f_term_getsize(typval_T *argvars, typval_T *rettv)
5461{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005462 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005463 list_T *l;
5464
5465 if (rettv_list_alloc(rettv) == FAIL)
5466 return;
5467 if (buf == NULL)
5468 return;
5469
5470 l = rettv->vval.v_list;
5471 list_append_number(l, buf->b_term->tl_rows);
5472 list_append_number(l, buf->b_term->tl_cols);
5473}
5474
5475/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005476 * "term_setsize(buf, rows, cols)" function
5477 */
5478 void
5479f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5480{
5481 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5482 term_T *term;
5483 varnumber_T rows, cols;
5484
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005485 if (buf == NULL)
5486 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005487 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005488 return;
5489 }
5490 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005491 return;
5492 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005493 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005494 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005495 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005496 cols = cols <= 0 ? term->tl_cols : cols;
5497 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005498 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02005499
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005500 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02005501 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5502 term_report_winsize(term, term->tl_rows, term->tl_cols);
5503}
5504
5505/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005506 * "term_getstatus(buf)" function
5507 */
5508 void
5509f_term_getstatus(typval_T *argvars, typval_T *rettv)
5510{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005511 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005512 term_T *term;
5513 char_u val[100];
5514
5515 rettv->v_type = VAR_STRING;
5516 if (buf == NULL)
5517 return;
5518 term = buf->b_term;
5519
5520 if (term_job_running(term))
5521 STRCPY(val, "running");
5522 else
5523 STRCPY(val, "finished");
5524 if (term->tl_normal_mode)
5525 STRCAT(val, ",normal");
5526 rettv->vval.v_string = vim_strsave(val);
5527}
5528
5529/*
5530 * "term_gettitle(buf)" function
5531 */
5532 void
5533f_term_gettitle(typval_T *argvars, typval_T *rettv)
5534{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005535 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005536
5537 rettv->v_type = VAR_STRING;
5538 if (buf == NULL)
5539 return;
5540
5541 if (buf->b_term->tl_title != NULL)
5542 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5543}
5544
5545/*
5546 * "term_gettty(buf)" function
5547 */
5548 void
5549f_term_gettty(typval_T *argvars, typval_T *rettv)
5550{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005551 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005552 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005553 int num = 0;
5554
5555 rettv->v_type = VAR_STRING;
5556 if (buf == NULL)
5557 return;
5558 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005559 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005560
5561 switch (num)
5562 {
5563 case 0:
5564 if (buf->b_term->tl_job != NULL)
5565 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005566 break;
5567 case 1:
5568 if (buf->b_term->tl_job != NULL)
5569 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005570 break;
5571 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005572 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005573 return;
5574 }
5575 if (p != NULL)
5576 rettv->vval.v_string = vim_strsave(p);
5577}
5578
5579/*
5580 * "term_list()" function
5581 */
5582 void
5583f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5584{
5585 term_T *tp;
5586 list_T *l;
5587
5588 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5589 return;
5590
5591 l = rettv->vval.v_list;
5592 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5593 if (tp != NULL && tp->tl_buffer != NULL)
5594 if (list_append_number(l,
5595 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5596 return;
5597}
5598
5599/*
5600 * "term_scrape(buf, row)" function
5601 */
5602 void
5603f_term_scrape(typval_T *argvars, typval_T *rettv)
5604{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005605 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005606 VTermScreen *screen = NULL;
5607 VTermPos pos;
5608 list_T *l;
5609 term_T *term;
5610 char_u *p;
5611 sb_line_T *line;
5612
5613 if (rettv_list_alloc(rettv) == FAIL)
5614 return;
5615 if (buf == NULL)
5616 return;
5617 term = buf->b_term;
5618
5619 l = rettv->vval.v_list;
5620 pos.row = get_row_number(&argvars[1], term);
5621
5622 if (term->tl_vterm != NULL)
5623 {
5624 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005625 if (screen == NULL) // can't really happen
5626 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005627 p = NULL;
5628 line = NULL;
5629 }
5630 else
5631 {
5632 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5633
5634 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5635 return;
5636 p = ml_get_buf(buf, lnum + 1, FALSE);
5637 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5638 }
5639
5640 for (pos.col = 0; pos.col < term->tl_cols; )
5641 {
5642 dict_T *dcell;
5643 int width;
5644 VTermScreenCellAttrs attrs;
5645 VTermColor fg, bg;
5646 char_u rgb[8];
5647 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5648 int off = 0;
5649 int i;
5650
5651 if (screen == NULL)
5652 {
5653 cellattr_T *cellattr;
5654 int len;
5655
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005656 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005657 if (pos.col >= line->sb_cols)
5658 break;
5659 cellattr = line->sb_cells + pos.col;
5660 width = cellattr->width;
5661 attrs = cellattr->attrs;
5662 fg = cellattr->fg;
5663 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005664 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005665 mch_memmove(mbs, p, len);
5666 mbs[len] = NUL;
5667 p += len;
5668 }
5669 else
5670 {
5671 VTermScreenCell cell;
5672 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5673 break;
5674 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5675 {
5676 if (cell.chars[i] == 0)
5677 break;
5678 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5679 }
5680 mbs[off] = NUL;
5681 width = cell.width;
5682 attrs = cell.attrs;
5683 fg = cell.fg;
5684 bg = cell.bg;
5685 }
5686 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005687 if (dcell == NULL)
5688 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005689 list_append_dict(l, dcell);
5690
Bram Moolenaare0be1672018-07-08 16:50:37 +02005691 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005692
5693 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5694 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005695 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005696 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5697 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005698 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005699
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005700 dict_add_number(dcell, "attr", cell2attr(NULL, attrs, fg, bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02005701 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005702
5703 ++pos.col;
5704 if (width == 2)
5705 ++pos.col;
5706 }
5707}
5708
5709/*
5710 * "term_sendkeys(buf, keys)" function
5711 */
5712 void
5713f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5714{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005715 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005716 char_u *msg;
5717 term_T *term;
5718
5719 rettv->v_type = VAR_UNKNOWN;
5720 if (buf == NULL)
5721 return;
5722
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005723 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005724 if (msg == NULL)
5725 return;
5726 term = buf->b_term;
5727 if (term->tl_vterm == NULL)
5728 return;
5729
5730 while (*msg != NUL)
5731 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005732 int c;
5733
5734 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5735 {
5736 c = TO_SPECIAL(msg[1], msg[2]);
5737 msg += 3;
5738 }
5739 else
5740 {
5741 c = PTR2CHAR(msg);
5742 msg += MB_CPTR2LEN(msg);
5743 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005744 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005745 }
5746}
5747
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005748#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5749/*
5750 * "term_getansicolors(buf)" function
5751 */
5752 void
5753f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5754{
5755 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5756 term_T *term;
5757 VTermState *state;
5758 VTermColor color;
5759 char_u hexbuf[10];
5760 int index;
5761 list_T *list;
5762
5763 if (rettv_list_alloc(rettv) == FAIL)
5764 return;
5765
5766 if (buf == NULL)
5767 return;
5768 term = buf->b_term;
5769 if (term->tl_vterm == NULL)
5770 return;
5771
5772 list = rettv->vval.v_list;
5773 state = vterm_obtain_state(term->tl_vterm);
5774 for (index = 0; index < 16; index++)
5775 {
5776 vterm_state_get_palette_color(state, index, &color);
5777 sprintf((char *)hexbuf, "#%02x%02x%02x",
5778 color.red, color.green, color.blue);
5779 if (list_append_string(list, hexbuf, 7) == FAIL)
5780 return;
5781 }
5782}
5783
5784/*
5785 * "term_setansicolors(buf, list)" function
5786 */
5787 void
5788f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5789{
5790 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5791 term_T *term;
5792
5793 if (buf == NULL)
5794 return;
5795 term = buf->b_term;
5796 if (term->tl_vterm == NULL)
5797 return;
5798
5799 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5800 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005801 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005802 return;
5803 }
5804
5805 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005806 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005807}
5808#endif
5809
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005810/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005811 * "term_setapi(buf, api)" function
5812 */
5813 void
5814f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5815{
5816 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5817 term_T *term;
5818 char_u *api;
5819
5820 if (buf == NULL)
5821 return;
5822 term = buf->b_term;
5823 vim_free(term->tl_api);
5824 api = tv_get_string_chk(&argvars[1]);
5825 if (api != NULL)
5826 term->tl_api = vim_strsave(api);
5827 else
5828 term->tl_api = NULL;
5829}
5830
5831/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005832 * "term_setrestore(buf, command)" function
5833 */
5834 void
5835f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5836{
5837#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005838 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005839 term_T *term;
5840 char_u *cmd;
5841
5842 if (buf == NULL)
5843 return;
5844 term = buf->b_term;
5845 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005846 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005847 if (cmd != NULL)
5848 term->tl_command = vim_strsave(cmd);
5849 else
5850 term->tl_command = NULL;
5851#endif
5852}
5853
5854/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005855 * "term_setkill(buf, how)" function
5856 */
5857 void
5858f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5859{
5860 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5861 term_T *term;
5862 char_u *how;
5863
5864 if (buf == NULL)
5865 return;
5866 term = buf->b_term;
5867 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005868 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005869 if (how != NULL)
5870 term->tl_kill = vim_strsave(how);
5871 else
5872 term->tl_kill = NULL;
5873}
5874
5875/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005876 * "term_start(command, options)" function
5877 */
5878 void
5879f_term_start(typval_T *argvars, typval_T *rettv)
5880{
5881 jobopt_T opt;
5882 buf_T *buf;
5883
5884 init_job_options(&opt);
5885 if (argvars[1].v_type != VAR_UNKNOWN
5886 && get_job_options(&argvars[1], &opt,
5887 JO_TIMEOUT_ALL + JO_STOPONEXIT
5888 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5889 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5890 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5891 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005892 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005893 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005894 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005895 return;
5896
Bram Moolenaar13568252018-03-16 20:46:58 +01005897 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005898
5899 if (buf != NULL && buf->b_term != NULL)
5900 rettv->vval.v_number = buf->b_fnum;
5901}
5902
5903/*
5904 * "term_wait" function
5905 */
5906 void
5907f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5908{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005909 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005910
5911 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005912 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005913 if (buf->b_term->tl_job == NULL)
5914 {
5915 ch_log(NULL, "term_wait(): no job to wait for");
5916 return;
5917 }
5918 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005919 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005920 return;
5921
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005922 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01005923 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005924 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5925 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005926 // The job is dead, keep reading channel I/O until the channel is
5927 // closed. buf->b_term may become NULL if the terminal was closed while
5928 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005929 ch_log(NULL, "term_wait(): waiting for channel to close");
5930 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5931 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005932 term_flush_messages();
5933
Bram Moolenaard45aa552018-05-21 22:50:29 +02005934 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005935 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005936 // If the terminal is closed when the channel is closed the
5937 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01005938 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005939 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005940
5941 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005942 }
5943 else
5944 {
5945 long wait = 10L;
5946
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005947 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005948
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005949 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005950 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005951 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005952 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005953
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005954 // Flushing messages on channels is hopefully sufficient.
5955 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005956 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005957 }
5958}
5959
5960/*
5961 * Called when a channel has sent all the lines to a terminal.
5962 * Send a CTRL-D to mark the end of the text.
5963 */
5964 void
5965term_send_eof(channel_T *ch)
5966{
5967 term_T *term;
5968
5969 for (term = first_term; term != NULL; term = term->tl_next)
5970 if (term->tl_job == ch->ch_job)
5971 {
5972 if (term->tl_eof_chars != NULL)
5973 {
5974 channel_send(ch, PART_IN, term->tl_eof_chars,
5975 (int)STRLEN(term->tl_eof_chars), NULL);
5976 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5977 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005978# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005979 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005980 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005981 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5982# endif
5983 }
5984}
5985
Bram Moolenaar113e1072019-01-20 15:30:40 +01005986#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005987 job_T *
5988term_getjob(term_T *term)
5989{
5990 return term != NULL ? term->tl_job : NULL;
5991}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005992#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005993
Bram Moolenaar4f974752019-02-17 17:44:42 +01005994# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005995
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005996///////////////////////////////////////
5997// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005998#ifdef PROTO
5999typedef int COORD;
6000typedef int DWORD;
6001typedef int HANDLE;
6002typedef int *DWORD_PTR;
6003typedef int HPCON;
6004typedef int HRESULT;
6005typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006006typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006007typedef int PSIZE_T;
6008typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006009typedef int BOOL;
6010# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006011#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006012
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006013HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6014HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6015HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006016BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6017BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6018void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006019
6020 static int
6021dyn_conpty_init(int verbose)
6022{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006023 static HMODULE hKerneldll = NULL;
6024 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006025 static struct
6026 {
6027 char *name;
6028 FARPROC *ptr;
6029 } conpty_entry[] =
6030 {
6031 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6032 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6033 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6034 {"InitializeProcThreadAttributeList",
6035 (FARPROC*)&pInitializeProcThreadAttributeList},
6036 {"UpdateProcThreadAttribute",
6037 (FARPROC*)&pUpdateProcThreadAttribute},
6038 {"DeleteProcThreadAttributeList",
6039 (FARPROC*)&pDeleteProcThreadAttributeList},
6040 {NULL, NULL}
6041 };
6042
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006043 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006044 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006045 if (verbose)
6046 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006047 return FAIL;
6048 }
6049
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006050 // No need to initialize twice.
6051 if (hKerneldll)
6052 return OK;
6053
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006054 hKerneldll = vimLoadLib("kernel32.dll");
6055 for (i = 0; conpty_entry[i].name != NULL
6056 && conpty_entry[i].ptr != NULL; ++i)
6057 {
6058 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6059 conpty_entry[i].name)) == NULL)
6060 {
6061 if (verbose)
6062 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006063 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006064 return FAIL;
6065 }
6066 }
6067
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006068 return OK;
6069}
6070
6071 static int
6072conpty_term_and_job_init(
6073 term_T *term,
6074 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006075 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006076 jobopt_T *opt,
6077 jobopt_T *orig_opt)
6078{
6079 WCHAR *cmd_wchar = NULL;
6080 WCHAR *cmd_wchar_copy = NULL;
6081 WCHAR *cwd_wchar = NULL;
6082 WCHAR *env_wchar = NULL;
6083 channel_T *channel = NULL;
6084 job_T *job = NULL;
6085 HANDLE jo = NULL;
6086 garray_T ga_cmd, ga_env;
6087 char_u *cmd = NULL;
6088 HRESULT hr;
6089 COORD consize;
6090 SIZE_T breq;
6091 PROCESS_INFORMATION proc_info;
6092 HANDLE i_theirs = NULL;
6093 HANDLE o_theirs = NULL;
6094 HANDLE i_ours = NULL;
6095 HANDLE o_ours = NULL;
6096
6097 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6098 ga_init2(&ga_env, (int)sizeof(char*), 20);
6099
6100 if (argvar->v_type == VAR_STRING)
6101 {
6102 cmd = argvar->vval.v_string;
6103 }
6104 else if (argvar->v_type == VAR_LIST)
6105 {
6106 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6107 goto failed;
6108 cmd = ga_cmd.ga_data;
6109 }
6110 if (cmd == NULL || *cmd == NUL)
6111 {
6112 emsg(_(e_invarg));
6113 goto failed;
6114 }
6115
6116 term->tl_arg0_cmd = vim_strsave(cmd);
6117
6118 cmd_wchar = enc_to_utf16(cmd, NULL);
6119
6120 if (cmd_wchar != NULL)
6121 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006122 // Request by CreateProcessW
6123 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006124 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006125 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6126 }
6127
6128 ga_clear(&ga_cmd);
6129 if (cmd_wchar == NULL)
6130 goto failed;
6131 if (opt->jo_cwd != NULL)
6132 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6133
6134 win32_build_env(opt->jo_env, &ga_env, TRUE);
6135 env_wchar = ga_env.ga_data;
6136
6137 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6138 goto failed;
6139 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6140 goto failed;
6141
6142 consize.X = term->tl_cols;
6143 consize.Y = term->tl_rows;
6144 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6145 &term->tl_conpty);
6146 if (FAILED(hr))
6147 goto failed;
6148
6149 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6150
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006151 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006152 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006153 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006154 if (!term->tl_siex.lpAttributeList)
6155 goto failed;
6156 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6157 0, &breq))
6158 goto failed;
6159 if (!pUpdateProcThreadAttribute(
6160 term->tl_siex.lpAttributeList, 0,
6161 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6162 sizeof(HPCON), NULL, NULL))
6163 goto failed;
6164
6165 channel = add_channel();
6166 if (channel == NULL)
6167 goto failed;
6168
6169 job = job_alloc();
6170 if (job == NULL)
6171 goto failed;
6172 if (argvar->v_type == VAR_STRING)
6173 {
6174 int argc;
6175
6176 build_argv_from_string(cmd, &job->jv_argv, &argc);
6177 }
6178 else
6179 {
6180 int argc;
6181
6182 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6183 }
6184
6185 if (opt->jo_set & JO_IN_BUF)
6186 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6187
6188 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6189 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
6190 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
6191 | CREATE_DEFAULT_ERROR_MODE,
6192 env_wchar, cwd_wchar,
6193 &term->tl_siex.StartupInfo, &proc_info))
6194 goto failed;
6195
6196 CloseHandle(i_theirs);
6197 CloseHandle(o_theirs);
6198
6199 channel_set_pipes(channel,
6200 (sock_T)i_ours,
6201 (sock_T)o_ours,
6202 (sock_T)o_ours);
6203
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006204 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006205 channel->ch_write_text_mode = TRUE;
6206
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006207 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006208 channel->ch_anonymous_pipe = TRUE;
6209
6210 jo = CreateJobObject(NULL, NULL);
6211 if (jo == NULL)
6212 goto failed;
6213
6214 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6215 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006216 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006217 CloseHandle(jo);
6218 jo = NULL;
6219 }
6220
6221 ResumeThread(proc_info.hThread);
6222 CloseHandle(proc_info.hThread);
6223
6224 vim_free(cmd_wchar);
6225 vim_free(cmd_wchar_copy);
6226 vim_free(cwd_wchar);
6227 vim_free(env_wchar);
6228
6229 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6230 goto failed;
6231
6232#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6233 if (opt->jo_set2 & JO2_ANSI_COLORS)
6234 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6235 else
6236 init_vterm_ansi_colors(term->tl_vterm);
6237#endif
6238
6239 channel_set_job(channel, job, opt);
6240 job_set_options(job, opt);
6241
6242 job->jv_channel = channel;
6243 job->jv_proc_info = proc_info;
6244 job->jv_job_object = jo;
6245 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006246 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006247 ++job->jv_refcount;
6248 term->tl_job = job;
6249
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006250 // Redirecting stdout and stderr doesn't work at the job level. Instead
6251 // open the file here and handle it in. opt->jo_io was changed in
6252 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006253 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6254 {
6255 char_u *fname = opt->jo_io_name[PART_OUT];
6256
6257 ch_log(channel, "Opening output file %s", fname);
6258 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6259 if (term->tl_out_fd == NULL)
6260 semsg(_(e_notopen), fname);
6261 }
6262
6263 return OK;
6264
6265failed:
6266 ga_clear(&ga_cmd);
6267 ga_clear(&ga_env);
6268 vim_free(cmd_wchar);
6269 vim_free(cmd_wchar_copy);
6270 vim_free(cwd_wchar);
6271 if (channel != NULL)
6272 channel_clear(channel);
6273 if (job != NULL)
6274 {
6275 job->jv_channel = NULL;
6276 job_cleanup(job);
6277 }
6278 term->tl_job = NULL;
6279 if (jo != NULL)
6280 CloseHandle(jo);
6281
6282 if (term->tl_siex.lpAttributeList != NULL)
6283 {
6284 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6285 vim_free(term->tl_siex.lpAttributeList);
6286 }
6287 term->tl_siex.lpAttributeList = NULL;
6288 if (o_theirs != NULL)
6289 CloseHandle(o_theirs);
6290 if (o_ours != NULL)
6291 CloseHandle(o_ours);
6292 if (i_ours != NULL)
6293 CloseHandle(i_ours);
6294 if (i_theirs != NULL)
6295 CloseHandle(i_theirs);
6296 if (term->tl_conpty != NULL)
6297 pClosePseudoConsole(term->tl_conpty);
6298 term->tl_conpty = NULL;
6299 return FAIL;
6300}
6301
6302 static void
6303conpty_term_report_winsize(term_T *term, int rows, int cols)
6304{
6305 COORD consize;
6306
6307 consize.X = cols;
6308 consize.Y = rows;
6309 pResizePseudoConsole(term->tl_conpty, consize);
6310}
6311
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006312 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006313term_free_conpty(term_T *term)
6314{
6315 if (term->tl_siex.lpAttributeList != NULL)
6316 {
6317 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6318 vim_free(term->tl_siex.lpAttributeList);
6319 }
6320 term->tl_siex.lpAttributeList = NULL;
6321 if (term->tl_conpty != NULL)
6322 pClosePseudoConsole(term->tl_conpty);
6323 term->tl_conpty = NULL;
6324}
6325
6326 int
6327use_conpty(void)
6328{
6329 return has_conpty;
6330}
6331
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006332# ifndef PROTO
6333
6334#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6335#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006336#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006337
6338void* (*winpty_config_new)(UINT64, void*);
6339void* (*winpty_open)(void*, void*);
6340void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6341BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6342void (*winpty_config_set_mouse_mode)(void*, int);
6343void (*winpty_config_set_initial_size)(void*, int, int);
6344LPCWSTR (*winpty_conin_name)(void*);
6345LPCWSTR (*winpty_conout_name)(void*);
6346LPCWSTR (*winpty_conerr_name)(void*);
6347void (*winpty_free)(void*);
6348void (*winpty_config_free)(void*);
6349void (*winpty_spawn_config_free)(void*);
6350void (*winpty_error_free)(void*);
6351LPCWSTR (*winpty_error_msg)(void*);
6352BOOL (*winpty_set_size)(void*, int, int, void*);
6353HANDLE (*winpty_agent_process)(void*);
6354
6355#define WINPTY_DLL "winpty.dll"
6356
6357static HINSTANCE hWinPtyDLL = NULL;
6358# endif
6359
6360 static int
6361dyn_winpty_init(int verbose)
6362{
6363 int i;
6364 static struct
6365 {
6366 char *name;
6367 FARPROC *ptr;
6368 } winpty_entry[] =
6369 {
6370 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6371 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6372 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6373 {"winpty_config_set_mouse_mode",
6374 (FARPROC*)&winpty_config_set_mouse_mode},
6375 {"winpty_config_set_initial_size",
6376 (FARPROC*)&winpty_config_set_initial_size},
6377 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6378 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6379 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6380 {"winpty_free", (FARPROC*)&winpty_free},
6381 {"winpty_open", (FARPROC*)&winpty_open},
6382 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6383 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6384 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6385 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6386 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6387 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6388 {NULL, NULL}
6389 };
6390
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006391 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006392 if (hWinPtyDLL)
6393 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006394 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6395 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006396 if (*p_winptydll != NUL)
6397 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6398 if (!hWinPtyDLL)
6399 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6400 if (!hWinPtyDLL)
6401 {
6402 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006403 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006404 : (char_u *)WINPTY_DLL);
6405 return FAIL;
6406 }
6407 for (i = 0; winpty_entry[i].name != NULL
6408 && winpty_entry[i].ptr != NULL; ++i)
6409 {
6410 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6411 winpty_entry[i].name)) == NULL)
6412 {
6413 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006414 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006415 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006416 return FAIL;
6417 }
6418 }
6419
6420 return OK;
6421}
6422
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006423 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006424winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006425 term_T *term,
6426 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006427 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006428 jobopt_T *opt,
6429 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006430{
6431 WCHAR *cmd_wchar = NULL;
6432 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006433 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006434 channel_T *channel = NULL;
6435 job_T *job = NULL;
6436 DWORD error;
6437 HANDLE jo = NULL;
6438 HANDLE child_process_handle;
6439 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006440 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006441 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006442 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006443 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006444
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006445 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6446 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006447
6448 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006449 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006450 cmd = argvar->vval.v_string;
6451 }
6452 else if (argvar->v_type == VAR_LIST)
6453 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006454 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006455 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006456 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006457 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006458 if (cmd == NULL || *cmd == NUL)
6459 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006460 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006461 goto failed;
6462 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006463
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006464 term->tl_arg0_cmd = vim_strsave(cmd);
6465
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006466 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006467 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006468 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006469 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006470 if (opt->jo_cwd != NULL)
6471 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006472
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006473 win32_build_env(opt->jo_env, &ga_env, TRUE);
6474 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006475
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006476 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6477 if (term->tl_winpty_config == NULL)
6478 goto failed;
6479
6480 winpty_config_set_mouse_mode(term->tl_winpty_config,
6481 WINPTY_MOUSE_MODE_FORCE);
6482 winpty_config_set_initial_size(term->tl_winpty_config,
6483 term->tl_cols, term->tl_rows);
6484 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6485 if (term->tl_winpty == NULL)
6486 goto failed;
6487
6488 spawn_config = winpty_spawn_config_new(
6489 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6490 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6491 NULL,
6492 cmd_wchar,
6493 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006494 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006495 &winpty_err);
6496 if (spawn_config == NULL)
6497 goto failed;
6498
6499 channel = add_channel();
6500 if (channel == NULL)
6501 goto failed;
6502
6503 job = job_alloc();
6504 if (job == NULL)
6505 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006506 if (argvar->v_type == VAR_STRING)
6507 {
6508 int argc;
6509
6510 build_argv_from_string(cmd, &job->jv_argv, &argc);
6511 }
6512 else
6513 {
6514 int argc;
6515
6516 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6517 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006518
6519 if (opt->jo_set & JO_IN_BUF)
6520 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6521
6522 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6523 &child_thread_handle, &error, &winpty_err))
6524 goto failed;
6525
6526 channel_set_pipes(channel,
6527 (sock_T)CreateFileW(
6528 winpty_conin_name(term->tl_winpty),
6529 GENERIC_WRITE, 0, NULL,
6530 OPEN_EXISTING, 0, NULL),
6531 (sock_T)CreateFileW(
6532 winpty_conout_name(term->tl_winpty),
6533 GENERIC_READ, 0, NULL,
6534 OPEN_EXISTING, 0, NULL),
6535 (sock_T)CreateFileW(
6536 winpty_conerr_name(term->tl_winpty),
6537 GENERIC_READ, 0, NULL,
6538 OPEN_EXISTING, 0, NULL));
6539
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006540 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006541 channel->ch_write_text_mode = TRUE;
6542
6543 jo = CreateJobObject(NULL, NULL);
6544 if (jo == NULL)
6545 goto failed;
6546
6547 if (!AssignProcessToJobObject(jo, child_process_handle))
6548 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006549 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006550 CloseHandle(jo);
6551 jo = NULL;
6552 }
6553
6554 winpty_spawn_config_free(spawn_config);
6555 vim_free(cmd_wchar);
6556 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006557 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006558
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006559 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6560 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006561
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006562#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6563 if (opt->jo_set2 & JO2_ANSI_COLORS)
6564 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6565 else
6566 init_vterm_ansi_colors(term->tl_vterm);
6567#endif
6568
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006569 channel_set_job(channel, job, opt);
6570 job_set_options(job, opt);
6571
6572 job->jv_channel = channel;
6573 job->jv_proc_info.hProcess = child_process_handle;
6574 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6575 job->jv_job_object = jo;
6576 job->jv_status = JOB_STARTED;
6577 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006578 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006579 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006580 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006581 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006582 ++job->jv_refcount;
6583 term->tl_job = job;
6584
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006585 // Redirecting stdout and stderr doesn't work at the job level. Instead
6586 // open the file here and handle it in. opt->jo_io was changed in
6587 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006588 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6589 {
6590 char_u *fname = opt->jo_io_name[PART_OUT];
6591
6592 ch_log(channel, "Opening output file %s", fname);
6593 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6594 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006595 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006596 }
6597
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006598 return OK;
6599
6600failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006601 ga_clear(&ga_cmd);
6602 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006603 vim_free(cmd_wchar);
6604 vim_free(cwd_wchar);
6605 if (spawn_config != NULL)
6606 winpty_spawn_config_free(spawn_config);
6607 if (channel != NULL)
6608 channel_clear(channel);
6609 if (job != NULL)
6610 {
6611 job->jv_channel = NULL;
6612 job_cleanup(job);
6613 }
6614 term->tl_job = NULL;
6615 if (jo != NULL)
6616 CloseHandle(jo);
6617 if (term->tl_winpty != NULL)
6618 winpty_free(term->tl_winpty);
6619 term->tl_winpty = NULL;
6620 if (term->tl_winpty_config != NULL)
6621 winpty_config_free(term->tl_winpty_config);
6622 term->tl_winpty_config = NULL;
6623 if (winpty_err != NULL)
6624 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006625 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006626 (short_u *)winpty_error_msg(winpty_err), NULL);
6627
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006628 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006629 winpty_error_free(winpty_err);
6630 }
6631 return FAIL;
6632}
6633
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006634/*
6635 * Create a new terminal of "rows" by "cols" cells.
6636 * Store a reference in "term".
6637 * Return OK or FAIL.
6638 */
6639 static int
6640term_and_job_init(
6641 term_T *term,
6642 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01006643 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006644 jobopt_T *opt,
6645 jobopt_T *orig_opt)
6646{
6647 int use_winpty = FALSE;
6648 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006649 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006650
6651 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6652 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6653
6654 if (!has_winpty && !has_conpty)
6655 // If neither is available give the errors for winpty, since when
6656 // conpty is not available it can't be installed either.
6657 return dyn_winpty_init(TRUE);
6658
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006659 if (opt->jo_tty_type != NUL)
6660 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006661
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006662 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006663 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006664 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006665 use_conpty = TRUE;
6666 else if (has_winpty)
6667 use_winpty = TRUE;
6668 // else: error
6669 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006670 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006671 {
6672 if (has_winpty)
6673 use_winpty = TRUE;
6674 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006675 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006676 {
6677 if (has_conpty)
6678 use_conpty = TRUE;
6679 else
6680 return dyn_conpty_init(TRUE);
6681 }
6682
6683 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006684 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006685
6686 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006687 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006688
6689 // error
6690 return dyn_winpty_init(TRUE);
6691}
6692
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006693 static int
6694create_pty_only(term_T *term, jobopt_T *options)
6695{
6696 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6697 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6698 char in_name[80], out_name[80];
6699 channel_T *channel = NULL;
6700
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006701 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6702 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006703
6704 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6705 GetCurrentProcessId(),
6706 curbuf->b_fnum);
6707 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6708 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6709 PIPE_UNLIMITED_INSTANCES,
6710 0, 0, NMPWAIT_NOWAIT, NULL);
6711 if (hPipeIn == INVALID_HANDLE_VALUE)
6712 goto failed;
6713
6714 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6715 GetCurrentProcessId(),
6716 curbuf->b_fnum);
6717 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6718 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6719 PIPE_UNLIMITED_INSTANCES,
6720 0, 0, 0, NULL);
6721 if (hPipeOut == INVALID_HANDLE_VALUE)
6722 goto failed;
6723
6724 ConnectNamedPipe(hPipeIn, NULL);
6725 ConnectNamedPipe(hPipeOut, NULL);
6726
6727 term->tl_job = job_alloc();
6728 if (term->tl_job == NULL)
6729 goto failed;
6730 ++term->tl_job->jv_refcount;
6731
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006732 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006733 term->tl_job->jv_status = JOB_FINISHED;
6734
6735 channel = add_channel();
6736 if (channel == NULL)
6737 goto failed;
6738 term->tl_job->jv_channel = channel;
6739 channel->ch_keep_open = TRUE;
6740 channel->ch_named_pipe = TRUE;
6741
6742 channel_set_pipes(channel,
6743 (sock_T)hPipeIn,
6744 (sock_T)hPipeOut,
6745 (sock_T)hPipeOut);
6746 channel_set_job(channel, term->tl_job, options);
6747 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6748 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6749
6750 return OK;
6751
6752failed:
6753 if (hPipeIn != NULL)
6754 CloseHandle(hPipeIn);
6755 if (hPipeOut != NULL)
6756 CloseHandle(hPipeOut);
6757 return FAIL;
6758}
6759
6760/*
6761 * Free the terminal emulator part of "term".
6762 */
6763 static void
6764term_free_vterm(term_T *term)
6765{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006766 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006767 if (term->tl_winpty != NULL)
6768 winpty_free(term->tl_winpty);
6769 term->tl_winpty = NULL;
6770 if (term->tl_winpty_config != NULL)
6771 winpty_config_free(term->tl_winpty_config);
6772 term->tl_winpty_config = NULL;
6773 if (term->tl_vterm != NULL)
6774 vterm_free(term->tl_vterm);
6775 term->tl_vterm = NULL;
6776}
6777
6778/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006779 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006780 */
6781 static void
6782term_report_winsize(term_T *term, int rows, int cols)
6783{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006784 if (term->tl_conpty)
6785 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006786 if (term->tl_winpty)
6787 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6788}
6789
6790 int
6791terminal_enabled(void)
6792{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006793 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006794}
6795
6796# else
6797
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006798///////////////////////////////////////
6799// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006800
6801/*
6802 * Create a new terminal of "rows" by "cols" cells.
6803 * Start job for "cmd".
6804 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006805 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006806 * Return OK or FAIL.
6807 */
6808 static int
6809term_and_job_init(
6810 term_T *term,
6811 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006812 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006813 jobopt_T *opt,
6814 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006815{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006816 term->tl_arg0_cmd = NULL;
6817
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006818 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6819 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006820
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006821#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6822 if (opt->jo_set2 & JO2_ANSI_COLORS)
6823 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6824 else
6825 init_vterm_ansi_colors(term->tl_vterm);
6826#endif
6827
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006828 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01006829 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006830 if (term->tl_job != NULL)
6831 ++term->tl_job->jv_refcount;
6832
6833 return term->tl_job != NULL
6834 && term->tl_job->jv_channel != NULL
6835 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6836}
6837
6838 static int
6839create_pty_only(term_T *term, jobopt_T *opt)
6840{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006841 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6842 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006843
6844 term->tl_job = job_alloc();
6845 if (term->tl_job == NULL)
6846 return FAIL;
6847 ++term->tl_job->jv_refcount;
6848
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006849 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006850 term->tl_job->jv_status = JOB_FINISHED;
6851
6852 return mch_create_pty_channel(term->tl_job, opt);
6853}
6854
6855/*
6856 * Free the terminal emulator part of "term".
6857 */
6858 static void
6859term_free_vterm(term_T *term)
6860{
6861 if (term->tl_vterm != NULL)
6862 vterm_free(term->tl_vterm);
6863 term->tl_vterm = NULL;
6864}
6865
6866/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006867 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006868 */
6869 static void
6870term_report_winsize(term_T *term, int rows, int cols)
6871{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006872 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006873 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6874 {
6875 int fd = -1;
6876 int part;
6877
6878 for (part = PART_OUT; part < PART_COUNT; ++part)
6879 {
6880 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006881 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006882 break;
6883 }
6884 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6885 mch_signal_job(term->tl_job, (char_u *)"winch");
6886 }
6887}
6888
6889# endif
6890
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006891#endif // FEAT_TERMINAL