blob: d4c605ed8fbd93a7f7f68e2f2cee1849041296a7 [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/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001799 * Loop over all windows in the current tab, and also curwin, which is not
1800 * encountered when using a terminal in a popup window.
1801 * Return TRUE if "*wp" was set to the next window.
1802 */
1803 static int
1804for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1805{
1806 if (*wp == NULL)
1807 *wp = firstwin;
1808 else if ((*wp)->w_next != NULL)
1809 *wp = (*wp)->w_next;
1810 else if (!*did_curwin)
1811 *wp = curwin;
1812 else
1813 return FALSE;
1814 if (*wp == curwin)
1815 *did_curwin = TRUE;
1816 return TRUE;
1817}
1818
1819/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001820 * If needed, add the current lines of the terminal to scrollback and to the
1821 * buffer. Called after the job has ended and when switching to
1822 * Terminal-Normal mode.
1823 * When "redraw" is TRUE redraw the windows that show the terminal.
1824 */
1825 static void
1826may_move_terminal_to_buffer(term_T *term, int redraw)
1827{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001828 if (term->tl_vterm == NULL)
1829 return;
1830
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001831 // Update the snapshot only if something changes or the buffer does not
1832 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001833 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1834 <= term->tl_scrollback_scrolled)
1835 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001836
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001837 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001838 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1839 &term->tl_default_color.fg, &term->tl_default_color.bg);
1840
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001841 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001842 {
1843 win_T *wp = NULL;
1844 int did_curwin = FALSE;
1845
1846 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001847 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001848 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001849 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001850 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1851 wp->w_cursor.col = 0;
1852 wp->w_valid = 0;
1853 if (wp->w_cursor.lnum >= wp->w_height)
1854 {
1855 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001856
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001857 if (wp->w_topline < min_topline)
1858 wp->w_topline = min_topline;
1859 }
1860 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001861 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001862 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001863 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001864}
1865
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001866#if defined(FEAT_TIMERS) || defined(PROTO)
1867/*
1868 * Check if any terminal timer expired. If so, copy text from the terminal to
1869 * the buffer.
1870 * Return the time until the next timer will expire.
1871 */
1872 int
1873term_check_timers(int next_due_arg, proftime_T *now)
1874{
1875 term_T *term;
1876 int next_due = next_due_arg;
1877
1878 for (term = first_term; term != NULL; term = term->tl_next)
1879 {
1880 if (term->tl_timer_set && !term->tl_normal_mode)
1881 {
1882 long this_due = proftime_time_left(&term->tl_timer_due, now);
1883
1884 if (this_due <= 1)
1885 {
1886 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001887 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001888 }
1889 else if (next_due == -1 || next_due > this_due)
1890 next_due = this_due;
1891 }
1892 }
1893
1894 return next_due;
1895}
1896#endif
1897
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001898/*
1899 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1900 * otherwise end it.
1901 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001902 static void
1903set_terminal_mode(term_T *term, int normal_mode)
1904{
1905 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001906 if (!normal_mode)
1907 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001908 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001909 if (term->tl_buffer == curbuf)
1910 maketitle();
1911}
1912
1913/*
1914 * Called after the job if finished and Terminal mode is not active:
1915 * Move the vterm contents into the scrollback buffer and free the vterm.
1916 */
1917 static void
1918cleanup_vterm(term_T *term)
1919{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001920 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001921 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001922 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001923 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001924}
1925
1926/*
1927 * Switch from Terminal-Job mode to Terminal-Normal mode.
1928 * Suspends updating the terminal window.
1929 */
1930 static void
1931term_enter_normal_mode(void)
1932{
1933 term_T *term = curbuf->b_term;
1934
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001935 set_terminal_mode(term, TRUE);
1936
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001937 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001938 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001939
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001940 // Move the window cursor to the position of the cursor in the
1941 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001942 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1943 + term->tl_cursor_pos.row + 1;
1944 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001945 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1946 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001947 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001948
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001949 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001950 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1951}
1952
1953/*
1954 * Returns TRUE if the current window contains a terminal and we are in
1955 * Terminal-Normal mode.
1956 */
1957 int
1958term_in_normal_mode(void)
1959{
1960 term_T *term = curbuf->b_term;
1961
1962 return term != NULL && term->tl_normal_mode;
1963}
1964
1965/*
1966 * Switch from Terminal-Normal mode to Terminal-Job mode.
1967 * Restores updating the terminal window.
1968 */
1969 void
1970term_enter_job_mode()
1971{
1972 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001973
1974 set_terminal_mode(term, FALSE);
1975
1976 if (term->tl_channel_closed)
1977 cleanup_vterm(term);
1978 redraw_buf_and_status_later(curbuf, NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001979#ifdef FEAT_PROP_POPUP
1980 if (WIN_IS_POPUP(curwin))
1981 redraw_win_later(curwin, NOT_VALID);
1982#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001983}
1984
1985/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001986 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001987 * Note: while waiting a terminal may be closed and freed if the channel is
1988 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001989 */
1990 static int
1991term_vgetc()
1992{
1993 int c;
1994 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001995 int modify_other_keys =
1996 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001997
1998 State = TERMINAL;
1999 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002000#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002001 ctrl_break_was_pressed = FALSE;
2002#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002003 if (modify_other_keys)
2004 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002005 c = vgetc();
2006 got_int = FALSE;
2007 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002008 if (modify_other_keys)
2009 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002010 return c;
2011}
2012
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002013static int mouse_was_outside = FALSE;
2014
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002015/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002016 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002017 * Return FAIL when the key needs to be handled in Normal mode.
2018 * Return OK when the key was dropped or sent to the terminal.
2019 */
2020 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002021send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022{
2023 char msg[KEY_BUF_LEN];
2024 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002025 int dragging_outside = FALSE;
2026
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002027 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 switch (c)
2029 {
2030 case NUL:
2031 case K_ZERO:
2032 if (typed)
2033 stuffcharReadbuff(c);
2034 return FAIL;
2035
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002036 case K_TABLINE:
2037 stuffcharReadbuff(c);
2038 return FAIL;
2039
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002040 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002041 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002042 return FAIL;
2043
2044 case K_LEFTDRAG:
2045 case K_MIDDLEDRAG:
2046 case K_RIGHTDRAG:
2047 case K_X1DRAG:
2048 case K_X2DRAG:
2049 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002050 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002051 case K_LEFTMOUSE:
2052 case K_LEFTMOUSE_NM:
2053 case K_LEFTRELEASE:
2054 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002055 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002056 case K_MIDDLEMOUSE:
2057 case K_MIDDLERELEASE:
2058 case K_RIGHTMOUSE:
2059 case K_RIGHTRELEASE:
2060 case K_X1MOUSE:
2061 case K_X1RELEASE:
2062 case K_X2MOUSE:
2063 case K_X2RELEASE:
2064
2065 case K_MOUSEUP:
2066 case K_MOUSEDOWN:
2067 case K_MOUSELEFT:
2068 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002069 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002070 int row = mouse_row;
2071 int col = mouse_col;
2072
2073#ifdef FEAT_PROP_POPUP
2074 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002075 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002076 row -= popup_top_extra(curwin);
2077 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002078 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002079#endif
2080 if (row < W_WINROW(curwin)
2081 || row >= (W_WINROW(curwin) + curwin->w_height)
2082 || col < curwin->w_wincol
2083 || col >= W_ENDCOL(curwin)
2084 || dragging_outside)
2085 {
2086 // click or scroll outside the current window or on status
2087 // line or vertical separator
2088 if (typed)
2089 {
2090 stuffcharReadbuff(c);
2091 mouse_was_outside = TRUE;
2092 }
2093 return FAIL;
2094 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002095 }
2096 }
2097 if (typed)
2098 mouse_was_outside = FALSE;
2099
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002100 // Convert the typed key to a sequence of bytes for the job.
2101 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002102 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002103 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002104 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2105 (char_u *)msg, (int)len, NULL);
2106
2107 return OK;
2108}
2109
2110 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002111position_cursor(win_T *wp, VTermPos *pos, int add_off UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002112{
2113 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2114 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002115#ifdef FEAT_PROP_POPUP
2116 if (add_off && popup_is_popup(curwin))
2117 {
2118 wp->w_wrow += popup_top_extra(curwin);
2119 wp->w_wcol += popup_left_extra(curwin);
2120 }
2121#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002122 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2123}
2124
2125/*
2126 * Handle CTRL-W "": send register contents to the job.
2127 */
2128 static void
2129term_paste_register(int prev_c UNUSED)
2130{
2131 int c;
2132 list_T *l;
2133 listitem_T *item;
2134 long reglen = 0;
2135 int type;
2136
2137#ifdef FEAT_CMDL_INFO
2138 if (add_to_showcmd(prev_c))
2139 if (add_to_showcmd('"'))
2140 out_flush();
2141#endif
2142 c = term_vgetc();
2143#ifdef FEAT_CMDL_INFO
2144 clear_showcmd();
2145#endif
2146 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002147 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002148 return;
2149
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002150 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002151 if (c == '=' && get_expr_register() != '=')
2152 return;
2153 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002154 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002155 return;
2156
2157 l = (list_T *)get_reg_contents(c, GREG_LIST);
2158 if (l != NULL)
2159 {
2160 type = get_reg_type(c, &reglen);
2161 for (item = l->lv_first; item != NULL; item = item->li_next)
2162 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002163 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002164#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002165 char_u *tmp = s;
2166
2167 if (!enc_utf8 && enc_codepage > 0)
2168 {
2169 WCHAR *ret = NULL;
2170 int length = 0;
2171
2172 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2173 (int)STRLEN(s), &ret, &length);
2174 if (ret != NULL)
2175 {
2176 WideCharToMultiByte_alloc(CP_UTF8, 0,
2177 ret, length, (char **)&s, &length, 0, 0);
2178 vim_free(ret);
2179 }
2180 }
2181#endif
2182 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2183 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002184#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002185 if (tmp != s)
2186 vim_free(s);
2187#endif
2188
2189 if (item->li_next != NULL || type == MLINE)
2190 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2191 (char_u *)"\r", 1, NULL);
2192 }
2193 list_free(l);
2194 }
2195}
2196
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002197/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002198 * Return TRUE when waiting for a character in the terminal, the cursor of the
2199 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002200 */
2201 int
2202terminal_is_active()
2203{
2204 return in_terminal_loop != NULL;
2205}
2206
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002207#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002208 cursorentry_T *
2209term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2210{
2211 term_T *term = in_terminal_loop;
2212 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002213 int id;
2214 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002215
2216 vim_memset(&entry, 0, sizeof(entry));
2217 entry.shape = entry.mshape =
2218 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2219 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2220 SHAPE_BLOCK;
2221 entry.percentage = 20;
2222 if (term->tl_cursor_blink)
2223 {
2224 entry.blinkwait = 700;
2225 entry.blinkon = 400;
2226 entry.blinkoff = 250;
2227 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002228
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002229 // The "Terminal" highlight group overrules the defaults.
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002230 id = syn_name2id((char_u *)"Terminal");
2231 if (id != 0)
2232 {
2233 syn_id2colors(id, &term_fg, &term_bg);
2234 *fg = term_bg;
2235 }
2236 else
2237 *fg = gui.back_pixel;
2238
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002239 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002240 {
2241 if (id != 0)
2242 *bg = term_fg;
2243 else
2244 *bg = gui.norm_pixel;
2245 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002246 else
2247 *bg = color_name2handle(term->tl_cursor_color);
2248 entry.name = "n";
2249 entry.used_for = SHAPE_CURSOR;
2250
2251 return &entry;
2252}
2253#endif
2254
Bram Moolenaard317b382018-02-08 22:33:31 +01002255 static void
2256may_output_cursor_props(void)
2257{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002258 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002259 || last_set_cursor_shape != desired_cursor_shape
2260 || last_set_cursor_blink != desired_cursor_blink)
2261 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002262 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002263 last_set_cursor_shape = desired_cursor_shape;
2264 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002265 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002266 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002267 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002268 ui_cursor_shape_forced(TRUE);
2269 else
2270 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2271 }
2272}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002273
Bram Moolenaard317b382018-02-08 22:33:31 +01002274/*
2275 * Set the cursor color and shape, if not last set to these.
2276 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002277 static void
2278may_set_cursor_props(term_T *term)
2279{
2280#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002281 // For the GUI the cursor properties are obtained with
2282 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002283 if (gui.in_use)
2284 return;
2285#endif
2286 if (in_terminal_loop == term)
2287 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002288 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002289 desired_cursor_shape = term->tl_cursor_shape;
2290 desired_cursor_blink = term->tl_cursor_blink;
2291 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002292 }
2293}
2294
Bram Moolenaard317b382018-02-08 22:33:31 +01002295/*
2296 * Reset the desired cursor properties and restore them when needed.
2297 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002298 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002299prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002300{
2301#ifdef FEAT_GUI
2302 if (gui.in_use)
2303 return;
2304#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002305 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002306 desired_cursor_shape = -1;
2307 desired_cursor_blink = -1;
2308 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002309}
2310
2311/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002312 * Returns TRUE if the current window contains a terminal and we are sending
2313 * keys to the job.
2314 * If "check_job_status" is TRUE update the job status.
2315 */
2316 static int
2317term_use_loop_check(int check_job_status)
2318{
2319 term_T *term = curbuf->b_term;
2320
2321 return term != NULL
2322 && !term->tl_normal_mode
2323 && term->tl_vterm != NULL
2324 && term_job_running_check(term, check_job_status);
2325}
2326
2327/*
2328 * Returns TRUE if the current window contains a terminal and we are sending
2329 * keys to the job.
2330 */
2331 int
2332term_use_loop(void)
2333{
2334 return term_use_loop_check(FALSE);
2335}
2336
2337/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002338 * Called when entering a window with the mouse. If this is a terminal window
2339 * we may want to change state.
2340 */
2341 void
2342term_win_entered()
2343{
2344 term_T *term = curbuf->b_term;
2345
2346 if (term != NULL)
2347 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002348 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002349 {
2350 reset_VIsual_and_resel();
2351 if (State & INSERT)
2352 stop_insert_mode = TRUE;
2353 }
2354 mouse_was_outside = FALSE;
2355 enter_mouse_col = mouse_col;
2356 enter_mouse_row = mouse_row;
2357 }
2358}
2359
2360/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002361 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2362 * Return the Ctrl-key value in that case.
2363 */
2364 static int
2365raw_c_to_ctrl(int c)
2366{
2367 if ((mod_mask & MOD_MASK_CTRL)
2368 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2369 return c & 0x1f;
2370 return c;
2371}
2372
2373/*
2374 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2375 * May set "mod_mask".
2376 */
2377 static int
2378ctrl_to_raw_c(int c)
2379{
2380 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2381 {
2382 mod_mask |= MOD_MASK_CTRL;
2383 return c + '@';
2384 }
2385 return c;
2386}
2387
2388/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002389 * Wait for input and send it to the job.
2390 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2391 * when there is no more typahead.
2392 * Return when the start of a CTRL-W command is typed or anything else that
2393 * should be handled as a Normal mode command.
2394 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2395 * the terminal was closed.
2396 */
2397 int
2398terminal_loop(int blocking)
2399{
2400 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002401 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002402 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002403 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002404#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002405 int tty_fd = curbuf->b_term->tl_job->jv_channel
2406 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002407#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002408 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002409
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002410 // Remember the terminal we are sending keys to. However, the terminal
2411 // might be closed while waiting for a character, e.g. typing "exit" in a
2412 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2413 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002414 in_terminal_loop = curbuf->b_term;
2415
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002416 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002417 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002418 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002419 if (termwinkey == Ctrl_W)
2420 termwinkey = 0;
2421 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002422 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002423 may_set_cursor_props(curbuf->b_term);
2424
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002425 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002426 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002427#ifdef FEAT_GUI
2428 if (!curbuf->b_term->tl_system)
2429#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002430 // TODO: skip screen update when handling a sequence of keys.
2431 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002432 while (must_redraw != 0)
2433 if (update_screen(0) == FAIL)
2434 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002435 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002436 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002437 break;
2438
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002439 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002440 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002441
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002442 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002443 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002444 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002445 // Job finished while waiting for a character. Push back the
2446 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002447 if (raw_c != K_IGNORE)
2448 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002449 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002450 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002451 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002452 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002453 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002454
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002455#ifdef UNIX
2456 /*
2457 * The shell or another program may change the tty settings. Getting
2458 * them for every typed character is a bit of overhead, but it's needed
2459 * for the first character typed, e.g. when Vim starts in a shell.
2460 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002461 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002462 {
2463 ttyinfo_T info;
2464
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002465 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002466 if (get_tty_info(tty_fd, &info) == OK)
2467 term_backspace_char = info.backspace;
2468 }
2469#endif
2470
Bram Moolenaar4f974752019-02-17 17:44:42 +01002471#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002472 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2473 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002474 if (ctrl_break_was_pressed)
2475 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2476#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002477 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2478 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002479 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002480#ifdef FEAT_GUI
2481 && !curbuf->b_term->tl_system
2482#endif
2483 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002484 {
2485 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002486 int prev_raw_c = raw_c;
2487 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002488
2489#ifdef FEAT_CMDL_INFO
2490 if (add_to_showcmd(c))
2491 out_flush();
2492#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002493 raw_c = term_vgetc();
2494 c = raw_c_to_ctrl(raw_c);
2495
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002496#ifdef FEAT_CMDL_INFO
2497 clear_showcmd();
2498#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002499 if (!term_use_loop_check(TRUE)
2500 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002501 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002502 break;
2503
2504 if (prev_c == Ctrl_BSL)
2505 {
2506 if (c == Ctrl_N)
2507 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002508 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002509 term_enter_normal_mode();
2510 ret = FAIL;
2511 goto theend;
2512 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002513 // Send both keys to the terminal, first one here, second one
2514 // below.
2515 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2516 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002517 }
2518 else if (c == Ctrl_C)
2519 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002520 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002521 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2522 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002523 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002524 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002525 // "CTRL-W .": send CTRL-W to the job
2526 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002527 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002528 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002529 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002530 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002531 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002532 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002533 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002534 else if (c == 'N')
2535 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002536 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002537 term_enter_normal_mode();
2538 ret = FAIL;
2539 goto theend;
2540 }
2541 else if (c == '"')
2542 {
2543 term_paste_register(prev_c);
2544 continue;
2545 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002546 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002547 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002548 char_u buf[MB_MAXBYTES + 2];
2549
2550 // Put the command into the typeahead buffer, when using the
2551 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2552 buf[0] = Ctrl_W;
2553 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2554 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002555 ret = OK;
2556 goto theend;
2557 }
2558 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002559# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002560 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002561 {
2562 WCHAR wc;
2563 char_u mb[3];
2564
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002565 mb[0] = (unsigned)raw_c >> 8;
2566 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002567 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002568 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002569 }
2570# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002571 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002572 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002573 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002574 // We are sure to come back here, don't reset the cursor color
2575 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002576 restore_cursor = FALSE;
2577
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002578 ret = OK;
2579 goto theend;
2580 }
2581 }
2582 ret = FAIL;
2583
2584theend:
2585 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002586 if (restore_cursor)
2587 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002588
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002589 // Move a snapshot of the screen contents to the buffer, so that completion
2590 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002591 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2592 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002593
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002594 return ret;
2595}
2596
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002597 static void
2598may_toggle_cursor(term_T *term)
2599{
2600 if (in_terminal_loop == term)
2601 {
2602 if (term->tl_cursor_visible)
2603 cursor_on();
2604 else
2605 cursor_off();
2606 }
2607}
2608
2609/*
2610 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002611 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002612 */
2613 static int
2614color2index(VTermColor *color, int fg, int *boldp)
2615{
2616 int red = color->red;
2617 int blue = color->blue;
2618 int green = color->green;
2619
Bram Moolenaar46359e12017-11-29 22:33:38 +01002620 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002621 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002622 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002623 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002624 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002625 case 0: return 0;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002626 case 1: return lookup_color( 0, fg, boldp) + 1; // black
2627 case 2: return lookup_color( 4, fg, boldp) + 1; // dark red
2628 case 3: return lookup_color( 2, fg, boldp) + 1; // dark green
2629 case 4: return lookup_color( 6, fg, boldp) + 1; // brown
2630 case 5: return lookup_color( 1, fg, boldp) + 1; // dark blue
2631 case 6: return lookup_color( 5, fg, boldp) + 1; // dark magenta
2632 case 7: return lookup_color( 3, fg, boldp) + 1; // dark cyan
2633 case 8: return lookup_color( 8, fg, boldp) + 1; // light grey
2634 case 9: return lookup_color(12, fg, boldp) + 1; // dark grey
2635 case 10: return lookup_color(20, fg, boldp) + 1; // red
2636 case 11: return lookup_color(16, fg, boldp) + 1; // green
2637 case 12: return lookup_color(24, fg, boldp) + 1; // yellow
2638 case 13: return lookup_color(14, fg, boldp) + 1; // blue
2639 case 14: return lookup_color(22, fg, boldp) + 1; // magenta
2640 case 15: return lookup_color(18, fg, boldp) + 1; // cyan
2641 case 16: return lookup_color(26, fg, boldp) + 1; // white
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002642 }
2643 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002644
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002645 if (t_colors >= 256)
2646 {
2647 if (red == blue && red == green)
2648 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002649 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002650 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002651 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2652 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2653 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002654 int i;
2655
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002656 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002657 return 17; // 00/00/00
2658 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002659 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002660 for (i = 0; i < 23; ++i)
2661 if (red < cutoff[i])
2662 return i + 233;
2663 return 256;
2664 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002665 {
2666 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2667 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002668
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002669 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002670 for (ri = 0; ri < 5; ++ri)
2671 if (red < cutoff[ri])
2672 break;
2673 for (gi = 0; gi < 5; ++gi)
2674 if (green < cutoff[gi])
2675 break;
2676 for (bi = 0; bi < 5; ++bi)
2677 if (blue < cutoff[bi])
2678 break;
2679 return 17 + ri * 36 + gi * 6 + bi;
2680 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002681 }
2682 return 0;
2683}
2684
2685/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002686 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002687 */
2688 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002689vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002690{
2691 int attr = 0;
2692
2693 if (cellattrs.bold)
2694 attr |= HL_BOLD;
2695 if (cellattrs.underline)
2696 attr |= HL_UNDERLINE;
2697 if (cellattrs.italic)
2698 attr |= HL_ITALIC;
2699 if (cellattrs.strike)
2700 attr |= HL_STRIKETHROUGH;
2701 if (cellattrs.reverse)
2702 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002703 return attr;
2704}
2705
2706/*
2707 * Store Vterm attributes in "cell" from highlight flags.
2708 */
2709 static void
2710hl2vtermAttr(int attr, cellattr_T *cell)
2711{
2712 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2713 if (attr & HL_BOLD)
2714 cell->attrs.bold = 1;
2715 if (attr & HL_UNDERLINE)
2716 cell->attrs.underline = 1;
2717 if (attr & HL_ITALIC)
2718 cell->attrs.italic = 1;
2719 if (attr & HL_STRIKETHROUGH)
2720 cell->attrs.strike = 1;
2721 if (attr & HL_INVERSE)
2722 cell->attrs.reverse = 1;
2723}
2724
2725/*
2726 * Convert the attributes of a vterm cell into an attribute index.
2727 */
2728 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002729cell2attr(
2730 win_T *wp,
2731 VTermScreenCellAttrs cellattrs,
2732 VTermColor cellfg,
2733 VTermColor cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002734{
2735 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002736
2737#ifdef FEAT_GUI
2738 if (gui.in_use)
2739 {
2740 guicolor_T fg, bg;
2741
2742 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2743 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2744 return get_gui_attr_idx(attr, fg, bg);
2745 }
2746 else
2747#endif
2748#ifdef FEAT_TERMGUICOLORS
2749 if (p_tgc)
2750 {
2751 guicolor_T fg, bg;
2752
2753 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2754 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2755
2756 return get_tgc_attr_idx(attr, fg, bg);
2757 }
2758 else
2759#endif
2760 {
2761 int bold = MAYBE;
2762 int fg = color2index(&cellfg, TRUE, &bold);
2763 int bg = color2index(&cellbg, FALSE, &bold);
2764
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002765 // Use the 'wincolor' or "Terminal" highlighting for the default
2766 // colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002767 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002768 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002769 int wincolor_fg = -1;
2770 int wincolor_bg = -1;
2771
2772 if (wp != NULL && *wp->w_p_wcr != NUL)
2773 {
2774 int id = syn_name2id(curwin->w_p_wcr);
2775
2776 // Get the 'wincolor' group colors.
2777 if (id > 0)
2778 syn_id2cterm_bg(id, &wincolor_fg, &wincolor_bg);
2779 }
2780 if (fg == 0)
2781 {
2782 if (wincolor_fg >= 0)
2783 fg = wincolor_fg + 1;
2784 else if (term_default_cterm_fg >= 0)
2785 fg = term_default_cterm_fg + 1;
2786 }
2787 if (bg == 0)
2788 {
2789 if (wincolor_bg >= 0)
2790 bg = wincolor_bg + 1;
2791 else if (term_default_cterm_bg >= 0)
2792 bg = term_default_cterm_bg + 1;
2793 }
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002794 }
2795
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002796 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002797 if (bold == TRUE)
2798 attr |= HL_BOLD;
2799 return get_cterm_attr_idx(attr, fg, bg);
2800 }
2801 return 0;
2802}
2803
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002804 static void
2805set_dirty_snapshot(term_T *term)
2806{
2807 term->tl_dirty_snapshot = TRUE;
2808#ifdef FEAT_TIMERS
2809 if (!term->tl_normal_mode)
2810 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002811 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002812 profile_setlimit(100L, &term->tl_timer_due);
2813 term->tl_timer_set = TRUE;
2814 }
2815#endif
2816}
2817
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002818 static int
2819handle_damage(VTermRect rect, void *user)
2820{
2821 term_T *term = (term_T *)user;
2822
2823 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2824 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002825 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002826 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002827 return 1;
2828}
2829
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002830 static void
2831term_scroll_up(term_T *term, int start_row, int count)
2832{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002833 win_T *wp = NULL;
2834 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002835 VTermColor fg, bg;
2836 VTermScreenCellAttrs attr;
2837 int clear_attr;
2838
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002839 vim_memset(&attr, 0, sizeof(attr));
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002840
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002841 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002842 {
2843 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002844 {
2845 // Set the color to clear lines with.
2846 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2847 &fg, &bg);
2848 clear_attr = cell2attr(wp, attr, fg, bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002849 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002850 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002851 }
2852}
2853
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002854 static int
2855handle_moverect(VTermRect dest, VTermRect src, void *user)
2856{
2857 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002858 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002859
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002860 // Scrolling up is done much more efficiently by deleting lines instead of
2861 // redrawing the text. But avoid doing this multiple times, postpone until
2862 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002863 if (dest.start_col == src.start_col
2864 && dest.end_col == src.end_col
2865 && dest.start_row < src.start_row)
2866 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002867 if (dest.start_row == 0)
2868 term->tl_postponed_scroll += count;
2869 else
2870 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002871 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002872
2873 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2874 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002875 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002876
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002877 // Note sure if the scrolling will work correctly, let's do a complete
2878 // redraw later.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002879 redraw_buf_later(term->tl_buffer, NOT_VALID);
2880 return 1;
2881}
2882
2883 static int
2884handle_movecursor(
2885 VTermPos pos,
2886 VTermPos oldpos UNUSED,
2887 int visible,
2888 void *user)
2889{
2890 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002891 win_T *wp = NULL;
2892 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002893
2894 term->tl_cursor_pos = pos;
2895 term->tl_cursor_visible = visible;
2896
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002897 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002898 {
2899 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002900 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002901 }
2902 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2903 {
2904 may_toggle_cursor(term);
2905 update_cursor(term, term->tl_cursor_visible);
2906 }
2907
2908 return 1;
2909}
2910
2911 static int
2912handle_settermprop(
2913 VTermProp prop,
2914 VTermValue *value,
2915 void *user)
2916{
2917 term_T *term = (term_T *)user;
2918
2919 switch (prop)
2920 {
2921 case VTERM_PROP_TITLE:
2922 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002923 // a blank title isn't useful, make it empty, so that "running" is
2924 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925 if (*skipwhite((char_u *)value->string) == NUL)
2926 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002927 // Same as blank
2928 else if (term->tl_arg0_cmd != NULL
2929 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2930 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2931 term->tl_title = NULL;
2932 // Empty corrupted data of winpty
2933 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2934 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002935#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002936 else if (!enc_utf8 && enc_codepage > 0)
2937 {
2938 WCHAR *ret = NULL;
2939 int length = 0;
2940
2941 MultiByteToWideChar_alloc(CP_UTF8, 0,
2942 (char*)value->string, (int)STRLEN(value->string),
2943 &ret, &length);
2944 if (ret != NULL)
2945 {
2946 WideCharToMultiByte_alloc(enc_codepage, 0,
2947 ret, length, (char**)&term->tl_title,
2948 &length, 0, 0);
2949 vim_free(ret);
2950 }
2951 }
2952#endif
2953 else
2954 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002955 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002956 if (term == curbuf->b_term)
2957 maketitle();
2958 break;
2959
2960 case VTERM_PROP_CURSORVISIBLE:
2961 term->tl_cursor_visible = value->boolean;
2962 may_toggle_cursor(term);
2963 out_flush();
2964 break;
2965
2966 case VTERM_PROP_CURSORBLINK:
2967 term->tl_cursor_blink = value->boolean;
2968 may_set_cursor_props(term);
2969 break;
2970
2971 case VTERM_PROP_CURSORSHAPE:
2972 term->tl_cursor_shape = value->number;
2973 may_set_cursor_props(term);
2974 break;
2975
2976 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002977 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002978 may_set_cursor_props(term);
2979 break;
2980
2981 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002982 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002983 term->tl_using_altscreen = value->boolean;
2984 break;
2985
2986 default:
2987 break;
2988 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002989 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002990 return 1;
2991}
2992
2993/*
2994 * The job running in the terminal resized the terminal.
2995 */
2996 static int
2997handle_resize(int rows, int cols, void *user)
2998{
2999 term_T *term = (term_T *)user;
3000 win_T *wp;
3001
3002 term->tl_rows = rows;
3003 term->tl_cols = cols;
3004 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003005 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003006 term->tl_vterm_size_changed = FALSE;
3007 else
3008 {
3009 FOR_ALL_WINDOWS(wp)
3010 {
3011 if (wp->w_buffer == term->tl_buffer)
3012 {
3013 win_setheight_win(rows, wp);
3014 win_setwidth_win(cols, wp);
3015 }
3016 }
3017 redraw_buf_later(term->tl_buffer, NOT_VALID);
3018 }
3019 return 1;
3020}
3021
3022/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003023 * If the number of lines that are stored goes over 'termscrollback' then
3024 * delete the first 10%.
3025 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3026 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003027 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003028 static void
3029limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003030{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003031 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003032 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003033 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003034 int i;
3035
3036 curbuf = term->tl_buffer;
3037 for (i = 0; i < todo; ++i)
3038 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003039 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3040 if (update_buffer)
3041 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003042 }
3043 curbuf = curwin->w_buffer;
3044
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003045 gap->ga_len -= todo;
3046 mch_memmove(gap->ga_data,
3047 (sb_line_T *)gap->ga_data + todo,
3048 sizeof(sb_line_T) * gap->ga_len);
3049 if (update_buffer)
3050 term->tl_scrollback_scrolled -= todo;
3051 }
3052}
3053
3054/*
3055 * Handle a line that is pushed off the top of the screen.
3056 */
3057 static int
3058handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3059{
3060 term_T *term = (term_T *)user;
3061 garray_T *gap;
3062 int update_buffer;
3063
3064 if (term->tl_normal_mode)
3065 {
3066 // In Terminal-Normal mode the user interacts with the buffer, thus we
3067 // must not change it. Postpone adding the scrollback lines.
3068 gap = &term->tl_scrollback_postponed;
3069 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003070 }
3071 else
3072 {
3073 // First remove the lines that were appended before, the pushed line
3074 // goes above it.
3075 cleanup_scrollback(term);
3076 gap = &term->tl_scrollback;
3077 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003078 }
3079
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003080 limit_scrollback(term, gap, update_buffer);
3081
3082 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003083 {
3084 cellattr_T *p = NULL;
3085 int len = 0;
3086 int i;
3087 int c;
3088 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003089 int text_len;
3090 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003091 sb_line_T *line;
3092 garray_T ga;
3093 cellattr_T fill_attr = term->tl_default_color;
3094
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003095 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003096 for (i = 0; i < cols; ++i)
3097 if (cells[i].chars[0] != 0)
3098 len = i + 1;
3099 else
3100 cell2cellattr(&cells[i], &fill_attr);
3101
3102 ga_init2(&ga, 1, 100);
3103 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003104 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003105 if (p != NULL)
3106 {
3107 for (col = 0; col < len; col += cells[col].width)
3108 {
3109 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3110 {
3111 ga.ga_len = 0;
3112 break;
3113 }
3114 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3115 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3116 (char_u *)ga.ga_data + ga.ga_len);
3117 cell2cellattr(&cells[col], &p[col]);
3118 }
3119 }
3120 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003121 {
3122 if (update_buffer)
3123 text = (char_u *)"";
3124 else
3125 text = vim_strsave((char_u *)"");
3126 text_len = 0;
3127 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003128 else
3129 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003130 text = ga.ga_data;
3131 text_len = ga.ga_len;
3132 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003133 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003134 if (update_buffer)
3135 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003136
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003137 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003138 line->sb_cols = len;
3139 line->sb_cells = p;
3140 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003141 if (update_buffer)
3142 {
3143 line->sb_text = NULL;
3144 ++term->tl_scrollback_scrolled;
3145 ga_clear(&ga); // free the text
3146 }
3147 else
3148 {
3149 line->sb_text = text;
3150 ga_init(&ga); // text is kept in tl_scrollback_postponed
3151 }
3152 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003154 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003155}
3156
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003157/*
3158 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3159 * received and stored in tl_scrollback_postponed.
3160 */
3161 static void
3162handle_postponed_scrollback(term_T *term)
3163{
3164 int i;
3165
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003166 if (term->tl_scrollback_postponed.ga_len == 0)
3167 return;
3168 ch_log(NULL, "Moving postponed scrollback to scrollback");
3169
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003170 // First remove the lines that were appended before, the pushed lines go
3171 // above it.
3172 cleanup_scrollback(term);
3173
3174 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3175 {
3176 char_u *text;
3177 sb_line_T *pp_line;
3178 sb_line_T *line;
3179
3180 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3181 break;
3182 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3183
3184 text = pp_line->sb_text;
3185 if (text == NULL)
3186 text = (char_u *)"";
3187 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3188 vim_free(pp_line->sb_text);
3189
3190 line = (sb_line_T *)term->tl_scrollback.ga_data
3191 + term->tl_scrollback.ga_len;
3192 line->sb_cols = pp_line->sb_cols;
3193 line->sb_cells = pp_line->sb_cells;
3194 line->sb_fill_attr = pp_line->sb_fill_attr;
3195 line->sb_text = NULL;
3196 ++term->tl_scrollback_scrolled;
3197 ++term->tl_scrollback.ga_len;
3198 }
3199
3200 ga_clear(&term->tl_scrollback_postponed);
3201 limit_scrollback(term, &term->tl_scrollback, TRUE);
3202}
3203
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003204static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003205 handle_damage, // damage
3206 handle_moverect, // moverect
3207 handle_movecursor, // movecursor
3208 handle_settermprop, // settermprop
3209 NULL, // bell
3210 handle_resize, // resize
3211 handle_pushline, // sb_pushline
3212 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003213};
3214
3215/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003216 * Do the work after the channel of a terminal was closed.
3217 * Must be called only when updating_screen is FALSE.
3218 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3219 */
3220 static int
3221term_after_channel_closed(term_T *term)
3222{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003223 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003224 if (!term->tl_normal_mode)
3225 {
3226 int fnum = term->tl_buffer->b_fnum;
3227
3228 cleanup_vterm(term);
3229
3230 if (term->tl_finish == TL_FINISH_CLOSE)
3231 {
3232 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003233 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003234#ifdef FEAT_PROP_POPUP
3235 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003236
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003237 // If this was a terminal in a popup window, go back to the
3238 // previous window.
3239 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3240 {
3241 pwin = curwin;
3242 if (win_valid(prevwin))
3243 win_enter(prevwin, FALSE);
3244 }
3245 else
3246#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003247 // If this is the last normal window: exit Vim.
3248 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3249 {
3250 exarg_T ea;
3251
3252 vim_memset(&ea, 0, sizeof(ea));
3253 ex_quit(&ea);
3254 return TRUE;
3255 }
3256
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003257 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003258 ch_log(NULL, "terminal job finished, closing window");
3259 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003260 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003261 if (curwin == aucmd_win)
3262 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003263 if (do_set_w_closing)
3264 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003265 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003266 if (do_set_w_closing)
3267 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003268 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003269#ifdef FEAT_PROP_POPUP
3270 if (pwin != NULL)
3271 popup_close_with_retval(pwin, 0);
3272#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003273 return TRUE;
3274 }
3275 if (term->tl_finish == TL_FINISH_OPEN
3276 && term->tl_buffer->b_nwindows == 0)
3277 {
3278 char buf[50];
3279
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003280 // TODO: use term_opencmd
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003281 ch_log(NULL, "terminal job finished, opening window");
3282 vim_snprintf(buf, sizeof(buf),
3283 term->tl_opencmd == NULL
3284 ? "botright sbuf %d"
3285 : (char *)term->tl_opencmd, fnum);
3286 do_cmdline_cmd((char_u *)buf);
3287 }
3288 else
3289 ch_log(NULL, "terminal job finished");
3290 }
3291
3292 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3293 return FALSE;
3294}
3295
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003296#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3297/*
3298 * If the current window is a terminal in a popup window and the job has
3299 * finished, close the popup window and to back to the previous window.
3300 * Otherwise return FAIL.
3301 */
3302 int
3303may_close_term_popup(void)
3304{
3305 if (popup_is_popup(curwin) && curbuf->b_term != NULL
3306 && !term_job_running(curbuf->b_term))
3307 {
3308 win_T *pwin = curwin;
3309
3310 if (win_valid(prevwin))
3311 win_enter(prevwin, FALSE);
3312 popup_close_with_retval(pwin, 0);
3313 return OK;
3314 }
3315 return FAIL;
3316}
3317#endif
3318
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003319/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003320 * Called when a channel has been closed.
3321 * If this was a channel for a terminal window then finish it up.
3322 */
3323 void
3324term_channel_closed(channel_T *ch)
3325{
3326 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003327 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003328 int did_one = FALSE;
3329
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003330 for (term = first_term; term != NULL; term = next_term)
3331 {
3332 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003333 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003334 {
3335 term->tl_channel_closed = TRUE;
3336 did_one = TRUE;
3337
Bram Moolenaard23a8232018-02-10 18:45:26 +01003338 VIM_CLEAR(term->tl_title);
3339 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003340#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003341 if (term->tl_out_fd != NULL)
3342 {
3343 fclose(term->tl_out_fd);
3344 term->tl_out_fd = NULL;
3345 }
3346#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003347
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003348 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003349 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003350 // Cannot open or close windows now. Can happen when
3351 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003352 term->tl_channel_recently_closed = TRUE;
3353 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003354 }
3355
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003356 if (term_after_channel_closed(term))
3357 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003358 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003359 }
3360
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003361 if (did_one)
3362 {
3363 redraw_statuslines();
3364
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003365 // Need to break out of vgetc().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003366 ins_char_typebuf(K_IGNORE);
3367 typebuf_was_filled = TRUE;
3368
3369 term = curbuf->b_term;
3370 if (term != NULL)
3371 {
3372 if (term->tl_job == ch->ch_job)
3373 maketitle();
3374 update_cursor(term, term->tl_cursor_visible);
3375 }
3376 }
3377}
3378
3379/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003380 * To be called after resetting updating_screen: handle any terminal where the
3381 * channel was closed.
3382 */
3383 void
3384term_check_channel_closed_recently()
3385{
3386 term_T *term;
3387 term_T *next_term;
3388
3389 for (term = first_term; term != NULL; term = next_term)
3390 {
3391 next_term = term->tl_next;
3392 if (term->tl_channel_recently_closed)
3393 {
3394 term->tl_channel_recently_closed = FALSE;
3395 if (term_after_channel_closed(term))
3396 // start over, the list may have changed
3397 next_term = first_term;
3398 }
3399 }
3400}
3401
3402/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003403 * Fill one screen line from a line of the terminal.
3404 * Advances "pos" to past the last column.
3405 */
3406 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003407term_line2screenline(
3408 win_T *wp,
3409 VTermScreen *screen,
3410 VTermPos *pos,
3411 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003412{
3413 int off = screen_get_current_line_off();
3414
3415 for (pos->col = 0; pos->col < max_col; )
3416 {
3417 VTermScreenCell cell;
3418 int c;
3419
3420 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3421 vim_memset(&cell, 0, sizeof(cell));
3422
3423 c = cell.chars[0];
3424 if (c == NUL)
3425 {
3426 ScreenLines[off] = ' ';
3427 if (enc_utf8)
3428 ScreenLinesUC[off] = NUL;
3429 }
3430 else
3431 {
3432 if (enc_utf8)
3433 {
3434 int i;
3435
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003436 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003437 for (i = 0; i < Screen_mco
3438 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3439 {
3440 ScreenLinesC[i][off] = cell.chars[i + 1];
3441 if (cell.chars[i + 1] == 0)
3442 break;
3443 }
3444 if (c >= 0x80 || (Screen_mco > 0
3445 && ScreenLinesC[0][off] != 0))
3446 {
3447 ScreenLines[off] = ' ';
3448 ScreenLinesUC[off] = c;
3449 }
3450 else
3451 {
3452 ScreenLines[off] = c;
3453 ScreenLinesUC[off] = NUL;
3454 }
3455 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003456#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003457 else if (has_mbyte && c >= 0x80)
3458 {
3459 char_u mb[MB_MAXBYTES+1];
3460 WCHAR wc = c;
3461
3462 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3463 (char*)mb, 2, 0, 0) > 1)
3464 {
3465 ScreenLines[off] = mb[0];
3466 ScreenLines[off + 1] = mb[1];
3467 cell.width = mb_ptr2cells(mb);
3468 }
3469 else
3470 ScreenLines[off] = c;
3471 }
3472#endif
3473 else
3474 ScreenLines[off] = c;
3475 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003476 ScreenAttrs[off] = cell2attr(wp, cell.attrs, cell.fg, cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003477
3478 ++pos->col;
3479 ++off;
3480 if (cell.width == 2)
3481 {
3482 if (enc_utf8)
3483 ScreenLinesUC[off] = NUL;
3484
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003485 // don't set the second byte to NUL for a DBCS encoding, it
3486 // has been set above
Bram Moolenaar13568252018-03-16 20:46:58 +01003487 if (enc_utf8 || !has_mbyte)
3488 ScreenLines[off] = NUL;
3489
3490 ++pos->col;
3491 ++off;
3492 }
3493 }
3494}
3495
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003496#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003497 static void
3498update_system_term(term_T *term)
3499{
3500 VTermPos pos;
3501 VTermScreen *screen;
3502
3503 if (term->tl_vterm == NULL)
3504 return;
3505 screen = vterm_obtain_screen(term->tl_vterm);
3506
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003507 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003508 while (term->tl_toprow > 0
3509 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3510 {
3511 int save_p_more = p_more;
3512
3513 p_more = FALSE;
3514 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003515 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003516 p_more = save_p_more;
3517 --term->tl_toprow;
3518 }
3519
3520 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3521 && pos.row < Rows; ++pos.row)
3522 {
3523 if (pos.row < term->tl_rows)
3524 {
3525 int max_col = MIN(Columns, term->tl_cols);
3526
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003527 term_line2screenline(NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003528 }
3529 else
3530 pos.col = 0;
3531
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003532 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003533 }
3534
3535 term->tl_dirty_row_start = MAX_ROW;
3536 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003537}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003538#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003539
3540/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003541 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3542 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003543 * Terminal-Normal mode.
3544 */
3545 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003546term_do_update_window(win_T *wp)
3547{
3548 term_T *term = wp->w_buffer->b_term;
3549
3550 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3551}
3552
3553/*
3554 * Called to update a window that contains an active terminal.
3555 */
3556 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003557term_update_window(win_T *wp)
3558{
3559 term_T *term = wp->w_buffer->b_term;
3560 VTerm *vterm;
3561 VTermScreen *screen;
3562 VTermState *state;
3563 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003564 int rows, cols;
3565 int newrows, newcols;
3566 int minsize;
3567 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003568
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003569 vterm = term->tl_vterm;
3570 screen = vterm_obtain_screen(vterm);
3571 state = vterm_obtain_state(vterm);
3572
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003573 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3574 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003575 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003576 {
3577 term->tl_dirty_row_start = 0;
3578 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003579
3580 if (term->tl_postponed_scroll > 0
3581 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003582 // Scrolling is usually faster than redrawing, when there are only
3583 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003584 term_scroll_up(term, 0, term->tl_postponed_scroll);
3585 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003586 }
3587
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003588 /*
3589 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003590 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003591 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003592 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003593
Bram Moolenaar498c2562018-04-15 23:45:15 +02003594 newrows = 99999;
3595 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003596 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003597 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003598 // Always use curwin, it may be a popup window.
3599 win_T *wwp = twp == NULL ? curwin : twp;
3600
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003601 // When more than one window shows the same terminal, use the
3602 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003603 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003604 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003605 newrows = MIN(newrows, wwp->w_height);
3606 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003607 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003608 if (twp == NULL)
3609 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003610 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003611 if (newrows == 99999 || newcols == 99999)
3612 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003613 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3614 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3615
3616 if (term->tl_rows != newrows || term->tl_cols != newcols)
3617 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003618 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003619 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003620 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003621 newrows);
3622 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003623
3624 // Updating the terminal size will cause the snapshot to be cleared.
3625 // When not in terminal_loop() we need to restore it.
3626 if (term != in_terminal_loop)
3627 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003628 }
3629
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003630 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003631 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003632 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003633
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003634 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3635 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003636 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003637 if (pos.row < term->tl_rows)
3638 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003639 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003640
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003641 term_line2screenline(wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003642 }
3643 else
3644 pos.col = 0;
3645
Bram Moolenaarf118d482018-03-13 13:14:00 +01003646 screen_line(wp->w_winrow + pos.row
3647#ifdef FEAT_MENU
3648 + winbar_height(wp)
3649#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003650 , wp->w_wincol, pos.col, wp->w_width,
3651#ifdef FEAT_PROP_POPUP
3652 popup_is_popup(wp) ? SLF_POPUP :
3653#endif
3654 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003655 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003656 term->tl_dirty_row_start = MAX_ROW;
3657 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003658}
3659
3660/*
3661 * Return TRUE if "wp" is a terminal window where the job has finished.
3662 */
3663 int
3664term_is_finished(buf_T *buf)
3665{
3666 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3667}
3668
3669/*
3670 * Return TRUE if "wp" is a terminal window where the job has finished or we
3671 * are in Terminal-Normal mode, thus we show the buffer contents.
3672 */
3673 int
3674term_show_buffer(buf_T *buf)
3675{
3676 term_T *term = buf->b_term;
3677
3678 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3679}
3680
3681/*
3682 * The current buffer is going to be changed. If there is terminal
3683 * highlighting remove it now.
3684 */
3685 void
3686term_change_in_curbuf(void)
3687{
3688 term_T *term = curbuf->b_term;
3689
3690 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3691 {
3692 free_scrollback(term);
3693 redraw_buf_later(term->tl_buffer, NOT_VALID);
3694
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003695 // The buffer is now like a normal buffer, it cannot be easily
3696 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003697 set_string_option_direct((char_u *)"buftype", -1,
3698 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3699 }
3700}
3701
3702/*
3703 * Get the screen attribute for a position in the buffer.
3704 * Use a negative "col" to get the filler background color.
3705 */
3706 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003707term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003708{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003709 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003710 term_T *term = buf->b_term;
3711 sb_line_T *line;
3712 cellattr_T *cellattr;
3713
3714 if (lnum > term->tl_scrollback.ga_len)
3715 cellattr = &term->tl_default_color;
3716 else
3717 {
3718 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3719 if (col < 0 || col >= line->sb_cols)
3720 cellattr = &line->sb_fill_attr;
3721 else
3722 cellattr = line->sb_cells + col;
3723 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003724 return cell2attr(wp, cellattr->attrs, cellattr->fg, cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003725}
3726
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003727/*
3728 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003729 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003730 */
3731 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003732cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003733{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003734 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003735}
3736
3737/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003738 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003739 */
3740 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003741init_default_colors(term_T *term, win_T *wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003742{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003743 VTermColor *fg, *bg;
3744 int fgval, bgval;
3745 int id;
3746
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003747 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3748 term->tl_default_color.width = 1;
3749 fg = &term->tl_default_color.fg;
3750 bg = &term->tl_default_color.bg;
3751
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003752 // Vterm uses a default black background. Set it to white when
3753 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003754 if (*p_bg == 'l')
3755 {
3756 fgval = 0;
3757 bgval = 255;
3758 }
3759 else
3760 {
3761 fgval = 255;
3762 bgval = 0;
3763 }
3764 fg->red = fg->green = fg->blue = fgval;
3765 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003766 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003767
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003768 // The 'wincolor' or "Terminal" highlight group overrules the defaults.
3769 if (wp != NULL && *wp->w_p_wcr != NUL)
3770 id = syn_name2id(wp->w_p_wcr);
3771 else
3772 id = syn_name2id((char_u *)"Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003773
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003774 // Use the actual color for the GUI and when 'termguicolors' is set.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003775#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3776 if (0
3777# ifdef FEAT_GUI
3778 || gui.in_use
3779# endif
3780# ifdef FEAT_TERMGUICOLORS
3781 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003782# ifdef FEAT_VTP
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003783 // Finally get INVALCOLOR on this execution path
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003784 || (!p_tgc && t_colors >= 256)
3785# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003786# endif
3787 )
3788 {
3789 guicolor_T fg_rgb = INVALCOLOR;
3790 guicolor_T bg_rgb = INVALCOLOR;
3791
3792 if (id != 0)
3793 syn_id2colors(id, &fg_rgb, &bg_rgb);
3794
3795# ifdef FEAT_GUI
3796 if (gui.in_use)
3797 {
3798 if (fg_rgb == INVALCOLOR)
3799 fg_rgb = gui.norm_pixel;
3800 if (bg_rgb == INVALCOLOR)
3801 bg_rgb = gui.back_pixel;
3802 }
3803# ifdef FEAT_TERMGUICOLORS
3804 else
3805# endif
3806# endif
3807# ifdef FEAT_TERMGUICOLORS
3808 {
3809 if (fg_rgb == INVALCOLOR)
3810 fg_rgb = cterm_normal_fg_gui_color;
3811 if (bg_rgb == INVALCOLOR)
3812 bg_rgb = cterm_normal_bg_gui_color;
3813 }
3814# endif
3815 if (fg_rgb != INVALCOLOR)
3816 {
3817 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3818
3819 fg->red = (unsigned)(rgb >> 16);
3820 fg->green = (unsigned)(rgb >> 8) & 255;
3821 fg->blue = (unsigned)rgb & 255;
3822 }
3823 if (bg_rgb != INVALCOLOR)
3824 {
3825 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3826
3827 bg->red = (unsigned)(rgb >> 16);
3828 bg->green = (unsigned)(rgb >> 8) & 255;
3829 bg->blue = (unsigned)rgb & 255;
3830 }
3831 }
3832 else
3833#endif
3834 if (id != 0 && t_colors >= 16)
3835 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003836 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003837 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003838 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003839 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003840 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003841 else
3842 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003843#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003844 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003845#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003846
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003847 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003848 if (cterm_normal_fg_color > 0)
3849 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003850 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003851# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3852# ifdef VIMDLL
3853 if (!gui.in_use)
3854# endif
3855 {
3856 tmp = fg->red;
3857 fg->red = fg->blue;
3858 fg->blue = tmp;
3859 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003860# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003861 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003862# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003863 else
3864 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003865# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003866
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003867 if (cterm_normal_bg_color > 0)
3868 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003869 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003870# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3871# ifdef VIMDLL
3872 if (!gui.in_use)
3873# endif
3874 {
3875 tmp = fg->red;
3876 fg->red = fg->blue;
3877 fg->blue = tmp;
3878 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003879# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003880 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003881# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003882 else
3883 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003884# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003885 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003886}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003887
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003888#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3889/*
3890 * Set the 16 ANSI colors from array of RGB values
3891 */
3892 static void
3893set_vterm_palette(VTerm *vterm, long_u *rgb)
3894{
3895 int index = 0;
3896 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003897
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003898 for (; index < 16; index++)
3899 {
3900 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003901
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003902 color.red = (unsigned)(rgb[index] >> 16);
3903 color.green = (unsigned)(rgb[index] >> 8) & 255;
3904 color.blue = (unsigned)rgb[index] & 255;
3905 vterm_state_set_palette_color(state, index, &color);
3906 }
3907}
3908
3909/*
3910 * Set the ANSI color palette from a list of colors
3911 */
3912 static int
3913set_ansi_colors_list(VTerm *vterm, list_T *list)
3914{
3915 int n = 0;
3916 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01003917 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003918
Bram Moolenaarb0992022020-01-30 14:55:42 +01003919 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003920 {
3921 char_u *color_name;
3922 guicolor_T guicolor;
3923
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003924 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003925 if (color_name == NULL)
3926 return FAIL;
3927
3928 guicolor = GUI_GET_COLOR(color_name);
3929 if (guicolor == INVALCOLOR)
3930 return FAIL;
3931
3932 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3933 }
3934
3935 if (n != 16 || li != NULL)
3936 return FAIL;
3937
3938 set_vterm_palette(vterm, rgb);
3939
3940 return OK;
3941}
3942
3943/*
3944 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3945 */
3946 static void
3947init_vterm_ansi_colors(VTerm *vterm)
3948{
3949 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3950
3951 if (var != NULL
3952 && (var->di_tv.v_type != VAR_LIST
3953 || var->di_tv.vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +01003954 || var->di_tv.vval.v_list->lv_first == &range_list_item
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003955 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003956 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003957}
3958#endif
3959
Bram Moolenaar52acb112018-03-18 19:20:22 +01003960/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003961 * Handles a "drop" command from the job in the terminal.
3962 * "item" is the file name, "item->li_next" may have options.
3963 */
3964 static void
3965handle_drop_command(listitem_T *item)
3966{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003967 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003968 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003969 int bufnr;
3970 win_T *wp;
3971 tabpage_T *tp;
3972 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003973 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003974
3975 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3976 FOR_ALL_TAB_WINDOWS(tp, wp)
3977 {
3978 if (wp->w_buffer->b_fnum == bufnr)
3979 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003980 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003981 goto_tabpage_win(tp, wp);
3982 return;
3983 }
3984 }
3985
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003986 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003987
3988 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3989 && opt_item->li_tv.vval.v_dict != NULL)
3990 {
3991 dict_T *dict = opt_item->li_tv.vval.v_dict;
3992 char_u *p;
3993
Bram Moolenaar8f667172018-12-14 15:38:31 +01003994 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003995 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003996 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003997 if (p != NULL)
3998 {
3999 if (check_ff_value(p) == FAIL)
4000 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4001 else
4002 ea.force_ff = *p;
4003 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01004004 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004005 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004006 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004007 if (p != NULL)
4008 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004009 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004010 if (ea.cmd != NULL)
4011 {
4012 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4013 ea.force_enc = 11;
4014 tofree = ea.cmd;
4015 }
4016 }
4017
Bram Moolenaar8f667172018-12-14 15:38:31 +01004018 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004019 if (p != NULL)
4020 get_bad_opt(p, &ea);
4021
4022 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
4023 ea.force_bin = FORCE_BIN;
4024 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
4025 ea.force_bin = FORCE_BIN;
4026 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
4027 ea.force_bin = FORCE_NOBIN;
4028 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
4029 ea.force_bin = FORCE_NOBIN;
4030 }
4031
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004032 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004033 if (ea.cmd == NULL)
4034 ea.cmd = (char_u *)"split";
4035 ea.arg = fname;
4036 ea.cmdidx = CMD_split;
4037 ex_splitview(&ea);
4038
4039 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004040}
4041
4042/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004043 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4044 */
4045 static int
4046is_permitted_term_api(char_u *func, char_u *pat)
4047{
4048 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4049}
4050
4051/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004052 * Handles a function call from the job running in a terminal.
4053 * "item" is the function name, "item->li_next" has the arguments.
4054 */
4055 static void
4056handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4057{
4058 char_u *func;
4059 typval_T argvars[2];
4060 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004061 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004062
4063 if (item->li_next == NULL)
4064 {
4065 ch_log(channel, "Missing function arguments for call");
4066 return;
4067 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004068 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004069
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004070 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004071 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004072 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004073 return;
4074 }
4075
4076 argvars[0].v_type = VAR_NUMBER;
4077 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4078 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004079 vim_memset(&funcexe, 0, sizeof(funcexe));
4080 funcexe.firstline = 1L;
4081 funcexe.lastline = 1L;
4082 funcexe.evaluate = TRUE;
4083 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004084 {
4085 clear_tv(&rettv);
4086 ch_log(channel, "Function %s called", func);
4087 }
4088 else
4089 ch_log(channel, "Calling function %s failed", func);
4090}
4091
4092/*
4093 * Called by libvterm when it cannot recognize an OSC sequence.
4094 * We recognize a terminal API command.
4095 */
4096 static int
4097parse_osc(const char *command, size_t cmdlen, void *user)
4098{
4099 term_T *term = (term_T *)user;
4100 js_read_T reader;
4101 typval_T tv;
4102 channel_T *channel = term->tl_job == NULL ? NULL
4103 : term->tl_job->jv_channel;
4104
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004105 // We recognize only OSC 5 1 ; {command}
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004106 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004107 return 0; // not handled
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004108
Bram Moolenaar878c96d2018-04-04 23:00:06 +02004109 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004110 if (reader.js_buf == NULL)
4111 return 1;
4112 reader.js_fill = NULL;
4113 reader.js_used = 0;
4114 if (json_decode(&reader, &tv, 0) == OK
4115 && tv.v_type == VAR_LIST
4116 && tv.vval.v_list != NULL)
4117 {
4118 listitem_T *item = tv.vval.v_list->lv_first;
4119
4120 if (item == NULL)
4121 ch_log(channel, "Missing command");
4122 else
4123 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004124 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004125
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004126 // Make sure an invoked command doesn't delete the buffer (and the
4127 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004128 ++term->tl_buffer->b_locked;
4129
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004130 item = item->li_next;
4131 if (item == NULL)
4132 ch_log(channel, "Missing argument for %s", cmd);
4133 else if (STRCMP(cmd, "drop") == 0)
4134 handle_drop_command(item);
4135 else if (STRCMP(cmd, "call") == 0)
4136 handle_call_command(term, channel, item);
4137 else
4138 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004139 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004140 }
4141 }
4142 else
4143 ch_log(channel, "Invalid JSON received");
4144
4145 vim_free(reader.js_buf);
4146 clear_tv(&tv);
4147 return 1;
4148}
4149
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004150/*
4151 * Called by libvterm when it cannot recognize a CSI sequence.
4152 * We recognize the window position report.
4153 */
4154 static int
4155parse_csi(
4156 const char *leader UNUSED,
4157 const long args[],
4158 int argcount,
4159 const char *intermed UNUSED,
4160 char command,
4161 void *user)
4162{
4163 term_T *term = (term_T *)user;
4164 char buf[100];
4165 int len;
4166 int x = 0;
4167 int y = 0;
4168 win_T *wp;
4169
4170 // We recognize only CSI 13 t
4171 if (command != 't' || argcount != 1 || args[0] != 13)
4172 return 0; // not handled
4173
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004174 // When getting the window position is not possible or it fails it results
4175 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004176#if defined(FEAT_GUI) \
4177 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4178 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004179 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004180#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004181
4182 FOR_ALL_WINDOWS(wp)
4183 if (wp->w_buffer == term->tl_buffer)
4184 break;
4185 if (wp != NULL)
4186 {
4187#ifdef FEAT_GUI
4188 if (gui.in_use)
4189 {
4190 x += wp->w_wincol * gui.char_width;
4191 y += W_WINROW(wp) * gui.char_height;
4192 }
4193 else
4194#endif
4195 {
4196 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004197 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004198 x += wp->w_wincol * 7;
4199 y += W_WINROW(wp) * 10;
4200 }
4201 }
4202
4203 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4204 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4205 (char_u *)buf, len, NULL);
4206 return 1;
4207}
4208
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004209static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004210 NULL, // text
4211 NULL, // control
4212 NULL, // escape
4213 parse_csi, // csi
4214 parse_osc, // osc
4215 NULL, // dcs
4216 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004217};
4218
4219/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004220 * Use Vim's allocation functions for vterm so profiling works.
4221 */
4222 static void *
4223vterm_malloc(size_t size, void *data UNUSED)
4224{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004225 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004226}
4227
4228 static void
4229vterm_memfree(void *ptr, void *data UNUSED)
4230{
4231 vim_free(ptr);
4232}
4233
4234static VTermAllocatorFunctions vterm_allocator = {
4235 &vterm_malloc,
4236 &vterm_memfree
4237};
4238
4239/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004240 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004241 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004242 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004243 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004244create_vterm(term_T *term, int rows, int cols)
4245{
4246 VTerm *vterm;
4247 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004248 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004249 VTermValue value;
4250
Bram Moolenaar756ef112018-04-10 12:04:27 +02004251 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004252 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004253 if (vterm == NULL)
4254 return FAIL;
4255
4256 // Allocate screen and state here, so we can bail out if that fails.
4257 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004258 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004259 if (state == NULL || screen == NULL)
4260 {
4261 vterm_free(vterm);
4262 return FAIL;
4263 }
4264
Bram Moolenaar52acb112018-03-18 19:20:22 +01004265 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004266 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004267 vterm_set_utf8(vterm, 1);
4268
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004269 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004270
4271 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004272 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004273 &term->tl_default_color.fg,
4274 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004275
Bram Moolenaar9e587872019-05-13 20:27:23 +02004276 if (t_colors < 16)
4277 // Less than 16 colors: assume that bold means using a bright color for
4278 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004279 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4280
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004281 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004282 vterm_screen_reset(screen, 1 /* hard */);
4283
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004284 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004285 vterm_screen_enable_altscreen(screen, 1);
4286
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004287 // For unix do not use a blinking cursor. In an xterm this causes the
4288 // cursor to blink if it's blinking in the xterm.
4289 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004290#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004291 if (GetCaretBlinkTime() == INFINITE)
4292 value.boolean = 0;
4293 else
4294 value.boolean = 1;
4295#else
4296 value.boolean = 0;
4297#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004298 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4299 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004300
4301 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004302}
4303
4304/*
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004305 * Called when 'wincolor' was set.
4306 */
4307 void
4308term_update_colors(void)
4309{
4310 term_T *term = curwin->w_buffer->b_term;
4311
Bram Moolenaar7ba3b912020-02-10 20:34:04 +01004312 if (term->tl_vterm == NULL)
4313 return;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004314 init_default_colors(term, curwin);
4315 vterm_state_set_default_colors(
4316 vterm_obtain_state(term->tl_vterm),
4317 &term->tl_default_color.fg,
4318 &term->tl_default_color.bg);
4319}
4320
4321/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004322 * Return the text to show for the buffer name and status.
4323 */
4324 char_u *
4325term_get_status_text(term_T *term)
4326{
4327 if (term->tl_status_text == NULL)
4328 {
4329 char_u *txt;
4330 size_t len;
4331
4332 if (term->tl_normal_mode)
4333 {
4334 if (term_job_running(term))
4335 txt = (char_u *)_("Terminal");
4336 else
4337 txt = (char_u *)_("Terminal-finished");
4338 }
4339 else if (term->tl_title != NULL)
4340 txt = term->tl_title;
4341 else if (term_none_open(term))
4342 txt = (char_u *)_("active");
4343 else if (term_job_running(term))
4344 txt = (char_u *)_("running");
4345 else
4346 txt = (char_u *)_("finished");
4347 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004348 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004349 if (term->tl_status_text != NULL)
4350 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4351 term->tl_buffer->b_fname, txt);
4352 }
4353 return term->tl_status_text;
4354}
4355
4356/*
4357 * Mark references in jobs of terminals.
4358 */
4359 int
4360set_ref_in_term(int copyID)
4361{
4362 int abort = FALSE;
4363 term_T *term;
4364 typval_T tv;
4365
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004366 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004367 if (term->tl_job != NULL)
4368 {
4369 tv.v_type = VAR_JOB;
4370 tv.vval.v_job = term->tl_job;
4371 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4372 }
4373 return abort;
4374}
4375
4376/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004377 * Cache "Terminal" highlight group colors.
4378 */
4379 void
4380set_terminal_default_colors(int cterm_fg, int cterm_bg)
4381{
4382 term_default_cterm_fg = cterm_fg - 1;
4383 term_default_cterm_bg = cterm_bg - 1;
4384}
4385
4386/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004387 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004388 * Returns NULL when the buffer is not for a terminal window and logs a message
4389 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004390 */
4391 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004392term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004393{
4394 buf_T *buf;
4395
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004396 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004397 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004398 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004399 --emsg_off;
4400 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004401 {
4402 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004403 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004404 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004405 return buf;
4406}
4407
Bram Moolenaard96ff162018-02-18 22:13:29 +01004408 static int
4409same_color(VTermColor *a, VTermColor *b)
4410{
4411 return a->red == b->red
4412 && a->green == b->green
4413 && a->blue == b->blue
4414 && a->ansi_index == b->ansi_index;
4415}
4416
4417 static void
4418dump_term_color(FILE *fd, VTermColor *color)
4419{
4420 fprintf(fd, "%02x%02x%02x%d",
4421 (int)color->red, (int)color->green, (int)color->blue,
4422 (int)color->ansi_index);
4423}
4424
4425/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004426 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004427 *
4428 * Each screen cell in full is:
4429 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4430 * {characters} is a space for an empty cell
4431 * For a double-width character "+" is changed to "*" and the next cell is
4432 * skipped.
4433 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4434 * when "&" use the same as the previous cell.
4435 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4436 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4437 * {color-idx} is a number from 0 to 255
4438 *
4439 * Screen cell with same width, attributes and color as the previous one:
4440 * |{characters}
4441 *
4442 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4443 *
4444 * Repeating the previous screen cell:
4445 * @{count}
4446 */
4447 void
4448f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4449{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004450 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004451 term_T *term;
4452 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004453 int max_height = 0;
4454 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004455 stat_T st;
4456 FILE *fd;
4457 VTermPos pos;
4458 VTermScreen *screen;
4459 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004460 VTermState *state;
4461 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004462
4463 if (check_restricted() || check_secure())
4464 return;
4465 if (buf == NULL)
4466 return;
4467 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004468 if (term->tl_vterm == NULL)
4469 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004470 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004471 return;
4472 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004473
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004474 if (argvars[2].v_type != VAR_UNKNOWN)
4475 {
4476 dict_T *d;
4477
4478 if (argvars[2].v_type != VAR_DICT)
4479 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004480 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004481 return;
4482 }
4483 d = argvars[2].vval.v_dict;
4484 if (d != NULL)
4485 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004486 max_height = dict_get_number(d, (char_u *)"rows");
4487 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004488 }
4489 }
4490
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004491 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004492 if (fname == NULL)
4493 return;
4494 if (mch_stat((char *)fname, &st) >= 0)
4495 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004496 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004497 return;
4498 }
4499
Bram Moolenaard96ff162018-02-18 22:13:29 +01004500 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4501 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004502 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004503 return;
4504 }
4505
4506 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4507
4508 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004509 state = vterm_obtain_state(term->tl_vterm);
4510 vterm_state_get_cursorpos(state, &cursor_pos);
4511
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004512 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4513 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004514 {
4515 int repeat = 0;
4516
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004517 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4518 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004519 {
4520 VTermScreenCell cell;
4521 int same_attr;
4522 int same_chars = TRUE;
4523 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004524 int is_cursor_pos = (pos.col == cursor_pos.col
4525 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004526
4527 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4528 vim_memset(&cell, 0, sizeof(cell));
4529
4530 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4531 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004532 int c = cell.chars[i];
4533 int pc = prev_cell.chars[i];
4534
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004535 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01004536 if (i == 0)
4537 {
4538 c = (c == NUL) ? ' ' : c;
4539 pc = (pc == NUL) ? ' ' : pc;
4540 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004541 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004542 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004543 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004544 break;
4545 }
4546 same_attr = vtermAttr2hl(cell.attrs)
4547 == vtermAttr2hl(prev_cell.attrs)
4548 && same_color(&cell.fg, &prev_cell.fg)
4549 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004550 if (same_chars && cell.width == prev_cell.width && same_attr
4551 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004552 {
4553 ++repeat;
4554 }
4555 else
4556 {
4557 if (repeat > 0)
4558 {
4559 fprintf(fd, "@%d", repeat);
4560 repeat = 0;
4561 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004562 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004563
4564 if (cell.chars[0] == NUL)
4565 fputs(" ", fd);
4566 else
4567 {
4568 char_u charbuf[10];
4569 int len;
4570
4571 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4572 && cell.chars[i] != NUL; ++i)
4573 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004574 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004575 fwrite(charbuf, len, 1, fd);
4576 }
4577 }
4578
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004579 // When only the characters differ we don't write anything, the
4580 // following "|", "@" or NL will indicate using the same
4581 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004582 if (cell.width != prev_cell.width || !same_attr)
4583 {
4584 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004585 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004586 else
4587 fputs("+", fd);
4588
4589 if (same_attr)
4590 {
4591 fputs("&", fd);
4592 }
4593 else
4594 {
4595 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4596 if (same_color(&cell.fg, &prev_cell.fg))
4597 fputs("&", fd);
4598 else
4599 {
4600 fputs("#", fd);
4601 dump_term_color(fd, &cell.fg);
4602 }
4603 if (same_color(&cell.bg, &prev_cell.bg))
4604 fputs("&", fd);
4605 else
4606 {
4607 fputs("#", fd);
4608 dump_term_color(fd, &cell.bg);
4609 }
4610 }
4611 }
4612
4613 prev_cell = cell;
4614 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004615
4616 if (cell.width == 2)
4617 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004618 }
4619 if (repeat > 0)
4620 fprintf(fd, "@%d", repeat);
4621 fputs("\n", fd);
4622 }
4623
4624 fclose(fd);
4625}
4626
4627/*
4628 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4629 */
4630 static void
4631dump_is_corrupt(garray_T *gap)
4632{
4633 ga_concat(gap, (char_u *)"CORRUPT");
4634}
4635
4636 static void
4637append_cell(garray_T *gap, cellattr_T *cell)
4638{
4639 if (ga_grow(gap, 1) == OK)
4640 {
4641 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4642 ++gap->ga_len;
4643 }
4644}
4645
4646/*
4647 * Read the dump file from "fd" and append lines to the current buffer.
4648 * Return the cell width of the longest line.
4649 */
4650 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004651read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004652{
4653 int c;
4654 garray_T ga_text;
4655 garray_T ga_cell;
4656 char_u *prev_char = NULL;
4657 int attr = 0;
4658 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004659 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004660 term_T *term = curbuf->b_term;
4661 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004662 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004663
4664 ga_init2(&ga_text, 1, 90);
4665 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4666 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004667 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004668 cursor_pos->row = -1;
4669 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004670
4671 c = fgetc(fd);
4672 for (;;)
4673 {
4674 if (c == EOF)
4675 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004676 if (c == '\r')
4677 {
4678 // DOS line endings? Ignore.
4679 c = fgetc(fd);
4680 }
4681 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004682 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004683 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004684 if (ga_text.ga_data == NULL)
4685 dump_is_corrupt(&ga_text);
4686 if (ga_grow(&term->tl_scrollback, 1) == OK)
4687 {
4688 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4689 + term->tl_scrollback.ga_len;
4690
4691 if (max_cells < ga_cell.ga_len)
4692 max_cells = ga_cell.ga_len;
4693 line->sb_cols = ga_cell.ga_len;
4694 line->sb_cells = ga_cell.ga_data;
4695 line->sb_fill_attr = term->tl_default_color;
4696 ++term->tl_scrollback.ga_len;
4697 ga_init(&ga_cell);
4698
4699 ga_append(&ga_text, NUL);
4700 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4701 ga_text.ga_len, FALSE);
4702 }
4703 else
4704 ga_clear(&ga_cell);
4705 ga_text.ga_len = 0;
4706
4707 c = fgetc(fd);
4708 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004709 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004710 {
4711 int prev_len = ga_text.ga_len;
4712
Bram Moolenaar9271d052018-02-25 21:39:46 +01004713 if (c == '>')
4714 {
4715 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004716 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004717 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4718 cursor_pos->col = ga_cell.ga_len;
4719 }
4720
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004721 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004722 c = fgetc(fd);
4723 if (c != EOF)
4724 ga_append(&ga_text, c);
4725 for (;;)
4726 {
4727 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004728 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004729 || c == EOF || c == '\n')
4730 break;
4731 ga_append(&ga_text, c);
4732 }
4733
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004734 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01004735 vim_free(prev_char);
4736 if (ga_text.ga_data != NULL)
4737 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4738 ga_text.ga_len - prev_len);
4739
Bram Moolenaar9271d052018-02-25 21:39:46 +01004740 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004741 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004742 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004743 }
4744 else if (c == '+' || c == '*')
4745 {
4746 int is_bg;
4747
4748 cell.width = c == '+' ? 1 : 2;
4749
4750 c = fgetc(fd);
4751 if (c == '&')
4752 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004753 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004754 c = fgetc(fd);
4755 }
4756 else if (isdigit(c))
4757 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004758 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01004759 attr = 0;
4760 while (isdigit(c))
4761 {
4762 attr = attr * 10 + (c - '0');
4763 c = fgetc(fd);
4764 }
4765 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004766
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004767 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004768 for (is_bg = 0; is_bg <= 1; ++is_bg)
4769 {
4770 if (c == '&')
4771 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004772 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004773 c = fgetc(fd);
4774 }
4775 else if (c == '#')
4776 {
4777 int red, green, blue, index = 0;
4778
4779 c = fgetc(fd);
4780 red = hex2nr(c);
4781 c = fgetc(fd);
4782 red = (red << 4) + hex2nr(c);
4783 c = fgetc(fd);
4784 green = hex2nr(c);
4785 c = fgetc(fd);
4786 green = (green << 4) + hex2nr(c);
4787 c = fgetc(fd);
4788 blue = hex2nr(c);
4789 c = fgetc(fd);
4790 blue = (blue << 4) + hex2nr(c);
4791 c = fgetc(fd);
4792 if (!isdigit(c))
4793 dump_is_corrupt(&ga_text);
4794 while (isdigit(c))
4795 {
4796 index = index * 10 + (c - '0');
4797 c = fgetc(fd);
4798 }
4799
4800 if (is_bg)
4801 {
4802 cell.bg.red = red;
4803 cell.bg.green = green;
4804 cell.bg.blue = blue;
4805 cell.bg.ansi_index = index;
4806 }
4807 else
4808 {
4809 cell.fg.red = red;
4810 cell.fg.green = green;
4811 cell.fg.blue = blue;
4812 cell.fg.ansi_index = index;
4813 }
4814 }
4815 else
4816 dump_is_corrupt(&ga_text);
4817 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004818 }
4819 else
4820 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004821 }
4822 else
4823 dump_is_corrupt(&ga_text);
4824
4825 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004826 if (cell.width == 2)
4827 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004828 }
4829 else if (c == '@')
4830 {
4831 if (prev_char == NULL)
4832 dump_is_corrupt(&ga_text);
4833 else
4834 {
4835 int count = 0;
4836
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004837 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01004838 for (;;)
4839 {
4840 c = fgetc(fd);
4841 if (!isdigit(c))
4842 break;
4843 count = count * 10 + (c - '0');
4844 }
4845
4846 while (count-- > 0)
4847 {
4848 ga_concat(&ga_text, prev_char);
4849 append_cell(&ga_cell, &cell);
4850 }
4851 }
4852 }
4853 else
4854 {
4855 dump_is_corrupt(&ga_text);
4856 c = fgetc(fd);
4857 }
4858 }
4859
4860 if (ga_text.ga_len > 0)
4861 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004862 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004863 dump_is_corrupt(&ga_text);
4864 ga_append(&ga_text, NUL);
4865 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4866 ga_text.ga_len, FALSE);
4867 }
4868
4869 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004870 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004871 vim_free(prev_char);
4872
4873 return max_cells;
4874}
4875
4876/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004877 * Return an allocated string with at least "text_width" "=" characters and
4878 * "fname" inserted in the middle.
4879 */
4880 static char_u *
4881get_separator(int text_width, char_u *fname)
4882{
4883 int width = MAX(text_width, curwin->w_width);
4884 char_u *textline;
4885 int fname_size;
4886 char_u *p = fname;
4887 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004888 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004889
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004890 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004891 if (textline == NULL)
4892 return NULL;
4893
4894 fname_size = vim_strsize(fname);
4895 if (fname_size < width - 8)
4896 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004897 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02004898 width = MAX(text_width, fname_size + 8);
4899 }
4900 else if (fname_size > width - 8)
4901 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004902 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02004903 p = gettail(fname);
4904 fname_size = vim_strsize(p);
4905 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004906 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02004907 while (fname_size > width - 8)
4908 {
4909 p += (*mb_ptr2len)(p);
4910 fname_size = vim_strsize(p);
4911 }
4912
4913 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4914 textline[i] = '=';
4915 textline[i++] = ' ';
4916
4917 STRCPY(textline + i, p);
4918 off = STRLEN(textline);
4919 textline[off] = ' ';
4920 for (i = 1; i < (width - fname_size) / 2; ++i)
4921 textline[off + i] = '=';
4922 textline[off + i] = NUL;
4923
4924 return textline;
4925}
4926
4927/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004928 * Common for "term_dumpdiff()" and "term_dumpload()".
4929 */
4930 static void
4931term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4932{
4933 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004934 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004935 char_u buf1[NUMBUFLEN];
4936 char_u buf2[NUMBUFLEN];
4937 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004938 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004939 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004940 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004941 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004942 char_u *textline = NULL;
4943
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004944 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004945 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004946 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004947 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004948 if (fname1 == NULL || (do_diff && fname2 == NULL))
4949 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004950 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004951 return;
4952 }
4953 fd1 = mch_fopen((char *)fname1, READBIN);
4954 if (fd1 == NULL)
4955 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004956 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004957 return;
4958 }
4959 if (do_diff)
4960 {
4961 fd2 = mch_fopen((char *)fname2, READBIN);
4962 if (fd2 == NULL)
4963 {
4964 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004965 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004966 return;
4967 }
4968 }
4969
4970 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004971 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4972 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4973 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4974 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4975 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004976
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004977 if (opt.jo_term_name == NULL)
4978 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004979 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004980
Bram Moolenaar51e14382019-05-25 20:21:28 +02004981 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004982 if (fname_tofree != NULL)
4983 {
4984 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4985 opt.jo_term_name = fname_tofree;
4986 }
4987 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004988
Bram Moolenaar87abab92019-06-03 21:14:59 +02004989 if (opt.jo_bufnr_buf != NULL)
4990 {
4991 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4992
4993 // With "bufnr" argument: enter the window with this buffer and make it
4994 // empty.
4995 if (wp == NULL)
4996 semsg(_(e_invarg2), "bufnr");
4997 else
4998 {
4999 buf = curbuf;
5000 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
5001 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02005002 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005003 redraw_later(NOT_VALID);
5004 }
5005 }
5006 else
5007 // Create a new terminal window.
5008 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5009
Bram Moolenaard96ff162018-02-18 22:13:29 +01005010 if (buf != NULL && buf->b_term != NULL)
5011 {
5012 int i;
5013 linenr_T bot_lnum;
5014 linenr_T lnum;
5015 term_T *term = buf->b_term;
5016 int width;
5017 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005018 VTermPos cursor_pos1;
5019 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005020
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005021 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005022
Bram Moolenaard96ff162018-02-18 22:13:29 +01005023 rettv->vval.v_number = buf->b_fnum;
5024
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005025 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005026 width = read_dump_file(fd1, &cursor_pos1);
5027
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005028 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005029 if (cursor_pos1.row >= 0)
5030 {
5031 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5032 coladvance(cursor_pos1.col);
5033 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005034
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005035 // Delete the empty line that was in the empty buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005036 ml_delete(1, FALSE);
5037
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005038 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005039 if (!do_diff)
5040 goto theend;
5041
5042 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5043
Bram Moolenaar4a696342018-04-05 18:45:26 +02005044 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005045 if (textline == NULL)
5046 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005047 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5048 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5049 vim_free(textline);
5050
5051 textline = get_separator(width, fname2);
5052 if (textline == NULL)
5053 goto theend;
5054 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5055 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005056 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005057
5058 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005059 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005060 if (width2 > width)
5061 {
5062 vim_free(textline);
5063 textline = alloc(width2 + 1);
5064 if (textline == NULL)
5065 goto theend;
5066 width = width2;
5067 textline[width] = NUL;
5068 }
5069 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5070
5071 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5072 {
5073 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5074 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005075 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005076 for (i = 0; i < width; ++i)
5077 textline[i] = '-';
5078 }
5079 else
5080 {
5081 char_u *line1;
5082 char_u *line2;
5083 char_u *p1;
5084 char_u *p2;
5085 int col;
5086 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5087 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5088 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5089 ->sb_cells;
5090
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005091 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005092 line1 = vim_strsave(ml_get(lnum));
5093 if (line1 == NULL)
5094 break;
5095 p1 = line1;
5096
5097 line2 = ml_get(lnum + bot_lnum);
5098 p2 = line2;
5099 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5100 {
5101 int len1 = utfc_ptr2len(p1);
5102 int len2 = utfc_ptr2len(p2);
5103
5104 textline[col] = ' ';
5105 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005106 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005107 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005108 else if (lnum == cursor_pos1.row + 1
5109 && col == cursor_pos1.col
5110 && (cursor_pos1.row != cursor_pos2.row
5111 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005112 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005113 textline[col] = '>';
5114 else if (lnum == cursor_pos2.row + 1
5115 && col == cursor_pos2.col
5116 && (cursor_pos1.row != cursor_pos2.row
5117 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005118 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005119 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005120 else if (cellattr1 != NULL && cellattr2 != NULL)
5121 {
5122 if ((cellattr1 + col)->width
5123 != (cellattr2 + col)->width)
5124 textline[col] = 'w';
5125 else if (!same_color(&(cellattr1 + col)->fg,
5126 &(cellattr2 + col)->fg))
5127 textline[col] = 'f';
5128 else if (!same_color(&(cellattr1 + col)->bg,
5129 &(cellattr2 + col)->bg))
5130 textline[col] = 'b';
5131 else if (vtermAttr2hl((cellattr1 + col)->attrs)
5132 != vtermAttr2hl(((cellattr2 + col)->attrs)))
5133 textline[col] = 'a';
5134 }
5135 p1 += len1;
5136 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005137 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005138 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005139
5140 while (col < width)
5141 {
5142 if (*p1 == NUL && *p2 == NUL)
5143 textline[col] = '?';
5144 else if (*p1 == NUL)
5145 {
5146 textline[col] = '+';
5147 p2 += utfc_ptr2len(p2);
5148 }
5149 else
5150 {
5151 textline[col] = '-';
5152 p1 += utfc_ptr2len(p1);
5153 }
5154 ++col;
5155 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005156
5157 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005158 }
5159 if (add_empty_scrollback(term, &term->tl_default_color,
5160 term->tl_top_diff_rows) == OK)
5161 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5162 ++bot_lnum;
5163 }
5164
5165 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5166 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005167 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005168 for (i = 0; i < width; ++i)
5169 textline[i] = '+';
5170 if (add_empty_scrollback(term, &term->tl_default_color,
5171 term->tl_top_diff_rows) == OK)
5172 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5173 ++lnum;
5174 ++bot_lnum;
5175 }
5176
5177 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005178
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005179 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005180 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005181 }
5182
5183theend:
5184 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005185 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005186 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005187 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005188 fclose(fd2);
5189}
5190
5191/*
5192 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5193 * bottom files.
5194 * Return FAIL when this is not possible.
5195 */
5196 int
5197term_swap_diff()
5198{
5199 term_T *term = curbuf->b_term;
5200 linenr_T line_count;
5201 linenr_T top_rows;
5202 linenr_T bot_rows;
5203 linenr_T bot_start;
5204 linenr_T lnum;
5205 char_u *p;
5206 sb_line_T *sb_line;
5207
5208 if (term == NULL
5209 || !term_is_finished(curbuf)
5210 || term->tl_top_diff_rows == 0
5211 || term->tl_scrollback.ga_len == 0)
5212 return FAIL;
5213
5214 line_count = curbuf->b_ml.ml_line_count;
5215 top_rows = term->tl_top_diff_rows;
5216 bot_rows = term->tl_bot_diff_rows;
5217 bot_start = line_count - bot_rows;
5218 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5219
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005220 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005221 for (lnum = 1; lnum <= top_rows; ++lnum)
5222 {
5223 p = vim_strsave(ml_get(1));
5224 if (p == NULL)
5225 return OK;
5226 ml_append(bot_start, p, 0, FALSE);
5227 ml_delete(1, FALSE);
5228 vim_free(p);
5229 }
5230
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005231 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005232 for (lnum = 1; lnum <= bot_rows; ++lnum)
5233 {
5234 p = vim_strsave(ml_get(bot_start + lnum));
5235 if (p == NULL)
5236 return OK;
5237 ml_delete(bot_start + lnum, FALSE);
5238 ml_append(lnum - 1, p, 0, FALSE);
5239 vim_free(p);
5240 }
5241
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005242 // move top title to bottom
5243 p = vim_strsave(ml_get(bot_rows + 1));
5244 if (p == NULL)
5245 return OK;
5246 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5247 ml_delete(bot_rows + 1, FALSE);
5248 vim_free(p);
5249
5250 // move bottom title to top
5251 p = vim_strsave(ml_get(line_count - top_rows));
5252 if (p == NULL)
5253 return OK;
5254 ml_delete(line_count - top_rows, FALSE);
5255 ml_append(bot_rows, p, 0, FALSE);
5256 vim_free(p);
5257
Bram Moolenaard96ff162018-02-18 22:13:29 +01005258 if (top_rows == bot_rows)
5259 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005260 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005261 for (lnum = 0; lnum < top_rows; ++lnum)
5262 {
5263 sb_line_T temp;
5264
5265 temp = *(sb_line + lnum);
5266 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5267 *(sb_line + bot_start + lnum) = temp;
5268 }
5269 }
5270 else
5271 {
5272 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005273 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005274
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005275 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005276 if (temp != NULL)
5277 {
5278 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5279 mch_memmove(term->tl_scrollback.ga_data,
5280 temp + bot_start,
5281 sizeof(sb_line_T) * bot_rows);
5282 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5283 temp + top_rows,
5284 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5285 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5286 + line_count - top_rows,
5287 temp,
5288 sizeof(sb_line_T) * top_rows);
5289 vim_free(temp);
5290 }
5291 }
5292
5293 term->tl_top_diff_rows = bot_rows;
5294 term->tl_bot_diff_rows = top_rows;
5295
5296 update_screen(NOT_VALID);
5297 return OK;
5298}
5299
5300/*
5301 * "term_dumpdiff(filename, filename, options)" function
5302 */
5303 void
5304f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5305{
5306 term_load_dump(argvars, rettv, TRUE);
5307}
5308
5309/*
5310 * "term_dumpload(filename, options)" function
5311 */
5312 void
5313f_term_dumpload(typval_T *argvars, typval_T *rettv)
5314{
5315 term_load_dump(argvars, rettv, FALSE);
5316}
5317
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005318/*
5319 * "term_getaltscreen(buf)" function
5320 */
5321 void
5322f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5323{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005324 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005325
5326 if (buf == NULL)
5327 return;
5328 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5329}
5330
5331/*
5332 * "term_getattr(attr, name)" function
5333 */
5334 void
5335f_term_getattr(typval_T *argvars, typval_T *rettv)
5336{
5337 int attr;
5338 size_t i;
5339 char_u *name;
5340
5341 static struct {
5342 char *name;
5343 int attr;
5344 } attrs[] = {
5345 {"bold", HL_BOLD},
5346 {"italic", HL_ITALIC},
5347 {"underline", HL_UNDERLINE},
5348 {"strike", HL_STRIKETHROUGH},
5349 {"reverse", HL_INVERSE},
5350 };
5351
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005352 attr = tv_get_number(&argvars[0]);
5353 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005354 if (name == NULL)
5355 return;
5356
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005357 if (attr > HL_ALL)
5358 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005359 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5360 if (STRCMP(name, attrs[i].name) == 0)
5361 {
5362 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5363 break;
5364 }
5365}
5366
5367/*
5368 * "term_getcursor(buf)" function
5369 */
5370 void
5371f_term_getcursor(typval_T *argvars, typval_T *rettv)
5372{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005373 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005374 term_T *term;
5375 list_T *l;
5376 dict_T *d;
5377
5378 if (rettv_list_alloc(rettv) == FAIL)
5379 return;
5380 if (buf == NULL)
5381 return;
5382 term = buf->b_term;
5383
5384 l = rettv->vval.v_list;
5385 list_append_number(l, term->tl_cursor_pos.row + 1);
5386 list_append_number(l, term->tl_cursor_pos.col + 1);
5387
5388 d = dict_alloc();
5389 if (d != NULL)
5390 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005391 dict_add_number(d, "visible", term->tl_cursor_visible);
5392 dict_add_number(d, "blink", blink_state_is_inverted()
5393 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5394 dict_add_number(d, "shape", term->tl_cursor_shape);
5395 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005396 list_append_dict(l, d);
5397 }
5398}
5399
5400/*
5401 * "term_getjob(buf)" function
5402 */
5403 void
5404f_term_getjob(typval_T *argvars, typval_T *rettv)
5405{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005406 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005407
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005408 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005409 {
5410 rettv->v_type = VAR_SPECIAL;
5411 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005412 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005413 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005414
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005415 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005416 rettv->vval.v_job = buf->b_term->tl_job;
5417 if (rettv->vval.v_job != NULL)
5418 ++rettv->vval.v_job->jv_refcount;
5419}
5420
5421 static int
5422get_row_number(typval_T *tv, term_T *term)
5423{
5424 if (tv->v_type == VAR_STRING
5425 && tv->vval.v_string != NULL
5426 && STRCMP(tv->vval.v_string, ".") == 0)
5427 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005428 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005429}
5430
5431/*
5432 * "term_getline(buf, row)" function
5433 */
5434 void
5435f_term_getline(typval_T *argvars, typval_T *rettv)
5436{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005437 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005438 term_T *term;
5439 int row;
5440
5441 rettv->v_type = VAR_STRING;
5442 if (buf == NULL)
5443 return;
5444 term = buf->b_term;
5445 row = get_row_number(&argvars[1], term);
5446
5447 if (term->tl_vterm == NULL)
5448 {
5449 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5450
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005451 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005452 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5453 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5454 }
5455 else
5456 {
5457 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5458 VTermRect rect;
5459 int len;
5460 char_u *p;
5461
5462 if (row < 0 || row >= term->tl_rows)
5463 return;
5464 len = term->tl_cols * MB_MAXBYTES + 1;
5465 p = alloc(len);
5466 if (p == NULL)
5467 return;
5468 rettv->vval.v_string = p;
5469
5470 rect.start_col = 0;
5471 rect.end_col = term->tl_cols;
5472 rect.start_row = row;
5473 rect.end_row = row + 1;
5474 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5475 }
5476}
5477
5478/*
5479 * "term_getscrolled(buf)" function
5480 */
5481 void
5482f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5483{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005484 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005485
5486 if (buf == NULL)
5487 return;
5488 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5489}
5490
5491/*
5492 * "term_getsize(buf)" function
5493 */
5494 void
5495f_term_getsize(typval_T *argvars, typval_T *rettv)
5496{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005497 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005498 list_T *l;
5499
5500 if (rettv_list_alloc(rettv) == FAIL)
5501 return;
5502 if (buf == NULL)
5503 return;
5504
5505 l = rettv->vval.v_list;
5506 list_append_number(l, buf->b_term->tl_rows);
5507 list_append_number(l, buf->b_term->tl_cols);
5508}
5509
5510/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005511 * "term_setsize(buf, rows, cols)" function
5512 */
5513 void
5514f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5515{
5516 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5517 term_T *term;
5518 varnumber_T rows, cols;
5519
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005520 if (buf == NULL)
5521 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005522 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005523 return;
5524 }
5525 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005526 return;
5527 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005528 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005529 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005530 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005531 cols = cols <= 0 ? term->tl_cols : cols;
5532 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005533 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02005534
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005535 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02005536 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5537 term_report_winsize(term, term->tl_rows, term->tl_cols);
5538}
5539
5540/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005541 * "term_getstatus(buf)" function
5542 */
5543 void
5544f_term_getstatus(typval_T *argvars, typval_T *rettv)
5545{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005546 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005547 term_T *term;
5548 char_u val[100];
5549
5550 rettv->v_type = VAR_STRING;
5551 if (buf == NULL)
5552 return;
5553 term = buf->b_term;
5554
5555 if (term_job_running(term))
5556 STRCPY(val, "running");
5557 else
5558 STRCPY(val, "finished");
5559 if (term->tl_normal_mode)
5560 STRCAT(val, ",normal");
5561 rettv->vval.v_string = vim_strsave(val);
5562}
5563
5564/*
5565 * "term_gettitle(buf)" function
5566 */
5567 void
5568f_term_gettitle(typval_T *argvars, typval_T *rettv)
5569{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005570 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005571
5572 rettv->v_type = VAR_STRING;
5573 if (buf == NULL)
5574 return;
5575
5576 if (buf->b_term->tl_title != NULL)
5577 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5578}
5579
5580/*
5581 * "term_gettty(buf)" function
5582 */
5583 void
5584f_term_gettty(typval_T *argvars, typval_T *rettv)
5585{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005586 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005587 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005588 int num = 0;
5589
5590 rettv->v_type = VAR_STRING;
5591 if (buf == NULL)
5592 return;
5593 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005594 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005595
5596 switch (num)
5597 {
5598 case 0:
5599 if (buf->b_term->tl_job != NULL)
5600 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005601 break;
5602 case 1:
5603 if (buf->b_term->tl_job != NULL)
5604 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005605 break;
5606 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005607 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005608 return;
5609 }
5610 if (p != NULL)
5611 rettv->vval.v_string = vim_strsave(p);
5612}
5613
5614/*
5615 * "term_list()" function
5616 */
5617 void
5618f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5619{
5620 term_T *tp;
5621 list_T *l;
5622
5623 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5624 return;
5625
5626 l = rettv->vval.v_list;
5627 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5628 if (tp != NULL && tp->tl_buffer != NULL)
5629 if (list_append_number(l,
5630 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5631 return;
5632}
5633
5634/*
5635 * "term_scrape(buf, row)" function
5636 */
5637 void
5638f_term_scrape(typval_T *argvars, typval_T *rettv)
5639{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005640 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005641 VTermScreen *screen = NULL;
5642 VTermPos pos;
5643 list_T *l;
5644 term_T *term;
5645 char_u *p;
5646 sb_line_T *line;
5647
5648 if (rettv_list_alloc(rettv) == FAIL)
5649 return;
5650 if (buf == NULL)
5651 return;
5652 term = buf->b_term;
5653
5654 l = rettv->vval.v_list;
5655 pos.row = get_row_number(&argvars[1], term);
5656
5657 if (term->tl_vterm != NULL)
5658 {
5659 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005660 if (screen == NULL) // can't really happen
5661 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005662 p = NULL;
5663 line = NULL;
5664 }
5665 else
5666 {
5667 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5668
5669 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5670 return;
5671 p = ml_get_buf(buf, lnum + 1, FALSE);
5672 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5673 }
5674
5675 for (pos.col = 0; pos.col < term->tl_cols; )
5676 {
5677 dict_T *dcell;
5678 int width;
5679 VTermScreenCellAttrs attrs;
5680 VTermColor fg, bg;
5681 char_u rgb[8];
5682 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5683 int off = 0;
5684 int i;
5685
5686 if (screen == NULL)
5687 {
5688 cellattr_T *cellattr;
5689 int len;
5690
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005691 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005692 if (pos.col >= line->sb_cols)
5693 break;
5694 cellattr = line->sb_cells + pos.col;
5695 width = cellattr->width;
5696 attrs = cellattr->attrs;
5697 fg = cellattr->fg;
5698 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005699 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005700 mch_memmove(mbs, p, len);
5701 mbs[len] = NUL;
5702 p += len;
5703 }
5704 else
5705 {
5706 VTermScreenCell cell;
5707 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5708 break;
5709 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5710 {
5711 if (cell.chars[i] == 0)
5712 break;
5713 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5714 }
5715 mbs[off] = NUL;
5716 width = cell.width;
5717 attrs = cell.attrs;
5718 fg = cell.fg;
5719 bg = cell.bg;
5720 }
5721 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005722 if (dcell == NULL)
5723 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005724 list_append_dict(l, dcell);
5725
Bram Moolenaare0be1672018-07-08 16:50:37 +02005726 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005727
5728 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5729 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005730 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005731 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5732 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005733 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005734
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005735 dict_add_number(dcell, "attr", cell2attr(NULL, attrs, fg, bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02005736 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005737
5738 ++pos.col;
5739 if (width == 2)
5740 ++pos.col;
5741 }
5742}
5743
5744/*
5745 * "term_sendkeys(buf, keys)" function
5746 */
5747 void
5748f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5749{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005750 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005751 char_u *msg;
5752 term_T *term;
5753
5754 rettv->v_type = VAR_UNKNOWN;
5755 if (buf == NULL)
5756 return;
5757
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005758 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005759 if (msg == NULL)
5760 return;
5761 term = buf->b_term;
5762 if (term->tl_vterm == NULL)
5763 return;
5764
5765 while (*msg != NUL)
5766 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005767 int c;
5768
5769 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5770 {
5771 c = TO_SPECIAL(msg[1], msg[2]);
5772 msg += 3;
5773 }
5774 else
5775 {
5776 c = PTR2CHAR(msg);
5777 msg += MB_CPTR2LEN(msg);
5778 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005779 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005780 }
5781}
5782
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005783#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5784/*
5785 * "term_getansicolors(buf)" function
5786 */
5787 void
5788f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5789{
5790 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5791 term_T *term;
5792 VTermState *state;
5793 VTermColor color;
5794 char_u hexbuf[10];
5795 int index;
5796 list_T *list;
5797
5798 if (rettv_list_alloc(rettv) == FAIL)
5799 return;
5800
5801 if (buf == NULL)
5802 return;
5803 term = buf->b_term;
5804 if (term->tl_vterm == NULL)
5805 return;
5806
5807 list = rettv->vval.v_list;
5808 state = vterm_obtain_state(term->tl_vterm);
5809 for (index = 0; index < 16; index++)
5810 {
5811 vterm_state_get_palette_color(state, index, &color);
5812 sprintf((char *)hexbuf, "#%02x%02x%02x",
5813 color.red, color.green, color.blue);
5814 if (list_append_string(list, hexbuf, 7) == FAIL)
5815 return;
5816 }
5817}
5818
5819/*
5820 * "term_setansicolors(buf, list)" function
5821 */
5822 void
5823f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5824{
5825 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5826 term_T *term;
5827
5828 if (buf == NULL)
5829 return;
5830 term = buf->b_term;
5831 if (term->tl_vterm == NULL)
5832 return;
5833
5834 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5835 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005836 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005837 return;
5838 }
5839
5840 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005841 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005842}
5843#endif
5844
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005845/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005846 * "term_setapi(buf, api)" function
5847 */
5848 void
5849f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5850{
5851 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5852 term_T *term;
5853 char_u *api;
5854
5855 if (buf == NULL)
5856 return;
5857 term = buf->b_term;
5858 vim_free(term->tl_api);
5859 api = tv_get_string_chk(&argvars[1]);
5860 if (api != NULL)
5861 term->tl_api = vim_strsave(api);
5862 else
5863 term->tl_api = NULL;
5864}
5865
5866/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005867 * "term_setrestore(buf, command)" function
5868 */
5869 void
5870f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5871{
5872#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005873 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005874 term_T *term;
5875 char_u *cmd;
5876
5877 if (buf == NULL)
5878 return;
5879 term = buf->b_term;
5880 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005881 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005882 if (cmd != NULL)
5883 term->tl_command = vim_strsave(cmd);
5884 else
5885 term->tl_command = NULL;
5886#endif
5887}
5888
5889/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005890 * "term_setkill(buf, how)" function
5891 */
5892 void
5893f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5894{
5895 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5896 term_T *term;
5897 char_u *how;
5898
5899 if (buf == NULL)
5900 return;
5901 term = buf->b_term;
5902 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005903 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005904 if (how != NULL)
5905 term->tl_kill = vim_strsave(how);
5906 else
5907 term->tl_kill = NULL;
5908}
5909
5910/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005911 * "term_start(command, options)" function
5912 */
5913 void
5914f_term_start(typval_T *argvars, typval_T *rettv)
5915{
5916 jobopt_T opt;
5917 buf_T *buf;
5918
5919 init_job_options(&opt);
5920 if (argvars[1].v_type != VAR_UNKNOWN
5921 && get_job_options(&argvars[1], &opt,
5922 JO_TIMEOUT_ALL + JO_STOPONEXIT
5923 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5924 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5925 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5926 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005927 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005928 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005929 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005930 return;
5931
Bram Moolenaar13568252018-03-16 20:46:58 +01005932 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005933
5934 if (buf != NULL && buf->b_term != NULL)
5935 rettv->vval.v_number = buf->b_fnum;
5936}
5937
5938/*
5939 * "term_wait" function
5940 */
5941 void
5942f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5943{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005944 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005945
5946 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005947 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005948 if (buf->b_term->tl_job == NULL)
5949 {
5950 ch_log(NULL, "term_wait(): no job to wait for");
5951 return;
5952 }
5953 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005954 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005955 return;
5956
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005957 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01005958 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005959 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5960 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005961 // The job is dead, keep reading channel I/O until the channel is
5962 // closed. buf->b_term may become NULL if the terminal was closed while
5963 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005964 ch_log(NULL, "term_wait(): waiting for channel to close");
5965 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5966 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005967 term_flush_messages();
5968
Bram Moolenaard45aa552018-05-21 22:50:29 +02005969 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005970 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005971 // If the terminal is closed when the channel is closed the
5972 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01005973 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005974 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005975
5976 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005977 }
5978 else
5979 {
5980 long wait = 10L;
5981
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005982 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005983
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005984 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005985 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005986 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005987 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005988
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005989 // Flushing messages on channels is hopefully sufficient.
5990 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005991 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005992 }
5993}
5994
5995/*
5996 * Called when a channel has sent all the lines to a terminal.
5997 * Send a CTRL-D to mark the end of the text.
5998 */
5999 void
6000term_send_eof(channel_T *ch)
6001{
6002 term_T *term;
6003
6004 for (term = first_term; term != NULL; term = term->tl_next)
6005 if (term->tl_job == ch->ch_job)
6006 {
6007 if (term->tl_eof_chars != NULL)
6008 {
6009 channel_send(ch, PART_IN, term->tl_eof_chars,
6010 (int)STRLEN(term->tl_eof_chars), NULL);
6011 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6012 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006013# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006014 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006015 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006016 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6017# endif
6018 }
6019}
6020
Bram Moolenaar113e1072019-01-20 15:30:40 +01006021#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006022 job_T *
6023term_getjob(term_T *term)
6024{
6025 return term != NULL ? term->tl_job : NULL;
6026}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006027#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006028
Bram Moolenaar4f974752019-02-17 17:44:42 +01006029# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006030
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006031///////////////////////////////////////
6032// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006033#ifdef PROTO
6034typedef int COORD;
6035typedef int DWORD;
6036typedef int HANDLE;
6037typedef int *DWORD_PTR;
6038typedef int HPCON;
6039typedef int HRESULT;
6040typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006041typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006042typedef int PSIZE_T;
6043typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006044typedef int BOOL;
6045# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006046#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006047
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006048HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6049HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6050HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006051BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6052BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6053void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006054
6055 static int
6056dyn_conpty_init(int verbose)
6057{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006058 static HMODULE hKerneldll = NULL;
6059 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006060 static struct
6061 {
6062 char *name;
6063 FARPROC *ptr;
6064 } conpty_entry[] =
6065 {
6066 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6067 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6068 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6069 {"InitializeProcThreadAttributeList",
6070 (FARPROC*)&pInitializeProcThreadAttributeList},
6071 {"UpdateProcThreadAttribute",
6072 (FARPROC*)&pUpdateProcThreadAttribute},
6073 {"DeleteProcThreadAttributeList",
6074 (FARPROC*)&pDeleteProcThreadAttributeList},
6075 {NULL, NULL}
6076 };
6077
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006078 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006079 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006080 if (verbose)
6081 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006082 return FAIL;
6083 }
6084
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006085 // No need to initialize twice.
6086 if (hKerneldll)
6087 return OK;
6088
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006089 hKerneldll = vimLoadLib("kernel32.dll");
6090 for (i = 0; conpty_entry[i].name != NULL
6091 && conpty_entry[i].ptr != NULL; ++i)
6092 {
6093 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6094 conpty_entry[i].name)) == NULL)
6095 {
6096 if (verbose)
6097 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006098 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006099 return FAIL;
6100 }
6101 }
6102
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006103 return OK;
6104}
6105
6106 static int
6107conpty_term_and_job_init(
6108 term_T *term,
6109 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006110 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006111 jobopt_T *opt,
6112 jobopt_T *orig_opt)
6113{
6114 WCHAR *cmd_wchar = NULL;
6115 WCHAR *cmd_wchar_copy = NULL;
6116 WCHAR *cwd_wchar = NULL;
6117 WCHAR *env_wchar = NULL;
6118 channel_T *channel = NULL;
6119 job_T *job = NULL;
6120 HANDLE jo = NULL;
6121 garray_T ga_cmd, ga_env;
6122 char_u *cmd = NULL;
6123 HRESULT hr;
6124 COORD consize;
6125 SIZE_T breq;
6126 PROCESS_INFORMATION proc_info;
6127 HANDLE i_theirs = NULL;
6128 HANDLE o_theirs = NULL;
6129 HANDLE i_ours = NULL;
6130 HANDLE o_ours = NULL;
6131
6132 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6133 ga_init2(&ga_env, (int)sizeof(char*), 20);
6134
6135 if (argvar->v_type == VAR_STRING)
6136 {
6137 cmd = argvar->vval.v_string;
6138 }
6139 else if (argvar->v_type == VAR_LIST)
6140 {
6141 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6142 goto failed;
6143 cmd = ga_cmd.ga_data;
6144 }
6145 if (cmd == NULL || *cmd == NUL)
6146 {
6147 emsg(_(e_invarg));
6148 goto failed;
6149 }
6150
6151 term->tl_arg0_cmd = vim_strsave(cmd);
6152
6153 cmd_wchar = enc_to_utf16(cmd, NULL);
6154
6155 if (cmd_wchar != NULL)
6156 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006157 // Request by CreateProcessW
6158 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006159 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006160 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6161 }
6162
6163 ga_clear(&ga_cmd);
6164 if (cmd_wchar == NULL)
6165 goto failed;
6166 if (opt->jo_cwd != NULL)
6167 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6168
6169 win32_build_env(opt->jo_env, &ga_env, TRUE);
6170 env_wchar = ga_env.ga_data;
6171
6172 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6173 goto failed;
6174 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6175 goto failed;
6176
6177 consize.X = term->tl_cols;
6178 consize.Y = term->tl_rows;
6179 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6180 &term->tl_conpty);
6181 if (FAILED(hr))
6182 goto failed;
6183
6184 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6185
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006186 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006187 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006188 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006189 if (!term->tl_siex.lpAttributeList)
6190 goto failed;
6191 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6192 0, &breq))
6193 goto failed;
6194 if (!pUpdateProcThreadAttribute(
6195 term->tl_siex.lpAttributeList, 0,
6196 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6197 sizeof(HPCON), NULL, NULL))
6198 goto failed;
6199
6200 channel = add_channel();
6201 if (channel == NULL)
6202 goto failed;
6203
6204 job = job_alloc();
6205 if (job == NULL)
6206 goto failed;
6207 if (argvar->v_type == VAR_STRING)
6208 {
6209 int argc;
6210
6211 build_argv_from_string(cmd, &job->jv_argv, &argc);
6212 }
6213 else
6214 {
6215 int argc;
6216
6217 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6218 }
6219
6220 if (opt->jo_set & JO_IN_BUF)
6221 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6222
6223 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6224 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
6225 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
6226 | CREATE_DEFAULT_ERROR_MODE,
6227 env_wchar, cwd_wchar,
6228 &term->tl_siex.StartupInfo, &proc_info))
6229 goto failed;
6230
6231 CloseHandle(i_theirs);
6232 CloseHandle(o_theirs);
6233
6234 channel_set_pipes(channel,
6235 (sock_T)i_ours,
6236 (sock_T)o_ours,
6237 (sock_T)o_ours);
6238
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006239 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006240 channel->ch_write_text_mode = TRUE;
6241
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006242 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006243 channel->ch_anonymous_pipe = TRUE;
6244
6245 jo = CreateJobObject(NULL, NULL);
6246 if (jo == NULL)
6247 goto failed;
6248
6249 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6250 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006251 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006252 CloseHandle(jo);
6253 jo = NULL;
6254 }
6255
6256 ResumeThread(proc_info.hThread);
6257 CloseHandle(proc_info.hThread);
6258
6259 vim_free(cmd_wchar);
6260 vim_free(cmd_wchar_copy);
6261 vim_free(cwd_wchar);
6262 vim_free(env_wchar);
6263
6264 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6265 goto failed;
6266
6267#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6268 if (opt->jo_set2 & JO2_ANSI_COLORS)
6269 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6270 else
6271 init_vterm_ansi_colors(term->tl_vterm);
6272#endif
6273
6274 channel_set_job(channel, job, opt);
6275 job_set_options(job, opt);
6276
6277 job->jv_channel = channel;
6278 job->jv_proc_info = proc_info;
6279 job->jv_job_object = jo;
6280 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006281 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006282 ++job->jv_refcount;
6283 term->tl_job = job;
6284
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006285 // Redirecting stdout and stderr doesn't work at the job level. Instead
6286 // open the file here and handle it in. opt->jo_io was changed in
6287 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006288 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6289 {
6290 char_u *fname = opt->jo_io_name[PART_OUT];
6291
6292 ch_log(channel, "Opening output file %s", fname);
6293 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6294 if (term->tl_out_fd == NULL)
6295 semsg(_(e_notopen), fname);
6296 }
6297
6298 return OK;
6299
6300failed:
6301 ga_clear(&ga_cmd);
6302 ga_clear(&ga_env);
6303 vim_free(cmd_wchar);
6304 vim_free(cmd_wchar_copy);
6305 vim_free(cwd_wchar);
6306 if (channel != NULL)
6307 channel_clear(channel);
6308 if (job != NULL)
6309 {
6310 job->jv_channel = NULL;
6311 job_cleanup(job);
6312 }
6313 term->tl_job = NULL;
6314 if (jo != NULL)
6315 CloseHandle(jo);
6316
6317 if (term->tl_siex.lpAttributeList != NULL)
6318 {
6319 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6320 vim_free(term->tl_siex.lpAttributeList);
6321 }
6322 term->tl_siex.lpAttributeList = NULL;
6323 if (o_theirs != NULL)
6324 CloseHandle(o_theirs);
6325 if (o_ours != NULL)
6326 CloseHandle(o_ours);
6327 if (i_ours != NULL)
6328 CloseHandle(i_ours);
6329 if (i_theirs != NULL)
6330 CloseHandle(i_theirs);
6331 if (term->tl_conpty != NULL)
6332 pClosePseudoConsole(term->tl_conpty);
6333 term->tl_conpty = NULL;
6334 return FAIL;
6335}
6336
6337 static void
6338conpty_term_report_winsize(term_T *term, int rows, int cols)
6339{
6340 COORD consize;
6341
6342 consize.X = cols;
6343 consize.Y = rows;
6344 pResizePseudoConsole(term->tl_conpty, consize);
6345}
6346
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006347 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006348term_free_conpty(term_T *term)
6349{
6350 if (term->tl_siex.lpAttributeList != NULL)
6351 {
6352 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6353 vim_free(term->tl_siex.lpAttributeList);
6354 }
6355 term->tl_siex.lpAttributeList = NULL;
6356 if (term->tl_conpty != NULL)
6357 pClosePseudoConsole(term->tl_conpty);
6358 term->tl_conpty = NULL;
6359}
6360
6361 int
6362use_conpty(void)
6363{
6364 return has_conpty;
6365}
6366
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006367# ifndef PROTO
6368
6369#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6370#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006371#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006372
6373void* (*winpty_config_new)(UINT64, void*);
6374void* (*winpty_open)(void*, void*);
6375void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6376BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6377void (*winpty_config_set_mouse_mode)(void*, int);
6378void (*winpty_config_set_initial_size)(void*, int, int);
6379LPCWSTR (*winpty_conin_name)(void*);
6380LPCWSTR (*winpty_conout_name)(void*);
6381LPCWSTR (*winpty_conerr_name)(void*);
6382void (*winpty_free)(void*);
6383void (*winpty_config_free)(void*);
6384void (*winpty_spawn_config_free)(void*);
6385void (*winpty_error_free)(void*);
6386LPCWSTR (*winpty_error_msg)(void*);
6387BOOL (*winpty_set_size)(void*, int, int, void*);
6388HANDLE (*winpty_agent_process)(void*);
6389
6390#define WINPTY_DLL "winpty.dll"
6391
6392static HINSTANCE hWinPtyDLL = NULL;
6393# endif
6394
6395 static int
6396dyn_winpty_init(int verbose)
6397{
6398 int i;
6399 static struct
6400 {
6401 char *name;
6402 FARPROC *ptr;
6403 } winpty_entry[] =
6404 {
6405 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6406 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6407 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6408 {"winpty_config_set_mouse_mode",
6409 (FARPROC*)&winpty_config_set_mouse_mode},
6410 {"winpty_config_set_initial_size",
6411 (FARPROC*)&winpty_config_set_initial_size},
6412 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6413 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6414 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6415 {"winpty_free", (FARPROC*)&winpty_free},
6416 {"winpty_open", (FARPROC*)&winpty_open},
6417 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6418 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6419 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6420 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6421 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6422 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6423 {NULL, NULL}
6424 };
6425
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006426 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006427 if (hWinPtyDLL)
6428 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006429 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6430 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006431 if (*p_winptydll != NUL)
6432 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6433 if (!hWinPtyDLL)
6434 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6435 if (!hWinPtyDLL)
6436 {
6437 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006438 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006439 : (char_u *)WINPTY_DLL);
6440 return FAIL;
6441 }
6442 for (i = 0; winpty_entry[i].name != NULL
6443 && winpty_entry[i].ptr != NULL; ++i)
6444 {
6445 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6446 winpty_entry[i].name)) == NULL)
6447 {
6448 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006449 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006450 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006451 return FAIL;
6452 }
6453 }
6454
6455 return OK;
6456}
6457
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006458 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006459winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006460 term_T *term,
6461 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006462 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006463 jobopt_T *opt,
6464 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006465{
6466 WCHAR *cmd_wchar = NULL;
6467 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006468 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006469 channel_T *channel = NULL;
6470 job_T *job = NULL;
6471 DWORD error;
6472 HANDLE jo = NULL;
6473 HANDLE child_process_handle;
6474 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006475 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006476 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006477 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006478 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006479
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006480 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6481 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006482
6483 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006484 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006485 cmd = argvar->vval.v_string;
6486 }
6487 else if (argvar->v_type == VAR_LIST)
6488 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006489 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006490 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006491 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006492 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006493 if (cmd == NULL || *cmd == NUL)
6494 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006495 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006496 goto failed;
6497 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006498
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006499 term->tl_arg0_cmd = vim_strsave(cmd);
6500
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006501 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006502 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006503 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006504 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006505 if (opt->jo_cwd != NULL)
6506 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006507
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006508 win32_build_env(opt->jo_env, &ga_env, TRUE);
6509 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006510
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006511 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6512 if (term->tl_winpty_config == NULL)
6513 goto failed;
6514
6515 winpty_config_set_mouse_mode(term->tl_winpty_config,
6516 WINPTY_MOUSE_MODE_FORCE);
6517 winpty_config_set_initial_size(term->tl_winpty_config,
6518 term->tl_cols, term->tl_rows);
6519 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6520 if (term->tl_winpty == NULL)
6521 goto failed;
6522
6523 spawn_config = winpty_spawn_config_new(
6524 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6525 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6526 NULL,
6527 cmd_wchar,
6528 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006529 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006530 &winpty_err);
6531 if (spawn_config == NULL)
6532 goto failed;
6533
6534 channel = add_channel();
6535 if (channel == NULL)
6536 goto failed;
6537
6538 job = job_alloc();
6539 if (job == NULL)
6540 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006541 if (argvar->v_type == VAR_STRING)
6542 {
6543 int argc;
6544
6545 build_argv_from_string(cmd, &job->jv_argv, &argc);
6546 }
6547 else
6548 {
6549 int argc;
6550
6551 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6552 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006553
6554 if (opt->jo_set & JO_IN_BUF)
6555 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6556
6557 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6558 &child_thread_handle, &error, &winpty_err))
6559 goto failed;
6560
6561 channel_set_pipes(channel,
6562 (sock_T)CreateFileW(
6563 winpty_conin_name(term->tl_winpty),
6564 GENERIC_WRITE, 0, NULL,
6565 OPEN_EXISTING, 0, NULL),
6566 (sock_T)CreateFileW(
6567 winpty_conout_name(term->tl_winpty),
6568 GENERIC_READ, 0, NULL,
6569 OPEN_EXISTING, 0, NULL),
6570 (sock_T)CreateFileW(
6571 winpty_conerr_name(term->tl_winpty),
6572 GENERIC_READ, 0, NULL,
6573 OPEN_EXISTING, 0, NULL));
6574
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006575 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006576 channel->ch_write_text_mode = TRUE;
6577
6578 jo = CreateJobObject(NULL, NULL);
6579 if (jo == NULL)
6580 goto failed;
6581
6582 if (!AssignProcessToJobObject(jo, child_process_handle))
6583 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006584 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006585 CloseHandle(jo);
6586 jo = NULL;
6587 }
6588
6589 winpty_spawn_config_free(spawn_config);
6590 vim_free(cmd_wchar);
6591 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006592 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006593
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006594 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6595 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006596
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006597#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6598 if (opt->jo_set2 & JO2_ANSI_COLORS)
6599 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6600 else
6601 init_vterm_ansi_colors(term->tl_vterm);
6602#endif
6603
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006604 channel_set_job(channel, job, opt);
6605 job_set_options(job, opt);
6606
6607 job->jv_channel = channel;
6608 job->jv_proc_info.hProcess = child_process_handle;
6609 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6610 job->jv_job_object = jo;
6611 job->jv_status = JOB_STARTED;
6612 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006613 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006614 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006615 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006616 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006617 ++job->jv_refcount;
6618 term->tl_job = job;
6619
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006620 // Redirecting stdout and stderr doesn't work at the job level. Instead
6621 // open the file here and handle it in. opt->jo_io was changed in
6622 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006623 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6624 {
6625 char_u *fname = opt->jo_io_name[PART_OUT];
6626
6627 ch_log(channel, "Opening output file %s", fname);
6628 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6629 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006630 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006631 }
6632
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006633 return OK;
6634
6635failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006636 ga_clear(&ga_cmd);
6637 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006638 vim_free(cmd_wchar);
6639 vim_free(cwd_wchar);
6640 if (spawn_config != NULL)
6641 winpty_spawn_config_free(spawn_config);
6642 if (channel != NULL)
6643 channel_clear(channel);
6644 if (job != NULL)
6645 {
6646 job->jv_channel = NULL;
6647 job_cleanup(job);
6648 }
6649 term->tl_job = NULL;
6650 if (jo != NULL)
6651 CloseHandle(jo);
6652 if (term->tl_winpty != NULL)
6653 winpty_free(term->tl_winpty);
6654 term->tl_winpty = NULL;
6655 if (term->tl_winpty_config != NULL)
6656 winpty_config_free(term->tl_winpty_config);
6657 term->tl_winpty_config = NULL;
6658 if (winpty_err != NULL)
6659 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006660 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006661 (short_u *)winpty_error_msg(winpty_err), NULL);
6662
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006663 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006664 winpty_error_free(winpty_err);
6665 }
6666 return FAIL;
6667}
6668
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006669/*
6670 * Create a new terminal of "rows" by "cols" cells.
6671 * Store a reference in "term".
6672 * Return OK or FAIL.
6673 */
6674 static int
6675term_and_job_init(
6676 term_T *term,
6677 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01006678 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006679 jobopt_T *opt,
6680 jobopt_T *orig_opt)
6681{
6682 int use_winpty = FALSE;
6683 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006684 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006685
6686 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6687 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6688
6689 if (!has_winpty && !has_conpty)
6690 // If neither is available give the errors for winpty, since when
6691 // conpty is not available it can't be installed either.
6692 return dyn_winpty_init(TRUE);
6693
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006694 if (opt->jo_tty_type != NUL)
6695 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006696
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006697 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006698 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006699 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006700 use_conpty = TRUE;
6701 else if (has_winpty)
6702 use_winpty = TRUE;
6703 // else: error
6704 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006705 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006706 {
6707 if (has_winpty)
6708 use_winpty = TRUE;
6709 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006710 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006711 {
6712 if (has_conpty)
6713 use_conpty = TRUE;
6714 else
6715 return dyn_conpty_init(TRUE);
6716 }
6717
6718 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006719 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006720
6721 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006722 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006723
6724 // error
6725 return dyn_winpty_init(TRUE);
6726}
6727
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006728 static int
6729create_pty_only(term_T *term, jobopt_T *options)
6730{
6731 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6732 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6733 char in_name[80], out_name[80];
6734 channel_T *channel = NULL;
6735
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006736 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6737 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006738
6739 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6740 GetCurrentProcessId(),
6741 curbuf->b_fnum);
6742 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6743 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6744 PIPE_UNLIMITED_INSTANCES,
6745 0, 0, NMPWAIT_NOWAIT, NULL);
6746 if (hPipeIn == INVALID_HANDLE_VALUE)
6747 goto failed;
6748
6749 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6750 GetCurrentProcessId(),
6751 curbuf->b_fnum);
6752 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6753 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6754 PIPE_UNLIMITED_INSTANCES,
6755 0, 0, 0, NULL);
6756 if (hPipeOut == INVALID_HANDLE_VALUE)
6757 goto failed;
6758
6759 ConnectNamedPipe(hPipeIn, NULL);
6760 ConnectNamedPipe(hPipeOut, NULL);
6761
6762 term->tl_job = job_alloc();
6763 if (term->tl_job == NULL)
6764 goto failed;
6765 ++term->tl_job->jv_refcount;
6766
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006767 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006768 term->tl_job->jv_status = JOB_FINISHED;
6769
6770 channel = add_channel();
6771 if (channel == NULL)
6772 goto failed;
6773 term->tl_job->jv_channel = channel;
6774 channel->ch_keep_open = TRUE;
6775 channel->ch_named_pipe = TRUE;
6776
6777 channel_set_pipes(channel,
6778 (sock_T)hPipeIn,
6779 (sock_T)hPipeOut,
6780 (sock_T)hPipeOut);
6781 channel_set_job(channel, term->tl_job, options);
6782 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6783 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6784
6785 return OK;
6786
6787failed:
6788 if (hPipeIn != NULL)
6789 CloseHandle(hPipeIn);
6790 if (hPipeOut != NULL)
6791 CloseHandle(hPipeOut);
6792 return FAIL;
6793}
6794
6795/*
6796 * Free the terminal emulator part of "term".
6797 */
6798 static void
6799term_free_vterm(term_T *term)
6800{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006801 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006802 if (term->tl_winpty != NULL)
6803 winpty_free(term->tl_winpty);
6804 term->tl_winpty = NULL;
6805 if (term->tl_winpty_config != NULL)
6806 winpty_config_free(term->tl_winpty_config);
6807 term->tl_winpty_config = NULL;
6808 if (term->tl_vterm != NULL)
6809 vterm_free(term->tl_vterm);
6810 term->tl_vterm = NULL;
6811}
6812
6813/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006814 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006815 */
6816 static void
6817term_report_winsize(term_T *term, int rows, int cols)
6818{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006819 if (term->tl_conpty)
6820 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006821 if (term->tl_winpty)
6822 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6823}
6824
6825 int
6826terminal_enabled(void)
6827{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006828 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006829}
6830
6831# else
6832
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006833///////////////////////////////////////
6834// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006835
6836/*
6837 * Create a new terminal of "rows" by "cols" cells.
6838 * Start job for "cmd".
6839 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006840 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006841 * Return OK or FAIL.
6842 */
6843 static int
6844term_and_job_init(
6845 term_T *term,
6846 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006847 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006848 jobopt_T *opt,
6849 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006850{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006851 term->tl_arg0_cmd = NULL;
6852
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006853 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6854 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006855
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006856#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6857 if (opt->jo_set2 & JO2_ANSI_COLORS)
6858 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6859 else
6860 init_vterm_ansi_colors(term->tl_vterm);
6861#endif
6862
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006863 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01006864 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006865 if (term->tl_job != NULL)
6866 ++term->tl_job->jv_refcount;
6867
6868 return term->tl_job != NULL
6869 && term->tl_job->jv_channel != NULL
6870 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6871}
6872
6873 static int
6874create_pty_only(term_T *term, jobopt_T *opt)
6875{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006876 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6877 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006878
6879 term->tl_job = job_alloc();
6880 if (term->tl_job == NULL)
6881 return FAIL;
6882 ++term->tl_job->jv_refcount;
6883
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006884 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006885 term->tl_job->jv_status = JOB_FINISHED;
6886
6887 return mch_create_pty_channel(term->tl_job, opt);
6888}
6889
6890/*
6891 * Free the terminal emulator part of "term".
6892 */
6893 static void
6894term_free_vterm(term_T *term)
6895{
6896 if (term->tl_vterm != NULL)
6897 vterm_free(term->tl_vterm);
6898 term->tl_vterm = NULL;
6899}
6900
6901/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006902 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006903 */
6904 static void
6905term_report_winsize(term_T *term, int rows, int cols)
6906{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006907 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006908 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6909 {
6910 int fd = -1;
6911 int part;
6912
6913 for (part = PART_OUT; part < PART_COUNT; ++part)
6914 {
6915 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006916 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006917 break;
6918 }
6919 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6920 mch_signal_job(term->tl_job, (char_u *)"winch");
6921 }
6922}
6923
6924# endif
6925
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006926#endif // FEAT_TERMINAL