blob: 10bfae8424041f815fb92f093e64b7b50213b09d [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
Bram Moolenaar7ba3b912020-02-10 20:34:04 +01004279 if (term->tl_vterm == NULL)
4280 return;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004281 init_default_colors(term, curwin);
4282 vterm_state_set_default_colors(
4283 vterm_obtain_state(term->tl_vterm),
4284 &term->tl_default_color.fg,
4285 &term->tl_default_color.bg);
4286}
4287
4288/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004289 * Return the text to show for the buffer name and status.
4290 */
4291 char_u *
4292term_get_status_text(term_T *term)
4293{
4294 if (term->tl_status_text == NULL)
4295 {
4296 char_u *txt;
4297 size_t len;
4298
4299 if (term->tl_normal_mode)
4300 {
4301 if (term_job_running(term))
4302 txt = (char_u *)_("Terminal");
4303 else
4304 txt = (char_u *)_("Terminal-finished");
4305 }
4306 else if (term->tl_title != NULL)
4307 txt = term->tl_title;
4308 else if (term_none_open(term))
4309 txt = (char_u *)_("active");
4310 else if (term_job_running(term))
4311 txt = (char_u *)_("running");
4312 else
4313 txt = (char_u *)_("finished");
4314 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004315 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004316 if (term->tl_status_text != NULL)
4317 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4318 term->tl_buffer->b_fname, txt);
4319 }
4320 return term->tl_status_text;
4321}
4322
4323/*
4324 * Mark references in jobs of terminals.
4325 */
4326 int
4327set_ref_in_term(int copyID)
4328{
4329 int abort = FALSE;
4330 term_T *term;
4331 typval_T tv;
4332
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004333 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004334 if (term->tl_job != NULL)
4335 {
4336 tv.v_type = VAR_JOB;
4337 tv.vval.v_job = term->tl_job;
4338 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4339 }
4340 return abort;
4341}
4342
4343/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004344 * Cache "Terminal" highlight group colors.
4345 */
4346 void
4347set_terminal_default_colors(int cterm_fg, int cterm_bg)
4348{
4349 term_default_cterm_fg = cterm_fg - 1;
4350 term_default_cterm_bg = cterm_bg - 1;
4351}
4352
4353/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004354 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004355 * Returns NULL when the buffer is not for a terminal window and logs a message
4356 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004357 */
4358 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004359term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004360{
4361 buf_T *buf;
4362
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004363 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004364 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004365 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004366 --emsg_off;
4367 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004368 {
4369 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004370 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004371 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004372 return buf;
4373}
4374
Bram Moolenaard96ff162018-02-18 22:13:29 +01004375 static int
4376same_color(VTermColor *a, VTermColor *b)
4377{
4378 return a->red == b->red
4379 && a->green == b->green
4380 && a->blue == b->blue
4381 && a->ansi_index == b->ansi_index;
4382}
4383
4384 static void
4385dump_term_color(FILE *fd, VTermColor *color)
4386{
4387 fprintf(fd, "%02x%02x%02x%d",
4388 (int)color->red, (int)color->green, (int)color->blue,
4389 (int)color->ansi_index);
4390}
4391
4392/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004393 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004394 *
4395 * Each screen cell in full is:
4396 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4397 * {characters} is a space for an empty cell
4398 * For a double-width character "+" is changed to "*" and the next cell is
4399 * skipped.
4400 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4401 * when "&" use the same as the previous cell.
4402 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4403 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4404 * {color-idx} is a number from 0 to 255
4405 *
4406 * Screen cell with same width, attributes and color as the previous one:
4407 * |{characters}
4408 *
4409 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4410 *
4411 * Repeating the previous screen cell:
4412 * @{count}
4413 */
4414 void
4415f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4416{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004417 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004418 term_T *term;
4419 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004420 int max_height = 0;
4421 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004422 stat_T st;
4423 FILE *fd;
4424 VTermPos pos;
4425 VTermScreen *screen;
4426 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004427 VTermState *state;
4428 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004429
4430 if (check_restricted() || check_secure())
4431 return;
4432 if (buf == NULL)
4433 return;
4434 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004435 if (term->tl_vterm == NULL)
4436 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004437 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004438 return;
4439 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004440
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004441 if (argvars[2].v_type != VAR_UNKNOWN)
4442 {
4443 dict_T *d;
4444
4445 if (argvars[2].v_type != VAR_DICT)
4446 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004447 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004448 return;
4449 }
4450 d = argvars[2].vval.v_dict;
4451 if (d != NULL)
4452 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004453 max_height = dict_get_number(d, (char_u *)"rows");
4454 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004455 }
4456 }
4457
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004458 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004459 if (fname == NULL)
4460 return;
4461 if (mch_stat((char *)fname, &st) >= 0)
4462 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004463 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004464 return;
4465 }
4466
Bram Moolenaard96ff162018-02-18 22:13:29 +01004467 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4468 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004469 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004470 return;
4471 }
4472
4473 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4474
4475 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004476 state = vterm_obtain_state(term->tl_vterm);
4477 vterm_state_get_cursorpos(state, &cursor_pos);
4478
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004479 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4480 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004481 {
4482 int repeat = 0;
4483
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004484 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4485 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004486 {
4487 VTermScreenCell cell;
4488 int same_attr;
4489 int same_chars = TRUE;
4490 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004491 int is_cursor_pos = (pos.col == cursor_pos.col
4492 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004493
4494 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4495 vim_memset(&cell, 0, sizeof(cell));
4496
4497 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4498 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004499 int c = cell.chars[i];
4500 int pc = prev_cell.chars[i];
4501
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004502 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01004503 if (i == 0)
4504 {
4505 c = (c == NUL) ? ' ' : c;
4506 pc = (pc == NUL) ? ' ' : pc;
4507 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004508 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004509 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004510 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004511 break;
4512 }
4513 same_attr = vtermAttr2hl(cell.attrs)
4514 == vtermAttr2hl(prev_cell.attrs)
4515 && same_color(&cell.fg, &prev_cell.fg)
4516 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004517 if (same_chars && cell.width == prev_cell.width && same_attr
4518 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004519 {
4520 ++repeat;
4521 }
4522 else
4523 {
4524 if (repeat > 0)
4525 {
4526 fprintf(fd, "@%d", repeat);
4527 repeat = 0;
4528 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004529 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004530
4531 if (cell.chars[0] == NUL)
4532 fputs(" ", fd);
4533 else
4534 {
4535 char_u charbuf[10];
4536 int len;
4537
4538 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4539 && cell.chars[i] != NUL; ++i)
4540 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004541 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004542 fwrite(charbuf, len, 1, fd);
4543 }
4544 }
4545
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004546 // When only the characters differ we don't write anything, the
4547 // following "|", "@" or NL will indicate using the same
4548 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004549 if (cell.width != prev_cell.width || !same_attr)
4550 {
4551 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004552 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004553 else
4554 fputs("+", fd);
4555
4556 if (same_attr)
4557 {
4558 fputs("&", fd);
4559 }
4560 else
4561 {
4562 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4563 if (same_color(&cell.fg, &prev_cell.fg))
4564 fputs("&", fd);
4565 else
4566 {
4567 fputs("#", fd);
4568 dump_term_color(fd, &cell.fg);
4569 }
4570 if (same_color(&cell.bg, &prev_cell.bg))
4571 fputs("&", fd);
4572 else
4573 {
4574 fputs("#", fd);
4575 dump_term_color(fd, &cell.bg);
4576 }
4577 }
4578 }
4579
4580 prev_cell = cell;
4581 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004582
4583 if (cell.width == 2)
4584 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004585 }
4586 if (repeat > 0)
4587 fprintf(fd, "@%d", repeat);
4588 fputs("\n", fd);
4589 }
4590
4591 fclose(fd);
4592}
4593
4594/*
4595 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4596 */
4597 static void
4598dump_is_corrupt(garray_T *gap)
4599{
4600 ga_concat(gap, (char_u *)"CORRUPT");
4601}
4602
4603 static void
4604append_cell(garray_T *gap, cellattr_T *cell)
4605{
4606 if (ga_grow(gap, 1) == OK)
4607 {
4608 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4609 ++gap->ga_len;
4610 }
4611}
4612
4613/*
4614 * Read the dump file from "fd" and append lines to the current buffer.
4615 * Return the cell width of the longest line.
4616 */
4617 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004618read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004619{
4620 int c;
4621 garray_T ga_text;
4622 garray_T ga_cell;
4623 char_u *prev_char = NULL;
4624 int attr = 0;
4625 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004626 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004627 term_T *term = curbuf->b_term;
4628 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004629 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004630
4631 ga_init2(&ga_text, 1, 90);
4632 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4633 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004634 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004635 cursor_pos->row = -1;
4636 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004637
4638 c = fgetc(fd);
4639 for (;;)
4640 {
4641 if (c == EOF)
4642 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004643 if (c == '\r')
4644 {
4645 // DOS line endings? Ignore.
4646 c = fgetc(fd);
4647 }
4648 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004649 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004650 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004651 if (ga_text.ga_data == NULL)
4652 dump_is_corrupt(&ga_text);
4653 if (ga_grow(&term->tl_scrollback, 1) == OK)
4654 {
4655 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4656 + term->tl_scrollback.ga_len;
4657
4658 if (max_cells < ga_cell.ga_len)
4659 max_cells = ga_cell.ga_len;
4660 line->sb_cols = ga_cell.ga_len;
4661 line->sb_cells = ga_cell.ga_data;
4662 line->sb_fill_attr = term->tl_default_color;
4663 ++term->tl_scrollback.ga_len;
4664 ga_init(&ga_cell);
4665
4666 ga_append(&ga_text, NUL);
4667 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4668 ga_text.ga_len, FALSE);
4669 }
4670 else
4671 ga_clear(&ga_cell);
4672 ga_text.ga_len = 0;
4673
4674 c = fgetc(fd);
4675 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004676 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004677 {
4678 int prev_len = ga_text.ga_len;
4679
Bram Moolenaar9271d052018-02-25 21:39:46 +01004680 if (c == '>')
4681 {
4682 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004683 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004684 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4685 cursor_pos->col = ga_cell.ga_len;
4686 }
4687
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004688 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004689 c = fgetc(fd);
4690 if (c != EOF)
4691 ga_append(&ga_text, c);
4692 for (;;)
4693 {
4694 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004695 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004696 || c == EOF || c == '\n')
4697 break;
4698 ga_append(&ga_text, c);
4699 }
4700
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004701 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01004702 vim_free(prev_char);
4703 if (ga_text.ga_data != NULL)
4704 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4705 ga_text.ga_len - prev_len);
4706
Bram Moolenaar9271d052018-02-25 21:39:46 +01004707 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004708 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004709 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004710 }
4711 else if (c == '+' || c == '*')
4712 {
4713 int is_bg;
4714
4715 cell.width = c == '+' ? 1 : 2;
4716
4717 c = fgetc(fd);
4718 if (c == '&')
4719 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004720 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004721 c = fgetc(fd);
4722 }
4723 else if (isdigit(c))
4724 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004725 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01004726 attr = 0;
4727 while (isdigit(c))
4728 {
4729 attr = attr * 10 + (c - '0');
4730 c = fgetc(fd);
4731 }
4732 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004733
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004734 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004735 for (is_bg = 0; is_bg <= 1; ++is_bg)
4736 {
4737 if (c == '&')
4738 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004739 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004740 c = fgetc(fd);
4741 }
4742 else if (c == '#')
4743 {
4744 int red, green, blue, index = 0;
4745
4746 c = fgetc(fd);
4747 red = hex2nr(c);
4748 c = fgetc(fd);
4749 red = (red << 4) + hex2nr(c);
4750 c = fgetc(fd);
4751 green = hex2nr(c);
4752 c = fgetc(fd);
4753 green = (green << 4) + hex2nr(c);
4754 c = fgetc(fd);
4755 blue = hex2nr(c);
4756 c = fgetc(fd);
4757 blue = (blue << 4) + hex2nr(c);
4758 c = fgetc(fd);
4759 if (!isdigit(c))
4760 dump_is_corrupt(&ga_text);
4761 while (isdigit(c))
4762 {
4763 index = index * 10 + (c - '0');
4764 c = fgetc(fd);
4765 }
4766
4767 if (is_bg)
4768 {
4769 cell.bg.red = red;
4770 cell.bg.green = green;
4771 cell.bg.blue = blue;
4772 cell.bg.ansi_index = index;
4773 }
4774 else
4775 {
4776 cell.fg.red = red;
4777 cell.fg.green = green;
4778 cell.fg.blue = blue;
4779 cell.fg.ansi_index = index;
4780 }
4781 }
4782 else
4783 dump_is_corrupt(&ga_text);
4784 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004785 }
4786 else
4787 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004788 }
4789 else
4790 dump_is_corrupt(&ga_text);
4791
4792 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004793 if (cell.width == 2)
4794 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004795 }
4796 else if (c == '@')
4797 {
4798 if (prev_char == NULL)
4799 dump_is_corrupt(&ga_text);
4800 else
4801 {
4802 int count = 0;
4803
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004804 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01004805 for (;;)
4806 {
4807 c = fgetc(fd);
4808 if (!isdigit(c))
4809 break;
4810 count = count * 10 + (c - '0');
4811 }
4812
4813 while (count-- > 0)
4814 {
4815 ga_concat(&ga_text, prev_char);
4816 append_cell(&ga_cell, &cell);
4817 }
4818 }
4819 }
4820 else
4821 {
4822 dump_is_corrupt(&ga_text);
4823 c = fgetc(fd);
4824 }
4825 }
4826
4827 if (ga_text.ga_len > 0)
4828 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004829 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004830 dump_is_corrupt(&ga_text);
4831 ga_append(&ga_text, NUL);
4832 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4833 ga_text.ga_len, FALSE);
4834 }
4835
4836 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004837 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004838 vim_free(prev_char);
4839
4840 return max_cells;
4841}
4842
4843/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004844 * Return an allocated string with at least "text_width" "=" characters and
4845 * "fname" inserted in the middle.
4846 */
4847 static char_u *
4848get_separator(int text_width, char_u *fname)
4849{
4850 int width = MAX(text_width, curwin->w_width);
4851 char_u *textline;
4852 int fname_size;
4853 char_u *p = fname;
4854 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004855 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004856
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004857 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004858 if (textline == NULL)
4859 return NULL;
4860
4861 fname_size = vim_strsize(fname);
4862 if (fname_size < width - 8)
4863 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004864 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02004865 width = MAX(text_width, fname_size + 8);
4866 }
4867 else if (fname_size > width - 8)
4868 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004869 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02004870 p = gettail(fname);
4871 fname_size = vim_strsize(p);
4872 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004873 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02004874 while (fname_size > width - 8)
4875 {
4876 p += (*mb_ptr2len)(p);
4877 fname_size = vim_strsize(p);
4878 }
4879
4880 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4881 textline[i] = '=';
4882 textline[i++] = ' ';
4883
4884 STRCPY(textline + i, p);
4885 off = STRLEN(textline);
4886 textline[off] = ' ';
4887 for (i = 1; i < (width - fname_size) / 2; ++i)
4888 textline[off + i] = '=';
4889 textline[off + i] = NUL;
4890
4891 return textline;
4892}
4893
4894/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004895 * Common for "term_dumpdiff()" and "term_dumpload()".
4896 */
4897 static void
4898term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4899{
4900 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004901 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004902 char_u buf1[NUMBUFLEN];
4903 char_u buf2[NUMBUFLEN];
4904 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004905 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004906 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004907 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004908 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004909 char_u *textline = NULL;
4910
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004911 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004912 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004913 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004914 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004915 if (fname1 == NULL || (do_diff && fname2 == NULL))
4916 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004917 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004918 return;
4919 }
4920 fd1 = mch_fopen((char *)fname1, READBIN);
4921 if (fd1 == NULL)
4922 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004923 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004924 return;
4925 }
4926 if (do_diff)
4927 {
4928 fd2 = mch_fopen((char *)fname2, READBIN);
4929 if (fd2 == NULL)
4930 {
4931 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004932 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004933 return;
4934 }
4935 }
4936
4937 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004938 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4939 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4940 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4941 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4942 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004943
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004944 if (opt.jo_term_name == NULL)
4945 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004946 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004947
Bram Moolenaar51e14382019-05-25 20:21:28 +02004948 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004949 if (fname_tofree != NULL)
4950 {
4951 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4952 opt.jo_term_name = fname_tofree;
4953 }
4954 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004955
Bram Moolenaar87abab92019-06-03 21:14:59 +02004956 if (opt.jo_bufnr_buf != NULL)
4957 {
4958 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4959
4960 // With "bufnr" argument: enter the window with this buffer and make it
4961 // empty.
4962 if (wp == NULL)
4963 semsg(_(e_invarg2), "bufnr");
4964 else
4965 {
4966 buf = curbuf;
4967 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4968 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02004969 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02004970 redraw_later(NOT_VALID);
4971 }
4972 }
4973 else
4974 // Create a new terminal window.
4975 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4976
Bram Moolenaard96ff162018-02-18 22:13:29 +01004977 if (buf != NULL && buf->b_term != NULL)
4978 {
4979 int i;
4980 linenr_T bot_lnum;
4981 linenr_T lnum;
4982 term_T *term = buf->b_term;
4983 int width;
4984 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004985 VTermPos cursor_pos1;
4986 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004987
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004988 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004989
Bram Moolenaard96ff162018-02-18 22:13:29 +01004990 rettv->vval.v_number = buf->b_fnum;
4991
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004992 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01004993 width = read_dump_file(fd1, &cursor_pos1);
4994
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004995 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004996 if (cursor_pos1.row >= 0)
4997 {
4998 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4999 coladvance(cursor_pos1.col);
5000 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005001
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005002 // Delete the empty line that was in the empty buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005003 ml_delete(1, FALSE);
5004
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005005 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005006 if (!do_diff)
5007 goto theend;
5008
5009 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5010
Bram Moolenaar4a696342018-04-05 18:45:26 +02005011 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005012 if (textline == NULL)
5013 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005014 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5015 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5016 vim_free(textline);
5017
5018 textline = get_separator(width, fname2);
5019 if (textline == NULL)
5020 goto theend;
5021 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5022 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005023 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005024
5025 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005026 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005027 if (width2 > width)
5028 {
5029 vim_free(textline);
5030 textline = alloc(width2 + 1);
5031 if (textline == NULL)
5032 goto theend;
5033 width = width2;
5034 textline[width] = NUL;
5035 }
5036 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5037
5038 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5039 {
5040 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5041 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005042 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005043 for (i = 0; i < width; ++i)
5044 textline[i] = '-';
5045 }
5046 else
5047 {
5048 char_u *line1;
5049 char_u *line2;
5050 char_u *p1;
5051 char_u *p2;
5052 int col;
5053 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5054 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5055 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5056 ->sb_cells;
5057
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005058 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005059 line1 = vim_strsave(ml_get(lnum));
5060 if (line1 == NULL)
5061 break;
5062 p1 = line1;
5063
5064 line2 = ml_get(lnum + bot_lnum);
5065 p2 = line2;
5066 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5067 {
5068 int len1 = utfc_ptr2len(p1);
5069 int len2 = utfc_ptr2len(p2);
5070
5071 textline[col] = ' ';
5072 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005073 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005074 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005075 else if (lnum == cursor_pos1.row + 1
5076 && col == cursor_pos1.col
5077 && (cursor_pos1.row != cursor_pos2.row
5078 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005079 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005080 textline[col] = '>';
5081 else if (lnum == cursor_pos2.row + 1
5082 && col == cursor_pos2.col
5083 && (cursor_pos1.row != cursor_pos2.row
5084 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005085 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005086 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005087 else if (cellattr1 != NULL && cellattr2 != NULL)
5088 {
5089 if ((cellattr1 + col)->width
5090 != (cellattr2 + col)->width)
5091 textline[col] = 'w';
5092 else if (!same_color(&(cellattr1 + col)->fg,
5093 &(cellattr2 + col)->fg))
5094 textline[col] = 'f';
5095 else if (!same_color(&(cellattr1 + col)->bg,
5096 &(cellattr2 + col)->bg))
5097 textline[col] = 'b';
5098 else if (vtermAttr2hl((cellattr1 + col)->attrs)
5099 != vtermAttr2hl(((cellattr2 + col)->attrs)))
5100 textline[col] = 'a';
5101 }
5102 p1 += len1;
5103 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005104 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005105 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005106
5107 while (col < width)
5108 {
5109 if (*p1 == NUL && *p2 == NUL)
5110 textline[col] = '?';
5111 else if (*p1 == NUL)
5112 {
5113 textline[col] = '+';
5114 p2 += utfc_ptr2len(p2);
5115 }
5116 else
5117 {
5118 textline[col] = '-';
5119 p1 += utfc_ptr2len(p1);
5120 }
5121 ++col;
5122 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005123
5124 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005125 }
5126 if (add_empty_scrollback(term, &term->tl_default_color,
5127 term->tl_top_diff_rows) == OK)
5128 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5129 ++bot_lnum;
5130 }
5131
5132 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5133 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005134 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005135 for (i = 0; i < width; ++i)
5136 textline[i] = '+';
5137 if (add_empty_scrollback(term, &term->tl_default_color,
5138 term->tl_top_diff_rows) == OK)
5139 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5140 ++lnum;
5141 ++bot_lnum;
5142 }
5143
5144 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005145
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005146 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005147 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005148 }
5149
5150theend:
5151 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005152 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005153 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005154 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005155 fclose(fd2);
5156}
5157
5158/*
5159 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5160 * bottom files.
5161 * Return FAIL when this is not possible.
5162 */
5163 int
5164term_swap_diff()
5165{
5166 term_T *term = curbuf->b_term;
5167 linenr_T line_count;
5168 linenr_T top_rows;
5169 linenr_T bot_rows;
5170 linenr_T bot_start;
5171 linenr_T lnum;
5172 char_u *p;
5173 sb_line_T *sb_line;
5174
5175 if (term == NULL
5176 || !term_is_finished(curbuf)
5177 || term->tl_top_diff_rows == 0
5178 || term->tl_scrollback.ga_len == 0)
5179 return FAIL;
5180
5181 line_count = curbuf->b_ml.ml_line_count;
5182 top_rows = term->tl_top_diff_rows;
5183 bot_rows = term->tl_bot_diff_rows;
5184 bot_start = line_count - bot_rows;
5185 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5186
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005187 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005188 for (lnum = 1; lnum <= top_rows; ++lnum)
5189 {
5190 p = vim_strsave(ml_get(1));
5191 if (p == NULL)
5192 return OK;
5193 ml_append(bot_start, p, 0, FALSE);
5194 ml_delete(1, FALSE);
5195 vim_free(p);
5196 }
5197
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005198 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005199 for (lnum = 1; lnum <= bot_rows; ++lnum)
5200 {
5201 p = vim_strsave(ml_get(bot_start + lnum));
5202 if (p == NULL)
5203 return OK;
5204 ml_delete(bot_start + lnum, FALSE);
5205 ml_append(lnum - 1, p, 0, FALSE);
5206 vim_free(p);
5207 }
5208
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005209 // move top title to bottom
5210 p = vim_strsave(ml_get(bot_rows + 1));
5211 if (p == NULL)
5212 return OK;
5213 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5214 ml_delete(bot_rows + 1, FALSE);
5215 vim_free(p);
5216
5217 // move bottom title to top
5218 p = vim_strsave(ml_get(line_count - top_rows));
5219 if (p == NULL)
5220 return OK;
5221 ml_delete(line_count - top_rows, FALSE);
5222 ml_append(bot_rows, p, 0, FALSE);
5223 vim_free(p);
5224
Bram Moolenaard96ff162018-02-18 22:13:29 +01005225 if (top_rows == bot_rows)
5226 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005227 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005228 for (lnum = 0; lnum < top_rows; ++lnum)
5229 {
5230 sb_line_T temp;
5231
5232 temp = *(sb_line + lnum);
5233 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5234 *(sb_line + bot_start + lnum) = temp;
5235 }
5236 }
5237 else
5238 {
5239 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005240 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005241
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005242 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005243 if (temp != NULL)
5244 {
5245 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5246 mch_memmove(term->tl_scrollback.ga_data,
5247 temp + bot_start,
5248 sizeof(sb_line_T) * bot_rows);
5249 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5250 temp + top_rows,
5251 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5252 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5253 + line_count - top_rows,
5254 temp,
5255 sizeof(sb_line_T) * top_rows);
5256 vim_free(temp);
5257 }
5258 }
5259
5260 term->tl_top_diff_rows = bot_rows;
5261 term->tl_bot_diff_rows = top_rows;
5262
5263 update_screen(NOT_VALID);
5264 return OK;
5265}
5266
5267/*
5268 * "term_dumpdiff(filename, filename, options)" function
5269 */
5270 void
5271f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5272{
5273 term_load_dump(argvars, rettv, TRUE);
5274}
5275
5276/*
5277 * "term_dumpload(filename, options)" function
5278 */
5279 void
5280f_term_dumpload(typval_T *argvars, typval_T *rettv)
5281{
5282 term_load_dump(argvars, rettv, FALSE);
5283}
5284
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005285/*
5286 * "term_getaltscreen(buf)" function
5287 */
5288 void
5289f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5290{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005291 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005292
5293 if (buf == NULL)
5294 return;
5295 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5296}
5297
5298/*
5299 * "term_getattr(attr, name)" function
5300 */
5301 void
5302f_term_getattr(typval_T *argvars, typval_T *rettv)
5303{
5304 int attr;
5305 size_t i;
5306 char_u *name;
5307
5308 static struct {
5309 char *name;
5310 int attr;
5311 } attrs[] = {
5312 {"bold", HL_BOLD},
5313 {"italic", HL_ITALIC},
5314 {"underline", HL_UNDERLINE},
5315 {"strike", HL_STRIKETHROUGH},
5316 {"reverse", HL_INVERSE},
5317 };
5318
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005319 attr = tv_get_number(&argvars[0]);
5320 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005321 if (name == NULL)
5322 return;
5323
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005324 if (attr > HL_ALL)
5325 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005326 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5327 if (STRCMP(name, attrs[i].name) == 0)
5328 {
5329 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5330 break;
5331 }
5332}
5333
5334/*
5335 * "term_getcursor(buf)" function
5336 */
5337 void
5338f_term_getcursor(typval_T *argvars, typval_T *rettv)
5339{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005340 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005341 term_T *term;
5342 list_T *l;
5343 dict_T *d;
5344
5345 if (rettv_list_alloc(rettv) == FAIL)
5346 return;
5347 if (buf == NULL)
5348 return;
5349 term = buf->b_term;
5350
5351 l = rettv->vval.v_list;
5352 list_append_number(l, term->tl_cursor_pos.row + 1);
5353 list_append_number(l, term->tl_cursor_pos.col + 1);
5354
5355 d = dict_alloc();
5356 if (d != NULL)
5357 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005358 dict_add_number(d, "visible", term->tl_cursor_visible);
5359 dict_add_number(d, "blink", blink_state_is_inverted()
5360 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5361 dict_add_number(d, "shape", term->tl_cursor_shape);
5362 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005363 list_append_dict(l, d);
5364 }
5365}
5366
5367/*
5368 * "term_getjob(buf)" function
5369 */
5370 void
5371f_term_getjob(typval_T *argvars, typval_T *rettv)
5372{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005373 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005374
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005375 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005376 {
5377 rettv->v_type = VAR_SPECIAL;
5378 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005379 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005380 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005381
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005382 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005383 rettv->vval.v_job = buf->b_term->tl_job;
5384 if (rettv->vval.v_job != NULL)
5385 ++rettv->vval.v_job->jv_refcount;
5386}
5387
5388 static int
5389get_row_number(typval_T *tv, term_T *term)
5390{
5391 if (tv->v_type == VAR_STRING
5392 && tv->vval.v_string != NULL
5393 && STRCMP(tv->vval.v_string, ".") == 0)
5394 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005395 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005396}
5397
5398/*
5399 * "term_getline(buf, row)" function
5400 */
5401 void
5402f_term_getline(typval_T *argvars, typval_T *rettv)
5403{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005404 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005405 term_T *term;
5406 int row;
5407
5408 rettv->v_type = VAR_STRING;
5409 if (buf == NULL)
5410 return;
5411 term = buf->b_term;
5412 row = get_row_number(&argvars[1], term);
5413
5414 if (term->tl_vterm == NULL)
5415 {
5416 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5417
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005418 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005419 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5420 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5421 }
5422 else
5423 {
5424 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5425 VTermRect rect;
5426 int len;
5427 char_u *p;
5428
5429 if (row < 0 || row >= term->tl_rows)
5430 return;
5431 len = term->tl_cols * MB_MAXBYTES + 1;
5432 p = alloc(len);
5433 if (p == NULL)
5434 return;
5435 rettv->vval.v_string = p;
5436
5437 rect.start_col = 0;
5438 rect.end_col = term->tl_cols;
5439 rect.start_row = row;
5440 rect.end_row = row + 1;
5441 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5442 }
5443}
5444
5445/*
5446 * "term_getscrolled(buf)" function
5447 */
5448 void
5449f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5450{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005451 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005452
5453 if (buf == NULL)
5454 return;
5455 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5456}
5457
5458/*
5459 * "term_getsize(buf)" function
5460 */
5461 void
5462f_term_getsize(typval_T *argvars, typval_T *rettv)
5463{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005464 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005465 list_T *l;
5466
5467 if (rettv_list_alloc(rettv) == FAIL)
5468 return;
5469 if (buf == NULL)
5470 return;
5471
5472 l = rettv->vval.v_list;
5473 list_append_number(l, buf->b_term->tl_rows);
5474 list_append_number(l, buf->b_term->tl_cols);
5475}
5476
5477/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005478 * "term_setsize(buf, rows, cols)" function
5479 */
5480 void
5481f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5482{
5483 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5484 term_T *term;
5485 varnumber_T rows, cols;
5486
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005487 if (buf == NULL)
5488 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005489 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005490 return;
5491 }
5492 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005493 return;
5494 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005495 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005496 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005497 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005498 cols = cols <= 0 ? term->tl_cols : cols;
5499 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005500 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02005501
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005502 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02005503 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5504 term_report_winsize(term, term->tl_rows, term->tl_cols);
5505}
5506
5507/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005508 * "term_getstatus(buf)" function
5509 */
5510 void
5511f_term_getstatus(typval_T *argvars, typval_T *rettv)
5512{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005513 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005514 term_T *term;
5515 char_u val[100];
5516
5517 rettv->v_type = VAR_STRING;
5518 if (buf == NULL)
5519 return;
5520 term = buf->b_term;
5521
5522 if (term_job_running(term))
5523 STRCPY(val, "running");
5524 else
5525 STRCPY(val, "finished");
5526 if (term->tl_normal_mode)
5527 STRCAT(val, ",normal");
5528 rettv->vval.v_string = vim_strsave(val);
5529}
5530
5531/*
5532 * "term_gettitle(buf)" function
5533 */
5534 void
5535f_term_gettitle(typval_T *argvars, typval_T *rettv)
5536{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005537 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005538
5539 rettv->v_type = VAR_STRING;
5540 if (buf == NULL)
5541 return;
5542
5543 if (buf->b_term->tl_title != NULL)
5544 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5545}
5546
5547/*
5548 * "term_gettty(buf)" function
5549 */
5550 void
5551f_term_gettty(typval_T *argvars, typval_T *rettv)
5552{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005553 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005554 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005555 int num = 0;
5556
5557 rettv->v_type = VAR_STRING;
5558 if (buf == NULL)
5559 return;
5560 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005561 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005562
5563 switch (num)
5564 {
5565 case 0:
5566 if (buf->b_term->tl_job != NULL)
5567 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005568 break;
5569 case 1:
5570 if (buf->b_term->tl_job != NULL)
5571 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005572 break;
5573 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005574 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005575 return;
5576 }
5577 if (p != NULL)
5578 rettv->vval.v_string = vim_strsave(p);
5579}
5580
5581/*
5582 * "term_list()" function
5583 */
5584 void
5585f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5586{
5587 term_T *tp;
5588 list_T *l;
5589
5590 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5591 return;
5592
5593 l = rettv->vval.v_list;
5594 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5595 if (tp != NULL && tp->tl_buffer != NULL)
5596 if (list_append_number(l,
5597 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5598 return;
5599}
5600
5601/*
5602 * "term_scrape(buf, row)" function
5603 */
5604 void
5605f_term_scrape(typval_T *argvars, typval_T *rettv)
5606{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005607 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005608 VTermScreen *screen = NULL;
5609 VTermPos pos;
5610 list_T *l;
5611 term_T *term;
5612 char_u *p;
5613 sb_line_T *line;
5614
5615 if (rettv_list_alloc(rettv) == FAIL)
5616 return;
5617 if (buf == NULL)
5618 return;
5619 term = buf->b_term;
5620
5621 l = rettv->vval.v_list;
5622 pos.row = get_row_number(&argvars[1], term);
5623
5624 if (term->tl_vterm != NULL)
5625 {
5626 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005627 if (screen == NULL) // can't really happen
5628 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005629 p = NULL;
5630 line = NULL;
5631 }
5632 else
5633 {
5634 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5635
5636 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5637 return;
5638 p = ml_get_buf(buf, lnum + 1, FALSE);
5639 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5640 }
5641
5642 for (pos.col = 0; pos.col < term->tl_cols; )
5643 {
5644 dict_T *dcell;
5645 int width;
5646 VTermScreenCellAttrs attrs;
5647 VTermColor fg, bg;
5648 char_u rgb[8];
5649 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5650 int off = 0;
5651 int i;
5652
5653 if (screen == NULL)
5654 {
5655 cellattr_T *cellattr;
5656 int len;
5657
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005658 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005659 if (pos.col >= line->sb_cols)
5660 break;
5661 cellattr = line->sb_cells + pos.col;
5662 width = cellattr->width;
5663 attrs = cellattr->attrs;
5664 fg = cellattr->fg;
5665 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005666 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005667 mch_memmove(mbs, p, len);
5668 mbs[len] = NUL;
5669 p += len;
5670 }
5671 else
5672 {
5673 VTermScreenCell cell;
5674 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5675 break;
5676 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5677 {
5678 if (cell.chars[i] == 0)
5679 break;
5680 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5681 }
5682 mbs[off] = NUL;
5683 width = cell.width;
5684 attrs = cell.attrs;
5685 fg = cell.fg;
5686 bg = cell.bg;
5687 }
5688 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005689 if (dcell == NULL)
5690 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005691 list_append_dict(l, dcell);
5692
Bram Moolenaare0be1672018-07-08 16:50:37 +02005693 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005694
5695 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5696 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005697 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005698 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5699 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005700 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005701
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005702 dict_add_number(dcell, "attr", cell2attr(NULL, attrs, fg, bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02005703 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005704
5705 ++pos.col;
5706 if (width == 2)
5707 ++pos.col;
5708 }
5709}
5710
5711/*
5712 * "term_sendkeys(buf, keys)" function
5713 */
5714 void
5715f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5716{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005717 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005718 char_u *msg;
5719 term_T *term;
5720
5721 rettv->v_type = VAR_UNKNOWN;
5722 if (buf == NULL)
5723 return;
5724
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005725 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005726 if (msg == NULL)
5727 return;
5728 term = buf->b_term;
5729 if (term->tl_vterm == NULL)
5730 return;
5731
5732 while (*msg != NUL)
5733 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005734 int c;
5735
5736 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5737 {
5738 c = TO_SPECIAL(msg[1], msg[2]);
5739 msg += 3;
5740 }
5741 else
5742 {
5743 c = PTR2CHAR(msg);
5744 msg += MB_CPTR2LEN(msg);
5745 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005746 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005747 }
5748}
5749
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005750#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5751/*
5752 * "term_getansicolors(buf)" function
5753 */
5754 void
5755f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5756{
5757 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5758 term_T *term;
5759 VTermState *state;
5760 VTermColor color;
5761 char_u hexbuf[10];
5762 int index;
5763 list_T *list;
5764
5765 if (rettv_list_alloc(rettv) == FAIL)
5766 return;
5767
5768 if (buf == NULL)
5769 return;
5770 term = buf->b_term;
5771 if (term->tl_vterm == NULL)
5772 return;
5773
5774 list = rettv->vval.v_list;
5775 state = vterm_obtain_state(term->tl_vterm);
5776 for (index = 0; index < 16; index++)
5777 {
5778 vterm_state_get_palette_color(state, index, &color);
5779 sprintf((char *)hexbuf, "#%02x%02x%02x",
5780 color.red, color.green, color.blue);
5781 if (list_append_string(list, hexbuf, 7) == FAIL)
5782 return;
5783 }
5784}
5785
5786/*
5787 * "term_setansicolors(buf, list)" function
5788 */
5789 void
5790f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5791{
5792 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5793 term_T *term;
5794
5795 if (buf == NULL)
5796 return;
5797 term = buf->b_term;
5798 if (term->tl_vterm == NULL)
5799 return;
5800
5801 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5802 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005803 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005804 return;
5805 }
5806
5807 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005808 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005809}
5810#endif
5811
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005812/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005813 * "term_setapi(buf, api)" function
5814 */
5815 void
5816f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5817{
5818 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5819 term_T *term;
5820 char_u *api;
5821
5822 if (buf == NULL)
5823 return;
5824 term = buf->b_term;
5825 vim_free(term->tl_api);
5826 api = tv_get_string_chk(&argvars[1]);
5827 if (api != NULL)
5828 term->tl_api = vim_strsave(api);
5829 else
5830 term->tl_api = NULL;
5831}
5832
5833/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005834 * "term_setrestore(buf, command)" function
5835 */
5836 void
5837f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5838{
5839#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005840 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005841 term_T *term;
5842 char_u *cmd;
5843
5844 if (buf == NULL)
5845 return;
5846 term = buf->b_term;
5847 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005848 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005849 if (cmd != NULL)
5850 term->tl_command = vim_strsave(cmd);
5851 else
5852 term->tl_command = NULL;
5853#endif
5854}
5855
5856/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005857 * "term_setkill(buf, how)" function
5858 */
5859 void
5860f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5861{
5862 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5863 term_T *term;
5864 char_u *how;
5865
5866 if (buf == NULL)
5867 return;
5868 term = buf->b_term;
5869 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005870 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005871 if (how != NULL)
5872 term->tl_kill = vim_strsave(how);
5873 else
5874 term->tl_kill = NULL;
5875}
5876
5877/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005878 * "term_start(command, options)" function
5879 */
5880 void
5881f_term_start(typval_T *argvars, typval_T *rettv)
5882{
5883 jobopt_T opt;
5884 buf_T *buf;
5885
5886 init_job_options(&opt);
5887 if (argvars[1].v_type != VAR_UNKNOWN
5888 && get_job_options(&argvars[1], &opt,
5889 JO_TIMEOUT_ALL + JO_STOPONEXIT
5890 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5891 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5892 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5893 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005894 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005895 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005896 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005897 return;
5898
Bram Moolenaar13568252018-03-16 20:46:58 +01005899 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005900
5901 if (buf != NULL && buf->b_term != NULL)
5902 rettv->vval.v_number = buf->b_fnum;
5903}
5904
5905/*
5906 * "term_wait" function
5907 */
5908 void
5909f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5910{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005911 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005912
5913 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005914 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005915 if (buf->b_term->tl_job == NULL)
5916 {
5917 ch_log(NULL, "term_wait(): no job to wait for");
5918 return;
5919 }
5920 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005921 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005922 return;
5923
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005924 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01005925 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005926 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5927 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005928 // The job is dead, keep reading channel I/O until the channel is
5929 // closed. buf->b_term may become NULL if the terminal was closed while
5930 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005931 ch_log(NULL, "term_wait(): waiting for channel to close");
5932 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5933 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005934 term_flush_messages();
5935
Bram Moolenaard45aa552018-05-21 22:50:29 +02005936 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005937 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005938 // If the terminal is closed when the channel is closed the
5939 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01005940 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005941 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005942
5943 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005944 }
5945 else
5946 {
5947 long wait = 10L;
5948
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005949 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005950
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005951 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005952 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005953 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005954 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005955
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005956 // Flushing messages on channels is hopefully sufficient.
5957 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005958 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005959 }
5960}
5961
5962/*
5963 * Called when a channel has sent all the lines to a terminal.
5964 * Send a CTRL-D to mark the end of the text.
5965 */
5966 void
5967term_send_eof(channel_T *ch)
5968{
5969 term_T *term;
5970
5971 for (term = first_term; term != NULL; term = term->tl_next)
5972 if (term->tl_job == ch->ch_job)
5973 {
5974 if (term->tl_eof_chars != NULL)
5975 {
5976 channel_send(ch, PART_IN, term->tl_eof_chars,
5977 (int)STRLEN(term->tl_eof_chars), NULL);
5978 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5979 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005980# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005981 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005982 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005983 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5984# endif
5985 }
5986}
5987
Bram Moolenaar113e1072019-01-20 15:30:40 +01005988#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005989 job_T *
5990term_getjob(term_T *term)
5991{
5992 return term != NULL ? term->tl_job : NULL;
5993}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005994#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005995
Bram Moolenaar4f974752019-02-17 17:44:42 +01005996# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005997
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005998///////////////////////////////////////
5999// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006000#ifdef PROTO
6001typedef int COORD;
6002typedef int DWORD;
6003typedef int HANDLE;
6004typedef int *DWORD_PTR;
6005typedef int HPCON;
6006typedef int HRESULT;
6007typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006008typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006009typedef int PSIZE_T;
6010typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006011typedef int BOOL;
6012# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006013#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006014
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006015HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6016HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6017HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006018BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6019BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6020void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006021
6022 static int
6023dyn_conpty_init(int verbose)
6024{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006025 static HMODULE hKerneldll = NULL;
6026 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006027 static struct
6028 {
6029 char *name;
6030 FARPROC *ptr;
6031 } conpty_entry[] =
6032 {
6033 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6034 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6035 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6036 {"InitializeProcThreadAttributeList",
6037 (FARPROC*)&pInitializeProcThreadAttributeList},
6038 {"UpdateProcThreadAttribute",
6039 (FARPROC*)&pUpdateProcThreadAttribute},
6040 {"DeleteProcThreadAttributeList",
6041 (FARPROC*)&pDeleteProcThreadAttributeList},
6042 {NULL, NULL}
6043 };
6044
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006045 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006046 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006047 if (verbose)
6048 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006049 return FAIL;
6050 }
6051
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006052 // No need to initialize twice.
6053 if (hKerneldll)
6054 return OK;
6055
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006056 hKerneldll = vimLoadLib("kernel32.dll");
6057 for (i = 0; conpty_entry[i].name != NULL
6058 && conpty_entry[i].ptr != NULL; ++i)
6059 {
6060 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6061 conpty_entry[i].name)) == NULL)
6062 {
6063 if (verbose)
6064 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006065 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006066 return FAIL;
6067 }
6068 }
6069
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006070 return OK;
6071}
6072
6073 static int
6074conpty_term_and_job_init(
6075 term_T *term,
6076 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006077 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006078 jobopt_T *opt,
6079 jobopt_T *orig_opt)
6080{
6081 WCHAR *cmd_wchar = NULL;
6082 WCHAR *cmd_wchar_copy = NULL;
6083 WCHAR *cwd_wchar = NULL;
6084 WCHAR *env_wchar = NULL;
6085 channel_T *channel = NULL;
6086 job_T *job = NULL;
6087 HANDLE jo = NULL;
6088 garray_T ga_cmd, ga_env;
6089 char_u *cmd = NULL;
6090 HRESULT hr;
6091 COORD consize;
6092 SIZE_T breq;
6093 PROCESS_INFORMATION proc_info;
6094 HANDLE i_theirs = NULL;
6095 HANDLE o_theirs = NULL;
6096 HANDLE i_ours = NULL;
6097 HANDLE o_ours = NULL;
6098
6099 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6100 ga_init2(&ga_env, (int)sizeof(char*), 20);
6101
6102 if (argvar->v_type == VAR_STRING)
6103 {
6104 cmd = argvar->vval.v_string;
6105 }
6106 else if (argvar->v_type == VAR_LIST)
6107 {
6108 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6109 goto failed;
6110 cmd = ga_cmd.ga_data;
6111 }
6112 if (cmd == NULL || *cmd == NUL)
6113 {
6114 emsg(_(e_invarg));
6115 goto failed;
6116 }
6117
6118 term->tl_arg0_cmd = vim_strsave(cmd);
6119
6120 cmd_wchar = enc_to_utf16(cmd, NULL);
6121
6122 if (cmd_wchar != NULL)
6123 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006124 // Request by CreateProcessW
6125 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006126 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006127 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6128 }
6129
6130 ga_clear(&ga_cmd);
6131 if (cmd_wchar == NULL)
6132 goto failed;
6133 if (opt->jo_cwd != NULL)
6134 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6135
6136 win32_build_env(opt->jo_env, &ga_env, TRUE);
6137 env_wchar = ga_env.ga_data;
6138
6139 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6140 goto failed;
6141 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6142 goto failed;
6143
6144 consize.X = term->tl_cols;
6145 consize.Y = term->tl_rows;
6146 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6147 &term->tl_conpty);
6148 if (FAILED(hr))
6149 goto failed;
6150
6151 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6152
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006153 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006154 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006155 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006156 if (!term->tl_siex.lpAttributeList)
6157 goto failed;
6158 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6159 0, &breq))
6160 goto failed;
6161 if (!pUpdateProcThreadAttribute(
6162 term->tl_siex.lpAttributeList, 0,
6163 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6164 sizeof(HPCON), NULL, NULL))
6165 goto failed;
6166
6167 channel = add_channel();
6168 if (channel == NULL)
6169 goto failed;
6170
6171 job = job_alloc();
6172 if (job == NULL)
6173 goto failed;
6174 if (argvar->v_type == VAR_STRING)
6175 {
6176 int argc;
6177
6178 build_argv_from_string(cmd, &job->jv_argv, &argc);
6179 }
6180 else
6181 {
6182 int argc;
6183
6184 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6185 }
6186
6187 if (opt->jo_set & JO_IN_BUF)
6188 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6189
6190 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6191 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
6192 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
6193 | CREATE_DEFAULT_ERROR_MODE,
6194 env_wchar, cwd_wchar,
6195 &term->tl_siex.StartupInfo, &proc_info))
6196 goto failed;
6197
6198 CloseHandle(i_theirs);
6199 CloseHandle(o_theirs);
6200
6201 channel_set_pipes(channel,
6202 (sock_T)i_ours,
6203 (sock_T)o_ours,
6204 (sock_T)o_ours);
6205
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006206 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006207 channel->ch_write_text_mode = TRUE;
6208
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006209 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006210 channel->ch_anonymous_pipe = TRUE;
6211
6212 jo = CreateJobObject(NULL, NULL);
6213 if (jo == NULL)
6214 goto failed;
6215
6216 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6217 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006218 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006219 CloseHandle(jo);
6220 jo = NULL;
6221 }
6222
6223 ResumeThread(proc_info.hThread);
6224 CloseHandle(proc_info.hThread);
6225
6226 vim_free(cmd_wchar);
6227 vim_free(cmd_wchar_copy);
6228 vim_free(cwd_wchar);
6229 vim_free(env_wchar);
6230
6231 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6232 goto failed;
6233
6234#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6235 if (opt->jo_set2 & JO2_ANSI_COLORS)
6236 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6237 else
6238 init_vterm_ansi_colors(term->tl_vterm);
6239#endif
6240
6241 channel_set_job(channel, job, opt);
6242 job_set_options(job, opt);
6243
6244 job->jv_channel = channel;
6245 job->jv_proc_info = proc_info;
6246 job->jv_job_object = jo;
6247 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006248 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006249 ++job->jv_refcount;
6250 term->tl_job = job;
6251
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006252 // Redirecting stdout and stderr doesn't work at the job level. Instead
6253 // open the file here and handle it in. opt->jo_io was changed in
6254 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006255 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6256 {
6257 char_u *fname = opt->jo_io_name[PART_OUT];
6258
6259 ch_log(channel, "Opening output file %s", fname);
6260 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6261 if (term->tl_out_fd == NULL)
6262 semsg(_(e_notopen), fname);
6263 }
6264
6265 return OK;
6266
6267failed:
6268 ga_clear(&ga_cmd);
6269 ga_clear(&ga_env);
6270 vim_free(cmd_wchar);
6271 vim_free(cmd_wchar_copy);
6272 vim_free(cwd_wchar);
6273 if (channel != NULL)
6274 channel_clear(channel);
6275 if (job != NULL)
6276 {
6277 job->jv_channel = NULL;
6278 job_cleanup(job);
6279 }
6280 term->tl_job = NULL;
6281 if (jo != NULL)
6282 CloseHandle(jo);
6283
6284 if (term->tl_siex.lpAttributeList != NULL)
6285 {
6286 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6287 vim_free(term->tl_siex.lpAttributeList);
6288 }
6289 term->tl_siex.lpAttributeList = NULL;
6290 if (o_theirs != NULL)
6291 CloseHandle(o_theirs);
6292 if (o_ours != NULL)
6293 CloseHandle(o_ours);
6294 if (i_ours != NULL)
6295 CloseHandle(i_ours);
6296 if (i_theirs != NULL)
6297 CloseHandle(i_theirs);
6298 if (term->tl_conpty != NULL)
6299 pClosePseudoConsole(term->tl_conpty);
6300 term->tl_conpty = NULL;
6301 return FAIL;
6302}
6303
6304 static void
6305conpty_term_report_winsize(term_T *term, int rows, int cols)
6306{
6307 COORD consize;
6308
6309 consize.X = cols;
6310 consize.Y = rows;
6311 pResizePseudoConsole(term->tl_conpty, consize);
6312}
6313
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006314 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006315term_free_conpty(term_T *term)
6316{
6317 if (term->tl_siex.lpAttributeList != NULL)
6318 {
6319 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6320 vim_free(term->tl_siex.lpAttributeList);
6321 }
6322 term->tl_siex.lpAttributeList = NULL;
6323 if (term->tl_conpty != NULL)
6324 pClosePseudoConsole(term->tl_conpty);
6325 term->tl_conpty = NULL;
6326}
6327
6328 int
6329use_conpty(void)
6330{
6331 return has_conpty;
6332}
6333
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006334# ifndef PROTO
6335
6336#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6337#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006338#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006339
6340void* (*winpty_config_new)(UINT64, void*);
6341void* (*winpty_open)(void*, void*);
6342void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6343BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6344void (*winpty_config_set_mouse_mode)(void*, int);
6345void (*winpty_config_set_initial_size)(void*, int, int);
6346LPCWSTR (*winpty_conin_name)(void*);
6347LPCWSTR (*winpty_conout_name)(void*);
6348LPCWSTR (*winpty_conerr_name)(void*);
6349void (*winpty_free)(void*);
6350void (*winpty_config_free)(void*);
6351void (*winpty_spawn_config_free)(void*);
6352void (*winpty_error_free)(void*);
6353LPCWSTR (*winpty_error_msg)(void*);
6354BOOL (*winpty_set_size)(void*, int, int, void*);
6355HANDLE (*winpty_agent_process)(void*);
6356
6357#define WINPTY_DLL "winpty.dll"
6358
6359static HINSTANCE hWinPtyDLL = NULL;
6360# endif
6361
6362 static int
6363dyn_winpty_init(int verbose)
6364{
6365 int i;
6366 static struct
6367 {
6368 char *name;
6369 FARPROC *ptr;
6370 } winpty_entry[] =
6371 {
6372 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6373 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6374 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6375 {"winpty_config_set_mouse_mode",
6376 (FARPROC*)&winpty_config_set_mouse_mode},
6377 {"winpty_config_set_initial_size",
6378 (FARPROC*)&winpty_config_set_initial_size},
6379 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6380 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6381 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6382 {"winpty_free", (FARPROC*)&winpty_free},
6383 {"winpty_open", (FARPROC*)&winpty_open},
6384 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6385 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6386 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6387 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6388 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6389 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6390 {NULL, NULL}
6391 };
6392
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006393 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006394 if (hWinPtyDLL)
6395 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006396 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6397 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006398 if (*p_winptydll != NUL)
6399 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6400 if (!hWinPtyDLL)
6401 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6402 if (!hWinPtyDLL)
6403 {
6404 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006405 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006406 : (char_u *)WINPTY_DLL);
6407 return FAIL;
6408 }
6409 for (i = 0; winpty_entry[i].name != NULL
6410 && winpty_entry[i].ptr != NULL; ++i)
6411 {
6412 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6413 winpty_entry[i].name)) == NULL)
6414 {
6415 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006416 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006417 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006418 return FAIL;
6419 }
6420 }
6421
6422 return OK;
6423}
6424
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006425 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006426winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006427 term_T *term,
6428 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006429 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006430 jobopt_T *opt,
6431 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006432{
6433 WCHAR *cmd_wchar = NULL;
6434 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006435 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006436 channel_T *channel = NULL;
6437 job_T *job = NULL;
6438 DWORD error;
6439 HANDLE jo = NULL;
6440 HANDLE child_process_handle;
6441 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006442 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006443 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006444 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006445 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006446
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006447 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6448 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006449
6450 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006451 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006452 cmd = argvar->vval.v_string;
6453 }
6454 else if (argvar->v_type == VAR_LIST)
6455 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006456 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006457 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006458 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006459 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006460 if (cmd == NULL || *cmd == NUL)
6461 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006462 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006463 goto failed;
6464 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006465
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006466 term->tl_arg0_cmd = vim_strsave(cmd);
6467
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006468 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006469 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006470 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006471 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006472 if (opt->jo_cwd != NULL)
6473 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006474
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006475 win32_build_env(opt->jo_env, &ga_env, TRUE);
6476 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006477
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006478 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6479 if (term->tl_winpty_config == NULL)
6480 goto failed;
6481
6482 winpty_config_set_mouse_mode(term->tl_winpty_config,
6483 WINPTY_MOUSE_MODE_FORCE);
6484 winpty_config_set_initial_size(term->tl_winpty_config,
6485 term->tl_cols, term->tl_rows);
6486 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6487 if (term->tl_winpty == NULL)
6488 goto failed;
6489
6490 spawn_config = winpty_spawn_config_new(
6491 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6492 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6493 NULL,
6494 cmd_wchar,
6495 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006496 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006497 &winpty_err);
6498 if (spawn_config == NULL)
6499 goto failed;
6500
6501 channel = add_channel();
6502 if (channel == NULL)
6503 goto failed;
6504
6505 job = job_alloc();
6506 if (job == NULL)
6507 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006508 if (argvar->v_type == VAR_STRING)
6509 {
6510 int argc;
6511
6512 build_argv_from_string(cmd, &job->jv_argv, &argc);
6513 }
6514 else
6515 {
6516 int argc;
6517
6518 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6519 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006520
6521 if (opt->jo_set & JO_IN_BUF)
6522 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6523
6524 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6525 &child_thread_handle, &error, &winpty_err))
6526 goto failed;
6527
6528 channel_set_pipes(channel,
6529 (sock_T)CreateFileW(
6530 winpty_conin_name(term->tl_winpty),
6531 GENERIC_WRITE, 0, NULL,
6532 OPEN_EXISTING, 0, NULL),
6533 (sock_T)CreateFileW(
6534 winpty_conout_name(term->tl_winpty),
6535 GENERIC_READ, 0, NULL,
6536 OPEN_EXISTING, 0, NULL),
6537 (sock_T)CreateFileW(
6538 winpty_conerr_name(term->tl_winpty),
6539 GENERIC_READ, 0, NULL,
6540 OPEN_EXISTING, 0, NULL));
6541
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006542 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006543 channel->ch_write_text_mode = TRUE;
6544
6545 jo = CreateJobObject(NULL, NULL);
6546 if (jo == NULL)
6547 goto failed;
6548
6549 if (!AssignProcessToJobObject(jo, child_process_handle))
6550 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006551 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006552 CloseHandle(jo);
6553 jo = NULL;
6554 }
6555
6556 winpty_spawn_config_free(spawn_config);
6557 vim_free(cmd_wchar);
6558 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006559 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006560
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006561 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6562 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006563
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006564#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6565 if (opt->jo_set2 & JO2_ANSI_COLORS)
6566 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6567 else
6568 init_vterm_ansi_colors(term->tl_vterm);
6569#endif
6570
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006571 channel_set_job(channel, job, opt);
6572 job_set_options(job, opt);
6573
6574 job->jv_channel = channel;
6575 job->jv_proc_info.hProcess = child_process_handle;
6576 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6577 job->jv_job_object = jo;
6578 job->jv_status = JOB_STARTED;
6579 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006580 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006581 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006582 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006583 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006584 ++job->jv_refcount;
6585 term->tl_job = job;
6586
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006587 // Redirecting stdout and stderr doesn't work at the job level. Instead
6588 // open the file here and handle it in. opt->jo_io was changed in
6589 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006590 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6591 {
6592 char_u *fname = opt->jo_io_name[PART_OUT];
6593
6594 ch_log(channel, "Opening output file %s", fname);
6595 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6596 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006597 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006598 }
6599
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006600 return OK;
6601
6602failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006603 ga_clear(&ga_cmd);
6604 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006605 vim_free(cmd_wchar);
6606 vim_free(cwd_wchar);
6607 if (spawn_config != NULL)
6608 winpty_spawn_config_free(spawn_config);
6609 if (channel != NULL)
6610 channel_clear(channel);
6611 if (job != NULL)
6612 {
6613 job->jv_channel = NULL;
6614 job_cleanup(job);
6615 }
6616 term->tl_job = NULL;
6617 if (jo != NULL)
6618 CloseHandle(jo);
6619 if (term->tl_winpty != NULL)
6620 winpty_free(term->tl_winpty);
6621 term->tl_winpty = NULL;
6622 if (term->tl_winpty_config != NULL)
6623 winpty_config_free(term->tl_winpty_config);
6624 term->tl_winpty_config = NULL;
6625 if (winpty_err != NULL)
6626 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006627 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006628 (short_u *)winpty_error_msg(winpty_err), NULL);
6629
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006630 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006631 winpty_error_free(winpty_err);
6632 }
6633 return FAIL;
6634}
6635
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006636/*
6637 * Create a new terminal of "rows" by "cols" cells.
6638 * Store a reference in "term".
6639 * Return OK or FAIL.
6640 */
6641 static int
6642term_and_job_init(
6643 term_T *term,
6644 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01006645 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006646 jobopt_T *opt,
6647 jobopt_T *orig_opt)
6648{
6649 int use_winpty = FALSE;
6650 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006651 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006652
6653 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6654 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6655
6656 if (!has_winpty && !has_conpty)
6657 // If neither is available give the errors for winpty, since when
6658 // conpty is not available it can't be installed either.
6659 return dyn_winpty_init(TRUE);
6660
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006661 if (opt->jo_tty_type != NUL)
6662 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006663
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006664 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006665 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006666 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006667 use_conpty = TRUE;
6668 else if (has_winpty)
6669 use_winpty = TRUE;
6670 // else: error
6671 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006672 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006673 {
6674 if (has_winpty)
6675 use_winpty = TRUE;
6676 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006677 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006678 {
6679 if (has_conpty)
6680 use_conpty = TRUE;
6681 else
6682 return dyn_conpty_init(TRUE);
6683 }
6684
6685 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006686 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006687
6688 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006689 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006690
6691 // error
6692 return dyn_winpty_init(TRUE);
6693}
6694
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006695 static int
6696create_pty_only(term_T *term, jobopt_T *options)
6697{
6698 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6699 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6700 char in_name[80], out_name[80];
6701 channel_T *channel = NULL;
6702
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006703 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6704 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006705
6706 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6707 GetCurrentProcessId(),
6708 curbuf->b_fnum);
6709 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6710 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6711 PIPE_UNLIMITED_INSTANCES,
6712 0, 0, NMPWAIT_NOWAIT, NULL);
6713 if (hPipeIn == INVALID_HANDLE_VALUE)
6714 goto failed;
6715
6716 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6717 GetCurrentProcessId(),
6718 curbuf->b_fnum);
6719 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6720 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6721 PIPE_UNLIMITED_INSTANCES,
6722 0, 0, 0, NULL);
6723 if (hPipeOut == INVALID_HANDLE_VALUE)
6724 goto failed;
6725
6726 ConnectNamedPipe(hPipeIn, NULL);
6727 ConnectNamedPipe(hPipeOut, NULL);
6728
6729 term->tl_job = job_alloc();
6730 if (term->tl_job == NULL)
6731 goto failed;
6732 ++term->tl_job->jv_refcount;
6733
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006734 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006735 term->tl_job->jv_status = JOB_FINISHED;
6736
6737 channel = add_channel();
6738 if (channel == NULL)
6739 goto failed;
6740 term->tl_job->jv_channel = channel;
6741 channel->ch_keep_open = TRUE;
6742 channel->ch_named_pipe = TRUE;
6743
6744 channel_set_pipes(channel,
6745 (sock_T)hPipeIn,
6746 (sock_T)hPipeOut,
6747 (sock_T)hPipeOut);
6748 channel_set_job(channel, term->tl_job, options);
6749 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6750 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6751
6752 return OK;
6753
6754failed:
6755 if (hPipeIn != NULL)
6756 CloseHandle(hPipeIn);
6757 if (hPipeOut != NULL)
6758 CloseHandle(hPipeOut);
6759 return FAIL;
6760}
6761
6762/*
6763 * Free the terminal emulator part of "term".
6764 */
6765 static void
6766term_free_vterm(term_T *term)
6767{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006768 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006769 if (term->tl_winpty != NULL)
6770 winpty_free(term->tl_winpty);
6771 term->tl_winpty = NULL;
6772 if (term->tl_winpty_config != NULL)
6773 winpty_config_free(term->tl_winpty_config);
6774 term->tl_winpty_config = NULL;
6775 if (term->tl_vterm != NULL)
6776 vterm_free(term->tl_vterm);
6777 term->tl_vterm = NULL;
6778}
6779
6780/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006781 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006782 */
6783 static void
6784term_report_winsize(term_T *term, int rows, int cols)
6785{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006786 if (term->tl_conpty)
6787 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006788 if (term->tl_winpty)
6789 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6790}
6791
6792 int
6793terminal_enabled(void)
6794{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006795 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006796}
6797
6798# else
6799
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006800///////////////////////////////////////
6801// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006802
6803/*
6804 * Create a new terminal of "rows" by "cols" cells.
6805 * Start job for "cmd".
6806 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006807 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006808 * Return OK or FAIL.
6809 */
6810 static int
6811term_and_job_init(
6812 term_T *term,
6813 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006814 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006815 jobopt_T *opt,
6816 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006817{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006818 term->tl_arg0_cmd = NULL;
6819
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006820 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6821 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006822
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006823#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6824 if (opt->jo_set2 & JO2_ANSI_COLORS)
6825 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6826 else
6827 init_vterm_ansi_colors(term->tl_vterm);
6828#endif
6829
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006830 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01006831 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006832 if (term->tl_job != NULL)
6833 ++term->tl_job->jv_refcount;
6834
6835 return term->tl_job != NULL
6836 && term->tl_job->jv_channel != NULL
6837 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6838}
6839
6840 static int
6841create_pty_only(term_T *term, jobopt_T *opt)
6842{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006843 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6844 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006845
6846 term->tl_job = job_alloc();
6847 if (term->tl_job == NULL)
6848 return FAIL;
6849 ++term->tl_job->jv_refcount;
6850
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006851 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006852 term->tl_job->jv_status = JOB_FINISHED;
6853
6854 return mch_create_pty_channel(term->tl_job, opt);
6855}
6856
6857/*
6858 * Free the terminal emulator part of "term".
6859 */
6860 static void
6861term_free_vterm(term_T *term)
6862{
6863 if (term->tl_vterm != NULL)
6864 vterm_free(term->tl_vterm);
6865 term->tl_vterm = NULL;
6866}
6867
6868/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006869 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006870 */
6871 static void
6872term_report_winsize(term_T *term, int rows, int cols)
6873{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006874 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006875 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6876 {
6877 int fd = -1;
6878 int part;
6879
6880 for (part = PART_OUT; part < PART_COUNT; ++part)
6881 {
6882 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006883 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006884 break;
6885 }
6886 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6887 mch_signal_job(term->tl_job, (char_u *)"winch");
6888 }
6889}
6890
6891# endif
6892
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006893#endif // FEAT_TERMINAL