blob: 342275e40ca6ef52360261bad9f810da98b76e66 [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 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100569 vim_free(curbuf->b_sfname);
570 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200571 curbuf->b_fname = curbuf->b_ffname;
572
573 if (opt->jo_term_opencmd != NULL)
574 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
575
576 if (opt->jo_eof_chars != NULL)
577 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
578
579 set_string_option_direct((char_u *)"buftype", -1,
580 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200581 // Avoid that 'buftype' is reset when this buffer is entered.
582 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200583
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100584 // Mark the buffer as not modifiable. It can only be made modifiable after
585 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200586 curbuf->b_p_ma = FALSE;
587
588 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100589#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200590 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
591#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200592 setup_job_options(opt, term->tl_rows, term->tl_cols);
593
Bram Moolenaar13568252018-03-16 20:46:58 +0100594 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100595 return curbuf;
596
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100597#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100598 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100599 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100600 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100601 else if (argvar->v_type == VAR_STRING)
602 {
603 char_u *cmd = argvar->vval.v_string;
604
605 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
606 term->tl_command = vim_strsave(cmd);
607 }
608 else if (argvar->v_type == VAR_LIST
609 && argvar->vval.v_list != NULL
610 && argvar->vval.v_list->lv_len > 0)
611 {
612 garray_T ga;
613 listitem_T *item;
614
615 ga_init2(&ga, 1, 100);
616 for (item = argvar->vval.v_list->lv_first;
617 item != NULL; item = item->li_next)
618 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100619 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100620 char_u *p;
621
622 if (s == NULL)
623 break;
624 p = vim_strsave_fnameescape(s, FALSE);
625 if (p == NULL)
626 break;
627 ga_concat(&ga, p);
628 vim_free(p);
629 ga_append(&ga, ' ');
630 }
631 if (item == NULL)
632 {
633 ga_append(&ga, NUL);
634 term->tl_command = ga.ga_data;
635 }
636 else
637 ga_clear(&ga);
638 }
639#endif
640
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100641 if (opt->jo_term_kill != NULL)
642 {
643 char_u *p = skiptowhite(opt->jo_term_kill);
644
645 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
646 }
647
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200648 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100649 {
650 char_u *p = skiptowhite(opt->jo_term_api);
651
652 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
653 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200654 else
655 term->tl_api = vim_strsave((char_u *)"Tapi_");
656
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100657 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100658 if (argv == NULL
659 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200660 && argvar->vval.v_string != NULL
661 && STRCMP(argvar->vval.v_string, "NONE") == 0)
662 res = create_pty_only(term, opt);
663 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200664 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200665
666 newbuf = curbuf;
667 if (res == OK)
668 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100669 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200670 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
671 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100672#ifdef FEAT_GUI
673 if (term->tl_system)
674 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100675 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100676 term->tl_toprow = msg_row + 1;
677 term->tl_dirty_row_end = 0;
678 }
679#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200680
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100681 // Make sure we don't get stuck on sending keys to the job, it leads to
682 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200683 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
684
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200685 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200686 {
687 --curbuf->b_nwindows;
688 curbuf = old_curbuf;
689 curwin->w_buffer = curbuf;
690 ++curbuf->b_nwindows;
691 }
692 }
693 else
694 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100695 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200696 return NULL;
697 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100698
Bram Moolenaar13568252018-03-16 20:46:58 +0100699 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200700 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
701 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200702 return newbuf;
703}
704
705/*
706 * ":terminal": open a terminal window and execute a job in it.
707 */
708 void
709ex_terminal(exarg_T *eap)
710{
711 typval_T argvar[2];
712 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100713 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200714 char_u *cmd;
715 char_u *tofree = NULL;
716
717 init_job_options(&opt);
718
719 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100720 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200721 {
722 char_u *p, *ep;
723
724 cmd += 2;
725 p = skiptowhite(cmd);
726 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200727 if (ep != NULL)
728 {
729 if (ep < p)
730 p = ep;
731 else
732 ep = NULL;
733 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200734
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200735# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
736 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
737 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200738 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200739 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100740 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200741 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200742 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200743 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200744 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200745 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200746 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200747 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100748 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100749 else if (OPTARG_HAS("shell"))
750 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200751 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100752 {
753 opt.jo_set2 |= JO2_TERM_KILL;
754 opt.jo_term_kill = ep + 1;
755 p = skiptowhite(cmd);
756 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200757 else if (OPTARG_HAS("api"))
758 {
759 opt.jo_set2 |= JO2_TERM_API;
760 if (ep != NULL)
761 {
762 opt.jo_term_api = ep + 1;
763 p = skiptowhite(cmd);
764 }
765 else
766 opt.jo_term_api = NULL;
767 }
768 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200769 {
770 opt.jo_set2 |= JO2_TERM_ROWS;
771 opt.jo_term_rows = atoi((char *)ep + 1);
772 p = skiptowhite(cmd);
773 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200774 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200775 {
776 opt.jo_set2 |= JO2_TERM_COLS;
777 opt.jo_term_cols = atoi((char *)ep + 1);
778 p = skiptowhite(cmd);
779 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200780 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200781 {
782 char_u *buf = NULL;
783 char_u *keys;
784
Bram Moolenaar21109272020-01-30 16:27:20 +0100785 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200786 p = skiptowhite(cmd);
787 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200788 keys = replace_termcodes(ep + 1, &buf,
789 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200790 opt.jo_set2 |= JO2_EOF_CHARS;
791 opt.jo_eof_chars = vim_strsave(keys);
792 vim_free(buf);
793 *p = ' ';
794 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100795#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100796 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
797 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100798 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100799 int tty_type = NUL;
800
801 p = skiptowhite(cmd);
802 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
803 tty_type = 'w';
804 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
805 tty_type = 'c';
806 else
807 {
808 semsg(e_invargval, "type");
809 goto theend;
810 }
811 opt.jo_set2 |= JO2_TTY_TYPE;
812 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100813 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100814#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200815 else
816 {
817 if (*p)
818 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100819 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100820 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200821 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200822# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200823 cmd = skipwhite(p);
824 }
825 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100826 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100827 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200828 tofree = cmd = vim_strsave(p_sh);
829
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100830 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100831 if (opt.jo_term_finish == NUL)
832 opt.jo_term_finish = 'c';
833 }
834
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200835 if (eap->addr_count > 0)
836 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100837 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200838 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
839 opt.jo_io[PART_IN] = JIO_BUFFER;
840 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
841 opt.jo_in_top = eap->line1;
842 opt.jo_in_bot = eap->line2;
843 }
844
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100845 if (opt_shell && tofree == NULL)
846 {
847#ifdef UNIX
848 char **argv = NULL;
849 char_u *tofree1 = NULL;
850 char_u *tofree2 = NULL;
851
852 // :term ++shell command
853 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
854 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100855 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100856 vim_free(tofree1);
857 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100858 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100859#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100860# ifdef MSWIN
861 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
862 char_u *newcmd;
863
864 newcmd = alloc(cmdlen);
865 if (newcmd == NULL)
866 goto theend;
867 tofree = newcmd;
868 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
869 cmd = newcmd;
870# else
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100871 emsg(_("E279: Sorry, ++shell is not supported on this system"));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100872 goto theend;
873# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100874#endif
875 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100876 argvar[0].v_type = VAR_STRING;
877 argvar[0].vval.v_string = cmd;
878 argvar[1].v_type = VAR_UNKNOWN;
879 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100880
881theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100882 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200883 vim_free(opt.jo_eof_chars);
884}
885
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100886#if defined(FEAT_SESSION) || defined(PROTO)
887/*
888 * Write a :terminal command to the session file to restore the terminal in
889 * window "wp".
890 * Return FAIL if writing fails.
891 */
892 int
893term_write_session(FILE *fd, win_T *wp)
894{
895 term_T *term = wp->w_buffer->b_term;
896
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100897 // Create the terminal and run the command. This is not without
898 // risk, but let's assume the user only creates a session when this
899 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100900 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
901 term->tl_cols, term->tl_rows) < 0)
902 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100903#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100904 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
905 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100906#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100907 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
908 return FAIL;
909
910 return put_eol(fd);
911}
912
913/*
914 * Return TRUE if "buf" has a terminal that should be restored.
915 */
916 int
917term_should_restore(buf_T *buf)
918{
919 term_T *term = buf->b_term;
920
921 return term != NULL && (term->tl_command == NULL
922 || STRCMP(term->tl_command, "NONE") != 0);
923}
924#endif
925
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200926/*
927 * Free the scrollback buffer for "term".
928 */
929 static void
930free_scrollback(term_T *term)
931{
932 int i;
933
934 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
935 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
936 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100937 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
938 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
939 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200940}
941
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100942
943// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200944static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100945
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200946/*
947 * Free a terminal and everything it refers to.
948 * Kills the job if there is one.
949 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100950 * The actual terminal structure is freed later in free_unused_terminals(),
951 * because callbacks may wipe out a buffer while the terminal is still
952 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200953 */
954 void
955free_terminal(buf_T *buf)
956{
957 term_T *term = buf->b_term;
958 term_T *tp;
959
960 if (term == NULL)
961 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100962
963 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200964 if (first_term == term)
965 first_term = term->tl_next;
966 else
967 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
968 if (tp->tl_next == term)
969 {
970 tp->tl_next = term->tl_next;
971 break;
972 }
973
974 if (term->tl_job != NULL)
975 {
976 if (term->tl_job->jv_status != JOB_ENDED
977 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100978 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200979 job_stop(term->tl_job, NULL, "kill");
980 job_unref(term->tl_job);
981 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100982 term->tl_next = terminals_to_free;
983 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200984
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200985 buf->b_term = NULL;
986 if (in_terminal_loop == term)
987 in_terminal_loop = NULL;
988}
989
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100990 void
991free_unused_terminals()
992{
993 while (terminals_to_free != NULL)
994 {
995 term_T *term = terminals_to_free;
996
997 terminals_to_free = term->tl_next;
998
999 free_scrollback(term);
1000
1001 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001002 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001003 vim_free(term->tl_title);
1004#ifdef FEAT_SESSION
1005 vim_free(term->tl_command);
1006#endif
1007 vim_free(term->tl_kill);
1008 vim_free(term->tl_status_text);
1009 vim_free(term->tl_opencmd);
1010 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001011 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001012#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001013 if (term->tl_out_fd != NULL)
1014 fclose(term->tl_out_fd);
1015#endif
1016 vim_free(term->tl_cursor_color);
1017 vim_free(term);
1018 }
1019}
1020
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001021/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001022 * Get the part that is connected to the tty. Normally this is PART_IN, but
1023 * when writing buffer lines to the job it can be another. This makes it
1024 * possible to do "1,5term vim -".
1025 */
1026 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001027get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001028{
1029#ifdef UNIX
1030 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1031 int i;
1032
1033 for (i = 0; i < 3; ++i)
1034 {
1035 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1036
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001037 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001038 return parts[i];
1039 }
1040#endif
1041 return PART_IN;
1042}
1043
1044/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001045 * Write job output "msg[len]" to the vterm.
1046 */
1047 static void
1048term_write_job_output(term_T *term, char_u *msg, size_t len)
1049{
1050 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001051 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001052
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001053 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001054
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001055 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001056 if (prevlen != vterm_output_get_buffer_current(vterm))
1057 {
1058 char buf[KEY_BUF_LEN];
1059 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1060
1061 if (curlen > 0)
1062 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1063 (char_u *)buf, (int)curlen, NULL);
1064 }
1065
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001066 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001067 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1068}
1069
1070 static void
1071update_cursor(term_T *term, int redraw)
1072{
1073 if (term->tl_normal_mode)
1074 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001075#ifdef FEAT_GUI
1076 if (term->tl_system)
1077 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1078 term->tl_cursor_pos.col);
1079 else
1080#endif
1081 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001082 if (redraw)
1083 {
1084 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1085 cursor_on();
1086 out_flush();
1087#ifdef FEAT_GUI
1088 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001089 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001090 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001091 gui_mch_flush();
1092 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001093#endif
1094 }
1095}
1096
1097/*
1098 * Invoked when "msg" output from a job was received. Write it to the terminal
1099 * of "buffer".
1100 */
1101 void
1102write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1103{
1104 size_t len = STRLEN(msg);
1105 term_T *term = buffer->b_term;
1106
Bram Moolenaar4f974752019-02-17 17:44:42 +01001107#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001108 // Win32: Cannot redirect output of the job, intercept it here and write to
1109 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001110 if (term->tl_out_fd != NULL)
1111 {
1112 ch_log(channel, "Writing %d bytes to output file", (int)len);
1113 fwrite(msg, len, 1, term->tl_out_fd);
1114 return;
1115 }
1116#endif
1117
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001118 if (term->tl_vterm == NULL)
1119 {
1120 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1121 return;
1122 }
1123 ch_log(channel, "writing %d bytes to terminal", (int)len);
1124 term_write_job_output(term, msg, len);
1125
Bram Moolenaar13568252018-03-16 20:46:58 +01001126#ifdef FEAT_GUI
1127 if (term->tl_system)
1128 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001129 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001130 update_system_term(term);
1131 update_cursor(term, TRUE);
1132 }
1133 else
1134#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001135 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1136 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001137 if (!term->tl_normal_mode)
1138 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001139 // Don't use update_screen() when editing the command line, it gets
1140 // cleared.
1141 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001142 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001143 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001144 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001145 update_screen(VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001146 // update_screen() can be slow, check the terminal wasn't closed
1147 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001148 if (buffer == curbuf && curbuf->b_term != NULL)
1149 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001150 }
1151 else
1152 redraw_after_callback(TRUE);
1153 }
1154}
1155
1156/*
1157 * Send a mouse position and click to the vterm
1158 */
1159 static int
1160term_send_mouse(VTerm *vterm, int button, int pressed)
1161{
1162 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001163 int row = mouse_row - W_WINROW(curwin);
1164 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001165
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001166#ifdef FEAT_PROP_POPUP
1167 if (popup_is_popup(curwin))
1168 {
1169 row -= popup_top_extra(curwin);
1170 col -= popup_left_extra(curwin);
1171 }
1172#endif
1173 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001174 if (button != 0)
1175 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001176 return TRUE;
1177}
1178
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001179static int enter_mouse_col = -1;
1180static int enter_mouse_row = -1;
1181
1182/*
1183 * Handle a mouse click, drag or release.
1184 * Return TRUE when a mouse event is sent to the terminal.
1185 */
1186 static int
1187term_mouse_click(VTerm *vterm, int key)
1188{
1189#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001190 // For modeless selection mouse drag and release events are ignored, unless
1191 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001192 static int ignore_drag_release = TRUE;
1193 VTermMouseState mouse_state;
1194
1195 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1196 if (mouse_state.flags == 0)
1197 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001198 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001199 switch (key)
1200 {
1201 case K_LEFTDRAG:
1202 case K_LEFTRELEASE:
1203 case K_RIGHTDRAG:
1204 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001205 // Ignore drag and release events when the button-down wasn't
1206 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001207 if (ignore_drag_release)
1208 {
1209 int save_mouse_col, save_mouse_row;
1210
1211 if (enter_mouse_col < 0)
1212 break;
1213
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001214 // mouse click in the window gave us focus, handle that
1215 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001216 save_mouse_col = mouse_col;
1217 save_mouse_row = mouse_row;
1218 mouse_col = enter_mouse_col;
1219 mouse_row = enter_mouse_row;
1220 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1221 mouse_col = save_mouse_col;
1222 mouse_row = save_mouse_row;
1223 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001224 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001225 case K_LEFTMOUSE:
1226 case K_RIGHTMOUSE:
1227 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1228 ignore_drag_release = TRUE;
1229 else
1230 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001231 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001232 if (clip_star.available)
1233 {
1234 int button, is_click, is_drag;
1235
1236 button = get_mouse_button(KEY2TERMCAP1(key),
1237 &is_click, &is_drag);
1238 if (mouse_model_popup() && button == MOUSE_LEFT
1239 && (mod_mask & MOD_MASK_SHIFT))
1240 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001241 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001242 button = MOUSE_RIGHT;
1243 mod_mask &= ~MOD_MASK_SHIFT;
1244 }
1245 clip_modeless(button, is_click, is_drag);
1246 }
1247 break;
1248
1249 case K_MIDDLEMOUSE:
1250 if (clip_star.available)
1251 insert_reg('*', TRUE);
1252 break;
1253 }
1254 enter_mouse_col = -1;
1255 return FALSE;
1256 }
1257#endif
1258 enter_mouse_col = -1;
1259
1260 switch (key)
1261 {
1262 case K_LEFTMOUSE:
1263 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1264 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1265 case K_LEFTRELEASE:
1266 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1267 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1268 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1269 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1270 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1271 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1272 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1273 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1274 }
1275 return TRUE;
1276}
1277
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001278/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001279 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1280 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001281 * Return the number of bytes in "buf".
1282 */
1283 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001284term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001285{
1286 VTerm *vterm = term->tl_vterm;
1287 VTermKey key = VTERM_KEY_NONE;
1288 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001289 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001290
1291 switch (c)
1292 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001293 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001294
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001295 // don't use VTERM_KEY_BACKSPACE, it always
1296 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001297 case K_BS: c = term_backspace_char; break;
1298
1299 case ESC: key = VTERM_KEY_ESCAPE; break;
1300 case K_DEL: key = VTERM_KEY_DEL; break;
1301 case K_DOWN: key = VTERM_KEY_DOWN; break;
1302 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1303 key = VTERM_KEY_DOWN; break;
1304 case K_END: key = VTERM_KEY_END; break;
1305 case K_S_END: mod = VTERM_MOD_SHIFT;
1306 key = VTERM_KEY_END; break;
1307 case K_C_END: mod = VTERM_MOD_CTRL;
1308 key = VTERM_KEY_END; break;
1309 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1310 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1311 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1312 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1313 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1314 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1315 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1316 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1317 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1318 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1319 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1320 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1321 case K_HOME: key = VTERM_KEY_HOME; break;
1322 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1323 key = VTERM_KEY_HOME; break;
1324 case K_C_HOME: mod = VTERM_MOD_CTRL;
1325 key = VTERM_KEY_HOME; break;
1326 case K_INS: key = VTERM_KEY_INS; break;
1327 case K_K0: key = VTERM_KEY_KP_0; break;
1328 case K_K1: key = VTERM_KEY_KP_1; break;
1329 case K_K2: key = VTERM_KEY_KP_2; break;
1330 case K_K3: key = VTERM_KEY_KP_3; break;
1331 case K_K4: key = VTERM_KEY_KP_4; break;
1332 case K_K5: key = VTERM_KEY_KP_5; break;
1333 case K_K6: key = VTERM_KEY_KP_6; break;
1334 case K_K7: key = VTERM_KEY_KP_7; break;
1335 case K_K8: key = VTERM_KEY_KP_8; break;
1336 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001337 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001338 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001339 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001340 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001341 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1342 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001343 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1344 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001345 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1346 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001347 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1348 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1349 case K_LEFT: key = VTERM_KEY_LEFT; break;
1350 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1351 key = VTERM_KEY_LEFT; break;
1352 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1353 key = VTERM_KEY_LEFT; break;
1354 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1355 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1356 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1357 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1358 key = VTERM_KEY_RIGHT; break;
1359 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1360 key = VTERM_KEY_RIGHT; break;
1361 case K_UP: key = VTERM_KEY_UP; break;
1362 case K_S_UP: mod = VTERM_MOD_SHIFT;
1363 key = VTERM_KEY_UP; break;
1364 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001365 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1366 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001367
Bram Moolenaara42ad572017-11-16 13:08:04 +01001368 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1369 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001370 case K_MOUSELEFT: /* TODO */ return 0;
1371 case K_MOUSERIGHT: /* TODO */ return 0;
1372
1373 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001374 case K_LEFTMOUSE_NM:
1375 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001376 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001377 case K_LEFTRELEASE_NM:
1378 case K_MOUSEMOVE:
1379 case K_MIDDLEMOUSE:
1380 case K_MIDDLEDRAG:
1381 case K_MIDDLERELEASE:
1382 case K_RIGHTMOUSE:
1383 case K_RIGHTDRAG:
1384 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1385 return 0;
1386 other = TRUE;
1387 break;
1388
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001389 case K_X1MOUSE: /* TODO */ return 0;
1390 case K_X1DRAG: /* TODO */ return 0;
1391 case K_X1RELEASE: /* TODO */ return 0;
1392 case K_X2MOUSE: /* TODO */ return 0;
1393 case K_X2DRAG: /* TODO */ return 0;
1394 case K_X2RELEASE: /* TODO */ return 0;
1395
1396 case K_IGNORE: return 0;
1397 case K_NOP: return 0;
1398 case K_UNDO: return 0;
1399 case K_HELP: return 0;
1400 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1401 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1402 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1403 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1404 case K_SELECT: return 0;
1405#ifdef FEAT_GUI
1406 case K_VER_SCROLLBAR: return 0;
1407 case K_HOR_SCROLLBAR: return 0;
1408#endif
1409#ifdef FEAT_GUI_TABLINE
1410 case K_TABLINE: return 0;
1411 case K_TABMENU: return 0;
1412#endif
1413#ifdef FEAT_NETBEANS_INTG
1414 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1415#endif
1416#ifdef FEAT_DND
1417 case K_DROP: return 0;
1418#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001419 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001420 case K_PS: vterm_keyboard_start_paste(vterm);
1421 other = TRUE;
1422 break;
1423 case K_PE: vterm_keyboard_end_paste(vterm);
1424 other = TRUE;
1425 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001426 }
1427
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001428 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001429 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001430 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001431 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001432 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001433 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001434 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001435
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001436 /*
1437 * Convert special keys to vterm keys:
1438 * - Write keys to vterm: vterm_keyboard_key()
1439 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001440 */
1441 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001442 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001443 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001444 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001445 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001446 vterm_keyboard_unichar(vterm, c, mod);
1447
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001448 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001449 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1450}
1451
1452/*
1453 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001454 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001455 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001456 */
1457 static int
1458term_job_running_check(term_T *term, int check_job_status)
1459{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001460 // Also consider the job finished when the channel is closed, to avoid a
1461 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001462 if (term != NULL
1463 && term->tl_job != NULL
1464 && channel_is_open(term->tl_job->jv_channel))
1465 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001466 job_T *job = term->tl_job;
1467
1468 // Careful: Checking the job status may invoked callbacks, which close
1469 // the buffer and terminate "term". However, "job" will not be freed
1470 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001471 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001472 job_status(job);
1473 return (job->jv_status == JOB_STARTED
1474 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001475 }
1476 return FALSE;
1477}
1478
1479/*
1480 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001481 */
1482 int
1483term_job_running(term_T *term)
1484{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001485 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001486}
1487
1488/*
1489 * Return TRUE if "term" has an active channel and used ":term NONE".
1490 */
1491 int
1492term_none_open(term_T *term)
1493{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001494 // Also consider the job finished when the channel is closed, to avoid a
1495 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001496 return term != NULL
1497 && term->tl_job != NULL
1498 && channel_is_open(term->tl_job->jv_channel)
1499 && term->tl_job->jv_channel->ch_keep_open;
1500}
1501
1502/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001503 * Used when exiting: kill the job in "buf" if so desired.
1504 * Return OK when the job finished.
1505 * Return FAIL when the job is still running.
1506 */
1507 int
1508term_try_stop_job(buf_T *buf)
1509{
1510 int count;
1511 char *how = (char *)buf->b_term->tl_kill;
1512
1513#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1514 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1515 {
1516 char_u buff[DIALOG_MSG_SIZE];
1517 int ret;
1518
1519 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1520 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1521 if (ret == VIM_YES)
1522 how = "kill";
1523 else if (ret == VIM_CANCEL)
1524 return FAIL;
1525 }
1526#endif
1527 if (how == NULL || *how == NUL)
1528 return FAIL;
1529
1530 job_stop(buf->b_term->tl_job, NULL, how);
1531
Bram Moolenaar9172d232019-01-29 23:06:54 +01001532 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001533 for (count = 0; count < 100; ++count)
1534 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001535 job_T *job;
1536
1537 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001538 if (!buf_valid(buf)
1539 || buf->b_term == NULL
1540 || buf->b_term->tl_job == NULL)
1541 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001542 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001543
Bram Moolenaar9172d232019-01-29 23:06:54 +01001544 // Call job_status() to update jv_status. It may cause the job to be
1545 // cleaned up but it won't be freed.
1546 job_status(job);
1547 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001548 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001549
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001550 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001551 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001552 }
1553 return FAIL;
1554}
1555
1556/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001557 * Add the last line of the scrollback buffer to the buffer in the window.
1558 */
1559 static void
1560add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1561{
1562 buf_T *buf = term->tl_buffer;
1563 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1564 linenr_T lnum = buf->b_ml.ml_line_count;
1565
Bram Moolenaar4f974752019-02-17 17:44:42 +01001566#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001567 if (!enc_utf8 && enc_codepage > 0)
1568 {
1569 WCHAR *ret = NULL;
1570 int length = 0;
1571
1572 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1573 &ret, &length);
1574 if (ret != NULL)
1575 {
1576 WideCharToMultiByte_alloc(enc_codepage, 0,
1577 ret, length, (char **)&text, &len, 0, 0);
1578 vim_free(ret);
1579 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1580 vim_free(text);
1581 }
1582 }
1583 else
1584#endif
1585 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1586 if (empty)
1587 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001588 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001589 curbuf = buf;
1590 ml_delete(1, FALSE);
1591 curbuf = curwin->w_buffer;
1592 }
1593}
1594
1595 static void
1596cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1597{
1598 attr->width = cell->width;
1599 attr->attrs = cell->attrs;
1600 attr->fg = cell->fg;
1601 attr->bg = cell->bg;
1602}
1603
1604 static int
1605equal_celattr(cellattr_T *a, cellattr_T *b)
1606{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001607 // Comparing the colors should be sufficient.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001608 return a->fg.red == b->fg.red
1609 && a->fg.green == b->fg.green
1610 && a->fg.blue == b->fg.blue
1611 && a->bg.red == b->bg.red
1612 && a->bg.green == b->bg.green
1613 && a->bg.blue == b->bg.blue;
1614}
1615
Bram Moolenaard96ff162018-02-18 22:13:29 +01001616/*
1617 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1618 * line at this position. Otherwise at the end.
1619 */
1620 static int
1621add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1622{
1623 if (ga_grow(&term->tl_scrollback, 1) == OK)
1624 {
1625 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1626 + term->tl_scrollback.ga_len;
1627
1628 if (lnum > 0)
1629 {
1630 int i;
1631
1632 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1633 {
1634 *line = *(line - 1);
1635 --line;
1636 }
1637 }
1638 line->sb_cols = 0;
1639 line->sb_cells = NULL;
1640 line->sb_fill_attr = *fill_attr;
1641 ++term->tl_scrollback.ga_len;
1642 return OK;
1643 }
1644 return FALSE;
1645}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001646
1647/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001648 * Remove the terminal contents from the scrollback and the buffer.
1649 * Used before adding a new scrollback line or updating the buffer for lines
1650 * displayed in the terminal.
1651 */
1652 static void
1653cleanup_scrollback(term_T *term)
1654{
1655 sb_line_T *line;
1656 garray_T *gap;
1657
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001658 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001659 gap = &term->tl_scrollback;
1660 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1661 && gap->ga_len > 0)
1662 {
1663 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1664 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1665 vim_free(line->sb_cells);
1666 --gap->ga_len;
1667 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001668 curbuf = curwin->w_buffer;
1669 if (curbuf == term->tl_buffer)
1670 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001671}
1672
1673/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001674 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001675 */
1676 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001677update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001678{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001679 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001680 int len;
1681 int lines_skipped = 0;
1682 VTermPos pos;
1683 VTermScreenCell cell;
1684 cellattr_T fill_attr, new_fill_attr;
1685 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001686
1687 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1688 "Adding terminal window snapshot to buffer");
1689
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001690 // First remove the lines that were appended before, they might be
1691 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001692 cleanup_scrollback(term);
1693
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001694 screen = vterm_obtain_screen(term->tl_vterm);
1695 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001696 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1697 {
1698 len = 0;
1699 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1700 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1701 && cell.chars[0] != NUL)
1702 {
1703 len = pos.col + 1;
1704 new_fill_attr = term->tl_default_color;
1705 }
1706 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001707 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001708 cell2cellattr(&cell, &new_fill_attr);
1709
1710 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1711 ++lines_skipped;
1712 else
1713 {
1714 while (lines_skipped > 0)
1715 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001716 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001717 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001718 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001719 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001720 }
1721
1722 if (len == 0)
1723 p = NULL;
1724 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001725 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001726 if ((p != NULL || len == 0)
1727 && ga_grow(&term->tl_scrollback, 1) == OK)
1728 {
1729 garray_T ga;
1730 int width;
1731 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1732 + term->tl_scrollback.ga_len;
1733
1734 ga_init2(&ga, 1, 100);
1735 for (pos.col = 0; pos.col < len; pos.col += width)
1736 {
1737 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1738 {
1739 width = 1;
1740 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1741 if (ga_grow(&ga, 1) == OK)
1742 ga.ga_len += utf_char2bytes(' ',
1743 (char_u *)ga.ga_data + ga.ga_len);
1744 }
1745 else
1746 {
1747 width = cell.width;
1748
1749 cell2cellattr(&cell, &p[pos.col]);
1750
Bram Moolenaara79fd562018-12-20 20:47:32 +01001751 // Each character can be up to 6 bytes.
1752 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001753 {
1754 int i;
1755 int c;
1756
1757 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1758 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1759 (char_u *)ga.ga_data + ga.ga_len);
1760 }
1761 }
1762 }
1763 line->sb_cols = len;
1764 line->sb_cells = p;
1765 line->sb_fill_attr = new_fill_attr;
1766 fill_attr = new_fill_attr;
1767 ++term->tl_scrollback.ga_len;
1768
1769 if (ga_grow(&ga, 1) == FAIL)
1770 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1771 else
1772 {
1773 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1774 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1775 }
1776 ga_clear(&ga);
1777 }
1778 else
1779 vim_free(p);
1780 }
1781 }
1782
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001783 // Add trailing empty lines.
1784 for (pos.row = term->tl_scrollback.ga_len;
1785 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1786 ++pos.row)
1787 {
1788 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1789 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1790 }
1791
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001792 term->tl_dirty_snapshot = FALSE;
1793#ifdef FEAT_TIMERS
1794 term->tl_timer_set = FALSE;
1795#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001796}
1797
1798/*
1799 * If needed, add the current lines of the terminal to scrollback and to the
1800 * buffer. Called after the job has ended and when switching to
1801 * Terminal-Normal mode.
1802 * When "redraw" is TRUE redraw the windows that show the terminal.
1803 */
1804 static void
1805may_move_terminal_to_buffer(term_T *term, int redraw)
1806{
1807 win_T *wp;
1808
1809 if (term->tl_vterm == NULL)
1810 return;
1811
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001812 // Update the snapshot only if something changes or the buffer does not
1813 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001814 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1815 <= term->tl_scrollback_scrolled)
1816 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001817
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001818 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001819 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1820 &term->tl_default_color.fg, &term->tl_default_color.bg);
1821
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001822 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001823 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001825 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001826 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001827 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1828 wp->w_cursor.col = 0;
1829 wp->w_valid = 0;
1830 if (wp->w_cursor.lnum >= wp->w_height)
1831 {
1832 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001833
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001834 if (wp->w_topline < min_topline)
1835 wp->w_topline = min_topline;
1836 }
1837 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001838 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001839 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001840}
1841
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001842#if defined(FEAT_TIMERS) || defined(PROTO)
1843/*
1844 * Check if any terminal timer expired. If so, copy text from the terminal to
1845 * the buffer.
1846 * Return the time until the next timer will expire.
1847 */
1848 int
1849term_check_timers(int next_due_arg, proftime_T *now)
1850{
1851 term_T *term;
1852 int next_due = next_due_arg;
1853
1854 for (term = first_term; term != NULL; term = term->tl_next)
1855 {
1856 if (term->tl_timer_set && !term->tl_normal_mode)
1857 {
1858 long this_due = proftime_time_left(&term->tl_timer_due, now);
1859
1860 if (this_due <= 1)
1861 {
1862 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001863 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001864 }
1865 else if (next_due == -1 || next_due > this_due)
1866 next_due = this_due;
1867 }
1868 }
1869
1870 return next_due;
1871}
1872#endif
1873
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001874/*
1875 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1876 * otherwise end it.
1877 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001878 static void
1879set_terminal_mode(term_T *term, int normal_mode)
1880{
1881 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001882 if (!normal_mode)
1883 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001884 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001885 if (term->tl_buffer == curbuf)
1886 maketitle();
1887}
1888
1889/*
1890 * Called after the job if finished and Terminal mode is not active:
1891 * Move the vterm contents into the scrollback buffer and free the vterm.
1892 */
1893 static void
1894cleanup_vterm(term_T *term)
1895{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001896 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001897 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001898 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001899 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001900}
1901
1902/*
1903 * Switch from Terminal-Job mode to Terminal-Normal mode.
1904 * Suspends updating the terminal window.
1905 */
1906 static void
1907term_enter_normal_mode(void)
1908{
1909 term_T *term = curbuf->b_term;
1910
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001911 set_terminal_mode(term, TRUE);
1912
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001913 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001914 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001915
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001916 // Move the window cursor to the position of the cursor in the
1917 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001918 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1919 + term->tl_cursor_pos.row + 1;
1920 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001921 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1922 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001923
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001924 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001925 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1926}
1927
1928/*
1929 * Returns TRUE if the current window contains a terminal and we are in
1930 * Terminal-Normal mode.
1931 */
1932 int
1933term_in_normal_mode(void)
1934{
1935 term_T *term = curbuf->b_term;
1936
1937 return term != NULL && term->tl_normal_mode;
1938}
1939
1940/*
1941 * Switch from Terminal-Normal mode to Terminal-Job mode.
1942 * Restores updating the terminal window.
1943 */
1944 void
1945term_enter_job_mode()
1946{
1947 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001948
1949 set_terminal_mode(term, FALSE);
1950
1951 if (term->tl_channel_closed)
1952 cleanup_vterm(term);
1953 redraw_buf_and_status_later(curbuf, NOT_VALID);
1954}
1955
1956/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001957 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001958 * Note: while waiting a terminal may be closed and freed if the channel is
1959 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001960 */
1961 static int
1962term_vgetc()
1963{
1964 int c;
1965 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001966 int modify_other_keys =
1967 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001968
1969 State = TERMINAL;
1970 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001971#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001972 ctrl_break_was_pressed = FALSE;
1973#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001974 if (modify_other_keys)
1975 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001976 c = vgetc();
1977 got_int = FALSE;
1978 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001979 if (modify_other_keys)
1980 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001981 return c;
1982}
1983
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001984static int mouse_was_outside = FALSE;
1985
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001986/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001987 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001988 * Return FAIL when the key needs to be handled in Normal mode.
1989 * Return OK when the key was dropped or sent to the terminal.
1990 */
1991 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001992send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993{
1994 char msg[KEY_BUF_LEN];
1995 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001996 int dragging_outside = FALSE;
1997
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001998 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001999 switch (c)
2000 {
2001 case NUL:
2002 case K_ZERO:
2003 if (typed)
2004 stuffcharReadbuff(c);
2005 return FAIL;
2006
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002007 case K_TABLINE:
2008 stuffcharReadbuff(c);
2009 return FAIL;
2010
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002012 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002013 return FAIL;
2014
2015 case K_LEFTDRAG:
2016 case K_MIDDLEDRAG:
2017 case K_RIGHTDRAG:
2018 case K_X1DRAG:
2019 case K_X2DRAG:
2020 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002021 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022 case K_LEFTMOUSE:
2023 case K_LEFTMOUSE_NM:
2024 case K_LEFTRELEASE:
2025 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002026 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002027 case K_MIDDLEMOUSE:
2028 case K_MIDDLERELEASE:
2029 case K_RIGHTMOUSE:
2030 case K_RIGHTRELEASE:
2031 case K_X1MOUSE:
2032 case K_X1RELEASE:
2033 case K_X2MOUSE:
2034 case K_X2RELEASE:
2035
2036 case K_MOUSEUP:
2037 case K_MOUSEDOWN:
2038 case K_MOUSELEFT:
2039 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002040 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002041 int row = mouse_row;
2042 int col = mouse_col;
2043
2044#ifdef FEAT_PROP_POPUP
2045 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002046 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002047 row -= popup_top_extra(curwin);
2048 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002049 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002050#endif
2051 if (row < W_WINROW(curwin)
2052 || row >= (W_WINROW(curwin) + curwin->w_height)
2053 || col < curwin->w_wincol
2054 || col >= W_ENDCOL(curwin)
2055 || dragging_outside)
2056 {
2057 // click or scroll outside the current window or on status
2058 // line or vertical separator
2059 if (typed)
2060 {
2061 stuffcharReadbuff(c);
2062 mouse_was_outside = TRUE;
2063 }
2064 return FAIL;
2065 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002066 }
2067 }
2068 if (typed)
2069 mouse_was_outside = FALSE;
2070
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002071 // Convert the typed key to a sequence of bytes for the job.
2072 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002073 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002074 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002075 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2076 (char_u *)msg, (int)len, NULL);
2077
2078 return OK;
2079}
2080
2081 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002082position_cursor(win_T *wp, VTermPos *pos, int add_off UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002083{
2084 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2085 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002086#ifdef FEAT_PROP_POPUP
2087 if (add_off && popup_is_popup(curwin))
2088 {
2089 wp->w_wrow += popup_top_extra(curwin);
2090 wp->w_wcol += popup_left_extra(curwin);
2091 }
2092#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002093 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2094}
2095
2096/*
2097 * Handle CTRL-W "": send register contents to the job.
2098 */
2099 static void
2100term_paste_register(int prev_c UNUSED)
2101{
2102 int c;
2103 list_T *l;
2104 listitem_T *item;
2105 long reglen = 0;
2106 int type;
2107
2108#ifdef FEAT_CMDL_INFO
2109 if (add_to_showcmd(prev_c))
2110 if (add_to_showcmd('"'))
2111 out_flush();
2112#endif
2113 c = term_vgetc();
2114#ifdef FEAT_CMDL_INFO
2115 clear_showcmd();
2116#endif
2117 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002118 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002119 return;
2120
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002121 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002122 if (c == '=' && get_expr_register() != '=')
2123 return;
2124 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002125 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002126 return;
2127
2128 l = (list_T *)get_reg_contents(c, GREG_LIST);
2129 if (l != NULL)
2130 {
2131 type = get_reg_type(c, &reglen);
2132 for (item = l->lv_first; item != NULL; item = item->li_next)
2133 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002134 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002135#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002136 char_u *tmp = s;
2137
2138 if (!enc_utf8 && enc_codepage > 0)
2139 {
2140 WCHAR *ret = NULL;
2141 int length = 0;
2142
2143 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2144 (int)STRLEN(s), &ret, &length);
2145 if (ret != NULL)
2146 {
2147 WideCharToMultiByte_alloc(CP_UTF8, 0,
2148 ret, length, (char **)&s, &length, 0, 0);
2149 vim_free(ret);
2150 }
2151 }
2152#endif
2153 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2154 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002155#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002156 if (tmp != s)
2157 vim_free(s);
2158#endif
2159
2160 if (item->li_next != NULL || type == MLINE)
2161 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2162 (char_u *)"\r", 1, NULL);
2163 }
2164 list_free(l);
2165 }
2166}
2167
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002168/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002169 * Return TRUE when waiting for a character in the terminal, the cursor of the
2170 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002171 */
2172 int
2173terminal_is_active()
2174{
2175 return in_terminal_loop != NULL;
2176}
2177
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002178#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002179 cursorentry_T *
2180term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2181{
2182 term_T *term = in_terminal_loop;
2183 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002184 int id;
2185 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002186
2187 vim_memset(&entry, 0, sizeof(entry));
2188 entry.shape = entry.mshape =
2189 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2190 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2191 SHAPE_BLOCK;
2192 entry.percentage = 20;
2193 if (term->tl_cursor_blink)
2194 {
2195 entry.blinkwait = 700;
2196 entry.blinkon = 400;
2197 entry.blinkoff = 250;
2198 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002199
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002200 // The "Terminal" highlight group overrules the defaults.
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002201 id = syn_name2id((char_u *)"Terminal");
2202 if (id != 0)
2203 {
2204 syn_id2colors(id, &term_fg, &term_bg);
2205 *fg = term_bg;
2206 }
2207 else
2208 *fg = gui.back_pixel;
2209
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002210 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002211 {
2212 if (id != 0)
2213 *bg = term_fg;
2214 else
2215 *bg = gui.norm_pixel;
2216 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002217 else
2218 *bg = color_name2handle(term->tl_cursor_color);
2219 entry.name = "n";
2220 entry.used_for = SHAPE_CURSOR;
2221
2222 return &entry;
2223}
2224#endif
2225
Bram Moolenaard317b382018-02-08 22:33:31 +01002226 static void
2227may_output_cursor_props(void)
2228{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002229 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002230 || last_set_cursor_shape != desired_cursor_shape
2231 || last_set_cursor_blink != desired_cursor_blink)
2232 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002233 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002234 last_set_cursor_shape = desired_cursor_shape;
2235 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002236 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002237 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002238 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002239 ui_cursor_shape_forced(TRUE);
2240 else
2241 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2242 }
2243}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002244
Bram Moolenaard317b382018-02-08 22:33:31 +01002245/*
2246 * Set the cursor color and shape, if not last set to these.
2247 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002248 static void
2249may_set_cursor_props(term_T *term)
2250{
2251#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002252 // For the GUI the cursor properties are obtained with
2253 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002254 if (gui.in_use)
2255 return;
2256#endif
2257 if (in_terminal_loop == term)
2258 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002259 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002260 desired_cursor_shape = term->tl_cursor_shape;
2261 desired_cursor_blink = term->tl_cursor_blink;
2262 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002263 }
2264}
2265
Bram Moolenaard317b382018-02-08 22:33:31 +01002266/*
2267 * Reset the desired cursor properties and restore them when needed.
2268 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002269 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002270prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002271{
2272#ifdef FEAT_GUI
2273 if (gui.in_use)
2274 return;
2275#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002276 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002277 desired_cursor_shape = -1;
2278 desired_cursor_blink = -1;
2279 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002280}
2281
2282/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002283 * Returns TRUE if the current window contains a terminal and we are sending
2284 * keys to the job.
2285 * If "check_job_status" is TRUE update the job status.
2286 */
2287 static int
2288term_use_loop_check(int check_job_status)
2289{
2290 term_T *term = curbuf->b_term;
2291
2292 return term != NULL
2293 && !term->tl_normal_mode
2294 && term->tl_vterm != NULL
2295 && term_job_running_check(term, check_job_status);
2296}
2297
2298/*
2299 * Returns TRUE if the current window contains a terminal and we are sending
2300 * keys to the job.
2301 */
2302 int
2303term_use_loop(void)
2304{
2305 return term_use_loop_check(FALSE);
2306}
2307
2308/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002309 * Called when entering a window with the mouse. If this is a terminal window
2310 * we may want to change state.
2311 */
2312 void
2313term_win_entered()
2314{
2315 term_T *term = curbuf->b_term;
2316
2317 if (term != NULL)
2318 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002319 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002320 {
2321 reset_VIsual_and_resel();
2322 if (State & INSERT)
2323 stop_insert_mode = TRUE;
2324 }
2325 mouse_was_outside = FALSE;
2326 enter_mouse_col = mouse_col;
2327 enter_mouse_row = mouse_row;
2328 }
2329}
2330
2331/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002332 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2333 * Return the Ctrl-key value in that case.
2334 */
2335 static int
2336raw_c_to_ctrl(int c)
2337{
2338 if ((mod_mask & MOD_MASK_CTRL)
2339 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2340 return c & 0x1f;
2341 return c;
2342}
2343
2344/*
2345 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2346 * May set "mod_mask".
2347 */
2348 static int
2349ctrl_to_raw_c(int c)
2350{
2351 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2352 {
2353 mod_mask |= MOD_MASK_CTRL;
2354 return c + '@';
2355 }
2356 return c;
2357}
2358
2359/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002360 * Wait for input and send it to the job.
2361 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2362 * when there is no more typahead.
2363 * Return when the start of a CTRL-W command is typed or anything else that
2364 * should be handled as a Normal mode command.
2365 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2366 * the terminal was closed.
2367 */
2368 int
2369terminal_loop(int blocking)
2370{
2371 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002372 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002373 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002374 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002375#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002376 int tty_fd = curbuf->b_term->tl_job->jv_channel
2377 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002378#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002379 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002380
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002381 // Remember the terminal we are sending keys to. However, the terminal
2382 // might be closed while waiting for a character, e.g. typing "exit" in a
2383 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2384 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002385 in_terminal_loop = curbuf->b_term;
2386
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002387 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002388 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002389 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002390 if (termwinkey == Ctrl_W)
2391 termwinkey = 0;
2392 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002393 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002394 may_set_cursor_props(curbuf->b_term);
2395
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002396 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002397 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002398#ifdef FEAT_GUI
2399 if (!curbuf->b_term->tl_system)
2400#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002401 // TODO: skip screen update when handling a sequence of keys.
2402 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002403 while (must_redraw != 0)
2404 if (update_screen(0) == FAIL)
2405 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002406 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002407 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002408 break;
2409
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002410 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002411 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002412
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002413 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002414 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002415 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002416 // Job finished while waiting for a character. Push back the
2417 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002418 if (raw_c != K_IGNORE)
2419 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002420 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002421 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002422 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002423 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002424 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002425
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002426#ifdef UNIX
2427 /*
2428 * The shell or another program may change the tty settings. Getting
2429 * them for every typed character is a bit of overhead, but it's needed
2430 * for the first character typed, e.g. when Vim starts in a shell.
2431 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002432 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002433 {
2434 ttyinfo_T info;
2435
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002436 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002437 if (get_tty_info(tty_fd, &info) == OK)
2438 term_backspace_char = info.backspace;
2439 }
2440#endif
2441
Bram Moolenaar4f974752019-02-17 17:44:42 +01002442#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002443 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2444 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002445 if (ctrl_break_was_pressed)
2446 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2447#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002448 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2449 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002450 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002451#ifdef FEAT_GUI
2452 && !curbuf->b_term->tl_system
2453#endif
2454 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002455 {
2456 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002457 int prev_raw_c = raw_c;
2458 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002459
2460#ifdef FEAT_CMDL_INFO
2461 if (add_to_showcmd(c))
2462 out_flush();
2463#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002464 raw_c = term_vgetc();
2465 c = raw_c_to_ctrl(raw_c);
2466
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002467#ifdef FEAT_CMDL_INFO
2468 clear_showcmd();
2469#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002470 if (!term_use_loop_check(TRUE)
2471 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002472 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002473 break;
2474
2475 if (prev_c == Ctrl_BSL)
2476 {
2477 if (c == Ctrl_N)
2478 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002479 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002480 term_enter_normal_mode();
2481 ret = FAIL;
2482 goto theend;
2483 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002484 // Send both keys to the terminal, first one here, second one
2485 // below.
2486 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2487 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002488 }
2489 else if (c == Ctrl_C)
2490 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002491 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002492 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2493 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002494 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002495 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002496 // "CTRL-W .": send CTRL-W to the job
2497 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002498 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002499 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002500 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002501 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002502 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002503 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002504 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002505 else if (c == 'N')
2506 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002507 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002508 term_enter_normal_mode();
2509 ret = FAIL;
2510 goto theend;
2511 }
2512 else if (c == '"')
2513 {
2514 term_paste_register(prev_c);
2515 continue;
2516 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002517 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002518 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002519 char_u buf[MB_MAXBYTES + 2];
2520
2521 // Put the command into the typeahead buffer, when using the
2522 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2523 buf[0] = Ctrl_W;
2524 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2525 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002526 ret = OK;
2527 goto theend;
2528 }
2529 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002530# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002531 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002532 {
2533 WCHAR wc;
2534 char_u mb[3];
2535
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002536 mb[0] = (unsigned)raw_c >> 8;
2537 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002538 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002539 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002540 }
2541# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002542 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002543 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002544 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002545 // We are sure to come back here, don't reset the cursor color
2546 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002547 restore_cursor = FALSE;
2548
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002549 ret = OK;
2550 goto theend;
2551 }
2552 }
2553 ret = FAIL;
2554
2555theend:
2556 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002557 if (restore_cursor)
2558 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002559
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002560 // Move a snapshot of the screen contents to the buffer, so that completion
2561 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002562 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2563 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002564
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002565 return ret;
2566}
2567
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002568 static void
2569may_toggle_cursor(term_T *term)
2570{
2571 if (in_terminal_loop == term)
2572 {
2573 if (term->tl_cursor_visible)
2574 cursor_on();
2575 else
2576 cursor_off();
2577 }
2578}
2579
2580/*
2581 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002582 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002583 */
2584 static int
2585color2index(VTermColor *color, int fg, int *boldp)
2586{
2587 int red = color->red;
2588 int blue = color->blue;
2589 int green = color->green;
2590
Bram Moolenaar46359e12017-11-29 22:33:38 +01002591 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002592 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002593 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002594 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002595 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002596 case 0: return 0;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002597 case 1: return lookup_color( 0, fg, boldp) + 1; // black
2598 case 2: return lookup_color( 4, fg, boldp) + 1; // dark red
2599 case 3: return lookup_color( 2, fg, boldp) + 1; // dark green
2600 case 4: return lookup_color( 6, fg, boldp) + 1; // brown
2601 case 5: return lookup_color( 1, fg, boldp) + 1; // dark blue
2602 case 6: return lookup_color( 5, fg, boldp) + 1; // dark magenta
2603 case 7: return lookup_color( 3, fg, boldp) + 1; // dark cyan
2604 case 8: return lookup_color( 8, fg, boldp) + 1; // light grey
2605 case 9: return lookup_color(12, fg, boldp) + 1; // dark grey
2606 case 10: return lookup_color(20, fg, boldp) + 1; // red
2607 case 11: return lookup_color(16, fg, boldp) + 1; // green
2608 case 12: return lookup_color(24, fg, boldp) + 1; // yellow
2609 case 13: return lookup_color(14, fg, boldp) + 1; // blue
2610 case 14: return lookup_color(22, fg, boldp) + 1; // magenta
2611 case 15: return lookup_color(18, fg, boldp) + 1; // cyan
2612 case 16: return lookup_color(26, fg, boldp) + 1; // white
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002613 }
2614 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002615
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002616 if (t_colors >= 256)
2617 {
2618 if (red == blue && red == green)
2619 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002620 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002621 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002622 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2623 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2624 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002625 int i;
2626
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002627 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002628 return 17; // 00/00/00
2629 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002630 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002631 for (i = 0; i < 23; ++i)
2632 if (red < cutoff[i])
2633 return i + 233;
2634 return 256;
2635 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002636 {
2637 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2638 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002639
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002640 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002641 for (ri = 0; ri < 5; ++ri)
2642 if (red < cutoff[ri])
2643 break;
2644 for (gi = 0; gi < 5; ++gi)
2645 if (green < cutoff[gi])
2646 break;
2647 for (bi = 0; bi < 5; ++bi)
2648 if (blue < cutoff[bi])
2649 break;
2650 return 17 + ri * 36 + gi * 6 + bi;
2651 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002652 }
2653 return 0;
2654}
2655
2656/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002657 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002658 */
2659 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002660vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002661{
2662 int attr = 0;
2663
2664 if (cellattrs.bold)
2665 attr |= HL_BOLD;
2666 if (cellattrs.underline)
2667 attr |= HL_UNDERLINE;
2668 if (cellattrs.italic)
2669 attr |= HL_ITALIC;
2670 if (cellattrs.strike)
2671 attr |= HL_STRIKETHROUGH;
2672 if (cellattrs.reverse)
2673 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002674 return attr;
2675}
2676
2677/*
2678 * Store Vterm attributes in "cell" from highlight flags.
2679 */
2680 static void
2681hl2vtermAttr(int attr, cellattr_T *cell)
2682{
2683 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2684 if (attr & HL_BOLD)
2685 cell->attrs.bold = 1;
2686 if (attr & HL_UNDERLINE)
2687 cell->attrs.underline = 1;
2688 if (attr & HL_ITALIC)
2689 cell->attrs.italic = 1;
2690 if (attr & HL_STRIKETHROUGH)
2691 cell->attrs.strike = 1;
2692 if (attr & HL_INVERSE)
2693 cell->attrs.reverse = 1;
2694}
2695
2696/*
2697 * Convert the attributes of a vterm cell into an attribute index.
2698 */
2699 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002700cell2attr(
2701 win_T *wp,
2702 VTermScreenCellAttrs cellattrs,
2703 VTermColor cellfg,
2704 VTermColor cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002705{
2706 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002707
2708#ifdef FEAT_GUI
2709 if (gui.in_use)
2710 {
2711 guicolor_T fg, bg;
2712
2713 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2714 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2715 return get_gui_attr_idx(attr, fg, bg);
2716 }
2717 else
2718#endif
2719#ifdef FEAT_TERMGUICOLORS
2720 if (p_tgc)
2721 {
2722 guicolor_T fg, bg;
2723
2724 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2725 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2726
2727 return get_tgc_attr_idx(attr, fg, bg);
2728 }
2729 else
2730#endif
2731 {
2732 int bold = MAYBE;
2733 int fg = color2index(&cellfg, TRUE, &bold);
2734 int bg = color2index(&cellbg, FALSE, &bold);
2735
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002736 // Use the 'wincolor' or "Terminal" highlighting for the default
2737 // colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002738 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002739 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002740 int wincolor_fg = -1;
2741 int wincolor_bg = -1;
2742
2743 if (wp != NULL && *wp->w_p_wcr != NUL)
2744 {
2745 int id = syn_name2id(curwin->w_p_wcr);
2746
2747 // Get the 'wincolor' group colors.
2748 if (id > 0)
2749 syn_id2cterm_bg(id, &wincolor_fg, &wincolor_bg);
2750 }
2751 if (fg == 0)
2752 {
2753 if (wincolor_fg >= 0)
2754 fg = wincolor_fg + 1;
2755 else if (term_default_cterm_fg >= 0)
2756 fg = term_default_cterm_fg + 1;
2757 }
2758 if (bg == 0)
2759 {
2760 if (wincolor_bg >= 0)
2761 bg = wincolor_bg + 1;
2762 else if (term_default_cterm_bg >= 0)
2763 bg = term_default_cterm_bg + 1;
2764 }
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002765 }
2766
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002767 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002768 if (bold == TRUE)
2769 attr |= HL_BOLD;
2770 return get_cterm_attr_idx(attr, fg, bg);
2771 }
2772 return 0;
2773}
2774
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002775 static void
2776set_dirty_snapshot(term_T *term)
2777{
2778 term->tl_dirty_snapshot = TRUE;
2779#ifdef FEAT_TIMERS
2780 if (!term->tl_normal_mode)
2781 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002782 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002783 profile_setlimit(100L, &term->tl_timer_due);
2784 term->tl_timer_set = TRUE;
2785 }
2786#endif
2787}
2788
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002789 static int
2790handle_damage(VTermRect rect, void *user)
2791{
2792 term_T *term = (term_T *)user;
2793
2794 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2795 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002796 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002797 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002798 return 1;
2799}
2800
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002801 static void
2802term_scroll_up(term_T *term, int start_row, int count)
2803{
2804 win_T *wp;
2805 VTermColor fg, bg;
2806 VTermScreenCellAttrs attr;
2807 int clear_attr;
2808
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002809 vim_memset(&attr, 0, sizeof(attr));
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002810
2811 FOR_ALL_WINDOWS(wp)
2812 {
2813 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002814 {
2815 // Set the color to clear lines with.
2816 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2817 &fg, &bg);
2818 clear_attr = cell2attr(wp, attr, fg, bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002819 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002820 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002821 }
2822}
2823
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002824 static int
2825handle_moverect(VTermRect dest, VTermRect src, void *user)
2826{
2827 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002828 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002829
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002830 // Scrolling up is done much more efficiently by deleting lines instead of
2831 // redrawing the text. But avoid doing this multiple times, postpone until
2832 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002833 if (dest.start_col == src.start_col
2834 && dest.end_col == src.end_col
2835 && dest.start_row < src.start_row)
2836 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002837 if (dest.start_row == 0)
2838 term->tl_postponed_scroll += count;
2839 else
2840 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002841 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002842
2843 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2844 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002845 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002846
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002847 // Note sure if the scrolling will work correctly, let's do a complete
2848 // redraw later.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002849 redraw_buf_later(term->tl_buffer, NOT_VALID);
2850 return 1;
2851}
2852
2853 static int
2854handle_movecursor(
2855 VTermPos pos,
2856 VTermPos oldpos UNUSED,
2857 int visible,
2858 void *user)
2859{
2860 term_T *term = (term_T *)user;
2861 win_T *wp;
2862
2863 term->tl_cursor_pos = pos;
2864 term->tl_cursor_visible = visible;
2865
2866 FOR_ALL_WINDOWS(wp)
2867 {
2868 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002869 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002870 }
2871 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2872 {
2873 may_toggle_cursor(term);
2874 update_cursor(term, term->tl_cursor_visible);
2875 }
2876
2877 return 1;
2878}
2879
2880 static int
2881handle_settermprop(
2882 VTermProp prop,
2883 VTermValue *value,
2884 void *user)
2885{
2886 term_T *term = (term_T *)user;
2887
2888 switch (prop)
2889 {
2890 case VTERM_PROP_TITLE:
2891 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002892 // a blank title isn't useful, make it empty, so that "running" is
2893 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002894 if (*skipwhite((char_u *)value->string) == NUL)
2895 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002896 // Same as blank
2897 else if (term->tl_arg0_cmd != NULL
2898 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2899 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2900 term->tl_title = NULL;
2901 // Empty corrupted data of winpty
2902 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2903 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002904#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002905 else if (!enc_utf8 && enc_codepage > 0)
2906 {
2907 WCHAR *ret = NULL;
2908 int length = 0;
2909
2910 MultiByteToWideChar_alloc(CP_UTF8, 0,
2911 (char*)value->string, (int)STRLEN(value->string),
2912 &ret, &length);
2913 if (ret != NULL)
2914 {
2915 WideCharToMultiByte_alloc(enc_codepage, 0,
2916 ret, length, (char**)&term->tl_title,
2917 &length, 0, 0);
2918 vim_free(ret);
2919 }
2920 }
2921#endif
2922 else
2923 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002924 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 if (term == curbuf->b_term)
2926 maketitle();
2927 break;
2928
2929 case VTERM_PROP_CURSORVISIBLE:
2930 term->tl_cursor_visible = value->boolean;
2931 may_toggle_cursor(term);
2932 out_flush();
2933 break;
2934
2935 case VTERM_PROP_CURSORBLINK:
2936 term->tl_cursor_blink = value->boolean;
2937 may_set_cursor_props(term);
2938 break;
2939
2940 case VTERM_PROP_CURSORSHAPE:
2941 term->tl_cursor_shape = value->number;
2942 may_set_cursor_props(term);
2943 break;
2944
2945 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002946 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002947 may_set_cursor_props(term);
2948 break;
2949
2950 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002951 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002952 term->tl_using_altscreen = value->boolean;
2953 break;
2954
2955 default:
2956 break;
2957 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002958 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002959 return 1;
2960}
2961
2962/*
2963 * The job running in the terminal resized the terminal.
2964 */
2965 static int
2966handle_resize(int rows, int cols, void *user)
2967{
2968 term_T *term = (term_T *)user;
2969 win_T *wp;
2970
2971 term->tl_rows = rows;
2972 term->tl_cols = cols;
2973 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002974 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002975 term->tl_vterm_size_changed = FALSE;
2976 else
2977 {
2978 FOR_ALL_WINDOWS(wp)
2979 {
2980 if (wp->w_buffer == term->tl_buffer)
2981 {
2982 win_setheight_win(rows, wp);
2983 win_setwidth_win(cols, wp);
2984 }
2985 }
2986 redraw_buf_later(term->tl_buffer, NOT_VALID);
2987 }
2988 return 1;
2989}
2990
2991/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002992 * If the number of lines that are stored goes over 'termscrollback' then
2993 * delete the first 10%.
2994 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2995 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002996 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002997 static void
2998limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002999{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003000 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003001 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003002 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003003 int i;
3004
3005 curbuf = term->tl_buffer;
3006 for (i = 0; i < todo; ++i)
3007 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003008 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3009 if (update_buffer)
3010 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003011 }
3012 curbuf = curwin->w_buffer;
3013
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003014 gap->ga_len -= todo;
3015 mch_memmove(gap->ga_data,
3016 (sb_line_T *)gap->ga_data + todo,
3017 sizeof(sb_line_T) * gap->ga_len);
3018 if (update_buffer)
3019 term->tl_scrollback_scrolled -= todo;
3020 }
3021}
3022
3023/*
3024 * Handle a line that is pushed off the top of the screen.
3025 */
3026 static int
3027handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3028{
3029 term_T *term = (term_T *)user;
3030 garray_T *gap;
3031 int update_buffer;
3032
3033 if (term->tl_normal_mode)
3034 {
3035 // In Terminal-Normal mode the user interacts with the buffer, thus we
3036 // must not change it. Postpone adding the scrollback lines.
3037 gap = &term->tl_scrollback_postponed;
3038 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003039 }
3040 else
3041 {
3042 // First remove the lines that were appended before, the pushed line
3043 // goes above it.
3044 cleanup_scrollback(term);
3045 gap = &term->tl_scrollback;
3046 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003047 }
3048
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003049 limit_scrollback(term, gap, update_buffer);
3050
3051 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003052 {
3053 cellattr_T *p = NULL;
3054 int len = 0;
3055 int i;
3056 int c;
3057 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003058 int text_len;
3059 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003060 sb_line_T *line;
3061 garray_T ga;
3062 cellattr_T fill_attr = term->tl_default_color;
3063
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003064 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003065 for (i = 0; i < cols; ++i)
3066 if (cells[i].chars[0] != 0)
3067 len = i + 1;
3068 else
3069 cell2cellattr(&cells[i], &fill_attr);
3070
3071 ga_init2(&ga, 1, 100);
3072 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003073 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003074 if (p != NULL)
3075 {
3076 for (col = 0; col < len; col += cells[col].width)
3077 {
3078 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3079 {
3080 ga.ga_len = 0;
3081 break;
3082 }
3083 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3084 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3085 (char_u *)ga.ga_data + ga.ga_len);
3086 cell2cellattr(&cells[col], &p[col]);
3087 }
3088 }
3089 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003090 {
3091 if (update_buffer)
3092 text = (char_u *)"";
3093 else
3094 text = vim_strsave((char_u *)"");
3095 text_len = 0;
3096 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097 else
3098 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003099 text = ga.ga_data;
3100 text_len = ga.ga_len;
3101 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003102 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003103 if (update_buffer)
3104 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003105
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003106 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003107 line->sb_cols = len;
3108 line->sb_cells = p;
3109 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003110 if (update_buffer)
3111 {
3112 line->sb_text = NULL;
3113 ++term->tl_scrollback_scrolled;
3114 ga_clear(&ga); // free the text
3115 }
3116 else
3117 {
3118 line->sb_text = text;
3119 ga_init(&ga); // text is kept in tl_scrollback_postponed
3120 }
3121 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003122 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003123 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003124}
3125
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003126/*
3127 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3128 * received and stored in tl_scrollback_postponed.
3129 */
3130 static void
3131handle_postponed_scrollback(term_T *term)
3132{
3133 int i;
3134
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003135 if (term->tl_scrollback_postponed.ga_len == 0)
3136 return;
3137 ch_log(NULL, "Moving postponed scrollback to scrollback");
3138
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003139 // First remove the lines that were appended before, the pushed lines go
3140 // above it.
3141 cleanup_scrollback(term);
3142
3143 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3144 {
3145 char_u *text;
3146 sb_line_T *pp_line;
3147 sb_line_T *line;
3148
3149 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3150 break;
3151 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3152
3153 text = pp_line->sb_text;
3154 if (text == NULL)
3155 text = (char_u *)"";
3156 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3157 vim_free(pp_line->sb_text);
3158
3159 line = (sb_line_T *)term->tl_scrollback.ga_data
3160 + term->tl_scrollback.ga_len;
3161 line->sb_cols = pp_line->sb_cols;
3162 line->sb_cells = pp_line->sb_cells;
3163 line->sb_fill_attr = pp_line->sb_fill_attr;
3164 line->sb_text = NULL;
3165 ++term->tl_scrollback_scrolled;
3166 ++term->tl_scrollback.ga_len;
3167 }
3168
3169 ga_clear(&term->tl_scrollback_postponed);
3170 limit_scrollback(term, &term->tl_scrollback, TRUE);
3171}
3172
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003173static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003174 handle_damage, // damage
3175 handle_moverect, // moverect
3176 handle_movecursor, // movecursor
3177 handle_settermprop, // settermprop
3178 NULL, // bell
3179 handle_resize, // resize
3180 handle_pushline, // sb_pushline
3181 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003182};
3183
3184/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003185 * Do the work after the channel of a terminal was closed.
3186 * Must be called only when updating_screen is FALSE.
3187 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3188 */
3189 static int
3190term_after_channel_closed(term_T *term)
3191{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003192 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003193 if (!term->tl_normal_mode)
3194 {
3195 int fnum = term->tl_buffer->b_fnum;
3196
3197 cleanup_vterm(term);
3198
3199 if (term->tl_finish == TL_FINISH_CLOSE)
3200 {
3201 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003202 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003203#ifdef FEAT_PROP_POPUP
3204 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003205
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003206 // If this was a terminal in a popup window, go back to the
3207 // previous window.
3208 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3209 {
3210 pwin = curwin;
3211 if (win_valid(prevwin))
3212 win_enter(prevwin, FALSE);
3213 }
3214 else
3215#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003216 // If this is the last normal window: exit Vim.
3217 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3218 {
3219 exarg_T ea;
3220
3221 vim_memset(&ea, 0, sizeof(ea));
3222 ex_quit(&ea);
3223 return TRUE;
3224 }
3225
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003226 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003227 ch_log(NULL, "terminal job finished, closing window");
3228 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003229 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003230 if (curwin == aucmd_win)
3231 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003232 if (do_set_w_closing)
3233 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003234 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003235 if (do_set_w_closing)
3236 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003237 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003238#ifdef FEAT_PROP_POPUP
3239 if (pwin != NULL)
3240 popup_close_with_retval(pwin, 0);
3241#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003242 return TRUE;
3243 }
3244 if (term->tl_finish == TL_FINISH_OPEN
3245 && term->tl_buffer->b_nwindows == 0)
3246 {
3247 char buf[50];
3248
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003249 // TODO: use term_opencmd
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003250 ch_log(NULL, "terminal job finished, opening window");
3251 vim_snprintf(buf, sizeof(buf),
3252 term->tl_opencmd == NULL
3253 ? "botright sbuf %d"
3254 : (char *)term->tl_opencmd, fnum);
3255 do_cmdline_cmd((char_u *)buf);
3256 }
3257 else
3258 ch_log(NULL, "terminal job finished");
3259 }
3260
3261 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3262 return FALSE;
3263}
3264
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003265#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3266/*
3267 * If the current window is a terminal in a popup window and the job has
3268 * finished, close the popup window and to back to the previous window.
3269 * Otherwise return FAIL.
3270 */
3271 int
3272may_close_term_popup(void)
3273{
3274 if (popup_is_popup(curwin) && curbuf->b_term != NULL
3275 && !term_job_running(curbuf->b_term))
3276 {
3277 win_T *pwin = curwin;
3278
3279 if (win_valid(prevwin))
3280 win_enter(prevwin, FALSE);
3281 popup_close_with_retval(pwin, 0);
3282 return OK;
3283 }
3284 return FAIL;
3285}
3286#endif
3287
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003288/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003289 * Called when a channel has been closed.
3290 * If this was a channel for a terminal window then finish it up.
3291 */
3292 void
3293term_channel_closed(channel_T *ch)
3294{
3295 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003296 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003297 int did_one = FALSE;
3298
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003299 for (term = first_term; term != NULL; term = next_term)
3300 {
3301 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003302 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003303 {
3304 term->tl_channel_closed = TRUE;
3305 did_one = TRUE;
3306
Bram Moolenaard23a8232018-02-10 18:45:26 +01003307 VIM_CLEAR(term->tl_title);
3308 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003309#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003310 if (term->tl_out_fd != NULL)
3311 {
3312 fclose(term->tl_out_fd);
3313 term->tl_out_fd = NULL;
3314 }
3315#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003316
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003317 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003318 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003319 // Cannot open or close windows now. Can happen when
3320 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003321 term->tl_channel_recently_closed = TRUE;
3322 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003323 }
3324
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003325 if (term_after_channel_closed(term))
3326 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003327 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003328 }
3329
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003330 if (did_one)
3331 {
3332 redraw_statuslines();
3333
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003334 // Need to break out of vgetc().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003335 ins_char_typebuf(K_IGNORE);
3336 typebuf_was_filled = TRUE;
3337
3338 term = curbuf->b_term;
3339 if (term != NULL)
3340 {
3341 if (term->tl_job == ch->ch_job)
3342 maketitle();
3343 update_cursor(term, term->tl_cursor_visible);
3344 }
3345 }
3346}
3347
3348/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003349 * To be called after resetting updating_screen: handle any terminal where the
3350 * channel was closed.
3351 */
3352 void
3353term_check_channel_closed_recently()
3354{
3355 term_T *term;
3356 term_T *next_term;
3357
3358 for (term = first_term; term != NULL; term = next_term)
3359 {
3360 next_term = term->tl_next;
3361 if (term->tl_channel_recently_closed)
3362 {
3363 term->tl_channel_recently_closed = FALSE;
3364 if (term_after_channel_closed(term))
3365 // start over, the list may have changed
3366 next_term = first_term;
3367 }
3368 }
3369}
3370
3371/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003372 * Fill one screen line from a line of the terminal.
3373 * Advances "pos" to past the last column.
3374 */
3375 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003376term_line2screenline(
3377 win_T *wp,
3378 VTermScreen *screen,
3379 VTermPos *pos,
3380 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003381{
3382 int off = screen_get_current_line_off();
3383
3384 for (pos->col = 0; pos->col < max_col; )
3385 {
3386 VTermScreenCell cell;
3387 int c;
3388
3389 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3390 vim_memset(&cell, 0, sizeof(cell));
3391
3392 c = cell.chars[0];
3393 if (c == NUL)
3394 {
3395 ScreenLines[off] = ' ';
3396 if (enc_utf8)
3397 ScreenLinesUC[off] = NUL;
3398 }
3399 else
3400 {
3401 if (enc_utf8)
3402 {
3403 int i;
3404
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003405 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003406 for (i = 0; i < Screen_mco
3407 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3408 {
3409 ScreenLinesC[i][off] = cell.chars[i + 1];
3410 if (cell.chars[i + 1] == 0)
3411 break;
3412 }
3413 if (c >= 0x80 || (Screen_mco > 0
3414 && ScreenLinesC[0][off] != 0))
3415 {
3416 ScreenLines[off] = ' ';
3417 ScreenLinesUC[off] = c;
3418 }
3419 else
3420 {
3421 ScreenLines[off] = c;
3422 ScreenLinesUC[off] = NUL;
3423 }
3424 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003425#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003426 else if (has_mbyte && c >= 0x80)
3427 {
3428 char_u mb[MB_MAXBYTES+1];
3429 WCHAR wc = c;
3430
3431 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3432 (char*)mb, 2, 0, 0) > 1)
3433 {
3434 ScreenLines[off] = mb[0];
3435 ScreenLines[off + 1] = mb[1];
3436 cell.width = mb_ptr2cells(mb);
3437 }
3438 else
3439 ScreenLines[off] = c;
3440 }
3441#endif
3442 else
3443 ScreenLines[off] = c;
3444 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003445 ScreenAttrs[off] = cell2attr(wp, cell.attrs, cell.fg, cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003446
3447 ++pos->col;
3448 ++off;
3449 if (cell.width == 2)
3450 {
3451 if (enc_utf8)
3452 ScreenLinesUC[off] = NUL;
3453
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003454 // don't set the second byte to NUL for a DBCS encoding, it
3455 // has been set above
Bram Moolenaar13568252018-03-16 20:46:58 +01003456 if (enc_utf8 || !has_mbyte)
3457 ScreenLines[off] = NUL;
3458
3459 ++pos->col;
3460 ++off;
3461 }
3462 }
3463}
3464
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003465#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003466 static void
3467update_system_term(term_T *term)
3468{
3469 VTermPos pos;
3470 VTermScreen *screen;
3471
3472 if (term->tl_vterm == NULL)
3473 return;
3474 screen = vterm_obtain_screen(term->tl_vterm);
3475
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003476 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003477 while (term->tl_toprow > 0
3478 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3479 {
3480 int save_p_more = p_more;
3481
3482 p_more = FALSE;
3483 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003484 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003485 p_more = save_p_more;
3486 --term->tl_toprow;
3487 }
3488
3489 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3490 && pos.row < Rows; ++pos.row)
3491 {
3492 if (pos.row < term->tl_rows)
3493 {
3494 int max_col = MIN(Columns, term->tl_cols);
3495
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003496 term_line2screenline(NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003497 }
3498 else
3499 pos.col = 0;
3500
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003501 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003502 }
3503
3504 term->tl_dirty_row_start = MAX_ROW;
3505 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003506}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003507#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003508
3509/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003510 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3511 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003512 * Terminal-Normal mode.
3513 */
3514 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003515term_do_update_window(win_T *wp)
3516{
3517 term_T *term = wp->w_buffer->b_term;
3518
3519 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3520}
3521
3522/*
3523 * Called to update a window that contains an active terminal.
3524 */
3525 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003526term_update_window(win_T *wp)
3527{
3528 term_T *term = wp->w_buffer->b_term;
3529 VTerm *vterm;
3530 VTermScreen *screen;
3531 VTermState *state;
3532 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003533 int rows, cols;
3534 int newrows, newcols;
3535 int minsize;
3536 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003537
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003538 vterm = term->tl_vterm;
3539 screen = vterm_obtain_screen(vterm);
3540 state = vterm_obtain_state(vterm);
3541
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003542 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3543 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003544 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003545 {
3546 term->tl_dirty_row_start = 0;
3547 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003548
3549 if (term->tl_postponed_scroll > 0
3550 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003551 // Scrolling is usually faster than redrawing, when there are only
3552 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003553 term_scroll_up(term, 0, term->tl_postponed_scroll);
3554 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003555 }
3556
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003557 /*
3558 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003559 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003560 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003561 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003562
Bram Moolenaar498c2562018-04-15 23:45:15 +02003563 newrows = 99999;
3564 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003565 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003566 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003567 // Always use curwin, it may be a popup window.
3568 win_T *wwp = twp == NULL ? curwin : twp;
3569
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003570 // When more than one window shows the same terminal, use the
3571 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003572 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003573 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003574 newrows = MIN(newrows, wwp->w_height);
3575 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003576 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003577 if (twp == NULL)
3578 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003579 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003580 if (newrows == 99999 || newcols == 99999)
3581 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003582 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3583 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3584
3585 if (term->tl_rows != newrows || term->tl_cols != newcols)
3586 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003587 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003588 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003589 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003590 newrows);
3591 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003592
3593 // Updating the terminal size will cause the snapshot to be cleared.
3594 // When not in terminal_loop() we need to restore it.
3595 if (term != in_terminal_loop)
3596 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003597 }
3598
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003599 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003600 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003601 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003602
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003603 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3604 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003605 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003606 if (pos.row < term->tl_rows)
3607 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003608 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003609
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003610 term_line2screenline(wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003611 }
3612 else
3613 pos.col = 0;
3614
Bram Moolenaarf118d482018-03-13 13:14:00 +01003615 screen_line(wp->w_winrow + pos.row
3616#ifdef FEAT_MENU
3617 + winbar_height(wp)
3618#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003619 , wp->w_wincol, pos.col, wp->w_width,
3620#ifdef FEAT_PROP_POPUP
3621 popup_is_popup(wp) ? SLF_POPUP :
3622#endif
3623 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003624 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003625 term->tl_dirty_row_start = MAX_ROW;
3626 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003627}
3628
3629/*
3630 * Return TRUE if "wp" is a terminal window where the job has finished.
3631 */
3632 int
3633term_is_finished(buf_T *buf)
3634{
3635 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3636}
3637
3638/*
3639 * Return TRUE if "wp" is a terminal window where the job has finished or we
3640 * are in Terminal-Normal mode, thus we show the buffer contents.
3641 */
3642 int
3643term_show_buffer(buf_T *buf)
3644{
3645 term_T *term = buf->b_term;
3646
3647 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3648}
3649
3650/*
3651 * The current buffer is going to be changed. If there is terminal
3652 * highlighting remove it now.
3653 */
3654 void
3655term_change_in_curbuf(void)
3656{
3657 term_T *term = curbuf->b_term;
3658
3659 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3660 {
3661 free_scrollback(term);
3662 redraw_buf_later(term->tl_buffer, NOT_VALID);
3663
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003664 // The buffer is now like a normal buffer, it cannot be easily
3665 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003666 set_string_option_direct((char_u *)"buftype", -1,
3667 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3668 }
3669}
3670
3671/*
3672 * Get the screen attribute for a position in the buffer.
3673 * Use a negative "col" to get the filler background color.
3674 */
3675 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003676term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003677{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003678 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003679 term_T *term = buf->b_term;
3680 sb_line_T *line;
3681 cellattr_T *cellattr;
3682
3683 if (lnum > term->tl_scrollback.ga_len)
3684 cellattr = &term->tl_default_color;
3685 else
3686 {
3687 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3688 if (col < 0 || col >= line->sb_cols)
3689 cellattr = &line->sb_fill_attr;
3690 else
3691 cellattr = line->sb_cells + col;
3692 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003693 return cell2attr(wp, cellattr->attrs, cellattr->fg, cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003694}
3695
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003696/*
3697 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003698 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003699 */
3700 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003701cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003702{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003703 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003704}
3705
3706/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003707 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003708 */
3709 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003710init_default_colors(term_T *term, win_T *wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003711{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003712 VTermColor *fg, *bg;
3713 int fgval, bgval;
3714 int id;
3715
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003716 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3717 term->tl_default_color.width = 1;
3718 fg = &term->tl_default_color.fg;
3719 bg = &term->tl_default_color.bg;
3720
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003721 // Vterm uses a default black background. Set it to white when
3722 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003723 if (*p_bg == 'l')
3724 {
3725 fgval = 0;
3726 bgval = 255;
3727 }
3728 else
3729 {
3730 fgval = 255;
3731 bgval = 0;
3732 }
3733 fg->red = fg->green = fg->blue = fgval;
3734 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003735 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003736
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003737 // The 'wincolor' or "Terminal" highlight group overrules the defaults.
3738 if (wp != NULL && *wp->w_p_wcr != NUL)
3739 id = syn_name2id(wp->w_p_wcr);
3740 else
3741 id = syn_name2id((char_u *)"Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003742
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003743 // Use the actual color for the GUI and when 'termguicolors' is set.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003744#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3745 if (0
3746# ifdef FEAT_GUI
3747 || gui.in_use
3748# endif
3749# ifdef FEAT_TERMGUICOLORS
3750 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003751# ifdef FEAT_VTP
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003752 // Finally get INVALCOLOR on this execution path
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003753 || (!p_tgc && t_colors >= 256)
3754# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003755# endif
3756 )
3757 {
3758 guicolor_T fg_rgb = INVALCOLOR;
3759 guicolor_T bg_rgb = INVALCOLOR;
3760
3761 if (id != 0)
3762 syn_id2colors(id, &fg_rgb, &bg_rgb);
3763
3764# ifdef FEAT_GUI
3765 if (gui.in_use)
3766 {
3767 if (fg_rgb == INVALCOLOR)
3768 fg_rgb = gui.norm_pixel;
3769 if (bg_rgb == INVALCOLOR)
3770 bg_rgb = gui.back_pixel;
3771 }
3772# ifdef FEAT_TERMGUICOLORS
3773 else
3774# endif
3775# endif
3776# ifdef FEAT_TERMGUICOLORS
3777 {
3778 if (fg_rgb == INVALCOLOR)
3779 fg_rgb = cterm_normal_fg_gui_color;
3780 if (bg_rgb == INVALCOLOR)
3781 bg_rgb = cterm_normal_bg_gui_color;
3782 }
3783# endif
3784 if (fg_rgb != INVALCOLOR)
3785 {
3786 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3787
3788 fg->red = (unsigned)(rgb >> 16);
3789 fg->green = (unsigned)(rgb >> 8) & 255;
3790 fg->blue = (unsigned)rgb & 255;
3791 }
3792 if (bg_rgb != INVALCOLOR)
3793 {
3794 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3795
3796 bg->red = (unsigned)(rgb >> 16);
3797 bg->green = (unsigned)(rgb >> 8) & 255;
3798 bg->blue = (unsigned)rgb & 255;
3799 }
3800 }
3801 else
3802#endif
3803 if (id != 0 && t_colors >= 16)
3804 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003805 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003806 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003807 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003808 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003809 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003810 else
3811 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003812#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003813 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003814#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003815
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003816 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003817 if (cterm_normal_fg_color > 0)
3818 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003819 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003820# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3821# ifdef VIMDLL
3822 if (!gui.in_use)
3823# endif
3824 {
3825 tmp = fg->red;
3826 fg->red = fg->blue;
3827 fg->blue = tmp;
3828 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003829# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003830 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003831# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003832 else
3833 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003834# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003835
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003836 if (cterm_normal_bg_color > 0)
3837 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003838 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003839# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3840# ifdef VIMDLL
3841 if (!gui.in_use)
3842# endif
3843 {
3844 tmp = fg->red;
3845 fg->red = fg->blue;
3846 fg->blue = tmp;
3847 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003848# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003849 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003850# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003851 else
3852 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003853# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003854 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003855}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003856
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003857#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3858/*
3859 * Set the 16 ANSI colors from array of RGB values
3860 */
3861 static void
3862set_vterm_palette(VTerm *vterm, long_u *rgb)
3863{
3864 int index = 0;
3865 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003866
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003867 for (; index < 16; index++)
3868 {
3869 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003870
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003871 color.red = (unsigned)(rgb[index] >> 16);
3872 color.green = (unsigned)(rgb[index] >> 8) & 255;
3873 color.blue = (unsigned)rgb[index] & 255;
3874 vterm_state_set_palette_color(state, index, &color);
3875 }
3876}
3877
3878/*
3879 * Set the ANSI color palette from a list of colors
3880 */
3881 static int
3882set_ansi_colors_list(VTerm *vterm, list_T *list)
3883{
3884 int n = 0;
3885 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01003886 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003887
Bram Moolenaarb0992022020-01-30 14:55:42 +01003888 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003889 {
3890 char_u *color_name;
3891 guicolor_T guicolor;
3892
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003893 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003894 if (color_name == NULL)
3895 return FAIL;
3896
3897 guicolor = GUI_GET_COLOR(color_name);
3898 if (guicolor == INVALCOLOR)
3899 return FAIL;
3900
3901 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3902 }
3903
3904 if (n != 16 || li != NULL)
3905 return FAIL;
3906
3907 set_vterm_palette(vterm, rgb);
3908
3909 return OK;
3910}
3911
3912/*
3913 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3914 */
3915 static void
3916init_vterm_ansi_colors(VTerm *vterm)
3917{
3918 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3919
3920 if (var != NULL
3921 && (var->di_tv.v_type != VAR_LIST
3922 || var->di_tv.vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +01003923 || var->di_tv.vval.v_list->lv_first == &range_list_item
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003924 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003925 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003926}
3927#endif
3928
Bram Moolenaar52acb112018-03-18 19:20:22 +01003929/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003930 * Handles a "drop" command from the job in the terminal.
3931 * "item" is the file name, "item->li_next" may have options.
3932 */
3933 static void
3934handle_drop_command(listitem_T *item)
3935{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003936 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003937 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003938 int bufnr;
3939 win_T *wp;
3940 tabpage_T *tp;
3941 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003942 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003943
3944 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3945 FOR_ALL_TAB_WINDOWS(tp, wp)
3946 {
3947 if (wp->w_buffer->b_fnum == bufnr)
3948 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003949 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003950 goto_tabpage_win(tp, wp);
3951 return;
3952 }
3953 }
3954
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003955 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003956
3957 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3958 && opt_item->li_tv.vval.v_dict != NULL)
3959 {
3960 dict_T *dict = opt_item->li_tv.vval.v_dict;
3961 char_u *p;
3962
Bram Moolenaar8f667172018-12-14 15:38:31 +01003963 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003964 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003965 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003966 if (p != NULL)
3967 {
3968 if (check_ff_value(p) == FAIL)
3969 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3970 else
3971 ea.force_ff = *p;
3972 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003973 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003974 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003975 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003976 if (p != NULL)
3977 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003978 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003979 if (ea.cmd != NULL)
3980 {
3981 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3982 ea.force_enc = 11;
3983 tofree = ea.cmd;
3984 }
3985 }
3986
Bram Moolenaar8f667172018-12-14 15:38:31 +01003987 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003988 if (p != NULL)
3989 get_bad_opt(p, &ea);
3990
3991 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3992 ea.force_bin = FORCE_BIN;
3993 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3994 ea.force_bin = FORCE_BIN;
3995 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3996 ea.force_bin = FORCE_NOBIN;
3997 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3998 ea.force_bin = FORCE_NOBIN;
3999 }
4000
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004001 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004002 if (ea.cmd == NULL)
4003 ea.cmd = (char_u *)"split";
4004 ea.arg = fname;
4005 ea.cmdidx = CMD_split;
4006 ex_splitview(&ea);
4007
4008 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004009}
4010
4011/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004012 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4013 */
4014 static int
4015is_permitted_term_api(char_u *func, char_u *pat)
4016{
4017 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4018}
4019
4020/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004021 * Handles a function call from the job running in a terminal.
4022 * "item" is the function name, "item->li_next" has the arguments.
4023 */
4024 static void
4025handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4026{
4027 char_u *func;
4028 typval_T argvars[2];
4029 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004030 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004031
4032 if (item->li_next == NULL)
4033 {
4034 ch_log(channel, "Missing function arguments for call");
4035 return;
4036 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004037 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004038
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004039 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004040 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004041 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004042 return;
4043 }
4044
4045 argvars[0].v_type = VAR_NUMBER;
4046 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4047 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004048 vim_memset(&funcexe, 0, sizeof(funcexe));
4049 funcexe.firstline = 1L;
4050 funcexe.lastline = 1L;
4051 funcexe.evaluate = TRUE;
4052 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004053 {
4054 clear_tv(&rettv);
4055 ch_log(channel, "Function %s called", func);
4056 }
4057 else
4058 ch_log(channel, "Calling function %s failed", func);
4059}
4060
4061/*
4062 * Called by libvterm when it cannot recognize an OSC sequence.
4063 * We recognize a terminal API command.
4064 */
4065 static int
4066parse_osc(const char *command, size_t cmdlen, void *user)
4067{
4068 term_T *term = (term_T *)user;
4069 js_read_T reader;
4070 typval_T tv;
4071 channel_T *channel = term->tl_job == NULL ? NULL
4072 : term->tl_job->jv_channel;
4073
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004074 // We recognize only OSC 5 1 ; {command}
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004075 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004076 return 0; // not handled
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004077
Bram Moolenaar878c96d2018-04-04 23:00:06 +02004078 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004079 if (reader.js_buf == NULL)
4080 return 1;
4081 reader.js_fill = NULL;
4082 reader.js_used = 0;
4083 if (json_decode(&reader, &tv, 0) == OK
4084 && tv.v_type == VAR_LIST
4085 && tv.vval.v_list != NULL)
4086 {
4087 listitem_T *item = tv.vval.v_list->lv_first;
4088
4089 if (item == NULL)
4090 ch_log(channel, "Missing command");
4091 else
4092 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004093 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004094
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004095 // Make sure an invoked command doesn't delete the buffer (and the
4096 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004097 ++term->tl_buffer->b_locked;
4098
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004099 item = item->li_next;
4100 if (item == NULL)
4101 ch_log(channel, "Missing argument for %s", cmd);
4102 else if (STRCMP(cmd, "drop") == 0)
4103 handle_drop_command(item);
4104 else if (STRCMP(cmd, "call") == 0)
4105 handle_call_command(term, channel, item);
4106 else
4107 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004108 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004109 }
4110 }
4111 else
4112 ch_log(channel, "Invalid JSON received");
4113
4114 vim_free(reader.js_buf);
4115 clear_tv(&tv);
4116 return 1;
4117}
4118
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004119/*
4120 * Called by libvterm when it cannot recognize a CSI sequence.
4121 * We recognize the window position report.
4122 */
4123 static int
4124parse_csi(
4125 const char *leader UNUSED,
4126 const long args[],
4127 int argcount,
4128 const char *intermed UNUSED,
4129 char command,
4130 void *user)
4131{
4132 term_T *term = (term_T *)user;
4133 char buf[100];
4134 int len;
4135 int x = 0;
4136 int y = 0;
4137 win_T *wp;
4138
4139 // We recognize only CSI 13 t
4140 if (command != 't' || argcount != 1 || args[0] != 13)
4141 return 0; // not handled
4142
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004143 // When getting the window position is not possible or it fails it results
4144 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004145#if defined(FEAT_GUI) \
4146 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4147 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004148 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004149#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004150
4151 FOR_ALL_WINDOWS(wp)
4152 if (wp->w_buffer == term->tl_buffer)
4153 break;
4154 if (wp != NULL)
4155 {
4156#ifdef FEAT_GUI
4157 if (gui.in_use)
4158 {
4159 x += wp->w_wincol * gui.char_width;
4160 y += W_WINROW(wp) * gui.char_height;
4161 }
4162 else
4163#endif
4164 {
4165 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004166 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004167 x += wp->w_wincol * 7;
4168 y += W_WINROW(wp) * 10;
4169 }
4170 }
4171
4172 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4173 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4174 (char_u *)buf, len, NULL);
4175 return 1;
4176}
4177
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004178static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004179 NULL, // text
4180 NULL, // control
4181 NULL, // escape
4182 parse_csi, // csi
4183 parse_osc, // osc
4184 NULL, // dcs
4185 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004186};
4187
4188/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004189 * Use Vim's allocation functions for vterm so profiling works.
4190 */
4191 static void *
4192vterm_malloc(size_t size, void *data UNUSED)
4193{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004194 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004195}
4196
4197 static void
4198vterm_memfree(void *ptr, void *data UNUSED)
4199{
4200 vim_free(ptr);
4201}
4202
4203static VTermAllocatorFunctions vterm_allocator = {
4204 &vterm_malloc,
4205 &vterm_memfree
4206};
4207
4208/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004209 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004210 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004211 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004212 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004213create_vterm(term_T *term, int rows, int cols)
4214{
4215 VTerm *vterm;
4216 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004217 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004218 VTermValue value;
4219
Bram Moolenaar756ef112018-04-10 12:04:27 +02004220 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004221 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004222 if (vterm == NULL)
4223 return FAIL;
4224
4225 // Allocate screen and state here, so we can bail out if that fails.
4226 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004227 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004228 if (state == NULL || screen == NULL)
4229 {
4230 vterm_free(vterm);
4231 return FAIL;
4232 }
4233
Bram Moolenaar52acb112018-03-18 19:20:22 +01004234 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004235 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004236 vterm_set_utf8(vterm, 1);
4237
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004238 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004239
4240 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004241 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004242 &term->tl_default_color.fg,
4243 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004244
Bram Moolenaar9e587872019-05-13 20:27:23 +02004245 if (t_colors < 16)
4246 // Less than 16 colors: assume that bold means using a bright color for
4247 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004248 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4249
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004250 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004251 vterm_screen_reset(screen, 1 /* hard */);
4252
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004253 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004254 vterm_screen_enable_altscreen(screen, 1);
4255
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004256 // For unix do not use a blinking cursor. In an xterm this causes the
4257 // cursor to blink if it's blinking in the xterm.
4258 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004259#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004260 if (GetCaretBlinkTime() == INFINITE)
4261 value.boolean = 0;
4262 else
4263 value.boolean = 1;
4264#else
4265 value.boolean = 0;
4266#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004267 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4268 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004269
4270 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004271}
4272
4273/*
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004274 * Called when 'wincolor' was set.
4275 */
4276 void
4277term_update_colors(void)
4278{
4279 term_T *term = curwin->w_buffer->b_term;
4280
Bram Moolenaar7ba3b912020-02-10 20:34:04 +01004281 if (term->tl_vterm == NULL)
4282 return;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004283 init_default_colors(term, curwin);
4284 vterm_state_set_default_colors(
4285 vterm_obtain_state(term->tl_vterm),
4286 &term->tl_default_color.fg,
4287 &term->tl_default_color.bg);
4288}
4289
4290/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004291 * Return the text to show for the buffer name and status.
4292 */
4293 char_u *
4294term_get_status_text(term_T *term)
4295{
4296 if (term->tl_status_text == NULL)
4297 {
4298 char_u *txt;
4299 size_t len;
4300
4301 if (term->tl_normal_mode)
4302 {
4303 if (term_job_running(term))
4304 txt = (char_u *)_("Terminal");
4305 else
4306 txt = (char_u *)_("Terminal-finished");
4307 }
4308 else if (term->tl_title != NULL)
4309 txt = term->tl_title;
4310 else if (term_none_open(term))
4311 txt = (char_u *)_("active");
4312 else if (term_job_running(term))
4313 txt = (char_u *)_("running");
4314 else
4315 txt = (char_u *)_("finished");
4316 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004317 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004318 if (term->tl_status_text != NULL)
4319 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4320 term->tl_buffer->b_fname, txt);
4321 }
4322 return term->tl_status_text;
4323}
4324
4325/*
4326 * Mark references in jobs of terminals.
4327 */
4328 int
4329set_ref_in_term(int copyID)
4330{
4331 int abort = FALSE;
4332 term_T *term;
4333 typval_T tv;
4334
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004335 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004336 if (term->tl_job != NULL)
4337 {
4338 tv.v_type = VAR_JOB;
4339 tv.vval.v_job = term->tl_job;
4340 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4341 }
4342 return abort;
4343}
4344
4345/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004346 * Cache "Terminal" highlight group colors.
4347 */
4348 void
4349set_terminal_default_colors(int cterm_fg, int cterm_bg)
4350{
4351 term_default_cterm_fg = cterm_fg - 1;
4352 term_default_cterm_bg = cterm_bg - 1;
4353}
4354
4355/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004356 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004357 * Returns NULL when the buffer is not for a terminal window and logs a message
4358 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004359 */
4360 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004361term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004362{
4363 buf_T *buf;
4364
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004365 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004366 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004367 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004368 --emsg_off;
4369 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004370 {
4371 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004372 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004373 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004374 return buf;
4375}
4376
Bram Moolenaard96ff162018-02-18 22:13:29 +01004377 static int
4378same_color(VTermColor *a, VTermColor *b)
4379{
4380 return a->red == b->red
4381 && a->green == b->green
4382 && a->blue == b->blue
4383 && a->ansi_index == b->ansi_index;
4384}
4385
4386 static void
4387dump_term_color(FILE *fd, VTermColor *color)
4388{
4389 fprintf(fd, "%02x%02x%02x%d",
4390 (int)color->red, (int)color->green, (int)color->blue,
4391 (int)color->ansi_index);
4392}
4393
4394/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004395 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004396 *
4397 * Each screen cell in full is:
4398 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4399 * {characters} is a space for an empty cell
4400 * For a double-width character "+" is changed to "*" and the next cell is
4401 * skipped.
4402 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4403 * when "&" use the same as the previous cell.
4404 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4405 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4406 * {color-idx} is a number from 0 to 255
4407 *
4408 * Screen cell with same width, attributes and color as the previous one:
4409 * |{characters}
4410 *
4411 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4412 *
4413 * Repeating the previous screen cell:
4414 * @{count}
4415 */
4416 void
4417f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4418{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004419 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004420 term_T *term;
4421 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004422 int max_height = 0;
4423 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004424 stat_T st;
4425 FILE *fd;
4426 VTermPos pos;
4427 VTermScreen *screen;
4428 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004429 VTermState *state;
4430 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004431
4432 if (check_restricted() || check_secure())
4433 return;
4434 if (buf == NULL)
4435 return;
4436 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004437 if (term->tl_vterm == NULL)
4438 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004439 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004440 return;
4441 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004442
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004443 if (argvars[2].v_type != VAR_UNKNOWN)
4444 {
4445 dict_T *d;
4446
4447 if (argvars[2].v_type != VAR_DICT)
4448 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004449 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004450 return;
4451 }
4452 d = argvars[2].vval.v_dict;
4453 if (d != NULL)
4454 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004455 max_height = dict_get_number(d, (char_u *)"rows");
4456 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004457 }
4458 }
4459
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004460 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004461 if (fname == NULL)
4462 return;
4463 if (mch_stat((char *)fname, &st) >= 0)
4464 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004465 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004466 return;
4467 }
4468
Bram Moolenaard96ff162018-02-18 22:13:29 +01004469 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4470 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004471 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004472 return;
4473 }
4474
4475 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4476
4477 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004478 state = vterm_obtain_state(term->tl_vterm);
4479 vterm_state_get_cursorpos(state, &cursor_pos);
4480
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004481 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4482 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004483 {
4484 int repeat = 0;
4485
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004486 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4487 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004488 {
4489 VTermScreenCell cell;
4490 int same_attr;
4491 int same_chars = TRUE;
4492 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004493 int is_cursor_pos = (pos.col == cursor_pos.col
4494 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004495
4496 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4497 vim_memset(&cell, 0, sizeof(cell));
4498
4499 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4500 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004501 int c = cell.chars[i];
4502 int pc = prev_cell.chars[i];
4503
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004504 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01004505 if (i == 0)
4506 {
4507 c = (c == NUL) ? ' ' : c;
4508 pc = (pc == NUL) ? ' ' : pc;
4509 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004510 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004511 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004512 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004513 break;
4514 }
4515 same_attr = vtermAttr2hl(cell.attrs)
4516 == vtermAttr2hl(prev_cell.attrs)
4517 && same_color(&cell.fg, &prev_cell.fg)
4518 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004519 if (same_chars && cell.width == prev_cell.width && same_attr
4520 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004521 {
4522 ++repeat;
4523 }
4524 else
4525 {
4526 if (repeat > 0)
4527 {
4528 fprintf(fd, "@%d", repeat);
4529 repeat = 0;
4530 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004531 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004532
4533 if (cell.chars[0] == NUL)
4534 fputs(" ", fd);
4535 else
4536 {
4537 char_u charbuf[10];
4538 int len;
4539
4540 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4541 && cell.chars[i] != NUL; ++i)
4542 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004543 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004544 fwrite(charbuf, len, 1, fd);
4545 }
4546 }
4547
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004548 // When only the characters differ we don't write anything, the
4549 // following "|", "@" or NL will indicate using the same
4550 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004551 if (cell.width != prev_cell.width || !same_attr)
4552 {
4553 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004554 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004555 else
4556 fputs("+", fd);
4557
4558 if (same_attr)
4559 {
4560 fputs("&", fd);
4561 }
4562 else
4563 {
4564 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4565 if (same_color(&cell.fg, &prev_cell.fg))
4566 fputs("&", fd);
4567 else
4568 {
4569 fputs("#", fd);
4570 dump_term_color(fd, &cell.fg);
4571 }
4572 if (same_color(&cell.bg, &prev_cell.bg))
4573 fputs("&", fd);
4574 else
4575 {
4576 fputs("#", fd);
4577 dump_term_color(fd, &cell.bg);
4578 }
4579 }
4580 }
4581
4582 prev_cell = cell;
4583 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004584
4585 if (cell.width == 2)
4586 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004587 }
4588 if (repeat > 0)
4589 fprintf(fd, "@%d", repeat);
4590 fputs("\n", fd);
4591 }
4592
4593 fclose(fd);
4594}
4595
4596/*
4597 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4598 */
4599 static void
4600dump_is_corrupt(garray_T *gap)
4601{
4602 ga_concat(gap, (char_u *)"CORRUPT");
4603}
4604
4605 static void
4606append_cell(garray_T *gap, cellattr_T *cell)
4607{
4608 if (ga_grow(gap, 1) == OK)
4609 {
4610 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4611 ++gap->ga_len;
4612 }
4613}
4614
4615/*
4616 * Read the dump file from "fd" and append lines to the current buffer.
4617 * Return the cell width of the longest line.
4618 */
4619 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004620read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004621{
4622 int c;
4623 garray_T ga_text;
4624 garray_T ga_cell;
4625 char_u *prev_char = NULL;
4626 int attr = 0;
4627 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004628 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004629 term_T *term = curbuf->b_term;
4630 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004631 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004632
4633 ga_init2(&ga_text, 1, 90);
4634 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4635 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004636 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004637 cursor_pos->row = -1;
4638 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004639
4640 c = fgetc(fd);
4641 for (;;)
4642 {
4643 if (c == EOF)
4644 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004645 if (c == '\r')
4646 {
4647 // DOS line endings? Ignore.
4648 c = fgetc(fd);
4649 }
4650 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004651 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004652 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004653 if (ga_text.ga_data == NULL)
4654 dump_is_corrupt(&ga_text);
4655 if (ga_grow(&term->tl_scrollback, 1) == OK)
4656 {
4657 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4658 + term->tl_scrollback.ga_len;
4659
4660 if (max_cells < ga_cell.ga_len)
4661 max_cells = ga_cell.ga_len;
4662 line->sb_cols = ga_cell.ga_len;
4663 line->sb_cells = ga_cell.ga_data;
4664 line->sb_fill_attr = term->tl_default_color;
4665 ++term->tl_scrollback.ga_len;
4666 ga_init(&ga_cell);
4667
4668 ga_append(&ga_text, NUL);
4669 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4670 ga_text.ga_len, FALSE);
4671 }
4672 else
4673 ga_clear(&ga_cell);
4674 ga_text.ga_len = 0;
4675
4676 c = fgetc(fd);
4677 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004678 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004679 {
4680 int prev_len = ga_text.ga_len;
4681
Bram Moolenaar9271d052018-02-25 21:39:46 +01004682 if (c == '>')
4683 {
4684 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004685 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004686 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4687 cursor_pos->col = ga_cell.ga_len;
4688 }
4689
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004690 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004691 c = fgetc(fd);
4692 if (c != EOF)
4693 ga_append(&ga_text, c);
4694 for (;;)
4695 {
4696 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004697 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004698 || c == EOF || c == '\n')
4699 break;
4700 ga_append(&ga_text, c);
4701 }
4702
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004703 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01004704 vim_free(prev_char);
4705 if (ga_text.ga_data != NULL)
4706 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4707 ga_text.ga_len - prev_len);
4708
Bram Moolenaar9271d052018-02-25 21:39:46 +01004709 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004710 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004711 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004712 }
4713 else if (c == '+' || c == '*')
4714 {
4715 int is_bg;
4716
4717 cell.width = c == '+' ? 1 : 2;
4718
4719 c = fgetc(fd);
4720 if (c == '&')
4721 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004722 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004723 c = fgetc(fd);
4724 }
4725 else if (isdigit(c))
4726 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004727 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01004728 attr = 0;
4729 while (isdigit(c))
4730 {
4731 attr = attr * 10 + (c - '0');
4732 c = fgetc(fd);
4733 }
4734 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004735
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004736 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004737 for (is_bg = 0; is_bg <= 1; ++is_bg)
4738 {
4739 if (c == '&')
4740 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004741 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004742 c = fgetc(fd);
4743 }
4744 else if (c == '#')
4745 {
4746 int red, green, blue, index = 0;
4747
4748 c = fgetc(fd);
4749 red = hex2nr(c);
4750 c = fgetc(fd);
4751 red = (red << 4) + hex2nr(c);
4752 c = fgetc(fd);
4753 green = hex2nr(c);
4754 c = fgetc(fd);
4755 green = (green << 4) + hex2nr(c);
4756 c = fgetc(fd);
4757 blue = hex2nr(c);
4758 c = fgetc(fd);
4759 blue = (blue << 4) + hex2nr(c);
4760 c = fgetc(fd);
4761 if (!isdigit(c))
4762 dump_is_corrupt(&ga_text);
4763 while (isdigit(c))
4764 {
4765 index = index * 10 + (c - '0');
4766 c = fgetc(fd);
4767 }
4768
4769 if (is_bg)
4770 {
4771 cell.bg.red = red;
4772 cell.bg.green = green;
4773 cell.bg.blue = blue;
4774 cell.bg.ansi_index = index;
4775 }
4776 else
4777 {
4778 cell.fg.red = red;
4779 cell.fg.green = green;
4780 cell.fg.blue = blue;
4781 cell.fg.ansi_index = index;
4782 }
4783 }
4784 else
4785 dump_is_corrupt(&ga_text);
4786 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004787 }
4788 else
4789 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004790 }
4791 else
4792 dump_is_corrupt(&ga_text);
4793
4794 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004795 if (cell.width == 2)
4796 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004797 }
4798 else if (c == '@')
4799 {
4800 if (prev_char == NULL)
4801 dump_is_corrupt(&ga_text);
4802 else
4803 {
4804 int count = 0;
4805
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004806 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01004807 for (;;)
4808 {
4809 c = fgetc(fd);
4810 if (!isdigit(c))
4811 break;
4812 count = count * 10 + (c - '0');
4813 }
4814
4815 while (count-- > 0)
4816 {
4817 ga_concat(&ga_text, prev_char);
4818 append_cell(&ga_cell, &cell);
4819 }
4820 }
4821 }
4822 else
4823 {
4824 dump_is_corrupt(&ga_text);
4825 c = fgetc(fd);
4826 }
4827 }
4828
4829 if (ga_text.ga_len > 0)
4830 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004831 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004832 dump_is_corrupt(&ga_text);
4833 ga_append(&ga_text, NUL);
4834 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4835 ga_text.ga_len, FALSE);
4836 }
4837
4838 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004839 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004840 vim_free(prev_char);
4841
4842 return max_cells;
4843}
4844
4845/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004846 * Return an allocated string with at least "text_width" "=" characters and
4847 * "fname" inserted in the middle.
4848 */
4849 static char_u *
4850get_separator(int text_width, char_u *fname)
4851{
4852 int width = MAX(text_width, curwin->w_width);
4853 char_u *textline;
4854 int fname_size;
4855 char_u *p = fname;
4856 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004857 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004858
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004859 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004860 if (textline == NULL)
4861 return NULL;
4862
4863 fname_size = vim_strsize(fname);
4864 if (fname_size < width - 8)
4865 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004866 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02004867 width = MAX(text_width, fname_size + 8);
4868 }
4869 else if (fname_size > width - 8)
4870 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004871 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02004872 p = gettail(fname);
4873 fname_size = vim_strsize(p);
4874 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004875 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02004876 while (fname_size > width - 8)
4877 {
4878 p += (*mb_ptr2len)(p);
4879 fname_size = vim_strsize(p);
4880 }
4881
4882 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4883 textline[i] = '=';
4884 textline[i++] = ' ';
4885
4886 STRCPY(textline + i, p);
4887 off = STRLEN(textline);
4888 textline[off] = ' ';
4889 for (i = 1; i < (width - fname_size) / 2; ++i)
4890 textline[off + i] = '=';
4891 textline[off + i] = NUL;
4892
4893 return textline;
4894}
4895
4896/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004897 * Common for "term_dumpdiff()" and "term_dumpload()".
4898 */
4899 static void
4900term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4901{
4902 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004903 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004904 char_u buf1[NUMBUFLEN];
4905 char_u buf2[NUMBUFLEN];
4906 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004907 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004908 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004909 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004910 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004911 char_u *textline = NULL;
4912
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004913 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004914 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004915 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004916 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004917 if (fname1 == NULL || (do_diff && fname2 == NULL))
4918 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004919 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004920 return;
4921 }
4922 fd1 = mch_fopen((char *)fname1, READBIN);
4923 if (fd1 == NULL)
4924 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004925 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004926 return;
4927 }
4928 if (do_diff)
4929 {
4930 fd2 = mch_fopen((char *)fname2, READBIN);
4931 if (fd2 == NULL)
4932 {
4933 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004934 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004935 return;
4936 }
4937 }
4938
4939 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004940 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4941 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4942 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4943 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4944 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004945
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004946 if (opt.jo_term_name == NULL)
4947 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004948 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004949
Bram Moolenaar51e14382019-05-25 20:21:28 +02004950 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004951 if (fname_tofree != NULL)
4952 {
4953 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4954 opt.jo_term_name = fname_tofree;
4955 }
4956 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004957
Bram Moolenaar87abab92019-06-03 21:14:59 +02004958 if (opt.jo_bufnr_buf != NULL)
4959 {
4960 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4961
4962 // With "bufnr" argument: enter the window with this buffer and make it
4963 // empty.
4964 if (wp == NULL)
4965 semsg(_(e_invarg2), "bufnr");
4966 else
4967 {
4968 buf = curbuf;
4969 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4970 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02004971 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02004972 redraw_later(NOT_VALID);
4973 }
4974 }
4975 else
4976 // Create a new terminal window.
4977 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4978
Bram Moolenaard96ff162018-02-18 22:13:29 +01004979 if (buf != NULL && buf->b_term != NULL)
4980 {
4981 int i;
4982 linenr_T bot_lnum;
4983 linenr_T lnum;
4984 term_T *term = buf->b_term;
4985 int width;
4986 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004987 VTermPos cursor_pos1;
4988 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004989
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004990 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004991
Bram Moolenaard96ff162018-02-18 22:13:29 +01004992 rettv->vval.v_number = buf->b_fnum;
4993
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004994 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01004995 width = read_dump_file(fd1, &cursor_pos1);
4996
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004997 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004998 if (cursor_pos1.row >= 0)
4999 {
5000 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5001 coladvance(cursor_pos1.col);
5002 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005003
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005004 // Delete the empty line that was in the empty buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005005 ml_delete(1, FALSE);
5006
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005007 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005008 if (!do_diff)
5009 goto theend;
5010
5011 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5012
Bram Moolenaar4a696342018-04-05 18:45:26 +02005013 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005014 if (textline == NULL)
5015 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005016 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5017 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5018 vim_free(textline);
5019
5020 textline = get_separator(width, fname2);
5021 if (textline == NULL)
5022 goto theend;
5023 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5024 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005025 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005026
5027 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005028 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005029 if (width2 > width)
5030 {
5031 vim_free(textline);
5032 textline = alloc(width2 + 1);
5033 if (textline == NULL)
5034 goto theend;
5035 width = width2;
5036 textline[width] = NUL;
5037 }
5038 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5039
5040 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5041 {
5042 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5043 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005044 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005045 for (i = 0; i < width; ++i)
5046 textline[i] = '-';
5047 }
5048 else
5049 {
5050 char_u *line1;
5051 char_u *line2;
5052 char_u *p1;
5053 char_u *p2;
5054 int col;
5055 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5056 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5057 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5058 ->sb_cells;
5059
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005060 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005061 line1 = vim_strsave(ml_get(lnum));
5062 if (line1 == NULL)
5063 break;
5064 p1 = line1;
5065
5066 line2 = ml_get(lnum + bot_lnum);
5067 p2 = line2;
5068 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5069 {
5070 int len1 = utfc_ptr2len(p1);
5071 int len2 = utfc_ptr2len(p2);
5072
5073 textline[col] = ' ';
5074 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005075 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005076 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005077 else if (lnum == cursor_pos1.row + 1
5078 && col == cursor_pos1.col
5079 && (cursor_pos1.row != cursor_pos2.row
5080 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005081 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005082 textline[col] = '>';
5083 else if (lnum == cursor_pos2.row + 1
5084 && col == cursor_pos2.col
5085 && (cursor_pos1.row != cursor_pos2.row
5086 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005087 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005088 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005089 else if (cellattr1 != NULL && cellattr2 != NULL)
5090 {
5091 if ((cellattr1 + col)->width
5092 != (cellattr2 + col)->width)
5093 textline[col] = 'w';
5094 else if (!same_color(&(cellattr1 + col)->fg,
5095 &(cellattr2 + col)->fg))
5096 textline[col] = 'f';
5097 else if (!same_color(&(cellattr1 + col)->bg,
5098 &(cellattr2 + col)->bg))
5099 textline[col] = 'b';
5100 else if (vtermAttr2hl((cellattr1 + col)->attrs)
5101 != vtermAttr2hl(((cellattr2 + col)->attrs)))
5102 textline[col] = 'a';
5103 }
5104 p1 += len1;
5105 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005106 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005107 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005108
5109 while (col < width)
5110 {
5111 if (*p1 == NUL && *p2 == NUL)
5112 textline[col] = '?';
5113 else if (*p1 == NUL)
5114 {
5115 textline[col] = '+';
5116 p2 += utfc_ptr2len(p2);
5117 }
5118 else
5119 {
5120 textline[col] = '-';
5121 p1 += utfc_ptr2len(p1);
5122 }
5123 ++col;
5124 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005125
5126 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005127 }
5128 if (add_empty_scrollback(term, &term->tl_default_color,
5129 term->tl_top_diff_rows) == OK)
5130 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5131 ++bot_lnum;
5132 }
5133
5134 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5135 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005136 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005137 for (i = 0; i < width; ++i)
5138 textline[i] = '+';
5139 if (add_empty_scrollback(term, &term->tl_default_color,
5140 term->tl_top_diff_rows) == OK)
5141 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5142 ++lnum;
5143 ++bot_lnum;
5144 }
5145
5146 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005147
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005148 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005149 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005150 }
5151
5152theend:
5153 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005154 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005155 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005156 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005157 fclose(fd2);
5158}
5159
5160/*
5161 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5162 * bottom files.
5163 * Return FAIL when this is not possible.
5164 */
5165 int
5166term_swap_diff()
5167{
5168 term_T *term = curbuf->b_term;
5169 linenr_T line_count;
5170 linenr_T top_rows;
5171 linenr_T bot_rows;
5172 linenr_T bot_start;
5173 linenr_T lnum;
5174 char_u *p;
5175 sb_line_T *sb_line;
5176
5177 if (term == NULL
5178 || !term_is_finished(curbuf)
5179 || term->tl_top_diff_rows == 0
5180 || term->tl_scrollback.ga_len == 0)
5181 return FAIL;
5182
5183 line_count = curbuf->b_ml.ml_line_count;
5184 top_rows = term->tl_top_diff_rows;
5185 bot_rows = term->tl_bot_diff_rows;
5186 bot_start = line_count - bot_rows;
5187 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5188
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005189 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005190 for (lnum = 1; lnum <= top_rows; ++lnum)
5191 {
5192 p = vim_strsave(ml_get(1));
5193 if (p == NULL)
5194 return OK;
5195 ml_append(bot_start, p, 0, FALSE);
5196 ml_delete(1, FALSE);
5197 vim_free(p);
5198 }
5199
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005200 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005201 for (lnum = 1; lnum <= bot_rows; ++lnum)
5202 {
5203 p = vim_strsave(ml_get(bot_start + lnum));
5204 if (p == NULL)
5205 return OK;
5206 ml_delete(bot_start + lnum, FALSE);
5207 ml_append(lnum - 1, p, 0, FALSE);
5208 vim_free(p);
5209 }
5210
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005211 // move top title to bottom
5212 p = vim_strsave(ml_get(bot_rows + 1));
5213 if (p == NULL)
5214 return OK;
5215 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5216 ml_delete(bot_rows + 1, FALSE);
5217 vim_free(p);
5218
5219 // move bottom title to top
5220 p = vim_strsave(ml_get(line_count - top_rows));
5221 if (p == NULL)
5222 return OK;
5223 ml_delete(line_count - top_rows, FALSE);
5224 ml_append(bot_rows, p, 0, FALSE);
5225 vim_free(p);
5226
Bram Moolenaard96ff162018-02-18 22:13:29 +01005227 if (top_rows == bot_rows)
5228 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005229 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005230 for (lnum = 0; lnum < top_rows; ++lnum)
5231 {
5232 sb_line_T temp;
5233
5234 temp = *(sb_line + lnum);
5235 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5236 *(sb_line + bot_start + lnum) = temp;
5237 }
5238 }
5239 else
5240 {
5241 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005242 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005243
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005244 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005245 if (temp != NULL)
5246 {
5247 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5248 mch_memmove(term->tl_scrollback.ga_data,
5249 temp + bot_start,
5250 sizeof(sb_line_T) * bot_rows);
5251 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5252 temp + top_rows,
5253 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5254 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5255 + line_count - top_rows,
5256 temp,
5257 sizeof(sb_line_T) * top_rows);
5258 vim_free(temp);
5259 }
5260 }
5261
5262 term->tl_top_diff_rows = bot_rows;
5263 term->tl_bot_diff_rows = top_rows;
5264
5265 update_screen(NOT_VALID);
5266 return OK;
5267}
5268
5269/*
5270 * "term_dumpdiff(filename, filename, options)" function
5271 */
5272 void
5273f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5274{
5275 term_load_dump(argvars, rettv, TRUE);
5276}
5277
5278/*
5279 * "term_dumpload(filename, options)" function
5280 */
5281 void
5282f_term_dumpload(typval_T *argvars, typval_T *rettv)
5283{
5284 term_load_dump(argvars, rettv, FALSE);
5285}
5286
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005287/*
5288 * "term_getaltscreen(buf)" function
5289 */
5290 void
5291f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5292{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005293 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005294
5295 if (buf == NULL)
5296 return;
5297 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5298}
5299
5300/*
5301 * "term_getattr(attr, name)" function
5302 */
5303 void
5304f_term_getattr(typval_T *argvars, typval_T *rettv)
5305{
5306 int attr;
5307 size_t i;
5308 char_u *name;
5309
5310 static struct {
5311 char *name;
5312 int attr;
5313 } attrs[] = {
5314 {"bold", HL_BOLD},
5315 {"italic", HL_ITALIC},
5316 {"underline", HL_UNDERLINE},
5317 {"strike", HL_STRIKETHROUGH},
5318 {"reverse", HL_INVERSE},
5319 };
5320
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005321 attr = tv_get_number(&argvars[0]);
5322 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005323 if (name == NULL)
5324 return;
5325
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005326 if (attr > HL_ALL)
5327 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005328 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5329 if (STRCMP(name, attrs[i].name) == 0)
5330 {
5331 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5332 break;
5333 }
5334}
5335
5336/*
5337 * "term_getcursor(buf)" function
5338 */
5339 void
5340f_term_getcursor(typval_T *argvars, typval_T *rettv)
5341{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005342 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005343 term_T *term;
5344 list_T *l;
5345 dict_T *d;
5346
5347 if (rettv_list_alloc(rettv) == FAIL)
5348 return;
5349 if (buf == NULL)
5350 return;
5351 term = buf->b_term;
5352
5353 l = rettv->vval.v_list;
5354 list_append_number(l, term->tl_cursor_pos.row + 1);
5355 list_append_number(l, term->tl_cursor_pos.col + 1);
5356
5357 d = dict_alloc();
5358 if (d != NULL)
5359 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005360 dict_add_number(d, "visible", term->tl_cursor_visible);
5361 dict_add_number(d, "blink", blink_state_is_inverted()
5362 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5363 dict_add_number(d, "shape", term->tl_cursor_shape);
5364 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005365 list_append_dict(l, d);
5366 }
5367}
5368
5369/*
5370 * "term_getjob(buf)" function
5371 */
5372 void
5373f_term_getjob(typval_T *argvars, typval_T *rettv)
5374{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005375 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005376
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005377 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005378 {
5379 rettv->v_type = VAR_SPECIAL;
5380 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005381 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005382 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005383
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005384 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005385 rettv->vval.v_job = buf->b_term->tl_job;
5386 if (rettv->vval.v_job != NULL)
5387 ++rettv->vval.v_job->jv_refcount;
5388}
5389
5390 static int
5391get_row_number(typval_T *tv, term_T *term)
5392{
5393 if (tv->v_type == VAR_STRING
5394 && tv->vval.v_string != NULL
5395 && STRCMP(tv->vval.v_string, ".") == 0)
5396 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005397 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005398}
5399
5400/*
5401 * "term_getline(buf, row)" function
5402 */
5403 void
5404f_term_getline(typval_T *argvars, typval_T *rettv)
5405{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005406 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005407 term_T *term;
5408 int row;
5409
5410 rettv->v_type = VAR_STRING;
5411 if (buf == NULL)
5412 return;
5413 term = buf->b_term;
5414 row = get_row_number(&argvars[1], term);
5415
5416 if (term->tl_vterm == NULL)
5417 {
5418 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5419
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005420 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005421 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5422 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5423 }
5424 else
5425 {
5426 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5427 VTermRect rect;
5428 int len;
5429 char_u *p;
5430
5431 if (row < 0 || row >= term->tl_rows)
5432 return;
5433 len = term->tl_cols * MB_MAXBYTES + 1;
5434 p = alloc(len);
5435 if (p == NULL)
5436 return;
5437 rettv->vval.v_string = p;
5438
5439 rect.start_col = 0;
5440 rect.end_col = term->tl_cols;
5441 rect.start_row = row;
5442 rect.end_row = row + 1;
5443 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5444 }
5445}
5446
5447/*
5448 * "term_getscrolled(buf)" function
5449 */
5450 void
5451f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5452{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005453 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005454
5455 if (buf == NULL)
5456 return;
5457 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5458}
5459
5460/*
5461 * "term_getsize(buf)" function
5462 */
5463 void
5464f_term_getsize(typval_T *argvars, typval_T *rettv)
5465{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005466 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005467 list_T *l;
5468
5469 if (rettv_list_alloc(rettv) == FAIL)
5470 return;
5471 if (buf == NULL)
5472 return;
5473
5474 l = rettv->vval.v_list;
5475 list_append_number(l, buf->b_term->tl_rows);
5476 list_append_number(l, buf->b_term->tl_cols);
5477}
5478
5479/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005480 * "term_setsize(buf, rows, cols)" function
5481 */
5482 void
5483f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5484{
5485 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5486 term_T *term;
5487 varnumber_T rows, cols;
5488
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005489 if (buf == NULL)
5490 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005491 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005492 return;
5493 }
5494 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005495 return;
5496 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005497 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005498 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005499 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005500 cols = cols <= 0 ? term->tl_cols : cols;
5501 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005502 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02005503
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005504 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02005505 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5506 term_report_winsize(term, term->tl_rows, term->tl_cols);
5507}
5508
5509/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005510 * "term_getstatus(buf)" function
5511 */
5512 void
5513f_term_getstatus(typval_T *argvars, typval_T *rettv)
5514{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005515 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005516 term_T *term;
5517 char_u val[100];
5518
5519 rettv->v_type = VAR_STRING;
5520 if (buf == NULL)
5521 return;
5522 term = buf->b_term;
5523
5524 if (term_job_running(term))
5525 STRCPY(val, "running");
5526 else
5527 STRCPY(val, "finished");
5528 if (term->tl_normal_mode)
5529 STRCAT(val, ",normal");
5530 rettv->vval.v_string = vim_strsave(val);
5531}
5532
5533/*
5534 * "term_gettitle(buf)" function
5535 */
5536 void
5537f_term_gettitle(typval_T *argvars, typval_T *rettv)
5538{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005539 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005540
5541 rettv->v_type = VAR_STRING;
5542 if (buf == NULL)
5543 return;
5544
5545 if (buf->b_term->tl_title != NULL)
5546 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5547}
5548
5549/*
5550 * "term_gettty(buf)" function
5551 */
5552 void
5553f_term_gettty(typval_T *argvars, typval_T *rettv)
5554{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005555 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005556 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005557 int num = 0;
5558
5559 rettv->v_type = VAR_STRING;
5560 if (buf == NULL)
5561 return;
5562 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005563 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005564
5565 switch (num)
5566 {
5567 case 0:
5568 if (buf->b_term->tl_job != NULL)
5569 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005570 break;
5571 case 1:
5572 if (buf->b_term->tl_job != NULL)
5573 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005574 break;
5575 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005576 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005577 return;
5578 }
5579 if (p != NULL)
5580 rettv->vval.v_string = vim_strsave(p);
5581}
5582
5583/*
5584 * "term_list()" function
5585 */
5586 void
5587f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5588{
5589 term_T *tp;
5590 list_T *l;
5591
5592 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5593 return;
5594
5595 l = rettv->vval.v_list;
5596 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5597 if (tp != NULL && tp->tl_buffer != NULL)
5598 if (list_append_number(l,
5599 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5600 return;
5601}
5602
5603/*
5604 * "term_scrape(buf, row)" function
5605 */
5606 void
5607f_term_scrape(typval_T *argvars, typval_T *rettv)
5608{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005609 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005610 VTermScreen *screen = NULL;
5611 VTermPos pos;
5612 list_T *l;
5613 term_T *term;
5614 char_u *p;
5615 sb_line_T *line;
5616
5617 if (rettv_list_alloc(rettv) == FAIL)
5618 return;
5619 if (buf == NULL)
5620 return;
5621 term = buf->b_term;
5622
5623 l = rettv->vval.v_list;
5624 pos.row = get_row_number(&argvars[1], term);
5625
5626 if (term->tl_vterm != NULL)
5627 {
5628 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005629 if (screen == NULL) // can't really happen
5630 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005631 p = NULL;
5632 line = NULL;
5633 }
5634 else
5635 {
5636 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5637
5638 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5639 return;
5640 p = ml_get_buf(buf, lnum + 1, FALSE);
5641 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5642 }
5643
5644 for (pos.col = 0; pos.col < term->tl_cols; )
5645 {
5646 dict_T *dcell;
5647 int width;
5648 VTermScreenCellAttrs attrs;
5649 VTermColor fg, bg;
5650 char_u rgb[8];
5651 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5652 int off = 0;
5653 int i;
5654
5655 if (screen == NULL)
5656 {
5657 cellattr_T *cellattr;
5658 int len;
5659
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005660 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005661 if (pos.col >= line->sb_cols)
5662 break;
5663 cellattr = line->sb_cells + pos.col;
5664 width = cellattr->width;
5665 attrs = cellattr->attrs;
5666 fg = cellattr->fg;
5667 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005668 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005669 mch_memmove(mbs, p, len);
5670 mbs[len] = NUL;
5671 p += len;
5672 }
5673 else
5674 {
5675 VTermScreenCell cell;
5676 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5677 break;
5678 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5679 {
5680 if (cell.chars[i] == 0)
5681 break;
5682 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5683 }
5684 mbs[off] = NUL;
5685 width = cell.width;
5686 attrs = cell.attrs;
5687 fg = cell.fg;
5688 bg = cell.bg;
5689 }
5690 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005691 if (dcell == NULL)
5692 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005693 list_append_dict(l, dcell);
5694
Bram Moolenaare0be1672018-07-08 16:50:37 +02005695 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005696
5697 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5698 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005699 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005700 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5701 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005702 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005703
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005704 dict_add_number(dcell, "attr", cell2attr(NULL, attrs, fg, bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02005705 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005706
5707 ++pos.col;
5708 if (width == 2)
5709 ++pos.col;
5710 }
5711}
5712
5713/*
5714 * "term_sendkeys(buf, keys)" function
5715 */
5716 void
5717f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5718{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005719 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005720 char_u *msg;
5721 term_T *term;
5722
5723 rettv->v_type = VAR_UNKNOWN;
5724 if (buf == NULL)
5725 return;
5726
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005727 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005728 if (msg == NULL)
5729 return;
5730 term = buf->b_term;
5731 if (term->tl_vterm == NULL)
5732 return;
5733
5734 while (*msg != NUL)
5735 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005736 int c;
5737
5738 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5739 {
5740 c = TO_SPECIAL(msg[1], msg[2]);
5741 msg += 3;
5742 }
5743 else
5744 {
5745 c = PTR2CHAR(msg);
5746 msg += MB_CPTR2LEN(msg);
5747 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005748 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005749 }
5750}
5751
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005752#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5753/*
5754 * "term_getansicolors(buf)" function
5755 */
5756 void
5757f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5758{
5759 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5760 term_T *term;
5761 VTermState *state;
5762 VTermColor color;
5763 char_u hexbuf[10];
5764 int index;
5765 list_T *list;
5766
5767 if (rettv_list_alloc(rettv) == FAIL)
5768 return;
5769
5770 if (buf == NULL)
5771 return;
5772 term = buf->b_term;
5773 if (term->tl_vterm == NULL)
5774 return;
5775
5776 list = rettv->vval.v_list;
5777 state = vterm_obtain_state(term->tl_vterm);
5778 for (index = 0; index < 16; index++)
5779 {
5780 vterm_state_get_palette_color(state, index, &color);
5781 sprintf((char *)hexbuf, "#%02x%02x%02x",
5782 color.red, color.green, color.blue);
5783 if (list_append_string(list, hexbuf, 7) == FAIL)
5784 return;
5785 }
5786}
5787
5788/*
5789 * "term_setansicolors(buf, list)" function
5790 */
5791 void
5792f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5793{
5794 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5795 term_T *term;
5796
5797 if (buf == NULL)
5798 return;
5799 term = buf->b_term;
5800 if (term->tl_vterm == NULL)
5801 return;
5802
5803 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5804 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005805 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005806 return;
5807 }
5808
5809 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005810 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005811}
5812#endif
5813
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005814/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005815 * "term_setapi(buf, api)" function
5816 */
5817 void
5818f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5819{
5820 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5821 term_T *term;
5822 char_u *api;
5823
5824 if (buf == NULL)
5825 return;
5826 term = buf->b_term;
5827 vim_free(term->tl_api);
5828 api = tv_get_string_chk(&argvars[1]);
5829 if (api != NULL)
5830 term->tl_api = vim_strsave(api);
5831 else
5832 term->tl_api = NULL;
5833}
5834
5835/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005836 * "term_setrestore(buf, command)" function
5837 */
5838 void
5839f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5840{
5841#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005842 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005843 term_T *term;
5844 char_u *cmd;
5845
5846 if (buf == NULL)
5847 return;
5848 term = buf->b_term;
5849 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005850 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005851 if (cmd != NULL)
5852 term->tl_command = vim_strsave(cmd);
5853 else
5854 term->tl_command = NULL;
5855#endif
5856}
5857
5858/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005859 * "term_setkill(buf, how)" function
5860 */
5861 void
5862f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5863{
5864 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5865 term_T *term;
5866 char_u *how;
5867
5868 if (buf == NULL)
5869 return;
5870 term = buf->b_term;
5871 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005872 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005873 if (how != NULL)
5874 term->tl_kill = vim_strsave(how);
5875 else
5876 term->tl_kill = NULL;
5877}
5878
5879/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005880 * "term_start(command, options)" function
5881 */
5882 void
5883f_term_start(typval_T *argvars, typval_T *rettv)
5884{
5885 jobopt_T opt;
5886 buf_T *buf;
5887
5888 init_job_options(&opt);
5889 if (argvars[1].v_type != VAR_UNKNOWN
5890 && get_job_options(&argvars[1], &opt,
5891 JO_TIMEOUT_ALL + JO_STOPONEXIT
5892 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5893 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5894 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5895 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005896 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005897 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005898 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005899 return;
5900
Bram Moolenaar13568252018-03-16 20:46:58 +01005901 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005902
5903 if (buf != NULL && buf->b_term != NULL)
5904 rettv->vval.v_number = buf->b_fnum;
5905}
5906
5907/*
5908 * "term_wait" function
5909 */
5910 void
5911f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5912{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005913 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005914
5915 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005916 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005917 if (buf->b_term->tl_job == NULL)
5918 {
5919 ch_log(NULL, "term_wait(): no job to wait for");
5920 return;
5921 }
5922 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005923 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005924 return;
5925
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005926 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01005927 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005928 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5929 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005930 // The job is dead, keep reading channel I/O until the channel is
5931 // closed. buf->b_term may become NULL if the terminal was closed while
5932 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005933 ch_log(NULL, "term_wait(): waiting for channel to close");
5934 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5935 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005936 term_flush_messages();
5937
Bram Moolenaard45aa552018-05-21 22:50:29 +02005938 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005939 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005940 // If the terminal is closed when the channel is closed the
5941 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01005942 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005943 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005944
5945 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005946 }
5947 else
5948 {
5949 long wait = 10L;
5950
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005951 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005952
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005953 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005954 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005955 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005956 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005957
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005958 // Flushing messages on channels is hopefully sufficient.
5959 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005960 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005961 }
5962}
5963
5964/*
5965 * Called when a channel has sent all the lines to a terminal.
5966 * Send a CTRL-D to mark the end of the text.
5967 */
5968 void
5969term_send_eof(channel_T *ch)
5970{
5971 term_T *term;
5972
5973 for (term = first_term; term != NULL; term = term->tl_next)
5974 if (term->tl_job == ch->ch_job)
5975 {
5976 if (term->tl_eof_chars != NULL)
5977 {
5978 channel_send(ch, PART_IN, term->tl_eof_chars,
5979 (int)STRLEN(term->tl_eof_chars), NULL);
5980 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5981 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005982# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005983 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005984 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005985 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5986# endif
5987 }
5988}
5989
Bram Moolenaar113e1072019-01-20 15:30:40 +01005990#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005991 job_T *
5992term_getjob(term_T *term)
5993{
5994 return term != NULL ? term->tl_job : NULL;
5995}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005996#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005997
Bram Moolenaar4f974752019-02-17 17:44:42 +01005998# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005999
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006000///////////////////////////////////////
6001// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006002#ifdef PROTO
6003typedef int COORD;
6004typedef int DWORD;
6005typedef int HANDLE;
6006typedef int *DWORD_PTR;
6007typedef int HPCON;
6008typedef int HRESULT;
6009typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006010typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006011typedef int PSIZE_T;
6012typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006013typedef int BOOL;
6014# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006015#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006016
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006017HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6018HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6019HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006020BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6021BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6022void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006023
6024 static int
6025dyn_conpty_init(int verbose)
6026{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006027 static HMODULE hKerneldll = NULL;
6028 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006029 static struct
6030 {
6031 char *name;
6032 FARPROC *ptr;
6033 } conpty_entry[] =
6034 {
6035 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6036 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6037 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6038 {"InitializeProcThreadAttributeList",
6039 (FARPROC*)&pInitializeProcThreadAttributeList},
6040 {"UpdateProcThreadAttribute",
6041 (FARPROC*)&pUpdateProcThreadAttribute},
6042 {"DeleteProcThreadAttributeList",
6043 (FARPROC*)&pDeleteProcThreadAttributeList},
6044 {NULL, NULL}
6045 };
6046
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006047 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006048 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006049 if (verbose)
6050 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006051 return FAIL;
6052 }
6053
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006054 // No need to initialize twice.
6055 if (hKerneldll)
6056 return OK;
6057
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006058 hKerneldll = vimLoadLib("kernel32.dll");
6059 for (i = 0; conpty_entry[i].name != NULL
6060 && conpty_entry[i].ptr != NULL; ++i)
6061 {
6062 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6063 conpty_entry[i].name)) == NULL)
6064 {
6065 if (verbose)
6066 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006067 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006068 return FAIL;
6069 }
6070 }
6071
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006072 return OK;
6073}
6074
6075 static int
6076conpty_term_and_job_init(
6077 term_T *term,
6078 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006079 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006080 jobopt_T *opt,
6081 jobopt_T *orig_opt)
6082{
6083 WCHAR *cmd_wchar = NULL;
6084 WCHAR *cmd_wchar_copy = NULL;
6085 WCHAR *cwd_wchar = NULL;
6086 WCHAR *env_wchar = NULL;
6087 channel_T *channel = NULL;
6088 job_T *job = NULL;
6089 HANDLE jo = NULL;
6090 garray_T ga_cmd, ga_env;
6091 char_u *cmd = NULL;
6092 HRESULT hr;
6093 COORD consize;
6094 SIZE_T breq;
6095 PROCESS_INFORMATION proc_info;
6096 HANDLE i_theirs = NULL;
6097 HANDLE o_theirs = NULL;
6098 HANDLE i_ours = NULL;
6099 HANDLE o_ours = NULL;
6100
6101 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6102 ga_init2(&ga_env, (int)sizeof(char*), 20);
6103
6104 if (argvar->v_type == VAR_STRING)
6105 {
6106 cmd = argvar->vval.v_string;
6107 }
6108 else if (argvar->v_type == VAR_LIST)
6109 {
6110 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6111 goto failed;
6112 cmd = ga_cmd.ga_data;
6113 }
6114 if (cmd == NULL || *cmd == NUL)
6115 {
6116 emsg(_(e_invarg));
6117 goto failed;
6118 }
6119
6120 term->tl_arg0_cmd = vim_strsave(cmd);
6121
6122 cmd_wchar = enc_to_utf16(cmd, NULL);
6123
6124 if (cmd_wchar != NULL)
6125 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006126 // Request by CreateProcessW
6127 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006128 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006129 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6130 }
6131
6132 ga_clear(&ga_cmd);
6133 if (cmd_wchar == NULL)
6134 goto failed;
6135 if (opt->jo_cwd != NULL)
6136 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6137
6138 win32_build_env(opt->jo_env, &ga_env, TRUE);
6139 env_wchar = ga_env.ga_data;
6140
6141 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6142 goto failed;
6143 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6144 goto failed;
6145
6146 consize.X = term->tl_cols;
6147 consize.Y = term->tl_rows;
6148 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6149 &term->tl_conpty);
6150 if (FAILED(hr))
6151 goto failed;
6152
6153 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6154
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006155 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006156 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006157 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006158 if (!term->tl_siex.lpAttributeList)
6159 goto failed;
6160 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6161 0, &breq))
6162 goto failed;
6163 if (!pUpdateProcThreadAttribute(
6164 term->tl_siex.lpAttributeList, 0,
6165 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6166 sizeof(HPCON), NULL, NULL))
6167 goto failed;
6168
6169 channel = add_channel();
6170 if (channel == NULL)
6171 goto failed;
6172
6173 job = job_alloc();
6174 if (job == NULL)
6175 goto failed;
6176 if (argvar->v_type == VAR_STRING)
6177 {
6178 int argc;
6179
6180 build_argv_from_string(cmd, &job->jv_argv, &argc);
6181 }
6182 else
6183 {
6184 int argc;
6185
6186 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6187 }
6188
6189 if (opt->jo_set & JO_IN_BUF)
6190 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6191
6192 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6193 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
6194 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
6195 | CREATE_DEFAULT_ERROR_MODE,
6196 env_wchar, cwd_wchar,
6197 &term->tl_siex.StartupInfo, &proc_info))
6198 goto failed;
6199
6200 CloseHandle(i_theirs);
6201 CloseHandle(o_theirs);
6202
6203 channel_set_pipes(channel,
6204 (sock_T)i_ours,
6205 (sock_T)o_ours,
6206 (sock_T)o_ours);
6207
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006208 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006209 channel->ch_write_text_mode = TRUE;
6210
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006211 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006212 channel->ch_anonymous_pipe = TRUE;
6213
6214 jo = CreateJobObject(NULL, NULL);
6215 if (jo == NULL)
6216 goto failed;
6217
6218 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6219 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006220 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006221 CloseHandle(jo);
6222 jo = NULL;
6223 }
6224
6225 ResumeThread(proc_info.hThread);
6226 CloseHandle(proc_info.hThread);
6227
6228 vim_free(cmd_wchar);
6229 vim_free(cmd_wchar_copy);
6230 vim_free(cwd_wchar);
6231 vim_free(env_wchar);
6232
6233 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6234 goto failed;
6235
6236#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6237 if (opt->jo_set2 & JO2_ANSI_COLORS)
6238 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6239 else
6240 init_vterm_ansi_colors(term->tl_vterm);
6241#endif
6242
6243 channel_set_job(channel, job, opt);
6244 job_set_options(job, opt);
6245
6246 job->jv_channel = channel;
6247 job->jv_proc_info = proc_info;
6248 job->jv_job_object = jo;
6249 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006250 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006251 ++job->jv_refcount;
6252 term->tl_job = job;
6253
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006254 // Redirecting stdout and stderr doesn't work at the job level. Instead
6255 // open the file here and handle it in. opt->jo_io was changed in
6256 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006257 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6258 {
6259 char_u *fname = opt->jo_io_name[PART_OUT];
6260
6261 ch_log(channel, "Opening output file %s", fname);
6262 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6263 if (term->tl_out_fd == NULL)
6264 semsg(_(e_notopen), fname);
6265 }
6266
6267 return OK;
6268
6269failed:
6270 ga_clear(&ga_cmd);
6271 ga_clear(&ga_env);
6272 vim_free(cmd_wchar);
6273 vim_free(cmd_wchar_copy);
6274 vim_free(cwd_wchar);
6275 if (channel != NULL)
6276 channel_clear(channel);
6277 if (job != NULL)
6278 {
6279 job->jv_channel = NULL;
6280 job_cleanup(job);
6281 }
6282 term->tl_job = NULL;
6283 if (jo != NULL)
6284 CloseHandle(jo);
6285
6286 if (term->tl_siex.lpAttributeList != NULL)
6287 {
6288 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6289 vim_free(term->tl_siex.lpAttributeList);
6290 }
6291 term->tl_siex.lpAttributeList = NULL;
6292 if (o_theirs != NULL)
6293 CloseHandle(o_theirs);
6294 if (o_ours != NULL)
6295 CloseHandle(o_ours);
6296 if (i_ours != NULL)
6297 CloseHandle(i_ours);
6298 if (i_theirs != NULL)
6299 CloseHandle(i_theirs);
6300 if (term->tl_conpty != NULL)
6301 pClosePseudoConsole(term->tl_conpty);
6302 term->tl_conpty = NULL;
6303 return FAIL;
6304}
6305
6306 static void
6307conpty_term_report_winsize(term_T *term, int rows, int cols)
6308{
6309 COORD consize;
6310
6311 consize.X = cols;
6312 consize.Y = rows;
6313 pResizePseudoConsole(term->tl_conpty, consize);
6314}
6315
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006316 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006317term_free_conpty(term_T *term)
6318{
6319 if (term->tl_siex.lpAttributeList != NULL)
6320 {
6321 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6322 vim_free(term->tl_siex.lpAttributeList);
6323 }
6324 term->tl_siex.lpAttributeList = NULL;
6325 if (term->tl_conpty != NULL)
6326 pClosePseudoConsole(term->tl_conpty);
6327 term->tl_conpty = NULL;
6328}
6329
6330 int
6331use_conpty(void)
6332{
6333 return has_conpty;
6334}
6335
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006336# ifndef PROTO
6337
6338#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6339#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006340#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006341
6342void* (*winpty_config_new)(UINT64, void*);
6343void* (*winpty_open)(void*, void*);
6344void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6345BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6346void (*winpty_config_set_mouse_mode)(void*, int);
6347void (*winpty_config_set_initial_size)(void*, int, int);
6348LPCWSTR (*winpty_conin_name)(void*);
6349LPCWSTR (*winpty_conout_name)(void*);
6350LPCWSTR (*winpty_conerr_name)(void*);
6351void (*winpty_free)(void*);
6352void (*winpty_config_free)(void*);
6353void (*winpty_spawn_config_free)(void*);
6354void (*winpty_error_free)(void*);
6355LPCWSTR (*winpty_error_msg)(void*);
6356BOOL (*winpty_set_size)(void*, int, int, void*);
6357HANDLE (*winpty_agent_process)(void*);
6358
6359#define WINPTY_DLL "winpty.dll"
6360
6361static HINSTANCE hWinPtyDLL = NULL;
6362# endif
6363
6364 static int
6365dyn_winpty_init(int verbose)
6366{
6367 int i;
6368 static struct
6369 {
6370 char *name;
6371 FARPROC *ptr;
6372 } winpty_entry[] =
6373 {
6374 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6375 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6376 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6377 {"winpty_config_set_mouse_mode",
6378 (FARPROC*)&winpty_config_set_mouse_mode},
6379 {"winpty_config_set_initial_size",
6380 (FARPROC*)&winpty_config_set_initial_size},
6381 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6382 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6383 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6384 {"winpty_free", (FARPROC*)&winpty_free},
6385 {"winpty_open", (FARPROC*)&winpty_open},
6386 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6387 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6388 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6389 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6390 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6391 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6392 {NULL, NULL}
6393 };
6394
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006395 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006396 if (hWinPtyDLL)
6397 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006398 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6399 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006400 if (*p_winptydll != NUL)
6401 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6402 if (!hWinPtyDLL)
6403 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6404 if (!hWinPtyDLL)
6405 {
6406 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006407 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006408 : (char_u *)WINPTY_DLL);
6409 return FAIL;
6410 }
6411 for (i = 0; winpty_entry[i].name != NULL
6412 && winpty_entry[i].ptr != NULL; ++i)
6413 {
6414 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6415 winpty_entry[i].name)) == NULL)
6416 {
6417 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006418 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006419 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006420 return FAIL;
6421 }
6422 }
6423
6424 return OK;
6425}
6426
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006427 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006428winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006429 term_T *term,
6430 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006431 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006432 jobopt_T *opt,
6433 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006434{
6435 WCHAR *cmd_wchar = NULL;
6436 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006437 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006438 channel_T *channel = NULL;
6439 job_T *job = NULL;
6440 DWORD error;
6441 HANDLE jo = NULL;
6442 HANDLE child_process_handle;
6443 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006444 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006445 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006446 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006447 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006448
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006449 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6450 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006451
6452 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006453 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006454 cmd = argvar->vval.v_string;
6455 }
6456 else if (argvar->v_type == VAR_LIST)
6457 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006458 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006459 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006460 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006461 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006462 if (cmd == NULL || *cmd == NUL)
6463 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006464 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006465 goto failed;
6466 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006467
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006468 term->tl_arg0_cmd = vim_strsave(cmd);
6469
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006470 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006471 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006472 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006473 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006474 if (opt->jo_cwd != NULL)
6475 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006476
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006477 win32_build_env(opt->jo_env, &ga_env, TRUE);
6478 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006479
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006480 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6481 if (term->tl_winpty_config == NULL)
6482 goto failed;
6483
6484 winpty_config_set_mouse_mode(term->tl_winpty_config,
6485 WINPTY_MOUSE_MODE_FORCE);
6486 winpty_config_set_initial_size(term->tl_winpty_config,
6487 term->tl_cols, term->tl_rows);
6488 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6489 if (term->tl_winpty == NULL)
6490 goto failed;
6491
6492 spawn_config = winpty_spawn_config_new(
6493 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6494 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6495 NULL,
6496 cmd_wchar,
6497 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006498 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006499 &winpty_err);
6500 if (spawn_config == NULL)
6501 goto failed;
6502
6503 channel = add_channel();
6504 if (channel == NULL)
6505 goto failed;
6506
6507 job = job_alloc();
6508 if (job == NULL)
6509 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006510 if (argvar->v_type == VAR_STRING)
6511 {
6512 int argc;
6513
6514 build_argv_from_string(cmd, &job->jv_argv, &argc);
6515 }
6516 else
6517 {
6518 int argc;
6519
6520 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6521 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006522
6523 if (opt->jo_set & JO_IN_BUF)
6524 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6525
6526 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6527 &child_thread_handle, &error, &winpty_err))
6528 goto failed;
6529
6530 channel_set_pipes(channel,
6531 (sock_T)CreateFileW(
6532 winpty_conin_name(term->tl_winpty),
6533 GENERIC_WRITE, 0, NULL,
6534 OPEN_EXISTING, 0, NULL),
6535 (sock_T)CreateFileW(
6536 winpty_conout_name(term->tl_winpty),
6537 GENERIC_READ, 0, NULL,
6538 OPEN_EXISTING, 0, NULL),
6539 (sock_T)CreateFileW(
6540 winpty_conerr_name(term->tl_winpty),
6541 GENERIC_READ, 0, NULL,
6542 OPEN_EXISTING, 0, NULL));
6543
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006544 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006545 channel->ch_write_text_mode = TRUE;
6546
6547 jo = CreateJobObject(NULL, NULL);
6548 if (jo == NULL)
6549 goto failed;
6550
6551 if (!AssignProcessToJobObject(jo, child_process_handle))
6552 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006553 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006554 CloseHandle(jo);
6555 jo = NULL;
6556 }
6557
6558 winpty_spawn_config_free(spawn_config);
6559 vim_free(cmd_wchar);
6560 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006561 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006562
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006563 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6564 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006565
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006566#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6567 if (opt->jo_set2 & JO2_ANSI_COLORS)
6568 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6569 else
6570 init_vterm_ansi_colors(term->tl_vterm);
6571#endif
6572
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006573 channel_set_job(channel, job, opt);
6574 job_set_options(job, opt);
6575
6576 job->jv_channel = channel;
6577 job->jv_proc_info.hProcess = child_process_handle;
6578 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6579 job->jv_job_object = jo;
6580 job->jv_status = JOB_STARTED;
6581 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006582 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006583 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006584 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006585 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006586 ++job->jv_refcount;
6587 term->tl_job = job;
6588
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006589 // Redirecting stdout and stderr doesn't work at the job level. Instead
6590 // open the file here and handle it in. opt->jo_io was changed in
6591 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006592 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6593 {
6594 char_u *fname = opt->jo_io_name[PART_OUT];
6595
6596 ch_log(channel, "Opening output file %s", fname);
6597 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6598 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006599 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006600 }
6601
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006602 return OK;
6603
6604failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006605 ga_clear(&ga_cmd);
6606 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006607 vim_free(cmd_wchar);
6608 vim_free(cwd_wchar);
6609 if (spawn_config != NULL)
6610 winpty_spawn_config_free(spawn_config);
6611 if (channel != NULL)
6612 channel_clear(channel);
6613 if (job != NULL)
6614 {
6615 job->jv_channel = NULL;
6616 job_cleanup(job);
6617 }
6618 term->tl_job = NULL;
6619 if (jo != NULL)
6620 CloseHandle(jo);
6621 if (term->tl_winpty != NULL)
6622 winpty_free(term->tl_winpty);
6623 term->tl_winpty = NULL;
6624 if (term->tl_winpty_config != NULL)
6625 winpty_config_free(term->tl_winpty_config);
6626 term->tl_winpty_config = NULL;
6627 if (winpty_err != NULL)
6628 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006629 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006630 (short_u *)winpty_error_msg(winpty_err), NULL);
6631
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006632 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006633 winpty_error_free(winpty_err);
6634 }
6635 return FAIL;
6636}
6637
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006638/*
6639 * Create a new terminal of "rows" by "cols" cells.
6640 * Store a reference in "term".
6641 * Return OK or FAIL.
6642 */
6643 static int
6644term_and_job_init(
6645 term_T *term,
6646 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01006647 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006648 jobopt_T *opt,
6649 jobopt_T *orig_opt)
6650{
6651 int use_winpty = FALSE;
6652 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006653 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006654
6655 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6656 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6657
6658 if (!has_winpty && !has_conpty)
6659 // If neither is available give the errors for winpty, since when
6660 // conpty is not available it can't be installed either.
6661 return dyn_winpty_init(TRUE);
6662
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006663 if (opt->jo_tty_type != NUL)
6664 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006665
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006666 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006667 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006668 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006669 use_conpty = TRUE;
6670 else if (has_winpty)
6671 use_winpty = TRUE;
6672 // else: error
6673 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006674 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006675 {
6676 if (has_winpty)
6677 use_winpty = TRUE;
6678 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006679 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006680 {
6681 if (has_conpty)
6682 use_conpty = TRUE;
6683 else
6684 return dyn_conpty_init(TRUE);
6685 }
6686
6687 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006688 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006689
6690 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006691 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006692
6693 // error
6694 return dyn_winpty_init(TRUE);
6695}
6696
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006697 static int
6698create_pty_only(term_T *term, jobopt_T *options)
6699{
6700 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6701 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6702 char in_name[80], out_name[80];
6703 channel_T *channel = NULL;
6704
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006705 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6706 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006707
6708 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6709 GetCurrentProcessId(),
6710 curbuf->b_fnum);
6711 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6712 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6713 PIPE_UNLIMITED_INSTANCES,
6714 0, 0, NMPWAIT_NOWAIT, NULL);
6715 if (hPipeIn == INVALID_HANDLE_VALUE)
6716 goto failed;
6717
6718 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6719 GetCurrentProcessId(),
6720 curbuf->b_fnum);
6721 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6722 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6723 PIPE_UNLIMITED_INSTANCES,
6724 0, 0, 0, NULL);
6725 if (hPipeOut == INVALID_HANDLE_VALUE)
6726 goto failed;
6727
6728 ConnectNamedPipe(hPipeIn, NULL);
6729 ConnectNamedPipe(hPipeOut, NULL);
6730
6731 term->tl_job = job_alloc();
6732 if (term->tl_job == NULL)
6733 goto failed;
6734 ++term->tl_job->jv_refcount;
6735
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006736 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006737 term->tl_job->jv_status = JOB_FINISHED;
6738
6739 channel = add_channel();
6740 if (channel == NULL)
6741 goto failed;
6742 term->tl_job->jv_channel = channel;
6743 channel->ch_keep_open = TRUE;
6744 channel->ch_named_pipe = TRUE;
6745
6746 channel_set_pipes(channel,
6747 (sock_T)hPipeIn,
6748 (sock_T)hPipeOut,
6749 (sock_T)hPipeOut);
6750 channel_set_job(channel, term->tl_job, options);
6751 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6752 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6753
6754 return OK;
6755
6756failed:
6757 if (hPipeIn != NULL)
6758 CloseHandle(hPipeIn);
6759 if (hPipeOut != NULL)
6760 CloseHandle(hPipeOut);
6761 return FAIL;
6762}
6763
6764/*
6765 * Free the terminal emulator part of "term".
6766 */
6767 static void
6768term_free_vterm(term_T *term)
6769{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006770 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006771 if (term->tl_winpty != NULL)
6772 winpty_free(term->tl_winpty);
6773 term->tl_winpty = NULL;
6774 if (term->tl_winpty_config != NULL)
6775 winpty_config_free(term->tl_winpty_config);
6776 term->tl_winpty_config = NULL;
6777 if (term->tl_vterm != NULL)
6778 vterm_free(term->tl_vterm);
6779 term->tl_vterm = NULL;
6780}
6781
6782/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006783 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006784 */
6785 static void
6786term_report_winsize(term_T *term, int rows, int cols)
6787{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006788 if (term->tl_conpty)
6789 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006790 if (term->tl_winpty)
6791 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6792}
6793
6794 int
6795terminal_enabled(void)
6796{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006797 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006798}
6799
6800# else
6801
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006802///////////////////////////////////////
6803// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006804
6805/*
6806 * Create a new terminal of "rows" by "cols" cells.
6807 * Start job for "cmd".
6808 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006809 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006810 * Return OK or FAIL.
6811 */
6812 static int
6813term_and_job_init(
6814 term_T *term,
6815 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006816 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006817 jobopt_T *opt,
6818 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006819{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006820 term->tl_arg0_cmd = NULL;
6821
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006822 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6823 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006824
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006825#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6826 if (opt->jo_set2 & JO2_ANSI_COLORS)
6827 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6828 else
6829 init_vterm_ansi_colors(term->tl_vterm);
6830#endif
6831
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006832 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01006833 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006834 if (term->tl_job != NULL)
6835 ++term->tl_job->jv_refcount;
6836
6837 return term->tl_job != NULL
6838 && term->tl_job->jv_channel != NULL
6839 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6840}
6841
6842 static int
6843create_pty_only(term_T *term, jobopt_T *opt)
6844{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006845 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6846 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006847
6848 term->tl_job = job_alloc();
6849 if (term->tl_job == NULL)
6850 return FAIL;
6851 ++term->tl_job->jv_refcount;
6852
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006853 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006854 term->tl_job->jv_status = JOB_FINISHED;
6855
6856 return mch_create_pty_channel(term->tl_job, opt);
6857}
6858
6859/*
6860 * Free the terminal emulator part of "term".
6861 */
6862 static void
6863term_free_vterm(term_T *term)
6864{
6865 if (term->tl_vterm != NULL)
6866 vterm_free(term->tl_vterm);
6867 term->tl_vterm = NULL;
6868}
6869
6870/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006871 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006872 */
6873 static void
6874term_report_winsize(term_T *term, int rows, int cols)
6875{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006876 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006877 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6878 {
6879 int fd = -1;
6880 int part;
6881
6882 for (part = PART_OUT; part < PART_COUNT; ++part)
6883 {
6884 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006885 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006886 break;
6887 }
6888 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6889 mch_signal_job(term->tl_job, (char_u *)"winch");
6890 }
6891}
6892
6893# endif
6894
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006895#endif // FEAT_TERMINAL