blob: 30590b623f8a6373ac926d70447126c76d039a12 [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020039 */
40
41#include "vim.h"
42
43#if defined(FEAT_TERMINAL) || defined(PROTO)
44
45#ifndef MIN
46# define MIN(x,y) ((x) < (y) ? (x) : (y))
47#endif
48#ifndef MAX
49# define MAX(x,y) ((x) > (y) ? (x) : (y))
50#endif
51
52#include "libvterm/include/vterm.h"
53
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010054// This is VTermScreenCell without the characters, thus much smaller.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055typedef struct {
56 VTermScreenCellAttrs attrs;
57 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010058 VTermColor fg;
59 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060} cellattr_T;
61
62typedef struct sb_line_S {
Bram Moolenaar29ae2232019-02-14 21:22:01 +010063 int sb_cols; // can differ per line
64 cellattr_T *sb_cells; // allocated
65 cellattr_T sb_fill_attr; // for short line
66 char_u *sb_text; // for tl_scrollback_postponed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067} sb_line_T;
68
Bram Moolenaar4f974752019-02-17 17:44:42 +010069#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010070# ifndef HPCON
71# define HPCON VOID*
72# endif
73# ifndef EXTENDED_STARTUPINFO_PRESENT
74# define EXTENDED_STARTUPINFO_PRESENT 0x00080000
75# endif
76# ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
77# define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE 0x00020016
78# endif
79typedef struct _DYN_STARTUPINFOEXW
80{
81 STARTUPINFOW StartupInfo;
82 LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
83} DYN_STARTUPINFOEXW, *PDYN_STARTUPINFOEXW;
84#endif
85
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010086// typedef term_T in structs.h
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020087struct terminal_S {
88 term_T *tl_next;
89
90 VTerm *tl_vterm;
91 job_T *tl_job;
92 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010093#if defined(FEAT_GUI)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010094 int tl_system; // when non-zero used for :!cmd output
95 int tl_toprow; // row with first line of system terminal
Bram Moolenaar13568252018-03-16 20:46:58 +010096#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010098 // Set when setting the size of a vterm, reset after redrawing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020099 int tl_vterm_size_changed;
100
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100101 int tl_normal_mode; // TRUE: Terminal-Normal mode
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200102 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200103 int tl_channel_recently_closed; // still need to handle tl_finish
104
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100105 int tl_finish;
106#define TL_FINISH_UNSET NUL
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100107#define TL_FINISH_CLOSE 'c' // ++close or :terminal without argument
108#define TL_FINISH_NOCLOSE 'n' // ++noclose
109#define TL_FINISH_OPEN 'o' // ++open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200110 char_u *tl_opencmd;
111 char_u *tl_eof_chars;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200112 char_u *tl_api; // prefix for terminal API function
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200113
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100114 char_u *tl_arg0_cmd; // To format the status bar
115
Bram Moolenaar4f974752019-02-17 17:44:42 +0100116#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200117 void *tl_winpty_config;
118 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200119
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100120 HPCON tl_conpty;
121 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
122
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200123 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200124#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100125#if defined(FEAT_SESSION)
126 char_u *tl_command;
127#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100128 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200129
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100130 // last known vterm size
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200131 int tl_rows;
132 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200133
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100134 char_u *tl_title; // NULL or allocated
135 char_u *tl_status_text; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200136
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100137 // Range of screen rows to update. Zero based.
138 int tl_dirty_row_start; // MAX_ROW if nothing dirty
139 int tl_dirty_row_end; // row below last one to update
140 int tl_dirty_snapshot; // text updated after making snapshot
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200141#ifdef FEAT_TIMERS
142 int tl_timer_set;
143 proftime_T tl_timer_due;
144#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100145 int tl_postponed_scroll; // to be scrolled up
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200146
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200147 garray_T tl_scrollback;
148 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100149 garray_T tl_scrollback_postponed;
150
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200151 cellattr_T tl_default_color;
152
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100153 linenr_T tl_top_diff_rows; // rows of top diff file or zero
154 linenr_T tl_bot_diff_rows; // rows of bottom diff file
Bram Moolenaard96ff162018-02-18 22:13:29 +0100155
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200156 VTermPos tl_cursor_pos;
157 int tl_cursor_visible;
158 int tl_cursor_blink;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100159 int tl_cursor_shape; // 1: block, 2: underline, 3: bar
160 char_u *tl_cursor_color; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200161
162 int tl_using_altscreen;
163};
164
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100165#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
166#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167
168/*
169 * List of all active terminals.
170 */
171static term_T *first_term = NULL;
172
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100173// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200174static term_T *in_terminal_loop = NULL;
175
Bram Moolenaar4f974752019-02-17 17:44:42 +0100176#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100177static BOOL has_winpty = FALSE;
178static BOOL has_conpty = FALSE;
179#endif
180
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100181#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200182#define KEY_BUF_LEN 200
183
184/*
185 * Functions with separate implementation for MS-Windows and Unix-like systems.
186 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200187static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188static int create_pty_only(term_T *term, jobopt_T *opt);
189static void term_report_winsize(term_T *term, int rows, int cols);
190static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100191#ifdef FEAT_GUI
192static void update_system_term(term_T *term);
193#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200194
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100195static void handle_postponed_scrollback(term_T *term);
196
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100197// The character that we know (or assume) that the terminal expects for the
198// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200199static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200200
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100201// "Terminal" highlight group colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100202static int term_default_cterm_fg = -1;
203static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200204
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100205// Store the last set and the desired cursor properties, so that we only update
206// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200207static char_u *last_set_cursor_color = NULL;
208static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100209static int last_set_cursor_shape = -1;
210static int desired_cursor_shape = -1;
211static int last_set_cursor_blink = -1;
212static int desired_cursor_blink = -1;
213
214
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100215///////////////////////////////////////
216// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200217
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200218 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200219cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
220{
221 if (lhs_color != NULL && rhs_color != NULL)
222 return STRCMP(lhs_color, rhs_color) == 0;
223 return lhs_color == NULL && rhs_color == NULL;
224}
225
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200226 static void
227cursor_color_copy(char_u **to_color, char_u *from_color)
228{
229 // Avoid a free & alloc if the value is already right.
230 if (cursor_color_equal(*to_color, from_color))
231 return;
232 vim_free(*to_color);
233 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
234}
235
236 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200237cursor_color_get(char_u *color)
238{
239 return (color == NULL) ? (char_u *)"" : color;
240}
241
242
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200243/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200244 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200245 * current window.
246 * Sets "rows" and/or "cols" to zero when it should follow the window size.
247 * Return TRUE if the size is the minimum size: "24*80".
248 */
249 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200250parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200251{
252 int minsize = FALSE;
253
254 *rows = 0;
255 *cols = 0;
256
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200257 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200258 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200259 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200260
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100261 // Syntax of value was already checked when it's set.
Bram Moolenaar498c2562018-04-15 23:45:15 +0200262 if (p == NULL)
263 {
264 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200265 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200266 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200267 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200268 *cols = atoi((char *)p + 1);
269 }
270 return minsize;
271}
272
273/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200274 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200275 */
276 static void
277set_term_and_win_size(term_T *term)
278{
Bram Moolenaar13568252018-03-16 20:46:58 +0100279#ifdef FEAT_GUI
280 if (term->tl_system)
281 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100282 // Use the whole screen for the system command. However, it will start
283 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100284 term->tl_rows = Rows;
285 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200286 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100287 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100288#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200289 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200290 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200291 if (term->tl_rows != 0)
292 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
293 if (term->tl_cols != 0)
294 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200295 }
296 if (term->tl_rows == 0)
297 term->tl_rows = curwin->w_height;
298 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200299 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 if (term->tl_cols == 0)
301 term->tl_cols = curwin->w_width;
302 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200303 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200304}
305
306/*
307 * Initialize job options for a terminal job.
308 * Caller may overrule some of them.
309 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100310 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311init_job_options(jobopt_T *opt)
312{
313 clear_job_options(opt);
314
315 opt->jo_mode = MODE_RAW;
316 opt->jo_out_mode = MODE_RAW;
317 opt->jo_err_mode = MODE_RAW;
318 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
319}
320
321/*
322 * Set job options mandatory for a terminal job.
323 */
324 static void
325setup_job_options(jobopt_T *opt, int rows, int cols)
326{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100327#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100328 // Win32: Redirecting the job output won't work, thus always connect stdout
329 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200330 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200331#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200332 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100333 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200334 opt->jo_io[PART_OUT] = JIO_BUFFER;
335 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
336 opt->jo_modifiable[PART_OUT] = 0;
337 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
338 }
339
Bram Moolenaar4f974752019-02-17 17:44:42 +0100340#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100341 // Win32: Redirecting the job output won't work, thus always connect stderr
342 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200343 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200344#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200345 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100346 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200347 opt->jo_io[PART_ERR] = JIO_BUFFER;
348 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
349 opt->jo_modifiable[PART_ERR] = 0;
350 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
351 }
352
353 opt->jo_pty = TRUE;
354 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
355 opt->jo_term_rows = rows;
356 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
357 opt->jo_term_cols = cols;
358}
359
360/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200361 * Flush messages on channels.
362 */
363 static void
364term_flush_messages()
365{
366 mch_check_messages();
367 parse_queued_messages();
368}
369
370/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100371 * Close a terminal buffer (and its window). Used when creating the terminal
372 * fails.
373 */
374 static void
375term_close_buffer(buf_T *buf, buf_T *old_curbuf)
376{
377 free_terminal(buf);
378 if (old_curbuf != NULL)
379 {
380 --curbuf->b_nwindows;
381 curbuf = old_curbuf;
382 curwin->w_buffer = curbuf;
383 ++curbuf->b_nwindows;
384 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100385 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100386
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100387 // Wiping out the buffer will also close the window and call
388 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100389 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
390}
391
392/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200393 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100394 * Use either "argvar" or "argv", the other must be NULL.
395 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
396 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200397 * Returns NULL when failed.
398 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100399 buf_T *
400term_start(
401 typval_T *argvar,
402 char **argv,
403 jobopt_T *opt,
404 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200405{
406 exarg_T split_ea;
407 win_T *old_curwin = curwin;
408 term_T *term;
409 buf_T *old_curbuf = NULL;
410 int res;
411 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100412 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200413 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200414
415 if (check_restricted() || check_secure())
416 return NULL;
417
418 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
419 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
420 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100421 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
422 || (argvar != NULL
423 && argvar->v_type == VAR_LIST
424 && argvar->vval.v_list != NULL
425 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200426 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100427 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 return NULL;
429 }
430
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200431 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200432 if (term == NULL)
433 return NULL;
434 term->tl_dirty_row_end = MAX_ROW;
435 term->tl_cursor_visible = TRUE;
436 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
437 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100438#ifdef FEAT_GUI
439 term->tl_system = (flags & TERM_START_SYSTEM);
440#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200441 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100442 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200443
444 vim_memset(&split_ea, 0, sizeof(split_ea));
445 if (opt->jo_curwin)
446 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100447 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100448 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200449 {
450 no_write_message();
451 vim_free(term);
452 return NULL;
453 }
454 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100455 ECMD_HIDE
456 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
457 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200458 {
459 vim_free(term);
460 return NULL;
461 }
462 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100463 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200464 {
465 buf_T *buf;
466
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100467 // Create a new buffer without a window. Make it the current buffer for
468 // a moment to be able to do the initialisations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200469 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
470 BLN_NEW | BLN_LISTED);
471 if (buf == NULL || ml_open(buf) == FAIL)
472 {
473 vim_free(term);
474 return NULL;
475 }
476 old_curbuf = curbuf;
477 --curbuf->b_nwindows;
478 curbuf = buf;
479 curwin->w_buffer = buf;
480 ++curbuf->b_nwindows;
481 }
482 else
483 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100484 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200485 split_ea.cmdidx = CMD_new;
486 split_ea.cmd = (char_u *)"new";
487 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100488 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200489 {
490 split_ea.line2 = opt->jo_term_rows;
491 split_ea.addr_count = 1;
492 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100493 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200494 {
495 split_ea.line2 = opt->jo_term_cols;
496 split_ea.addr_count = 1;
497 }
498
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100499 if (vertical)
500 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200501 ex_splitview(&split_ea);
502 if (curwin == old_curwin)
503 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100504 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200505 vim_free(term);
506 return NULL;
507 }
508 }
509 term->tl_buffer = curbuf;
510 curbuf->b_term = term;
511
512 if (!opt->jo_hidden)
513 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100514 // Only one size was taken care of with :new, do the other one. With
515 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100516 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200517 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100518 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200519 win_setwidth(opt->jo_term_cols);
520 }
521
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100522 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200523 term->tl_next = first_term;
524 first_term = term;
525
526 if (opt->jo_term_name != NULL)
527 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100528 else if (argv != NULL)
529 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200530 else
531 {
532 int i;
533 size_t len;
534 char_u *cmd, *p;
535
536 if (argvar->v_type == VAR_STRING)
537 {
538 cmd = argvar->vval.v_string;
539 if (cmd == NULL)
540 cmd = (char_u *)"";
541 else if (STRCMP(cmd, "NONE") == 0)
542 cmd = (char_u *)"pty";
543 }
544 else if (argvar->v_type != VAR_LIST
545 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100546 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100547 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200548 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
549 cmd = (char_u*)"";
550
551 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200552 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200553
554 for (i = 0; p != NULL; ++i)
555 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100556 // Prepend a ! to the command name to avoid the buffer name equals
557 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200558 if (i == 0)
559 vim_snprintf((char *)p, len, "!%s", cmd);
560 else
561 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
562 if (buflist_findname(p) == NULL)
563 {
564 vim_free(curbuf->b_ffname);
565 curbuf->b_ffname = p;
566 break;
567 }
568 }
569 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100570 vim_free(curbuf->b_sfname);
571 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200572 curbuf->b_fname = curbuf->b_ffname;
573
574 if (opt->jo_term_opencmd != NULL)
575 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
576
577 if (opt->jo_eof_chars != NULL)
578 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
579
580 set_string_option_direct((char_u *)"buftype", -1,
581 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200582 // Avoid that 'buftype' is reset when this buffer is entered.
583 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200584
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100585 // Mark the buffer as not modifiable. It can only be made modifiable after
586 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200587 curbuf->b_p_ma = FALSE;
588
589 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100590#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200591 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
592#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200593 setup_job_options(opt, term->tl_rows, term->tl_cols);
594
Bram Moolenaar13568252018-03-16 20:46:58 +0100595 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100596 return curbuf;
597
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100598#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100599 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100600 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100601 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100602 else if (argvar->v_type == VAR_STRING)
603 {
604 char_u *cmd = argvar->vval.v_string;
605
606 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
607 term->tl_command = vim_strsave(cmd);
608 }
609 else if (argvar->v_type == VAR_LIST
610 && argvar->vval.v_list != NULL
611 && argvar->vval.v_list->lv_len > 0)
612 {
613 garray_T ga;
614 listitem_T *item;
615
616 ga_init2(&ga, 1, 100);
617 for (item = argvar->vval.v_list->lv_first;
618 item != NULL; item = item->li_next)
619 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100620 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100621 char_u *p;
622
623 if (s == NULL)
624 break;
625 p = vim_strsave_fnameescape(s, FALSE);
626 if (p == NULL)
627 break;
628 ga_concat(&ga, p);
629 vim_free(p);
630 ga_append(&ga, ' ');
631 }
632 if (item == NULL)
633 {
634 ga_append(&ga, NUL);
635 term->tl_command = ga.ga_data;
636 }
637 else
638 ga_clear(&ga);
639 }
640#endif
641
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100642 if (opt->jo_term_kill != NULL)
643 {
644 char_u *p = skiptowhite(opt->jo_term_kill);
645
646 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
647 }
648
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200649 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100650 {
651 char_u *p = skiptowhite(opt->jo_term_api);
652
653 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
654 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200655 else
656 term->tl_api = vim_strsave((char_u *)"Tapi_");
657
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100658 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100659 if (argv == NULL
660 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200661 && argvar->vval.v_string != NULL
662 && STRCMP(argvar->vval.v_string, "NONE") == 0)
663 res = create_pty_only(term, opt);
664 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200665 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200666
667 newbuf = curbuf;
668 if (res == OK)
669 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100670 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200671 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
672 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100673#ifdef FEAT_GUI
674 if (term->tl_system)
675 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100676 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100677 term->tl_toprow = msg_row + 1;
678 term->tl_dirty_row_end = 0;
679 }
680#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200681
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100682 // Make sure we don't get stuck on sending keys to the job, it leads to
683 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200684 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
685
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200686 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200687 {
688 --curbuf->b_nwindows;
689 curbuf = old_curbuf;
690 curwin->w_buffer = curbuf;
691 ++curbuf->b_nwindows;
692 }
693 }
694 else
695 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100696 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200697 return NULL;
698 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100699
Bram Moolenaar13568252018-03-16 20:46:58 +0100700 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200701 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
702 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200703 return newbuf;
704}
705
706/*
707 * ":terminal": open a terminal window and execute a job in it.
708 */
709 void
710ex_terminal(exarg_T *eap)
711{
712 typval_T argvar[2];
713 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100714 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200715 char_u *cmd;
716 char_u *tofree = NULL;
717
718 init_job_options(&opt);
719
720 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100721 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200722 {
723 char_u *p, *ep;
724
725 cmd += 2;
726 p = skiptowhite(cmd);
727 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200728 if (ep != NULL)
729 {
730 if (ep < p)
731 p = ep;
732 else
733 ep = NULL;
734 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200735
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200736# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
737 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
738 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200739 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200740 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100741 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200742 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200743 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200744 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200745 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200746 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200747 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200748 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100749 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100750 else if (OPTARG_HAS("shell"))
751 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200752 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100753 {
754 opt.jo_set2 |= JO2_TERM_KILL;
755 opt.jo_term_kill = ep + 1;
756 p = skiptowhite(cmd);
757 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200758 else if (OPTARG_HAS("api"))
759 {
760 opt.jo_set2 |= JO2_TERM_API;
761 if (ep != NULL)
762 {
763 opt.jo_term_api = ep + 1;
764 p = skiptowhite(cmd);
765 }
766 else
767 opt.jo_term_api = NULL;
768 }
769 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200770 {
771 opt.jo_set2 |= JO2_TERM_ROWS;
772 opt.jo_term_rows = atoi((char *)ep + 1);
773 p = skiptowhite(cmd);
774 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200775 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200776 {
777 opt.jo_set2 |= JO2_TERM_COLS;
778 opt.jo_term_cols = atoi((char *)ep + 1);
779 p = skiptowhite(cmd);
780 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200781 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200782 {
783 char_u *buf = NULL;
784 char_u *keys;
785
Bram Moolenaar21109272020-01-30 16:27:20 +0100786 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200787 p = skiptowhite(cmd);
788 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200789 keys = replace_termcodes(ep + 1, &buf,
790 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200791 opt.jo_set2 |= JO2_EOF_CHARS;
792 opt.jo_eof_chars = vim_strsave(keys);
793 vim_free(buf);
794 *p = ' ';
795 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100796#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100797 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
798 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100799 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100800 int tty_type = NUL;
801
802 p = skiptowhite(cmd);
803 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
804 tty_type = 'w';
805 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
806 tty_type = 'c';
807 else
808 {
809 semsg(e_invargval, "type");
810 goto theend;
811 }
812 opt.jo_set2 |= JO2_TTY_TYPE;
813 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100814 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100815#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200816 else
817 {
818 if (*p)
819 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100820 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100821 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200822 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200823# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200824 cmd = skipwhite(p);
825 }
826 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100827 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100828 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200829 tofree = cmd = vim_strsave(p_sh);
830
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100831 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100832 if (opt.jo_term_finish == NUL)
833 opt.jo_term_finish = 'c';
834 }
835
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200836 if (eap->addr_count > 0)
837 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100838 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200839 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
840 opt.jo_io[PART_IN] = JIO_BUFFER;
841 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
842 opt.jo_in_top = eap->line1;
843 opt.jo_in_bot = eap->line2;
844 }
845
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100846 if (opt_shell && tofree == NULL)
847 {
848#ifdef UNIX
849 char **argv = NULL;
850 char_u *tofree1 = NULL;
851 char_u *tofree2 = NULL;
852
853 // :term ++shell command
854 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
855 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100856 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100857 vim_free(tofree1);
858 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100859 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100860#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100861# ifdef MSWIN
862 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
863 char_u *newcmd;
864
865 newcmd = alloc(cmdlen);
866 if (newcmd == NULL)
867 goto theend;
868 tofree = newcmd;
869 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
870 cmd = newcmd;
871# else
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100872 emsg(_("E279: Sorry, ++shell is not supported on this system"));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100873 goto theend;
874# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100875#endif
876 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100877 argvar[0].v_type = VAR_STRING;
878 argvar[0].vval.v_string = cmd;
879 argvar[1].v_type = VAR_UNKNOWN;
880 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100881
882theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100883 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200884 vim_free(opt.jo_eof_chars);
885}
886
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100887#if defined(FEAT_SESSION) || defined(PROTO)
888/*
889 * Write a :terminal command to the session file to restore the terminal in
890 * window "wp".
891 * Return FAIL if writing fails.
892 */
893 int
894term_write_session(FILE *fd, win_T *wp)
895{
896 term_T *term = wp->w_buffer->b_term;
897
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100898 // Create the terminal and run the command. This is not without
899 // risk, but let's assume the user only creates a session when this
900 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100901 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
902 term->tl_cols, term->tl_rows) < 0)
903 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100904#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100905 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
906 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100907#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100908 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
909 return FAIL;
910
911 return put_eol(fd);
912}
913
914/*
915 * Return TRUE if "buf" has a terminal that should be restored.
916 */
917 int
918term_should_restore(buf_T *buf)
919{
920 term_T *term = buf->b_term;
921
922 return term != NULL && (term->tl_command == NULL
923 || STRCMP(term->tl_command, "NONE") != 0);
924}
925#endif
926
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200927/*
928 * Free the scrollback buffer for "term".
929 */
930 static void
931free_scrollback(term_T *term)
932{
933 int i;
934
935 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
936 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
937 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100938 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
939 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
940 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200941}
942
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100943
944// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200945static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100946
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200947/*
948 * Free a terminal and everything it refers to.
949 * Kills the job if there is one.
950 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100951 * The actual terminal structure is freed later in free_unused_terminals(),
952 * because callbacks may wipe out a buffer while the terminal is still
953 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200954 */
955 void
956free_terminal(buf_T *buf)
957{
958 term_T *term = buf->b_term;
959 term_T *tp;
960
961 if (term == NULL)
962 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100963
964 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200965 if (first_term == term)
966 first_term = term->tl_next;
967 else
968 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
969 if (tp->tl_next == term)
970 {
971 tp->tl_next = term->tl_next;
972 break;
973 }
974
975 if (term->tl_job != NULL)
976 {
977 if (term->tl_job->jv_status != JOB_ENDED
978 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100979 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200980 job_stop(term->tl_job, NULL, "kill");
981 job_unref(term->tl_job);
982 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100983 term->tl_next = terminals_to_free;
984 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200985
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200986 buf->b_term = NULL;
987 if (in_terminal_loop == term)
988 in_terminal_loop = NULL;
989}
990
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100991 void
992free_unused_terminals()
993{
994 while (terminals_to_free != NULL)
995 {
996 term_T *term = terminals_to_free;
997
998 terminals_to_free = term->tl_next;
999
1000 free_scrollback(term);
1001
1002 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001003 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001004 vim_free(term->tl_title);
1005#ifdef FEAT_SESSION
1006 vim_free(term->tl_command);
1007#endif
1008 vim_free(term->tl_kill);
1009 vim_free(term->tl_status_text);
1010 vim_free(term->tl_opencmd);
1011 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001012 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001013#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001014 if (term->tl_out_fd != NULL)
1015 fclose(term->tl_out_fd);
1016#endif
1017 vim_free(term->tl_cursor_color);
1018 vim_free(term);
1019 }
1020}
1021
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001022/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001023 * Get the part that is connected to the tty. Normally this is PART_IN, but
1024 * when writing buffer lines to the job it can be another. This makes it
1025 * possible to do "1,5term vim -".
1026 */
1027 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001028get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001029{
1030#ifdef UNIX
1031 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1032 int i;
1033
1034 for (i = 0; i < 3; ++i)
1035 {
1036 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1037
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001038 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001039 return parts[i];
1040 }
1041#endif
1042 return PART_IN;
1043}
1044
1045/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001046 * Write job output "msg[len]" to the vterm.
1047 */
1048 static void
1049term_write_job_output(term_T *term, char_u *msg, size_t len)
1050{
1051 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001052 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001053
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001054 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001055
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001056 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001057 if (prevlen != vterm_output_get_buffer_current(vterm))
1058 {
1059 char buf[KEY_BUF_LEN];
1060 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1061
1062 if (curlen > 0)
1063 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1064 (char_u *)buf, (int)curlen, NULL);
1065 }
1066
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001067 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001068 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1069}
1070
1071 static void
1072update_cursor(term_T *term, int redraw)
1073{
1074 if (term->tl_normal_mode)
1075 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001076#ifdef FEAT_GUI
1077 if (term->tl_system)
1078 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1079 term->tl_cursor_pos.col);
1080 else
1081#endif
1082 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001083 if (redraw)
1084 {
1085 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1086 cursor_on();
1087 out_flush();
1088#ifdef FEAT_GUI
1089 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001090 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001091 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001092 gui_mch_flush();
1093 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001094#endif
1095 }
1096}
1097
1098/*
1099 * Invoked when "msg" output from a job was received. Write it to the terminal
1100 * of "buffer".
1101 */
1102 void
1103write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1104{
1105 size_t len = STRLEN(msg);
1106 term_T *term = buffer->b_term;
1107
Bram Moolenaar4f974752019-02-17 17:44:42 +01001108#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001109 // Win32: Cannot redirect output of the job, intercept it here and write to
1110 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001111 if (term->tl_out_fd != NULL)
1112 {
1113 ch_log(channel, "Writing %d bytes to output file", (int)len);
1114 fwrite(msg, len, 1, term->tl_out_fd);
1115 return;
1116 }
1117#endif
1118
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001119 if (term->tl_vterm == NULL)
1120 {
1121 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1122 return;
1123 }
1124 ch_log(channel, "writing %d bytes to terminal", (int)len);
1125 term_write_job_output(term, msg, len);
1126
Bram Moolenaar13568252018-03-16 20:46:58 +01001127#ifdef FEAT_GUI
1128 if (term->tl_system)
1129 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001130 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001131 update_system_term(term);
1132 update_cursor(term, TRUE);
1133 }
1134 else
1135#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001136 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1137 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001138 if (!term->tl_normal_mode)
1139 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001140 // Don't use update_screen() when editing the command line, it gets
1141 // cleared.
1142 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001143 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001144 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001145 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001146 update_screen(VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001147 // update_screen() can be slow, check the terminal wasn't closed
1148 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001149 if (buffer == curbuf && curbuf->b_term != NULL)
1150 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001151 }
1152 else
1153 redraw_after_callback(TRUE);
1154 }
1155}
1156
1157/*
1158 * Send a mouse position and click to the vterm
1159 */
1160 static int
1161term_send_mouse(VTerm *vterm, int button, int pressed)
1162{
1163 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001164 int row = mouse_row - W_WINROW(curwin);
1165 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001166
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001167#ifdef FEAT_PROP_POPUP
1168 if (popup_is_popup(curwin))
1169 {
1170 row -= popup_top_extra(curwin);
1171 col -= popup_left_extra(curwin);
1172 }
1173#endif
1174 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001175 if (button != 0)
1176 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001177 return TRUE;
1178}
1179
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001180static int enter_mouse_col = -1;
1181static int enter_mouse_row = -1;
1182
1183/*
1184 * Handle a mouse click, drag or release.
1185 * Return TRUE when a mouse event is sent to the terminal.
1186 */
1187 static int
1188term_mouse_click(VTerm *vterm, int key)
1189{
1190#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001191 // For modeless selection mouse drag and release events are ignored, unless
1192 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001193 static int ignore_drag_release = TRUE;
1194 VTermMouseState mouse_state;
1195
1196 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1197 if (mouse_state.flags == 0)
1198 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001199 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001200 switch (key)
1201 {
1202 case K_LEFTDRAG:
1203 case K_LEFTRELEASE:
1204 case K_RIGHTDRAG:
1205 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001206 // Ignore drag and release events when the button-down wasn't
1207 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001208 if (ignore_drag_release)
1209 {
1210 int save_mouse_col, save_mouse_row;
1211
1212 if (enter_mouse_col < 0)
1213 break;
1214
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001215 // mouse click in the window gave us focus, handle that
1216 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001217 save_mouse_col = mouse_col;
1218 save_mouse_row = mouse_row;
1219 mouse_col = enter_mouse_col;
1220 mouse_row = enter_mouse_row;
1221 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1222 mouse_col = save_mouse_col;
1223 mouse_row = save_mouse_row;
1224 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001225 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001226 case K_LEFTMOUSE:
1227 case K_RIGHTMOUSE:
1228 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1229 ignore_drag_release = TRUE;
1230 else
1231 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001232 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001233 if (clip_star.available)
1234 {
1235 int button, is_click, is_drag;
1236
1237 button = get_mouse_button(KEY2TERMCAP1(key),
1238 &is_click, &is_drag);
1239 if (mouse_model_popup() && button == MOUSE_LEFT
1240 && (mod_mask & MOD_MASK_SHIFT))
1241 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001242 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001243 button = MOUSE_RIGHT;
1244 mod_mask &= ~MOD_MASK_SHIFT;
1245 }
1246 clip_modeless(button, is_click, is_drag);
1247 }
1248 break;
1249
1250 case K_MIDDLEMOUSE:
1251 if (clip_star.available)
1252 insert_reg('*', TRUE);
1253 break;
1254 }
1255 enter_mouse_col = -1;
1256 return FALSE;
1257 }
1258#endif
1259 enter_mouse_col = -1;
1260
1261 switch (key)
1262 {
1263 case K_LEFTMOUSE:
1264 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1265 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1266 case K_LEFTRELEASE:
1267 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1268 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1269 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1270 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1271 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1272 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1273 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1274 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1275 }
1276 return TRUE;
1277}
1278
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001279/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001280 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1281 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001282 * Return the number of bytes in "buf".
1283 */
1284 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001285term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001286{
1287 VTerm *vterm = term->tl_vterm;
1288 VTermKey key = VTERM_KEY_NONE;
1289 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001290 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001291
1292 switch (c)
1293 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001294 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001295
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001296 // don't use VTERM_KEY_BACKSPACE, it always
1297 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001298 case K_BS: c = term_backspace_char; break;
1299
1300 case ESC: key = VTERM_KEY_ESCAPE; break;
1301 case K_DEL: key = VTERM_KEY_DEL; break;
1302 case K_DOWN: key = VTERM_KEY_DOWN; break;
1303 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1304 key = VTERM_KEY_DOWN; break;
1305 case K_END: key = VTERM_KEY_END; break;
1306 case K_S_END: mod = VTERM_MOD_SHIFT;
1307 key = VTERM_KEY_END; break;
1308 case K_C_END: mod = VTERM_MOD_CTRL;
1309 key = VTERM_KEY_END; break;
1310 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1311 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1312 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1313 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1314 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1315 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1316 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1317 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1318 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1319 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1320 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1321 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1322 case K_HOME: key = VTERM_KEY_HOME; break;
1323 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1324 key = VTERM_KEY_HOME; break;
1325 case K_C_HOME: mod = VTERM_MOD_CTRL;
1326 key = VTERM_KEY_HOME; break;
1327 case K_INS: key = VTERM_KEY_INS; break;
1328 case K_K0: key = VTERM_KEY_KP_0; break;
1329 case K_K1: key = VTERM_KEY_KP_1; break;
1330 case K_K2: key = VTERM_KEY_KP_2; break;
1331 case K_K3: key = VTERM_KEY_KP_3; break;
1332 case K_K4: key = VTERM_KEY_KP_4; break;
1333 case K_K5: key = VTERM_KEY_KP_5; break;
1334 case K_K6: key = VTERM_KEY_KP_6; break;
1335 case K_K7: key = VTERM_KEY_KP_7; break;
1336 case K_K8: key = VTERM_KEY_KP_8; break;
1337 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001338 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001339 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001340 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001341 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001342 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1343 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001344 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1345 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001346 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1347 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001348 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1349 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1350 case K_LEFT: key = VTERM_KEY_LEFT; break;
1351 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1352 key = VTERM_KEY_LEFT; break;
1353 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1354 key = VTERM_KEY_LEFT; break;
1355 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1356 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1357 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1358 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1359 key = VTERM_KEY_RIGHT; break;
1360 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1361 key = VTERM_KEY_RIGHT; break;
1362 case K_UP: key = VTERM_KEY_UP; break;
1363 case K_S_UP: mod = VTERM_MOD_SHIFT;
1364 key = VTERM_KEY_UP; break;
1365 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001366 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1367 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001368
Bram Moolenaara42ad572017-11-16 13:08:04 +01001369 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1370 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001371 case K_MOUSELEFT: /* TODO */ return 0;
1372 case K_MOUSERIGHT: /* TODO */ return 0;
1373
1374 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001375 case K_LEFTMOUSE_NM:
1376 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001377 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001378 case K_LEFTRELEASE_NM:
1379 case K_MOUSEMOVE:
1380 case K_MIDDLEMOUSE:
1381 case K_MIDDLEDRAG:
1382 case K_MIDDLERELEASE:
1383 case K_RIGHTMOUSE:
1384 case K_RIGHTDRAG:
1385 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1386 return 0;
1387 other = TRUE;
1388 break;
1389
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001390 case K_X1MOUSE: /* TODO */ return 0;
1391 case K_X1DRAG: /* TODO */ return 0;
1392 case K_X1RELEASE: /* TODO */ return 0;
1393 case K_X2MOUSE: /* TODO */ return 0;
1394 case K_X2DRAG: /* TODO */ return 0;
1395 case K_X2RELEASE: /* TODO */ return 0;
1396
1397 case K_IGNORE: return 0;
1398 case K_NOP: return 0;
1399 case K_UNDO: return 0;
1400 case K_HELP: return 0;
1401 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1402 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1403 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1404 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1405 case K_SELECT: return 0;
1406#ifdef FEAT_GUI
1407 case K_VER_SCROLLBAR: return 0;
1408 case K_HOR_SCROLLBAR: return 0;
1409#endif
1410#ifdef FEAT_GUI_TABLINE
1411 case K_TABLINE: return 0;
1412 case K_TABMENU: return 0;
1413#endif
1414#ifdef FEAT_NETBEANS_INTG
1415 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1416#endif
1417#ifdef FEAT_DND
1418 case K_DROP: return 0;
1419#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001420 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001421 case K_PS: vterm_keyboard_start_paste(vterm);
1422 other = TRUE;
1423 break;
1424 case K_PE: vterm_keyboard_end_paste(vterm);
1425 other = TRUE;
1426 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001427 }
1428
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001429 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001430 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001431 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001432 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001433 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001434 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001435 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001436
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001437 /*
1438 * Convert special keys to vterm keys:
1439 * - Write keys to vterm: vterm_keyboard_key()
1440 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001441 */
1442 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001443 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001444 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001445 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001446 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001447 vterm_keyboard_unichar(vterm, c, mod);
1448
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001449 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001450 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1451}
1452
1453/*
1454 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001455 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001456 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001457 */
1458 static int
1459term_job_running_check(term_T *term, int check_job_status)
1460{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001461 // Also consider the job finished when the channel is closed, to avoid a
1462 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001463 if (term != NULL
1464 && term->tl_job != NULL
1465 && channel_is_open(term->tl_job->jv_channel))
1466 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001467 job_T *job = term->tl_job;
1468
1469 // Careful: Checking the job status may invoked callbacks, which close
1470 // the buffer and terminate "term". However, "job" will not be freed
1471 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001472 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001473 job_status(job);
1474 return (job->jv_status == JOB_STARTED
1475 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001476 }
1477 return FALSE;
1478}
1479
1480/*
1481 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001482 */
1483 int
1484term_job_running(term_T *term)
1485{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001486 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001487}
1488
1489/*
1490 * Return TRUE if "term" has an active channel and used ":term NONE".
1491 */
1492 int
1493term_none_open(term_T *term)
1494{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001495 // Also consider the job finished when the channel is closed, to avoid a
1496 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001497 return term != NULL
1498 && term->tl_job != NULL
1499 && channel_is_open(term->tl_job->jv_channel)
1500 && term->tl_job->jv_channel->ch_keep_open;
1501}
1502
1503/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001504 * Used when exiting: kill the job in "buf" if so desired.
1505 * Return OK when the job finished.
1506 * Return FAIL when the job is still running.
1507 */
1508 int
1509term_try_stop_job(buf_T *buf)
1510{
1511 int count;
1512 char *how = (char *)buf->b_term->tl_kill;
1513
1514#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1515 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1516 {
1517 char_u buff[DIALOG_MSG_SIZE];
1518 int ret;
1519
1520 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1521 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1522 if (ret == VIM_YES)
1523 how = "kill";
1524 else if (ret == VIM_CANCEL)
1525 return FAIL;
1526 }
1527#endif
1528 if (how == NULL || *how == NUL)
1529 return FAIL;
1530
1531 job_stop(buf->b_term->tl_job, NULL, how);
1532
Bram Moolenaar9172d232019-01-29 23:06:54 +01001533 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001534 for (count = 0; count < 100; ++count)
1535 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001536 job_T *job;
1537
1538 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001539 if (!buf_valid(buf)
1540 || buf->b_term == NULL
1541 || buf->b_term->tl_job == NULL)
1542 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001543 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001544
Bram Moolenaar9172d232019-01-29 23:06:54 +01001545 // Call job_status() to update jv_status. It may cause the job to be
1546 // cleaned up but it won't be freed.
1547 job_status(job);
1548 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001549 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001550
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001551 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001552 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001553 }
1554 return FAIL;
1555}
1556
1557/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001558 * Add the last line of the scrollback buffer to the buffer in the window.
1559 */
1560 static void
1561add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1562{
1563 buf_T *buf = term->tl_buffer;
1564 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1565 linenr_T lnum = buf->b_ml.ml_line_count;
1566
Bram Moolenaar4f974752019-02-17 17:44:42 +01001567#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001568 if (!enc_utf8 && enc_codepage > 0)
1569 {
1570 WCHAR *ret = NULL;
1571 int length = 0;
1572
1573 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1574 &ret, &length);
1575 if (ret != NULL)
1576 {
1577 WideCharToMultiByte_alloc(enc_codepage, 0,
1578 ret, length, (char **)&text, &len, 0, 0);
1579 vim_free(ret);
1580 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1581 vim_free(text);
1582 }
1583 }
1584 else
1585#endif
1586 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1587 if (empty)
1588 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001589 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001590 curbuf = buf;
1591 ml_delete(1, FALSE);
1592 curbuf = curwin->w_buffer;
1593 }
1594}
1595
1596 static void
1597cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1598{
1599 attr->width = cell->width;
1600 attr->attrs = cell->attrs;
1601 attr->fg = cell->fg;
1602 attr->bg = cell->bg;
1603}
1604
1605 static int
1606equal_celattr(cellattr_T *a, cellattr_T *b)
1607{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001608 // Comparing the colors should be sufficient.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001609 return a->fg.red == b->fg.red
1610 && a->fg.green == b->fg.green
1611 && a->fg.blue == b->fg.blue
1612 && a->bg.red == b->bg.red
1613 && a->bg.green == b->bg.green
1614 && a->bg.blue == b->bg.blue;
1615}
1616
Bram Moolenaard96ff162018-02-18 22:13:29 +01001617/*
1618 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1619 * line at this position. Otherwise at the end.
1620 */
1621 static int
1622add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1623{
1624 if (ga_grow(&term->tl_scrollback, 1) == OK)
1625 {
1626 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1627 + term->tl_scrollback.ga_len;
1628
1629 if (lnum > 0)
1630 {
1631 int i;
1632
1633 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1634 {
1635 *line = *(line - 1);
1636 --line;
1637 }
1638 }
1639 line->sb_cols = 0;
1640 line->sb_cells = NULL;
1641 line->sb_fill_attr = *fill_attr;
1642 ++term->tl_scrollback.ga_len;
1643 return OK;
1644 }
1645 return FALSE;
1646}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001647
1648/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001649 * Remove the terminal contents from the scrollback and the buffer.
1650 * Used before adding a new scrollback line or updating the buffer for lines
1651 * displayed in the terminal.
1652 */
1653 static void
1654cleanup_scrollback(term_T *term)
1655{
1656 sb_line_T *line;
1657 garray_T *gap;
1658
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001659 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001660 gap = &term->tl_scrollback;
1661 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1662 && gap->ga_len > 0)
1663 {
1664 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1665 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1666 vim_free(line->sb_cells);
1667 --gap->ga_len;
1668 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001669 curbuf = curwin->w_buffer;
1670 if (curbuf == term->tl_buffer)
1671 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001672}
1673
1674/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001675 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001676 */
1677 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001678update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001679{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001680 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001681 int len;
1682 int lines_skipped = 0;
1683 VTermPos pos;
1684 VTermScreenCell cell;
1685 cellattr_T fill_attr, new_fill_attr;
1686 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001687
1688 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1689 "Adding terminal window snapshot to buffer");
1690
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001691 // First remove the lines that were appended before, they might be
1692 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001693 cleanup_scrollback(term);
1694
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001695 screen = vterm_obtain_screen(term->tl_vterm);
1696 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001697 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1698 {
1699 len = 0;
1700 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1701 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1702 && cell.chars[0] != NUL)
1703 {
1704 len = pos.col + 1;
1705 new_fill_attr = term->tl_default_color;
1706 }
1707 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001708 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001709 cell2cellattr(&cell, &new_fill_attr);
1710
1711 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1712 ++lines_skipped;
1713 else
1714 {
1715 while (lines_skipped > 0)
1716 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001717 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001718 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001719 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001720 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001721 }
1722
1723 if (len == 0)
1724 p = NULL;
1725 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001726 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001727 if ((p != NULL || len == 0)
1728 && ga_grow(&term->tl_scrollback, 1) == OK)
1729 {
1730 garray_T ga;
1731 int width;
1732 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1733 + term->tl_scrollback.ga_len;
1734
1735 ga_init2(&ga, 1, 100);
1736 for (pos.col = 0; pos.col < len; pos.col += width)
1737 {
1738 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1739 {
1740 width = 1;
1741 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1742 if (ga_grow(&ga, 1) == OK)
1743 ga.ga_len += utf_char2bytes(' ',
1744 (char_u *)ga.ga_data + ga.ga_len);
1745 }
1746 else
1747 {
1748 width = cell.width;
1749
1750 cell2cellattr(&cell, &p[pos.col]);
1751
Bram Moolenaara79fd562018-12-20 20:47:32 +01001752 // Each character can be up to 6 bytes.
1753 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001754 {
1755 int i;
1756 int c;
1757
1758 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1759 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1760 (char_u *)ga.ga_data + ga.ga_len);
1761 }
1762 }
1763 }
1764 line->sb_cols = len;
1765 line->sb_cells = p;
1766 line->sb_fill_attr = new_fill_attr;
1767 fill_attr = new_fill_attr;
1768 ++term->tl_scrollback.ga_len;
1769
1770 if (ga_grow(&ga, 1) == FAIL)
1771 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1772 else
1773 {
1774 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1775 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1776 }
1777 ga_clear(&ga);
1778 }
1779 else
1780 vim_free(p);
1781 }
1782 }
1783
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001784 // Add trailing empty lines.
1785 for (pos.row = term->tl_scrollback.ga_len;
1786 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1787 ++pos.row)
1788 {
1789 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1790 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1791 }
1792
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001793 term->tl_dirty_snapshot = FALSE;
1794#ifdef FEAT_TIMERS
1795 term->tl_timer_set = FALSE;
1796#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001797}
1798
1799/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001800 * Loop over all windows in the current tab, and also curwin, which is not
1801 * encountered when using a terminal in a popup window.
1802 * Return TRUE if "*wp" was set to the next window.
1803 */
1804 static int
1805for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1806{
1807 if (*wp == NULL)
1808 *wp = firstwin;
1809 else if ((*wp)->w_next != NULL)
1810 *wp = (*wp)->w_next;
1811 else if (!*did_curwin)
1812 *wp = curwin;
1813 else
1814 return FALSE;
1815 if (*wp == curwin)
1816 *did_curwin = TRUE;
1817 return TRUE;
1818}
1819
1820/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001821 * If needed, add the current lines of the terminal to scrollback and to the
1822 * buffer. Called after the job has ended and when switching to
1823 * Terminal-Normal mode.
1824 * When "redraw" is TRUE redraw the windows that show the terminal.
1825 */
1826 static void
1827may_move_terminal_to_buffer(term_T *term, int redraw)
1828{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001829 if (term->tl_vterm == NULL)
1830 return;
1831
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001832 // Update the snapshot only if something changes or the buffer does not
1833 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001834 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1835 <= term->tl_scrollback_scrolled)
1836 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001837
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001838 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001839 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1840 &term->tl_default_color.fg, &term->tl_default_color.bg);
1841
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001842 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001843 {
1844 win_T *wp = NULL;
1845 int did_curwin = FALSE;
1846
1847 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001848 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001849 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001850 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001851 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1852 wp->w_cursor.col = 0;
1853 wp->w_valid = 0;
1854 if (wp->w_cursor.lnum >= wp->w_height)
1855 {
1856 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001857
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001858 if (wp->w_topline < min_topline)
1859 wp->w_topline = min_topline;
1860 }
1861 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001862 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001863 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001864 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001865}
1866
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001867#if defined(FEAT_TIMERS) || defined(PROTO)
1868/*
1869 * Check if any terminal timer expired. If so, copy text from the terminal to
1870 * the buffer.
1871 * Return the time until the next timer will expire.
1872 */
1873 int
1874term_check_timers(int next_due_arg, proftime_T *now)
1875{
1876 term_T *term;
1877 int next_due = next_due_arg;
1878
1879 for (term = first_term; term != NULL; term = term->tl_next)
1880 {
1881 if (term->tl_timer_set && !term->tl_normal_mode)
1882 {
1883 long this_due = proftime_time_left(&term->tl_timer_due, now);
1884
1885 if (this_due <= 1)
1886 {
1887 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001888 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001889 }
1890 else if (next_due == -1 || next_due > this_due)
1891 next_due = this_due;
1892 }
1893 }
1894
1895 return next_due;
1896}
1897#endif
1898
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001899/*
1900 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1901 * otherwise end it.
1902 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001903 static void
1904set_terminal_mode(term_T *term, int normal_mode)
1905{
1906 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001907 if (!normal_mode)
1908 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001909 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001910 if (term->tl_buffer == curbuf)
1911 maketitle();
1912}
1913
1914/*
1915 * Called after the job if finished and Terminal mode is not active:
1916 * Move the vterm contents into the scrollback buffer and free the vterm.
1917 */
1918 static void
1919cleanup_vterm(term_T *term)
1920{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001921 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001922 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001923 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001924 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001925}
1926
1927/*
1928 * Switch from Terminal-Job mode to Terminal-Normal mode.
1929 * Suspends updating the terminal window.
1930 */
1931 static void
1932term_enter_normal_mode(void)
1933{
1934 term_T *term = curbuf->b_term;
1935
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001936 set_terminal_mode(term, TRUE);
1937
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001938 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001939 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001940
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001941 // Move the window cursor to the position of the cursor in the
1942 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001943 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1944 + term->tl_cursor_pos.row + 1;
1945 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001946 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1947 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001948 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001949
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001950 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001951 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1952}
1953
1954/*
1955 * Returns TRUE if the current window contains a terminal and we are in
1956 * Terminal-Normal mode.
1957 */
1958 int
1959term_in_normal_mode(void)
1960{
1961 term_T *term = curbuf->b_term;
1962
1963 return term != NULL && term->tl_normal_mode;
1964}
1965
1966/*
1967 * Switch from Terminal-Normal mode to Terminal-Job mode.
1968 * Restores updating the terminal window.
1969 */
1970 void
1971term_enter_job_mode()
1972{
1973 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001974
1975 set_terminal_mode(term, FALSE);
1976
1977 if (term->tl_channel_closed)
1978 cleanup_vterm(term);
1979 redraw_buf_and_status_later(curbuf, NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001980#ifdef FEAT_PROP_POPUP
1981 if (WIN_IS_POPUP(curwin))
1982 redraw_win_later(curwin, NOT_VALID);
1983#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001984}
1985
1986/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001987 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001988 * Note: while waiting a terminal may be closed and freed if the channel is
1989 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001990 */
1991 static int
1992term_vgetc()
1993{
1994 int c;
1995 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001996 int modify_other_keys =
1997 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001998
1999 State = TERMINAL;
2000 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002001#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002002 ctrl_break_was_pressed = FALSE;
2003#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002004 if (modify_other_keys)
2005 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002006 c = vgetc();
2007 got_int = FALSE;
2008 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002009 if (modify_other_keys)
2010 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 return c;
2012}
2013
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002014static int mouse_was_outside = FALSE;
2015
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002017 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002018 * Return FAIL when the key needs to be handled in Normal mode.
2019 * Return OK when the key was dropped or sent to the terminal.
2020 */
2021 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002022send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002023{
2024 char msg[KEY_BUF_LEN];
2025 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002026 int dragging_outside = FALSE;
2027
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002028 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002029 switch (c)
2030 {
2031 case NUL:
2032 case K_ZERO:
2033 if (typed)
2034 stuffcharReadbuff(c);
2035 return FAIL;
2036
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002037 case K_TABLINE:
2038 stuffcharReadbuff(c);
2039 return FAIL;
2040
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002041 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002042 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002043 return FAIL;
2044
2045 case K_LEFTDRAG:
2046 case K_MIDDLEDRAG:
2047 case K_RIGHTDRAG:
2048 case K_X1DRAG:
2049 case K_X2DRAG:
2050 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002051 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002052 case K_LEFTMOUSE:
2053 case K_LEFTMOUSE_NM:
2054 case K_LEFTRELEASE:
2055 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002056 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002057 case K_MIDDLEMOUSE:
2058 case K_MIDDLERELEASE:
2059 case K_RIGHTMOUSE:
2060 case K_RIGHTRELEASE:
2061 case K_X1MOUSE:
2062 case K_X1RELEASE:
2063 case K_X2MOUSE:
2064 case K_X2RELEASE:
2065
2066 case K_MOUSEUP:
2067 case K_MOUSEDOWN:
2068 case K_MOUSELEFT:
2069 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002070 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002071 int row = mouse_row;
2072 int col = mouse_col;
2073
2074#ifdef FEAT_PROP_POPUP
2075 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002076 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002077 row -= popup_top_extra(curwin);
2078 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002079 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002080#endif
2081 if (row < W_WINROW(curwin)
2082 || row >= (W_WINROW(curwin) + curwin->w_height)
2083 || col < curwin->w_wincol
2084 || col >= W_ENDCOL(curwin)
2085 || dragging_outside)
2086 {
2087 // click or scroll outside the current window or on status
2088 // line or vertical separator
2089 if (typed)
2090 {
2091 stuffcharReadbuff(c);
2092 mouse_was_outside = TRUE;
2093 }
2094 return FAIL;
2095 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002096 }
2097 }
2098 if (typed)
2099 mouse_was_outside = FALSE;
2100
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002101 // Convert the typed key to a sequence of bytes for the job.
2102 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002103 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002104 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002105 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2106 (char_u *)msg, (int)len, NULL);
2107
2108 return OK;
2109}
2110
2111 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002112position_cursor(win_T *wp, VTermPos *pos, int add_off UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002113{
2114 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2115 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002116#ifdef FEAT_PROP_POPUP
2117 if (add_off && popup_is_popup(curwin))
2118 {
2119 wp->w_wrow += popup_top_extra(curwin);
2120 wp->w_wcol += popup_left_extra(curwin);
2121 }
2122#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002123 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2124}
2125
2126/*
2127 * Handle CTRL-W "": send register contents to the job.
2128 */
2129 static void
2130term_paste_register(int prev_c UNUSED)
2131{
2132 int c;
2133 list_T *l;
2134 listitem_T *item;
2135 long reglen = 0;
2136 int type;
2137
2138#ifdef FEAT_CMDL_INFO
2139 if (add_to_showcmd(prev_c))
2140 if (add_to_showcmd('"'))
2141 out_flush();
2142#endif
2143 c = term_vgetc();
2144#ifdef FEAT_CMDL_INFO
2145 clear_showcmd();
2146#endif
2147 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002148 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002149 return;
2150
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002151 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002152 if (c == '=' && get_expr_register() != '=')
2153 return;
2154 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002155 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002156 return;
2157
2158 l = (list_T *)get_reg_contents(c, GREG_LIST);
2159 if (l != NULL)
2160 {
2161 type = get_reg_type(c, &reglen);
2162 for (item = l->lv_first; item != NULL; item = item->li_next)
2163 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002164 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002165#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166 char_u *tmp = s;
2167
2168 if (!enc_utf8 && enc_codepage > 0)
2169 {
2170 WCHAR *ret = NULL;
2171 int length = 0;
2172
2173 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2174 (int)STRLEN(s), &ret, &length);
2175 if (ret != NULL)
2176 {
2177 WideCharToMultiByte_alloc(CP_UTF8, 0,
2178 ret, length, (char **)&s, &length, 0, 0);
2179 vim_free(ret);
2180 }
2181 }
2182#endif
2183 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2184 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002185#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002186 if (tmp != s)
2187 vim_free(s);
2188#endif
2189
2190 if (item->li_next != NULL || type == MLINE)
2191 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2192 (char_u *)"\r", 1, NULL);
2193 }
2194 list_free(l);
2195 }
2196}
2197
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002198/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002199 * Return TRUE when waiting for a character in the terminal, the cursor of the
2200 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002201 */
2202 int
2203terminal_is_active()
2204{
2205 return in_terminal_loop != NULL;
2206}
2207
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002208#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002209 cursorentry_T *
2210term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2211{
2212 term_T *term = in_terminal_loop;
2213 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002214 int id;
2215 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002216
2217 vim_memset(&entry, 0, sizeof(entry));
2218 entry.shape = entry.mshape =
2219 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2220 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2221 SHAPE_BLOCK;
2222 entry.percentage = 20;
2223 if (term->tl_cursor_blink)
2224 {
2225 entry.blinkwait = 700;
2226 entry.blinkon = 400;
2227 entry.blinkoff = 250;
2228 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002229
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002230 // The "Terminal" highlight group overrules the defaults.
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002231 id = syn_name2id((char_u *)"Terminal");
2232 if (id != 0)
2233 {
2234 syn_id2colors(id, &term_fg, &term_bg);
2235 *fg = term_bg;
2236 }
2237 else
2238 *fg = gui.back_pixel;
2239
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002240 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002241 {
2242 if (id != 0)
2243 *bg = term_fg;
2244 else
2245 *bg = gui.norm_pixel;
2246 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002247 else
2248 *bg = color_name2handle(term->tl_cursor_color);
2249 entry.name = "n";
2250 entry.used_for = SHAPE_CURSOR;
2251
2252 return &entry;
2253}
2254#endif
2255
Bram Moolenaard317b382018-02-08 22:33:31 +01002256 static void
2257may_output_cursor_props(void)
2258{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002259 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002260 || last_set_cursor_shape != desired_cursor_shape
2261 || last_set_cursor_blink != desired_cursor_blink)
2262 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002263 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002264 last_set_cursor_shape = desired_cursor_shape;
2265 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002266 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002267 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002268 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002269 ui_cursor_shape_forced(TRUE);
2270 else
2271 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2272 }
2273}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002274
Bram Moolenaard317b382018-02-08 22:33:31 +01002275/*
2276 * Set the cursor color and shape, if not last set to these.
2277 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002278 static void
2279may_set_cursor_props(term_T *term)
2280{
2281#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002282 // For the GUI the cursor properties are obtained with
2283 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002284 if (gui.in_use)
2285 return;
2286#endif
2287 if (in_terminal_loop == term)
2288 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002289 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002290 desired_cursor_shape = term->tl_cursor_shape;
2291 desired_cursor_blink = term->tl_cursor_blink;
2292 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002293 }
2294}
2295
Bram Moolenaard317b382018-02-08 22:33:31 +01002296/*
2297 * Reset the desired cursor properties and restore them when needed.
2298 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002299 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002300prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002301{
2302#ifdef FEAT_GUI
2303 if (gui.in_use)
2304 return;
2305#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002306 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002307 desired_cursor_shape = -1;
2308 desired_cursor_blink = -1;
2309 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002310}
2311
2312/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002313 * Returns TRUE if the current window contains a terminal and we are sending
2314 * keys to the job.
2315 * If "check_job_status" is TRUE update the job status.
2316 */
2317 static int
2318term_use_loop_check(int check_job_status)
2319{
2320 term_T *term = curbuf->b_term;
2321
2322 return term != NULL
2323 && !term->tl_normal_mode
2324 && term->tl_vterm != NULL
2325 && term_job_running_check(term, check_job_status);
2326}
2327
2328/*
2329 * Returns TRUE if the current window contains a terminal and we are sending
2330 * keys to the job.
2331 */
2332 int
2333term_use_loop(void)
2334{
2335 return term_use_loop_check(FALSE);
2336}
2337
2338/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002339 * Called when entering a window with the mouse. If this is a terminal window
2340 * we may want to change state.
2341 */
2342 void
2343term_win_entered()
2344{
2345 term_T *term = curbuf->b_term;
2346
2347 if (term != NULL)
2348 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002349 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002350 {
2351 reset_VIsual_and_resel();
2352 if (State & INSERT)
2353 stop_insert_mode = TRUE;
2354 }
2355 mouse_was_outside = FALSE;
2356 enter_mouse_col = mouse_col;
2357 enter_mouse_row = mouse_row;
2358 }
2359}
2360
2361/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002362 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2363 * Return the Ctrl-key value in that case.
2364 */
2365 static int
2366raw_c_to_ctrl(int c)
2367{
2368 if ((mod_mask & MOD_MASK_CTRL)
2369 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2370 return c & 0x1f;
2371 return c;
2372}
2373
2374/*
2375 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2376 * May set "mod_mask".
2377 */
2378 static int
2379ctrl_to_raw_c(int c)
2380{
2381 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2382 {
2383 mod_mask |= MOD_MASK_CTRL;
2384 return c + '@';
2385 }
2386 return c;
2387}
2388
2389/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002390 * Wait for input and send it to the job.
2391 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2392 * when there is no more typahead.
2393 * Return when the start of a CTRL-W command is typed or anything else that
2394 * should be handled as a Normal mode command.
2395 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2396 * the terminal was closed.
2397 */
2398 int
2399terminal_loop(int blocking)
2400{
2401 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002402 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002403 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002404 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002405#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002406 int tty_fd = curbuf->b_term->tl_job->jv_channel
2407 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002408#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002409 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002410
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002411 // Remember the terminal we are sending keys to. However, the terminal
2412 // might be closed while waiting for a character, e.g. typing "exit" in a
2413 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2414 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002415 in_terminal_loop = curbuf->b_term;
2416
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002417 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002418 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002419 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002420 if (termwinkey == Ctrl_W)
2421 termwinkey = 0;
2422 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002423 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002424 may_set_cursor_props(curbuf->b_term);
2425
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002426 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002427 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002428#ifdef FEAT_GUI
2429 if (!curbuf->b_term->tl_system)
2430#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002431 // TODO: skip screen update when handling a sequence of keys.
2432 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002433 while (must_redraw != 0)
2434 if (update_screen(0) == FAIL)
2435 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002436 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002437 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002438 break;
2439
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002440 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002441 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002442
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002443 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002444 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002445 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002446 // Job finished while waiting for a character. Push back the
2447 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002448 if (raw_c != K_IGNORE)
2449 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002450 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002451 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002452 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002453 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002454 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002455
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002456#ifdef UNIX
2457 /*
2458 * The shell or another program may change the tty settings. Getting
2459 * them for every typed character is a bit of overhead, but it's needed
2460 * for the first character typed, e.g. when Vim starts in a shell.
2461 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002462 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002463 {
2464 ttyinfo_T info;
2465
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002466 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002467 if (get_tty_info(tty_fd, &info) == OK)
2468 term_backspace_char = info.backspace;
2469 }
2470#endif
2471
Bram Moolenaar4f974752019-02-17 17:44:42 +01002472#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002473 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2474 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002475 if (ctrl_break_was_pressed)
2476 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2477#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002478 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2479 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002480 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002481#ifdef FEAT_GUI
2482 && !curbuf->b_term->tl_system
2483#endif
2484 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002485 {
2486 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002487 int prev_raw_c = raw_c;
2488 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002489
2490#ifdef FEAT_CMDL_INFO
2491 if (add_to_showcmd(c))
2492 out_flush();
2493#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002494 raw_c = term_vgetc();
2495 c = raw_c_to_ctrl(raw_c);
2496
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002497#ifdef FEAT_CMDL_INFO
2498 clear_showcmd();
2499#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002500 if (!term_use_loop_check(TRUE)
2501 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002502 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 break;
2504
2505 if (prev_c == Ctrl_BSL)
2506 {
2507 if (c == Ctrl_N)
2508 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002509 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002510 term_enter_normal_mode();
2511 ret = FAIL;
2512 goto theend;
2513 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002514 // Send both keys to the terminal, first one here, second one
2515 // below.
2516 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2517 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002518 }
2519 else if (c == Ctrl_C)
2520 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002521 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002522 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2523 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002524 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002525 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002526 // "CTRL-W .": send CTRL-W to the job
2527 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002528 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002529 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002530 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002531 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002532 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002533 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002534 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002535 else if (c == 'N')
2536 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002537 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002538 term_enter_normal_mode();
2539 ret = FAIL;
2540 goto theend;
2541 }
2542 else if (c == '"')
2543 {
2544 term_paste_register(prev_c);
2545 continue;
2546 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002547 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002548 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002549 char_u buf[MB_MAXBYTES + 2];
2550
2551 // Put the command into the typeahead buffer, when using the
2552 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2553 buf[0] = Ctrl_W;
2554 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2555 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002556 ret = OK;
2557 goto theend;
2558 }
2559 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002560# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002561 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002562 {
2563 WCHAR wc;
2564 char_u mb[3];
2565
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002566 mb[0] = (unsigned)raw_c >> 8;
2567 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002568 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002569 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002570 }
2571# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002572 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002573 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002574 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002575 // We are sure to come back here, don't reset the cursor color
2576 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002577 restore_cursor = FALSE;
2578
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002579 ret = OK;
2580 goto theend;
2581 }
2582 }
2583 ret = FAIL;
2584
2585theend:
2586 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002587 if (restore_cursor)
2588 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002589
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002590 // Move a snapshot of the screen contents to the buffer, so that completion
2591 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002592 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2593 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002594
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002595 return ret;
2596}
2597
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002598 static void
2599may_toggle_cursor(term_T *term)
2600{
2601 if (in_terminal_loop == term)
2602 {
2603 if (term->tl_cursor_visible)
2604 cursor_on();
2605 else
2606 cursor_off();
2607 }
2608}
2609
2610/*
2611 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002612 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002613 */
2614 static int
2615color2index(VTermColor *color, int fg, int *boldp)
2616{
2617 int red = color->red;
2618 int blue = color->blue;
2619 int green = color->green;
2620
Bram Moolenaar46359e12017-11-29 22:33:38 +01002621 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002622 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002623 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002624 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002625 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002626 case 0: return 0;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002627 case 1: return lookup_color( 0, fg, boldp) + 1; // black
2628 case 2: return lookup_color( 4, fg, boldp) + 1; // dark red
2629 case 3: return lookup_color( 2, fg, boldp) + 1; // dark green
2630 case 4: return lookup_color( 6, fg, boldp) + 1; // brown
2631 case 5: return lookup_color( 1, fg, boldp) + 1; // dark blue
2632 case 6: return lookup_color( 5, fg, boldp) + 1; // dark magenta
2633 case 7: return lookup_color( 3, fg, boldp) + 1; // dark cyan
2634 case 8: return lookup_color( 8, fg, boldp) + 1; // light grey
2635 case 9: return lookup_color(12, fg, boldp) + 1; // dark grey
2636 case 10: return lookup_color(20, fg, boldp) + 1; // red
2637 case 11: return lookup_color(16, fg, boldp) + 1; // green
2638 case 12: return lookup_color(24, fg, boldp) + 1; // yellow
2639 case 13: return lookup_color(14, fg, boldp) + 1; // blue
2640 case 14: return lookup_color(22, fg, boldp) + 1; // magenta
2641 case 15: return lookup_color(18, fg, boldp) + 1; // cyan
2642 case 16: return lookup_color(26, fg, boldp) + 1; // white
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002643 }
2644 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002645
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002646 if (t_colors >= 256)
2647 {
2648 if (red == blue && red == green)
2649 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002650 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002651 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002652 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2653 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2654 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002655 int i;
2656
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002657 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002658 return 17; // 00/00/00
2659 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002660 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002661 for (i = 0; i < 23; ++i)
2662 if (red < cutoff[i])
2663 return i + 233;
2664 return 256;
2665 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002666 {
2667 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2668 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002669
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002670 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002671 for (ri = 0; ri < 5; ++ri)
2672 if (red < cutoff[ri])
2673 break;
2674 for (gi = 0; gi < 5; ++gi)
2675 if (green < cutoff[gi])
2676 break;
2677 for (bi = 0; bi < 5; ++bi)
2678 if (blue < cutoff[bi])
2679 break;
2680 return 17 + ri * 36 + gi * 6 + bi;
2681 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002682 }
2683 return 0;
2684}
2685
2686/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002687 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002688 */
2689 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002690vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002691{
2692 int attr = 0;
2693
2694 if (cellattrs.bold)
2695 attr |= HL_BOLD;
2696 if (cellattrs.underline)
2697 attr |= HL_UNDERLINE;
2698 if (cellattrs.italic)
2699 attr |= HL_ITALIC;
2700 if (cellattrs.strike)
2701 attr |= HL_STRIKETHROUGH;
2702 if (cellattrs.reverse)
2703 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002704 return attr;
2705}
2706
2707/*
2708 * Store Vterm attributes in "cell" from highlight flags.
2709 */
2710 static void
2711hl2vtermAttr(int attr, cellattr_T *cell)
2712{
2713 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2714 if (attr & HL_BOLD)
2715 cell->attrs.bold = 1;
2716 if (attr & HL_UNDERLINE)
2717 cell->attrs.underline = 1;
2718 if (attr & HL_ITALIC)
2719 cell->attrs.italic = 1;
2720 if (attr & HL_STRIKETHROUGH)
2721 cell->attrs.strike = 1;
2722 if (attr & HL_INVERSE)
2723 cell->attrs.reverse = 1;
2724}
2725
2726/*
2727 * Convert the attributes of a vterm cell into an attribute index.
2728 */
2729 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002730cell2attr(
2731 win_T *wp,
2732 VTermScreenCellAttrs cellattrs,
2733 VTermColor cellfg,
2734 VTermColor cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002735{
2736 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002737
2738#ifdef FEAT_GUI
2739 if (gui.in_use)
2740 {
2741 guicolor_T fg, bg;
2742
2743 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2744 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2745 return get_gui_attr_idx(attr, fg, bg);
2746 }
2747 else
2748#endif
2749#ifdef FEAT_TERMGUICOLORS
2750 if (p_tgc)
2751 {
2752 guicolor_T fg, bg;
2753
2754 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2755 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2756
2757 return get_tgc_attr_idx(attr, fg, bg);
2758 }
2759 else
2760#endif
2761 {
2762 int bold = MAYBE;
2763 int fg = color2index(&cellfg, TRUE, &bold);
2764 int bg = color2index(&cellbg, FALSE, &bold);
2765
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002766 // Use the 'wincolor' or "Terminal" highlighting for the default
2767 // colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002768 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002769 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002770 int wincolor_fg = -1;
2771 int wincolor_bg = -1;
2772
2773 if (wp != NULL && *wp->w_p_wcr != NUL)
2774 {
2775 int id = syn_name2id(curwin->w_p_wcr);
2776
2777 // Get the 'wincolor' group colors.
2778 if (id > 0)
2779 syn_id2cterm_bg(id, &wincolor_fg, &wincolor_bg);
2780 }
2781 if (fg == 0)
2782 {
2783 if (wincolor_fg >= 0)
2784 fg = wincolor_fg + 1;
2785 else if (term_default_cterm_fg >= 0)
2786 fg = term_default_cterm_fg + 1;
2787 }
2788 if (bg == 0)
2789 {
2790 if (wincolor_bg >= 0)
2791 bg = wincolor_bg + 1;
2792 else if (term_default_cterm_bg >= 0)
2793 bg = term_default_cterm_bg + 1;
2794 }
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002795 }
2796
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002797 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002798 if (bold == TRUE)
2799 attr |= HL_BOLD;
2800 return get_cterm_attr_idx(attr, fg, bg);
2801 }
2802 return 0;
2803}
2804
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002805 static void
2806set_dirty_snapshot(term_T *term)
2807{
2808 term->tl_dirty_snapshot = TRUE;
2809#ifdef FEAT_TIMERS
2810 if (!term->tl_normal_mode)
2811 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002812 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002813 profile_setlimit(100L, &term->tl_timer_due);
2814 term->tl_timer_set = TRUE;
2815 }
2816#endif
2817}
2818
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002819 static int
2820handle_damage(VTermRect rect, void *user)
2821{
2822 term_T *term = (term_T *)user;
2823
2824 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2825 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002826 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002827 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002828 return 1;
2829}
2830
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002831 static void
2832term_scroll_up(term_T *term, int start_row, int count)
2833{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002834 win_T *wp = NULL;
2835 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002836 VTermColor fg, bg;
2837 VTermScreenCellAttrs attr;
2838 int clear_attr;
2839
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002840 vim_memset(&attr, 0, sizeof(attr));
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002841
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002842 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002843 {
2844 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002845 {
2846 // Set the color to clear lines with.
2847 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2848 &fg, &bg);
2849 clear_attr = cell2attr(wp, attr, fg, bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002850 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002851 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002852 }
2853}
2854
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002855 static int
2856handle_moverect(VTermRect dest, VTermRect src, void *user)
2857{
2858 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002859 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002860
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002861 // Scrolling up is done much more efficiently by deleting lines instead of
2862 // redrawing the text. But avoid doing this multiple times, postpone until
2863 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002864 if (dest.start_col == src.start_col
2865 && dest.end_col == src.end_col
2866 && dest.start_row < src.start_row)
2867 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002868 if (dest.start_row == 0)
2869 term->tl_postponed_scroll += count;
2870 else
2871 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002872 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002873
2874 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2875 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002876 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002877
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002878 // Note sure if the scrolling will work correctly, let's do a complete
2879 // redraw later.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880 redraw_buf_later(term->tl_buffer, NOT_VALID);
2881 return 1;
2882}
2883
2884 static int
2885handle_movecursor(
2886 VTermPos pos,
2887 VTermPos oldpos UNUSED,
2888 int visible,
2889 void *user)
2890{
2891 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002892 win_T *wp = NULL;
2893 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002894
2895 term->tl_cursor_pos = pos;
2896 term->tl_cursor_visible = visible;
2897
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002898 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002899 {
2900 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002901 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002902 }
2903 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2904 {
2905 may_toggle_cursor(term);
2906 update_cursor(term, term->tl_cursor_visible);
2907 }
2908
2909 return 1;
2910}
2911
2912 static int
2913handle_settermprop(
2914 VTermProp prop,
2915 VTermValue *value,
2916 void *user)
2917{
2918 term_T *term = (term_T *)user;
2919
2920 switch (prop)
2921 {
2922 case VTERM_PROP_TITLE:
2923 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002924 // a blank title isn't useful, make it empty, so that "running" is
2925 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002926 if (*skipwhite((char_u *)value->string) == NUL)
2927 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002928 // Same as blank
2929 else if (term->tl_arg0_cmd != NULL
2930 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2931 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2932 term->tl_title = NULL;
2933 // Empty corrupted data of winpty
2934 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2935 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002936#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002937 else if (!enc_utf8 && enc_codepage > 0)
2938 {
2939 WCHAR *ret = NULL;
2940 int length = 0;
2941
2942 MultiByteToWideChar_alloc(CP_UTF8, 0,
2943 (char*)value->string, (int)STRLEN(value->string),
2944 &ret, &length);
2945 if (ret != NULL)
2946 {
2947 WideCharToMultiByte_alloc(enc_codepage, 0,
2948 ret, length, (char**)&term->tl_title,
2949 &length, 0, 0);
2950 vim_free(ret);
2951 }
2952 }
2953#endif
2954 else
2955 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002956 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002957 if (term == curbuf->b_term)
2958 maketitle();
2959 break;
2960
2961 case VTERM_PROP_CURSORVISIBLE:
2962 term->tl_cursor_visible = value->boolean;
2963 may_toggle_cursor(term);
2964 out_flush();
2965 break;
2966
2967 case VTERM_PROP_CURSORBLINK:
2968 term->tl_cursor_blink = value->boolean;
2969 may_set_cursor_props(term);
2970 break;
2971
2972 case VTERM_PROP_CURSORSHAPE:
2973 term->tl_cursor_shape = value->number;
2974 may_set_cursor_props(term);
2975 break;
2976
2977 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002978 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002979 may_set_cursor_props(term);
2980 break;
2981
2982 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002983 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002984 term->tl_using_altscreen = value->boolean;
2985 break;
2986
2987 default:
2988 break;
2989 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002990 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002991 return 1;
2992}
2993
2994/*
2995 * The job running in the terminal resized the terminal.
2996 */
2997 static int
2998handle_resize(int rows, int cols, void *user)
2999{
3000 term_T *term = (term_T *)user;
3001 win_T *wp;
3002
3003 term->tl_rows = rows;
3004 term->tl_cols = cols;
3005 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003006 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003007 term->tl_vterm_size_changed = FALSE;
3008 else
3009 {
3010 FOR_ALL_WINDOWS(wp)
3011 {
3012 if (wp->w_buffer == term->tl_buffer)
3013 {
3014 win_setheight_win(rows, wp);
3015 win_setwidth_win(cols, wp);
3016 }
3017 }
3018 redraw_buf_later(term->tl_buffer, NOT_VALID);
3019 }
3020 return 1;
3021}
3022
3023/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003024 * If the number of lines that are stored goes over 'termscrollback' then
3025 * delete the first 10%.
3026 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3027 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003028 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003029 static void
3030limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003031{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003032 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003033 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003034 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003035 int i;
3036
3037 curbuf = term->tl_buffer;
3038 for (i = 0; i < todo; ++i)
3039 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003040 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3041 if (update_buffer)
3042 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003043 }
3044 curbuf = curwin->w_buffer;
3045
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003046 gap->ga_len -= todo;
3047 mch_memmove(gap->ga_data,
3048 (sb_line_T *)gap->ga_data + todo,
3049 sizeof(sb_line_T) * gap->ga_len);
3050 if (update_buffer)
3051 term->tl_scrollback_scrolled -= todo;
3052 }
3053}
3054
3055/*
3056 * Handle a line that is pushed off the top of the screen.
3057 */
3058 static int
3059handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3060{
3061 term_T *term = (term_T *)user;
3062 garray_T *gap;
3063 int update_buffer;
3064
3065 if (term->tl_normal_mode)
3066 {
3067 // In Terminal-Normal mode the user interacts with the buffer, thus we
3068 // must not change it. Postpone adding the scrollback lines.
3069 gap = &term->tl_scrollback_postponed;
3070 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003071 }
3072 else
3073 {
3074 // First remove the lines that were appended before, the pushed line
3075 // goes above it.
3076 cleanup_scrollback(term);
3077 gap = &term->tl_scrollback;
3078 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003079 }
3080
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003081 limit_scrollback(term, gap, update_buffer);
3082
3083 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003084 {
3085 cellattr_T *p = NULL;
3086 int len = 0;
3087 int i;
3088 int c;
3089 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003090 int text_len;
3091 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003092 sb_line_T *line;
3093 garray_T ga;
3094 cellattr_T fill_attr = term->tl_default_color;
3095
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003096 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097 for (i = 0; i < cols; ++i)
3098 if (cells[i].chars[0] != 0)
3099 len = i + 1;
3100 else
3101 cell2cellattr(&cells[i], &fill_attr);
3102
3103 ga_init2(&ga, 1, 100);
3104 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003105 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003106 if (p != NULL)
3107 {
3108 for (col = 0; col < len; col += cells[col].width)
3109 {
3110 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3111 {
3112 ga.ga_len = 0;
3113 break;
3114 }
3115 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3116 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3117 (char_u *)ga.ga_data + ga.ga_len);
3118 cell2cellattr(&cells[col], &p[col]);
3119 }
3120 }
3121 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003122 {
3123 if (update_buffer)
3124 text = (char_u *)"";
3125 else
3126 text = vim_strsave((char_u *)"");
3127 text_len = 0;
3128 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003129 else
3130 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003131 text = ga.ga_data;
3132 text_len = ga.ga_len;
3133 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003134 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003135 if (update_buffer)
3136 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003137
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003138 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003139 line->sb_cols = len;
3140 line->sb_cells = p;
3141 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003142 if (update_buffer)
3143 {
3144 line->sb_text = NULL;
3145 ++term->tl_scrollback_scrolled;
3146 ga_clear(&ga); // free the text
3147 }
3148 else
3149 {
3150 line->sb_text = text;
3151 ga_init(&ga); // text is kept in tl_scrollback_postponed
3152 }
3153 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003154 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003155 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156}
3157
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003158/*
3159 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3160 * received and stored in tl_scrollback_postponed.
3161 */
3162 static void
3163handle_postponed_scrollback(term_T *term)
3164{
3165 int i;
3166
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003167 if (term->tl_scrollback_postponed.ga_len == 0)
3168 return;
3169 ch_log(NULL, "Moving postponed scrollback to scrollback");
3170
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003171 // First remove the lines that were appended before, the pushed lines go
3172 // above it.
3173 cleanup_scrollback(term);
3174
3175 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3176 {
3177 char_u *text;
3178 sb_line_T *pp_line;
3179 sb_line_T *line;
3180
3181 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3182 break;
3183 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3184
3185 text = pp_line->sb_text;
3186 if (text == NULL)
3187 text = (char_u *)"";
3188 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3189 vim_free(pp_line->sb_text);
3190
3191 line = (sb_line_T *)term->tl_scrollback.ga_data
3192 + term->tl_scrollback.ga_len;
3193 line->sb_cols = pp_line->sb_cols;
3194 line->sb_cells = pp_line->sb_cells;
3195 line->sb_fill_attr = pp_line->sb_fill_attr;
3196 line->sb_text = NULL;
3197 ++term->tl_scrollback_scrolled;
3198 ++term->tl_scrollback.ga_len;
3199 }
3200
3201 ga_clear(&term->tl_scrollback_postponed);
3202 limit_scrollback(term, &term->tl_scrollback, TRUE);
3203}
3204
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003205static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003206 handle_damage, // damage
3207 handle_moverect, // moverect
3208 handle_movecursor, // movecursor
3209 handle_settermprop, // settermprop
3210 NULL, // bell
3211 handle_resize, // resize
3212 handle_pushline, // sb_pushline
3213 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003214};
3215
3216/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003217 * Do the work after the channel of a terminal was closed.
3218 * Must be called only when updating_screen is FALSE.
3219 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3220 */
3221 static int
3222term_after_channel_closed(term_T *term)
3223{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003224 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003225 if (!term->tl_normal_mode)
3226 {
3227 int fnum = term->tl_buffer->b_fnum;
3228
3229 cleanup_vterm(term);
3230
3231 if (term->tl_finish == TL_FINISH_CLOSE)
3232 {
3233 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003234 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003235#ifdef FEAT_PROP_POPUP
3236 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003237
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003238 // If this was a terminal in a popup window, go back to the
3239 // previous window.
3240 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3241 {
3242 pwin = curwin;
3243 if (win_valid(prevwin))
3244 win_enter(prevwin, FALSE);
3245 }
3246 else
3247#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003248 // If this is the last normal window: exit Vim.
3249 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3250 {
3251 exarg_T ea;
3252
3253 vim_memset(&ea, 0, sizeof(ea));
3254 ex_quit(&ea);
3255 return TRUE;
3256 }
3257
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003258 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003259 ch_log(NULL, "terminal job finished, closing window");
3260 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003261 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003262 if (curwin == aucmd_win)
3263 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003264 if (do_set_w_closing)
3265 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003266 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003267 if (do_set_w_closing)
3268 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003269 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003270#ifdef FEAT_PROP_POPUP
3271 if (pwin != NULL)
3272 popup_close_with_retval(pwin, 0);
3273#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003274 return TRUE;
3275 }
3276 if (term->tl_finish == TL_FINISH_OPEN
3277 && term->tl_buffer->b_nwindows == 0)
3278 {
3279 char buf[50];
3280
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003281 // TODO: use term_opencmd
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003282 ch_log(NULL, "terminal job finished, opening window");
3283 vim_snprintf(buf, sizeof(buf),
3284 term->tl_opencmd == NULL
3285 ? "botright sbuf %d"
3286 : (char *)term->tl_opencmd, fnum);
3287 do_cmdline_cmd((char_u *)buf);
3288 }
3289 else
3290 ch_log(NULL, "terminal job finished");
3291 }
3292
3293 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3294 return FALSE;
3295}
3296
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003297#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3298/*
3299 * If the current window is a terminal in a popup window and the job has
3300 * finished, close the popup window and to back to the previous window.
3301 * Otherwise return FAIL.
3302 */
3303 int
3304may_close_term_popup(void)
3305{
3306 if (popup_is_popup(curwin) && curbuf->b_term != NULL
3307 && !term_job_running(curbuf->b_term))
3308 {
3309 win_T *pwin = curwin;
3310
3311 if (win_valid(prevwin))
3312 win_enter(prevwin, FALSE);
3313 popup_close_with_retval(pwin, 0);
3314 return OK;
3315 }
3316 return FAIL;
3317}
3318#endif
3319
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003320/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003321 * Called when a channel has been closed.
3322 * If this was a channel for a terminal window then finish it up.
3323 */
3324 void
3325term_channel_closed(channel_T *ch)
3326{
3327 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003328 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003329 int did_one = FALSE;
3330
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003331 for (term = first_term; term != NULL; term = next_term)
3332 {
3333 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003334 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003335 {
3336 term->tl_channel_closed = TRUE;
3337 did_one = TRUE;
3338
Bram Moolenaard23a8232018-02-10 18:45:26 +01003339 VIM_CLEAR(term->tl_title);
3340 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003341#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003342 if (term->tl_out_fd != NULL)
3343 {
3344 fclose(term->tl_out_fd);
3345 term->tl_out_fd = NULL;
3346 }
3347#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003348
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003349 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003350 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003351 // Cannot open or close windows now. Can happen when
3352 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003353 term->tl_channel_recently_closed = TRUE;
3354 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003355 }
3356
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003357 if (term_after_channel_closed(term))
3358 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003359 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003360 }
3361
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003362 if (did_one)
3363 {
3364 redraw_statuslines();
3365
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003366 // Need to break out of vgetc().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003367 ins_char_typebuf(K_IGNORE);
3368 typebuf_was_filled = TRUE;
3369
3370 term = curbuf->b_term;
3371 if (term != NULL)
3372 {
3373 if (term->tl_job == ch->ch_job)
3374 maketitle();
3375 update_cursor(term, term->tl_cursor_visible);
3376 }
3377 }
3378}
3379
3380/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003381 * To be called after resetting updating_screen: handle any terminal where the
3382 * channel was closed.
3383 */
3384 void
3385term_check_channel_closed_recently()
3386{
3387 term_T *term;
3388 term_T *next_term;
3389
3390 for (term = first_term; term != NULL; term = next_term)
3391 {
3392 next_term = term->tl_next;
3393 if (term->tl_channel_recently_closed)
3394 {
3395 term->tl_channel_recently_closed = FALSE;
3396 if (term_after_channel_closed(term))
3397 // start over, the list may have changed
3398 next_term = first_term;
3399 }
3400 }
3401}
3402
3403/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003404 * Fill one screen line from a line of the terminal.
3405 * Advances "pos" to past the last column.
3406 */
3407 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003408term_line2screenline(
3409 win_T *wp,
3410 VTermScreen *screen,
3411 VTermPos *pos,
3412 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003413{
3414 int off = screen_get_current_line_off();
3415
3416 for (pos->col = 0; pos->col < max_col; )
3417 {
3418 VTermScreenCell cell;
3419 int c;
3420
3421 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3422 vim_memset(&cell, 0, sizeof(cell));
3423
3424 c = cell.chars[0];
3425 if (c == NUL)
3426 {
3427 ScreenLines[off] = ' ';
3428 if (enc_utf8)
3429 ScreenLinesUC[off] = NUL;
3430 }
3431 else
3432 {
3433 if (enc_utf8)
3434 {
3435 int i;
3436
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003437 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003438 for (i = 0; i < Screen_mco
3439 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3440 {
3441 ScreenLinesC[i][off] = cell.chars[i + 1];
3442 if (cell.chars[i + 1] == 0)
3443 break;
3444 }
3445 if (c >= 0x80 || (Screen_mco > 0
3446 && ScreenLinesC[0][off] != 0))
3447 {
3448 ScreenLines[off] = ' ';
3449 ScreenLinesUC[off] = c;
3450 }
3451 else
3452 {
3453 ScreenLines[off] = c;
3454 ScreenLinesUC[off] = NUL;
3455 }
3456 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003457#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003458 else if (has_mbyte && c >= 0x80)
3459 {
3460 char_u mb[MB_MAXBYTES+1];
3461 WCHAR wc = c;
3462
3463 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3464 (char*)mb, 2, 0, 0) > 1)
3465 {
3466 ScreenLines[off] = mb[0];
3467 ScreenLines[off + 1] = mb[1];
3468 cell.width = mb_ptr2cells(mb);
3469 }
3470 else
3471 ScreenLines[off] = c;
3472 }
3473#endif
3474 else
3475 ScreenLines[off] = c;
3476 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003477 ScreenAttrs[off] = cell2attr(wp, cell.attrs, cell.fg, cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003478
3479 ++pos->col;
3480 ++off;
3481 if (cell.width == 2)
3482 {
3483 if (enc_utf8)
3484 ScreenLinesUC[off] = NUL;
3485
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003486 // don't set the second byte to NUL for a DBCS encoding, it
3487 // has been set above
Bram Moolenaar13568252018-03-16 20:46:58 +01003488 if (enc_utf8 || !has_mbyte)
3489 ScreenLines[off] = NUL;
3490
3491 ++pos->col;
3492 ++off;
3493 }
3494 }
3495}
3496
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003497#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003498 static void
3499update_system_term(term_T *term)
3500{
3501 VTermPos pos;
3502 VTermScreen *screen;
3503
3504 if (term->tl_vterm == NULL)
3505 return;
3506 screen = vterm_obtain_screen(term->tl_vterm);
3507
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003508 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003509 while (term->tl_toprow > 0
3510 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3511 {
3512 int save_p_more = p_more;
3513
3514 p_more = FALSE;
3515 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003516 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003517 p_more = save_p_more;
3518 --term->tl_toprow;
3519 }
3520
3521 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3522 && pos.row < Rows; ++pos.row)
3523 {
3524 if (pos.row < term->tl_rows)
3525 {
3526 int max_col = MIN(Columns, term->tl_cols);
3527
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003528 term_line2screenline(NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003529 }
3530 else
3531 pos.col = 0;
3532
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003533 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003534 }
3535
3536 term->tl_dirty_row_start = MAX_ROW;
3537 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003538}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003539#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003540
3541/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003542 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3543 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003544 * Terminal-Normal mode.
3545 */
3546 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003547term_do_update_window(win_T *wp)
3548{
3549 term_T *term = wp->w_buffer->b_term;
3550
3551 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3552}
3553
3554/*
3555 * Called to update a window that contains an active terminal.
3556 */
3557 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003558term_update_window(win_T *wp)
3559{
3560 term_T *term = wp->w_buffer->b_term;
3561 VTerm *vterm;
3562 VTermScreen *screen;
3563 VTermState *state;
3564 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003565 int rows, cols;
3566 int newrows, newcols;
3567 int minsize;
3568 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003569
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003570 vterm = term->tl_vterm;
3571 screen = vterm_obtain_screen(vterm);
3572 state = vterm_obtain_state(vterm);
3573
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003574 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3575 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003576 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003577 {
3578 term->tl_dirty_row_start = 0;
3579 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003580
3581 if (term->tl_postponed_scroll > 0
3582 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003583 // Scrolling is usually faster than redrawing, when there are only
3584 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003585 term_scroll_up(term, 0, term->tl_postponed_scroll);
3586 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003587 }
3588
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003589 /*
3590 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003591 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003592 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003593 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003594
Bram Moolenaar498c2562018-04-15 23:45:15 +02003595 newrows = 99999;
3596 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003597 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003598 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003599 // Always use curwin, it may be a popup window.
3600 win_T *wwp = twp == NULL ? curwin : twp;
3601
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003602 // When more than one window shows the same terminal, use the
3603 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003604 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003605 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003606 newrows = MIN(newrows, wwp->w_height);
3607 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003608 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003609 if (twp == NULL)
3610 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003611 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003612 if (newrows == 99999 || newcols == 99999)
3613 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003614 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3615 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3616
3617 if (term->tl_rows != newrows || term->tl_cols != newcols)
3618 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003619 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003620 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003621 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003622 newrows);
3623 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003624
3625 // Updating the terminal size will cause the snapshot to be cleared.
3626 // When not in terminal_loop() we need to restore it.
3627 if (term != in_terminal_loop)
3628 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003629 }
3630
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003631 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003632 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003633 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003634
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003635 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3636 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003637 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003638 if (pos.row < term->tl_rows)
3639 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003640 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003641
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003642 term_line2screenline(wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003643 }
3644 else
3645 pos.col = 0;
3646
Bram Moolenaarf118d482018-03-13 13:14:00 +01003647 screen_line(wp->w_winrow + pos.row
3648#ifdef FEAT_MENU
3649 + winbar_height(wp)
3650#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003651 , wp->w_wincol, pos.col, wp->w_width,
3652#ifdef FEAT_PROP_POPUP
3653 popup_is_popup(wp) ? SLF_POPUP :
3654#endif
3655 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003656 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003657 term->tl_dirty_row_start = MAX_ROW;
3658 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003659}
3660
3661/*
3662 * Return TRUE if "wp" is a terminal window where the job has finished.
3663 */
3664 int
3665term_is_finished(buf_T *buf)
3666{
3667 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3668}
3669
3670/*
3671 * Return TRUE if "wp" is a terminal window where the job has finished or we
3672 * are in Terminal-Normal mode, thus we show the buffer contents.
3673 */
3674 int
3675term_show_buffer(buf_T *buf)
3676{
3677 term_T *term = buf->b_term;
3678
3679 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3680}
3681
3682/*
3683 * The current buffer is going to be changed. If there is terminal
3684 * highlighting remove it now.
3685 */
3686 void
3687term_change_in_curbuf(void)
3688{
3689 term_T *term = curbuf->b_term;
3690
3691 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3692 {
3693 free_scrollback(term);
3694 redraw_buf_later(term->tl_buffer, NOT_VALID);
3695
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003696 // The buffer is now like a normal buffer, it cannot be easily
3697 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003698 set_string_option_direct((char_u *)"buftype", -1,
3699 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3700 }
3701}
3702
3703/*
3704 * Get the screen attribute for a position in the buffer.
3705 * Use a negative "col" to get the filler background color.
3706 */
3707 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003708term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003709{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003710 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003711 term_T *term = buf->b_term;
3712 sb_line_T *line;
3713 cellattr_T *cellattr;
3714
3715 if (lnum > term->tl_scrollback.ga_len)
3716 cellattr = &term->tl_default_color;
3717 else
3718 {
3719 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3720 if (col < 0 || col >= line->sb_cols)
3721 cellattr = &line->sb_fill_attr;
3722 else
3723 cellattr = line->sb_cells + col;
3724 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003725 return cell2attr(wp, cellattr->attrs, cellattr->fg, cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003726}
3727
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003728/*
3729 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003730 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003731 */
3732 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003733cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003734{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003735 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003736}
3737
3738/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003739 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003740 */
3741 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003742init_default_colors(term_T *term, win_T *wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003743{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003744 VTermColor *fg, *bg;
3745 int fgval, bgval;
3746 int id;
3747
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003748 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3749 term->tl_default_color.width = 1;
3750 fg = &term->tl_default_color.fg;
3751 bg = &term->tl_default_color.bg;
3752
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003753 // Vterm uses a default black background. Set it to white when
3754 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003755 if (*p_bg == 'l')
3756 {
3757 fgval = 0;
3758 bgval = 255;
3759 }
3760 else
3761 {
3762 fgval = 255;
3763 bgval = 0;
3764 }
3765 fg->red = fg->green = fg->blue = fgval;
3766 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003767 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003768
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003769 // The 'wincolor' or "Terminal" highlight group overrules the defaults.
3770 if (wp != NULL && *wp->w_p_wcr != NUL)
3771 id = syn_name2id(wp->w_p_wcr);
3772 else
3773 id = syn_name2id((char_u *)"Terminal");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003774
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003775 // Use the actual color for the GUI and when 'termguicolors' is set.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003776#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3777 if (0
3778# ifdef FEAT_GUI
3779 || gui.in_use
3780# endif
3781# ifdef FEAT_TERMGUICOLORS
3782 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003783# ifdef FEAT_VTP
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003784 // Finally get INVALCOLOR on this execution path
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003785 || (!p_tgc && t_colors >= 256)
3786# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003787# endif
3788 )
3789 {
3790 guicolor_T fg_rgb = INVALCOLOR;
3791 guicolor_T bg_rgb = INVALCOLOR;
3792
3793 if (id != 0)
3794 syn_id2colors(id, &fg_rgb, &bg_rgb);
3795
3796# ifdef FEAT_GUI
3797 if (gui.in_use)
3798 {
3799 if (fg_rgb == INVALCOLOR)
3800 fg_rgb = gui.norm_pixel;
3801 if (bg_rgb == INVALCOLOR)
3802 bg_rgb = gui.back_pixel;
3803 }
3804# ifdef FEAT_TERMGUICOLORS
3805 else
3806# endif
3807# endif
3808# ifdef FEAT_TERMGUICOLORS
3809 {
3810 if (fg_rgb == INVALCOLOR)
3811 fg_rgb = cterm_normal_fg_gui_color;
3812 if (bg_rgb == INVALCOLOR)
3813 bg_rgb = cterm_normal_bg_gui_color;
3814 }
3815# endif
3816 if (fg_rgb != INVALCOLOR)
3817 {
3818 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3819
3820 fg->red = (unsigned)(rgb >> 16);
3821 fg->green = (unsigned)(rgb >> 8) & 255;
3822 fg->blue = (unsigned)rgb & 255;
3823 }
3824 if (bg_rgb != INVALCOLOR)
3825 {
3826 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3827
3828 bg->red = (unsigned)(rgb >> 16);
3829 bg->green = (unsigned)(rgb >> 8) & 255;
3830 bg->blue = (unsigned)rgb & 255;
3831 }
3832 }
3833 else
3834#endif
3835 if (id != 0 && t_colors >= 16)
3836 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003837 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003838 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003839 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003840 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003841 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003842 else
3843 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003844#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003845 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003846#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003847
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003848 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003849 if (cterm_normal_fg_color > 0)
3850 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003851 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003852# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3853# ifdef VIMDLL
3854 if (!gui.in_use)
3855# endif
3856 {
3857 tmp = fg->red;
3858 fg->red = fg->blue;
3859 fg->blue = tmp;
3860 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003861# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003862 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003863# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003864 else
3865 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003866# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003867
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003868 if (cterm_normal_bg_color > 0)
3869 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003870 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003871# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3872# ifdef VIMDLL
3873 if (!gui.in_use)
3874# endif
3875 {
3876 tmp = fg->red;
3877 fg->red = fg->blue;
3878 fg->blue = tmp;
3879 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003880# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003881 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003882# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003883 else
3884 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003885# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003886 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003887}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003888
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003889#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3890/*
3891 * Set the 16 ANSI colors from array of RGB values
3892 */
3893 static void
3894set_vterm_palette(VTerm *vterm, long_u *rgb)
3895{
3896 int index = 0;
3897 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003898
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003899 for (; index < 16; index++)
3900 {
3901 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003902
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003903 color.red = (unsigned)(rgb[index] >> 16);
3904 color.green = (unsigned)(rgb[index] >> 8) & 255;
3905 color.blue = (unsigned)rgb[index] & 255;
3906 vterm_state_set_palette_color(state, index, &color);
3907 }
3908}
3909
3910/*
3911 * Set the ANSI color palette from a list of colors
3912 */
3913 static int
3914set_ansi_colors_list(VTerm *vterm, list_T *list)
3915{
3916 int n = 0;
3917 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01003918 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003919
Bram Moolenaarb0992022020-01-30 14:55:42 +01003920 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003921 {
3922 char_u *color_name;
3923 guicolor_T guicolor;
3924
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003925 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003926 if (color_name == NULL)
3927 return FAIL;
3928
3929 guicolor = GUI_GET_COLOR(color_name);
3930 if (guicolor == INVALCOLOR)
3931 return FAIL;
3932
3933 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3934 }
3935
3936 if (n != 16 || li != NULL)
3937 return FAIL;
3938
3939 set_vterm_palette(vterm, rgb);
3940
3941 return OK;
3942}
3943
3944/*
3945 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3946 */
3947 static void
3948init_vterm_ansi_colors(VTerm *vterm)
3949{
3950 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3951
3952 if (var != NULL
3953 && (var->di_tv.v_type != VAR_LIST
3954 || var->di_tv.vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +01003955 || var->di_tv.vval.v_list->lv_first == &range_list_item
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003956 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003957 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003958}
3959#endif
3960
Bram Moolenaar52acb112018-03-18 19:20:22 +01003961/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003962 * Handles a "drop" command from the job in the terminal.
3963 * "item" is the file name, "item->li_next" may have options.
3964 */
3965 static void
3966handle_drop_command(listitem_T *item)
3967{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003968 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003969 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003970 int bufnr;
3971 win_T *wp;
3972 tabpage_T *tp;
3973 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003974 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003975
3976 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3977 FOR_ALL_TAB_WINDOWS(tp, wp)
3978 {
3979 if (wp->w_buffer->b_fnum == bufnr)
3980 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003981 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003982 goto_tabpage_win(tp, wp);
3983 return;
3984 }
3985 }
3986
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003987 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003988
3989 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3990 && opt_item->li_tv.vval.v_dict != NULL)
3991 {
3992 dict_T *dict = opt_item->li_tv.vval.v_dict;
3993 char_u *p;
3994
Bram Moolenaar8f667172018-12-14 15:38:31 +01003995 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003996 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003997 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003998 if (p != NULL)
3999 {
4000 if (check_ff_value(p) == FAIL)
4001 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4002 else
4003 ea.force_ff = *p;
4004 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01004005 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004006 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004007 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004008 if (p != NULL)
4009 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004010 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004011 if (ea.cmd != NULL)
4012 {
4013 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4014 ea.force_enc = 11;
4015 tofree = ea.cmd;
4016 }
4017 }
4018
Bram Moolenaar8f667172018-12-14 15:38:31 +01004019 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004020 if (p != NULL)
4021 get_bad_opt(p, &ea);
4022
4023 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
4024 ea.force_bin = FORCE_BIN;
4025 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
4026 ea.force_bin = FORCE_BIN;
4027 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
4028 ea.force_bin = FORCE_NOBIN;
4029 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
4030 ea.force_bin = FORCE_NOBIN;
4031 }
4032
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004033 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004034 if (ea.cmd == NULL)
4035 ea.cmd = (char_u *)"split";
4036 ea.arg = fname;
4037 ea.cmdidx = CMD_split;
4038 ex_splitview(&ea);
4039
4040 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004041}
4042
4043/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004044 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4045 */
4046 static int
4047is_permitted_term_api(char_u *func, char_u *pat)
4048{
4049 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4050}
4051
4052/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004053 * Handles a function call from the job running in a terminal.
4054 * "item" is the function name, "item->li_next" has the arguments.
4055 */
4056 static void
4057handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4058{
4059 char_u *func;
4060 typval_T argvars[2];
4061 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004062 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004063
4064 if (item->li_next == NULL)
4065 {
4066 ch_log(channel, "Missing function arguments for call");
4067 return;
4068 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004069 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004070
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004071 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004072 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004073 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004074 return;
4075 }
4076
4077 argvars[0].v_type = VAR_NUMBER;
4078 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4079 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004080 vim_memset(&funcexe, 0, sizeof(funcexe));
4081 funcexe.firstline = 1L;
4082 funcexe.lastline = 1L;
4083 funcexe.evaluate = TRUE;
4084 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004085 {
4086 clear_tv(&rettv);
4087 ch_log(channel, "Function %s called", func);
4088 }
4089 else
4090 ch_log(channel, "Calling function %s failed", func);
4091}
4092
4093/*
4094 * Called by libvterm when it cannot recognize an OSC sequence.
4095 * We recognize a terminal API command.
4096 */
4097 static int
4098parse_osc(const char *command, size_t cmdlen, void *user)
4099{
4100 term_T *term = (term_T *)user;
4101 js_read_T reader;
4102 typval_T tv;
4103 channel_T *channel = term->tl_job == NULL ? NULL
4104 : term->tl_job->jv_channel;
4105
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004106 // We recognize only OSC 5 1 ; {command}
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004107 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004108 return 0; // not handled
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004109
Bram Moolenaar878c96d2018-04-04 23:00:06 +02004110 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004111 if (reader.js_buf == NULL)
4112 return 1;
4113 reader.js_fill = NULL;
4114 reader.js_used = 0;
4115 if (json_decode(&reader, &tv, 0) == OK
4116 && tv.v_type == VAR_LIST
4117 && tv.vval.v_list != NULL)
4118 {
4119 listitem_T *item = tv.vval.v_list->lv_first;
4120
4121 if (item == NULL)
4122 ch_log(channel, "Missing command");
4123 else
4124 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004125 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004126
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004127 // Make sure an invoked command doesn't delete the buffer (and the
4128 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004129 ++term->tl_buffer->b_locked;
4130
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004131 item = item->li_next;
4132 if (item == NULL)
4133 ch_log(channel, "Missing argument for %s", cmd);
4134 else if (STRCMP(cmd, "drop") == 0)
4135 handle_drop_command(item);
4136 else if (STRCMP(cmd, "call") == 0)
4137 handle_call_command(term, channel, item);
4138 else
4139 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004140 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004141 }
4142 }
4143 else
4144 ch_log(channel, "Invalid JSON received");
4145
4146 vim_free(reader.js_buf);
4147 clear_tv(&tv);
4148 return 1;
4149}
4150
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004151/*
4152 * Called by libvterm when it cannot recognize a CSI sequence.
4153 * We recognize the window position report.
4154 */
4155 static int
4156parse_csi(
4157 const char *leader UNUSED,
4158 const long args[],
4159 int argcount,
4160 const char *intermed UNUSED,
4161 char command,
4162 void *user)
4163{
4164 term_T *term = (term_T *)user;
4165 char buf[100];
4166 int len;
4167 int x = 0;
4168 int y = 0;
4169 win_T *wp;
4170
4171 // We recognize only CSI 13 t
4172 if (command != 't' || argcount != 1 || args[0] != 13)
4173 return 0; // not handled
4174
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004175 // When getting the window position is not possible or it fails it results
4176 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004177#if defined(FEAT_GUI) \
4178 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4179 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004180 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004181#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004182
4183 FOR_ALL_WINDOWS(wp)
4184 if (wp->w_buffer == term->tl_buffer)
4185 break;
4186 if (wp != NULL)
4187 {
4188#ifdef FEAT_GUI
4189 if (gui.in_use)
4190 {
4191 x += wp->w_wincol * gui.char_width;
4192 y += W_WINROW(wp) * gui.char_height;
4193 }
4194 else
4195#endif
4196 {
4197 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004198 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004199 x += wp->w_wincol * 7;
4200 y += W_WINROW(wp) * 10;
4201 }
4202 }
4203
4204 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4205 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4206 (char_u *)buf, len, NULL);
4207 return 1;
4208}
4209
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004210static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004211 NULL, // text
4212 NULL, // control
4213 NULL, // escape
4214 parse_csi, // csi
4215 parse_osc, // osc
4216 NULL, // dcs
4217 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004218};
4219
4220/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004221 * Use Vim's allocation functions for vterm so profiling works.
4222 */
4223 static void *
4224vterm_malloc(size_t size, void *data UNUSED)
4225{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004226 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004227}
4228
4229 static void
4230vterm_memfree(void *ptr, void *data UNUSED)
4231{
4232 vim_free(ptr);
4233}
4234
4235static VTermAllocatorFunctions vterm_allocator = {
4236 &vterm_malloc,
4237 &vterm_memfree
4238};
4239
4240/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004241 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004242 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004243 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004244 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004245create_vterm(term_T *term, int rows, int cols)
4246{
4247 VTerm *vterm;
4248 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004249 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004250 VTermValue value;
4251
Bram Moolenaar756ef112018-04-10 12:04:27 +02004252 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004253 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004254 if (vterm == NULL)
4255 return FAIL;
4256
4257 // Allocate screen and state here, so we can bail out if that fails.
4258 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004259 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004260 if (state == NULL || screen == NULL)
4261 {
4262 vterm_free(vterm);
4263 return FAIL;
4264 }
4265
Bram Moolenaar52acb112018-03-18 19:20:22 +01004266 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004267 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004268 vterm_set_utf8(vterm, 1);
4269
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004270 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004271
4272 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004273 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004274 &term->tl_default_color.fg,
4275 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004276
Bram Moolenaar9e587872019-05-13 20:27:23 +02004277 if (t_colors < 16)
4278 // Less than 16 colors: assume that bold means using a bright color for
4279 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004280 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4281
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004282 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004283 vterm_screen_reset(screen, 1 /* hard */);
4284
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004285 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004286 vterm_screen_enable_altscreen(screen, 1);
4287
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004288 // For unix do not use a blinking cursor. In an xterm this causes the
4289 // cursor to blink if it's blinking in the xterm.
4290 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004291#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004292 if (GetCaretBlinkTime() == INFINITE)
4293 value.boolean = 0;
4294 else
4295 value.boolean = 1;
4296#else
4297 value.boolean = 0;
4298#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004299 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4300 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004301
4302 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004303}
4304
4305/*
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004306 * Called when 'wincolor' was set.
4307 */
4308 void
4309term_update_colors(void)
4310{
4311 term_T *term = curwin->w_buffer->b_term;
4312
Bram Moolenaar7ba3b912020-02-10 20:34:04 +01004313 if (term->tl_vterm == NULL)
4314 return;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004315 init_default_colors(term, curwin);
4316 vterm_state_set_default_colors(
4317 vterm_obtain_state(term->tl_vterm),
4318 &term->tl_default_color.fg,
4319 &term->tl_default_color.bg);
4320}
4321
4322/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004323 * Return the text to show for the buffer name and status.
4324 */
4325 char_u *
4326term_get_status_text(term_T *term)
4327{
4328 if (term->tl_status_text == NULL)
4329 {
4330 char_u *txt;
4331 size_t len;
4332
4333 if (term->tl_normal_mode)
4334 {
4335 if (term_job_running(term))
4336 txt = (char_u *)_("Terminal");
4337 else
4338 txt = (char_u *)_("Terminal-finished");
4339 }
4340 else if (term->tl_title != NULL)
4341 txt = term->tl_title;
4342 else if (term_none_open(term))
4343 txt = (char_u *)_("active");
4344 else if (term_job_running(term))
4345 txt = (char_u *)_("running");
4346 else
4347 txt = (char_u *)_("finished");
4348 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004349 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004350 if (term->tl_status_text != NULL)
4351 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4352 term->tl_buffer->b_fname, txt);
4353 }
4354 return term->tl_status_text;
4355}
4356
4357/*
4358 * Mark references in jobs of terminals.
4359 */
4360 int
4361set_ref_in_term(int copyID)
4362{
4363 int abort = FALSE;
4364 term_T *term;
4365 typval_T tv;
4366
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004367 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004368 if (term->tl_job != NULL)
4369 {
4370 tv.v_type = VAR_JOB;
4371 tv.vval.v_job = term->tl_job;
4372 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4373 }
4374 return abort;
4375}
4376
4377/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004378 * Cache "Terminal" highlight group colors.
4379 */
4380 void
4381set_terminal_default_colors(int cterm_fg, int cterm_bg)
4382{
4383 term_default_cterm_fg = cterm_fg - 1;
4384 term_default_cterm_bg = cterm_bg - 1;
4385}
4386
4387/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004388 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004389 * Returns NULL when the buffer is not for a terminal window and logs a message
4390 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004391 */
4392 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004393term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004394{
4395 buf_T *buf;
4396
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004397 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004398 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004399 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004400 --emsg_off;
4401 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004402 {
4403 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004404 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004405 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004406 return buf;
4407}
4408
Bram Moolenaard96ff162018-02-18 22:13:29 +01004409 static int
4410same_color(VTermColor *a, VTermColor *b)
4411{
4412 return a->red == b->red
4413 && a->green == b->green
4414 && a->blue == b->blue
4415 && a->ansi_index == b->ansi_index;
4416}
4417
4418 static void
4419dump_term_color(FILE *fd, VTermColor *color)
4420{
4421 fprintf(fd, "%02x%02x%02x%d",
4422 (int)color->red, (int)color->green, (int)color->blue,
4423 (int)color->ansi_index);
4424}
4425
4426/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004427 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004428 *
4429 * Each screen cell in full is:
4430 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4431 * {characters} is a space for an empty cell
4432 * For a double-width character "+" is changed to "*" and the next cell is
4433 * skipped.
4434 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4435 * when "&" use the same as the previous cell.
4436 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4437 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4438 * {color-idx} is a number from 0 to 255
4439 *
4440 * Screen cell with same width, attributes and color as the previous one:
4441 * |{characters}
4442 *
4443 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4444 *
4445 * Repeating the previous screen cell:
4446 * @{count}
4447 */
4448 void
4449f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4450{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004451 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004452 term_T *term;
4453 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004454 int max_height = 0;
4455 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004456 stat_T st;
4457 FILE *fd;
4458 VTermPos pos;
4459 VTermScreen *screen;
4460 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004461 VTermState *state;
4462 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004463
4464 if (check_restricted() || check_secure())
4465 return;
4466 if (buf == NULL)
4467 return;
4468 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004469 if (term->tl_vterm == NULL)
4470 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004471 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004472 return;
4473 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004474
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004475 if (argvars[2].v_type != VAR_UNKNOWN)
4476 {
4477 dict_T *d;
4478
4479 if (argvars[2].v_type != VAR_DICT)
4480 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004481 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004482 return;
4483 }
4484 d = argvars[2].vval.v_dict;
4485 if (d != NULL)
4486 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004487 max_height = dict_get_number(d, (char_u *)"rows");
4488 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004489 }
4490 }
4491
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004492 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004493 if (fname == NULL)
4494 return;
4495 if (mch_stat((char *)fname, &st) >= 0)
4496 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004497 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004498 return;
4499 }
4500
Bram Moolenaard96ff162018-02-18 22:13:29 +01004501 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4502 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004503 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004504 return;
4505 }
4506
4507 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4508
4509 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004510 state = vterm_obtain_state(term->tl_vterm);
4511 vterm_state_get_cursorpos(state, &cursor_pos);
4512
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004513 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4514 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004515 {
4516 int repeat = 0;
4517
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004518 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4519 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004520 {
4521 VTermScreenCell cell;
4522 int same_attr;
4523 int same_chars = TRUE;
4524 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004525 int is_cursor_pos = (pos.col == cursor_pos.col
4526 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004527
4528 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4529 vim_memset(&cell, 0, sizeof(cell));
4530
4531 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4532 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004533 int c = cell.chars[i];
4534 int pc = prev_cell.chars[i];
4535
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004536 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01004537 if (i == 0)
4538 {
4539 c = (c == NUL) ? ' ' : c;
4540 pc = (pc == NUL) ? ' ' : pc;
4541 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004542 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004543 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004544 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004545 break;
4546 }
4547 same_attr = vtermAttr2hl(cell.attrs)
4548 == vtermAttr2hl(prev_cell.attrs)
4549 && same_color(&cell.fg, &prev_cell.fg)
4550 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004551 if (same_chars && cell.width == prev_cell.width && same_attr
4552 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004553 {
4554 ++repeat;
4555 }
4556 else
4557 {
4558 if (repeat > 0)
4559 {
4560 fprintf(fd, "@%d", repeat);
4561 repeat = 0;
4562 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004563 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004564
4565 if (cell.chars[0] == NUL)
4566 fputs(" ", fd);
4567 else
4568 {
4569 char_u charbuf[10];
4570 int len;
4571
4572 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4573 && cell.chars[i] != NUL; ++i)
4574 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004575 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004576 fwrite(charbuf, len, 1, fd);
4577 }
4578 }
4579
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004580 // When only the characters differ we don't write anything, the
4581 // following "|", "@" or NL will indicate using the same
4582 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004583 if (cell.width != prev_cell.width || !same_attr)
4584 {
4585 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004586 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004587 else
4588 fputs("+", fd);
4589
4590 if (same_attr)
4591 {
4592 fputs("&", fd);
4593 }
4594 else
4595 {
4596 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4597 if (same_color(&cell.fg, &prev_cell.fg))
4598 fputs("&", fd);
4599 else
4600 {
4601 fputs("#", fd);
4602 dump_term_color(fd, &cell.fg);
4603 }
4604 if (same_color(&cell.bg, &prev_cell.bg))
4605 fputs("&", fd);
4606 else
4607 {
4608 fputs("#", fd);
4609 dump_term_color(fd, &cell.bg);
4610 }
4611 }
4612 }
4613
4614 prev_cell = cell;
4615 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004616
4617 if (cell.width == 2)
4618 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004619 }
4620 if (repeat > 0)
4621 fprintf(fd, "@%d", repeat);
4622 fputs("\n", fd);
4623 }
4624
4625 fclose(fd);
4626}
4627
4628/*
4629 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4630 */
4631 static void
4632dump_is_corrupt(garray_T *gap)
4633{
4634 ga_concat(gap, (char_u *)"CORRUPT");
4635}
4636
4637 static void
4638append_cell(garray_T *gap, cellattr_T *cell)
4639{
4640 if (ga_grow(gap, 1) == OK)
4641 {
4642 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4643 ++gap->ga_len;
4644 }
4645}
4646
4647/*
4648 * Read the dump file from "fd" and append lines to the current buffer.
4649 * Return the cell width of the longest line.
4650 */
4651 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004652read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004653{
4654 int c;
4655 garray_T ga_text;
4656 garray_T ga_cell;
4657 char_u *prev_char = NULL;
4658 int attr = 0;
4659 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004660 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004661 term_T *term = curbuf->b_term;
4662 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004663 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004664
4665 ga_init2(&ga_text, 1, 90);
4666 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4667 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004668 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004669 cursor_pos->row = -1;
4670 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004671
4672 c = fgetc(fd);
4673 for (;;)
4674 {
4675 if (c == EOF)
4676 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004677 if (c == '\r')
4678 {
4679 // DOS line endings? Ignore.
4680 c = fgetc(fd);
4681 }
4682 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004683 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004684 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004685 if (ga_text.ga_data == NULL)
4686 dump_is_corrupt(&ga_text);
4687 if (ga_grow(&term->tl_scrollback, 1) == OK)
4688 {
4689 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4690 + term->tl_scrollback.ga_len;
4691
4692 if (max_cells < ga_cell.ga_len)
4693 max_cells = ga_cell.ga_len;
4694 line->sb_cols = ga_cell.ga_len;
4695 line->sb_cells = ga_cell.ga_data;
4696 line->sb_fill_attr = term->tl_default_color;
4697 ++term->tl_scrollback.ga_len;
4698 ga_init(&ga_cell);
4699
4700 ga_append(&ga_text, NUL);
4701 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4702 ga_text.ga_len, FALSE);
4703 }
4704 else
4705 ga_clear(&ga_cell);
4706 ga_text.ga_len = 0;
4707
4708 c = fgetc(fd);
4709 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004710 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004711 {
4712 int prev_len = ga_text.ga_len;
4713
Bram Moolenaar9271d052018-02-25 21:39:46 +01004714 if (c == '>')
4715 {
4716 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004717 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004718 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4719 cursor_pos->col = ga_cell.ga_len;
4720 }
4721
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004722 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004723 c = fgetc(fd);
4724 if (c != EOF)
4725 ga_append(&ga_text, c);
4726 for (;;)
4727 {
4728 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004729 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004730 || c == EOF || c == '\n')
4731 break;
4732 ga_append(&ga_text, c);
4733 }
4734
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004735 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01004736 vim_free(prev_char);
4737 if (ga_text.ga_data != NULL)
4738 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4739 ga_text.ga_len - prev_len);
4740
Bram Moolenaar9271d052018-02-25 21:39:46 +01004741 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004742 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004743 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004744 }
4745 else if (c == '+' || c == '*')
4746 {
4747 int is_bg;
4748
4749 cell.width = c == '+' ? 1 : 2;
4750
4751 c = fgetc(fd);
4752 if (c == '&')
4753 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004754 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004755 c = fgetc(fd);
4756 }
4757 else if (isdigit(c))
4758 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004759 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01004760 attr = 0;
4761 while (isdigit(c))
4762 {
4763 attr = attr * 10 + (c - '0');
4764 c = fgetc(fd);
4765 }
4766 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004767
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004768 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004769 for (is_bg = 0; is_bg <= 1; ++is_bg)
4770 {
4771 if (c == '&')
4772 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004773 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004774 c = fgetc(fd);
4775 }
4776 else if (c == '#')
4777 {
4778 int red, green, blue, index = 0;
4779
4780 c = fgetc(fd);
4781 red = hex2nr(c);
4782 c = fgetc(fd);
4783 red = (red << 4) + hex2nr(c);
4784 c = fgetc(fd);
4785 green = hex2nr(c);
4786 c = fgetc(fd);
4787 green = (green << 4) + hex2nr(c);
4788 c = fgetc(fd);
4789 blue = hex2nr(c);
4790 c = fgetc(fd);
4791 blue = (blue << 4) + hex2nr(c);
4792 c = fgetc(fd);
4793 if (!isdigit(c))
4794 dump_is_corrupt(&ga_text);
4795 while (isdigit(c))
4796 {
4797 index = index * 10 + (c - '0');
4798 c = fgetc(fd);
4799 }
4800
4801 if (is_bg)
4802 {
4803 cell.bg.red = red;
4804 cell.bg.green = green;
4805 cell.bg.blue = blue;
4806 cell.bg.ansi_index = index;
4807 }
4808 else
4809 {
4810 cell.fg.red = red;
4811 cell.fg.green = green;
4812 cell.fg.blue = blue;
4813 cell.fg.ansi_index = index;
4814 }
4815 }
4816 else
4817 dump_is_corrupt(&ga_text);
4818 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004819 }
4820 else
4821 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004822 }
4823 else
4824 dump_is_corrupt(&ga_text);
4825
4826 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004827 if (cell.width == 2)
4828 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004829 }
4830 else if (c == '@')
4831 {
4832 if (prev_char == NULL)
4833 dump_is_corrupt(&ga_text);
4834 else
4835 {
4836 int count = 0;
4837
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004838 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01004839 for (;;)
4840 {
4841 c = fgetc(fd);
4842 if (!isdigit(c))
4843 break;
4844 count = count * 10 + (c - '0');
4845 }
4846
4847 while (count-- > 0)
4848 {
4849 ga_concat(&ga_text, prev_char);
4850 append_cell(&ga_cell, &cell);
4851 }
4852 }
4853 }
4854 else
4855 {
4856 dump_is_corrupt(&ga_text);
4857 c = fgetc(fd);
4858 }
4859 }
4860
4861 if (ga_text.ga_len > 0)
4862 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004863 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004864 dump_is_corrupt(&ga_text);
4865 ga_append(&ga_text, NUL);
4866 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4867 ga_text.ga_len, FALSE);
4868 }
4869
4870 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004871 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004872 vim_free(prev_char);
4873
4874 return max_cells;
4875}
4876
4877/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004878 * Return an allocated string with at least "text_width" "=" characters and
4879 * "fname" inserted in the middle.
4880 */
4881 static char_u *
4882get_separator(int text_width, char_u *fname)
4883{
4884 int width = MAX(text_width, curwin->w_width);
4885 char_u *textline;
4886 int fname_size;
4887 char_u *p = fname;
4888 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004889 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004890
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004891 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004892 if (textline == NULL)
4893 return NULL;
4894
4895 fname_size = vim_strsize(fname);
4896 if (fname_size < width - 8)
4897 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004898 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02004899 width = MAX(text_width, fname_size + 8);
4900 }
4901 else if (fname_size > width - 8)
4902 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004903 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02004904 p = gettail(fname);
4905 fname_size = vim_strsize(p);
4906 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004907 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02004908 while (fname_size > width - 8)
4909 {
4910 p += (*mb_ptr2len)(p);
4911 fname_size = vim_strsize(p);
4912 }
4913
4914 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4915 textline[i] = '=';
4916 textline[i++] = ' ';
4917
4918 STRCPY(textline + i, p);
4919 off = STRLEN(textline);
4920 textline[off] = ' ';
4921 for (i = 1; i < (width - fname_size) / 2; ++i)
4922 textline[off + i] = '=';
4923 textline[off + i] = NUL;
4924
4925 return textline;
4926}
4927
4928/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004929 * Common for "term_dumpdiff()" and "term_dumpload()".
4930 */
4931 static void
4932term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4933{
4934 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004935 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004936 char_u buf1[NUMBUFLEN];
4937 char_u buf2[NUMBUFLEN];
4938 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004939 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004940 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004941 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004942 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004943 char_u *textline = NULL;
4944
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004945 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004946 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004947 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004948 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004949 if (fname1 == NULL || (do_diff && fname2 == NULL))
4950 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004951 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004952 return;
4953 }
4954 fd1 = mch_fopen((char *)fname1, READBIN);
4955 if (fd1 == NULL)
4956 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004957 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004958 return;
4959 }
4960 if (do_diff)
4961 {
4962 fd2 = mch_fopen((char *)fname2, READBIN);
4963 if (fd2 == NULL)
4964 {
4965 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004966 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004967 return;
4968 }
4969 }
4970
4971 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004972 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4973 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4974 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4975 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4976 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004977
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004978 if (opt.jo_term_name == NULL)
4979 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004980 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004981
Bram Moolenaar51e14382019-05-25 20:21:28 +02004982 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004983 if (fname_tofree != NULL)
4984 {
4985 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4986 opt.jo_term_name = fname_tofree;
4987 }
4988 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004989
Bram Moolenaar87abab92019-06-03 21:14:59 +02004990 if (opt.jo_bufnr_buf != NULL)
4991 {
4992 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4993
4994 // With "bufnr" argument: enter the window with this buffer and make it
4995 // empty.
4996 if (wp == NULL)
4997 semsg(_(e_invarg2), "bufnr");
4998 else
4999 {
5000 buf = curbuf;
5001 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
5002 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02005003 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005004 redraw_later(NOT_VALID);
5005 }
5006 }
5007 else
5008 // Create a new terminal window.
5009 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5010
Bram Moolenaard96ff162018-02-18 22:13:29 +01005011 if (buf != NULL && buf->b_term != NULL)
5012 {
5013 int i;
5014 linenr_T bot_lnum;
5015 linenr_T lnum;
5016 term_T *term = buf->b_term;
5017 int width;
5018 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005019 VTermPos cursor_pos1;
5020 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005021
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005022 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005023
Bram Moolenaard96ff162018-02-18 22:13:29 +01005024 rettv->vval.v_number = buf->b_fnum;
5025
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005026 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005027 width = read_dump_file(fd1, &cursor_pos1);
5028
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005029 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005030 if (cursor_pos1.row >= 0)
5031 {
5032 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5033 coladvance(cursor_pos1.col);
5034 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005035
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005036 // Delete the empty line that was in the empty buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005037 ml_delete(1, FALSE);
5038
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005039 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005040 if (!do_diff)
5041 goto theend;
5042
5043 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5044
Bram Moolenaar4a696342018-04-05 18:45:26 +02005045 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005046 if (textline == NULL)
5047 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005048 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5049 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5050 vim_free(textline);
5051
5052 textline = get_separator(width, fname2);
5053 if (textline == NULL)
5054 goto theend;
5055 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5056 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005057 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005058
5059 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005060 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005061 if (width2 > width)
5062 {
5063 vim_free(textline);
5064 textline = alloc(width2 + 1);
5065 if (textline == NULL)
5066 goto theend;
5067 width = width2;
5068 textline[width] = NUL;
5069 }
5070 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5071
5072 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5073 {
5074 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5075 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005076 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005077 for (i = 0; i < width; ++i)
5078 textline[i] = '-';
5079 }
5080 else
5081 {
5082 char_u *line1;
5083 char_u *line2;
5084 char_u *p1;
5085 char_u *p2;
5086 int col;
5087 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5088 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5089 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5090 ->sb_cells;
5091
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005092 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005093 line1 = vim_strsave(ml_get(lnum));
5094 if (line1 == NULL)
5095 break;
5096 p1 = line1;
5097
5098 line2 = ml_get(lnum + bot_lnum);
5099 p2 = line2;
5100 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5101 {
5102 int len1 = utfc_ptr2len(p1);
5103 int len2 = utfc_ptr2len(p2);
5104
5105 textline[col] = ' ';
5106 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005107 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005108 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005109 else if (lnum == cursor_pos1.row + 1
5110 && col == cursor_pos1.col
5111 && (cursor_pos1.row != cursor_pos2.row
5112 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005113 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005114 textline[col] = '>';
5115 else if (lnum == cursor_pos2.row + 1
5116 && col == cursor_pos2.col
5117 && (cursor_pos1.row != cursor_pos2.row
5118 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005119 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005120 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005121 else if (cellattr1 != NULL && cellattr2 != NULL)
5122 {
5123 if ((cellattr1 + col)->width
5124 != (cellattr2 + col)->width)
5125 textline[col] = 'w';
5126 else if (!same_color(&(cellattr1 + col)->fg,
5127 &(cellattr2 + col)->fg))
5128 textline[col] = 'f';
5129 else if (!same_color(&(cellattr1 + col)->bg,
5130 &(cellattr2 + col)->bg))
5131 textline[col] = 'b';
5132 else if (vtermAttr2hl((cellattr1 + col)->attrs)
5133 != vtermAttr2hl(((cellattr2 + col)->attrs)))
5134 textline[col] = 'a';
5135 }
5136 p1 += len1;
5137 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005138 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005139 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005140
5141 while (col < width)
5142 {
5143 if (*p1 == NUL && *p2 == NUL)
5144 textline[col] = '?';
5145 else if (*p1 == NUL)
5146 {
5147 textline[col] = '+';
5148 p2 += utfc_ptr2len(p2);
5149 }
5150 else
5151 {
5152 textline[col] = '-';
5153 p1 += utfc_ptr2len(p1);
5154 }
5155 ++col;
5156 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005157
5158 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005159 }
5160 if (add_empty_scrollback(term, &term->tl_default_color,
5161 term->tl_top_diff_rows) == OK)
5162 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5163 ++bot_lnum;
5164 }
5165
5166 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5167 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005168 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005169 for (i = 0; i < width; ++i)
5170 textline[i] = '+';
5171 if (add_empty_scrollback(term, &term->tl_default_color,
5172 term->tl_top_diff_rows) == OK)
5173 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5174 ++lnum;
5175 ++bot_lnum;
5176 }
5177
5178 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005179
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005180 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005181 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005182 }
5183
5184theend:
5185 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005186 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005187 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005188 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005189 fclose(fd2);
5190}
5191
5192/*
5193 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5194 * bottom files.
5195 * Return FAIL when this is not possible.
5196 */
5197 int
5198term_swap_diff()
5199{
5200 term_T *term = curbuf->b_term;
5201 linenr_T line_count;
5202 linenr_T top_rows;
5203 linenr_T bot_rows;
5204 linenr_T bot_start;
5205 linenr_T lnum;
5206 char_u *p;
5207 sb_line_T *sb_line;
5208
5209 if (term == NULL
5210 || !term_is_finished(curbuf)
5211 || term->tl_top_diff_rows == 0
5212 || term->tl_scrollback.ga_len == 0)
5213 return FAIL;
5214
5215 line_count = curbuf->b_ml.ml_line_count;
5216 top_rows = term->tl_top_diff_rows;
5217 bot_rows = term->tl_bot_diff_rows;
5218 bot_start = line_count - bot_rows;
5219 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5220
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005221 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005222 for (lnum = 1; lnum <= top_rows; ++lnum)
5223 {
5224 p = vim_strsave(ml_get(1));
5225 if (p == NULL)
5226 return OK;
5227 ml_append(bot_start, p, 0, FALSE);
5228 ml_delete(1, FALSE);
5229 vim_free(p);
5230 }
5231
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005232 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005233 for (lnum = 1; lnum <= bot_rows; ++lnum)
5234 {
5235 p = vim_strsave(ml_get(bot_start + lnum));
5236 if (p == NULL)
5237 return OK;
5238 ml_delete(bot_start + lnum, FALSE);
5239 ml_append(lnum - 1, p, 0, FALSE);
5240 vim_free(p);
5241 }
5242
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005243 // move top title to bottom
5244 p = vim_strsave(ml_get(bot_rows + 1));
5245 if (p == NULL)
5246 return OK;
5247 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5248 ml_delete(bot_rows + 1, FALSE);
5249 vim_free(p);
5250
5251 // move bottom title to top
5252 p = vim_strsave(ml_get(line_count - top_rows));
5253 if (p == NULL)
5254 return OK;
5255 ml_delete(line_count - top_rows, FALSE);
5256 ml_append(bot_rows, p, 0, FALSE);
5257 vim_free(p);
5258
Bram Moolenaard96ff162018-02-18 22:13:29 +01005259 if (top_rows == bot_rows)
5260 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005261 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005262 for (lnum = 0; lnum < top_rows; ++lnum)
5263 {
5264 sb_line_T temp;
5265
5266 temp = *(sb_line + lnum);
5267 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5268 *(sb_line + bot_start + lnum) = temp;
5269 }
5270 }
5271 else
5272 {
5273 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005274 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005275
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005276 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005277 if (temp != NULL)
5278 {
5279 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5280 mch_memmove(term->tl_scrollback.ga_data,
5281 temp + bot_start,
5282 sizeof(sb_line_T) * bot_rows);
5283 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5284 temp + top_rows,
5285 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5286 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5287 + line_count - top_rows,
5288 temp,
5289 sizeof(sb_line_T) * top_rows);
5290 vim_free(temp);
5291 }
5292 }
5293
5294 term->tl_top_diff_rows = bot_rows;
5295 term->tl_bot_diff_rows = top_rows;
5296
5297 update_screen(NOT_VALID);
5298 return OK;
5299}
5300
5301/*
5302 * "term_dumpdiff(filename, filename, options)" function
5303 */
5304 void
5305f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5306{
5307 term_load_dump(argvars, rettv, TRUE);
5308}
5309
5310/*
5311 * "term_dumpload(filename, options)" function
5312 */
5313 void
5314f_term_dumpload(typval_T *argvars, typval_T *rettv)
5315{
5316 term_load_dump(argvars, rettv, FALSE);
5317}
5318
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005319/*
5320 * "term_getaltscreen(buf)" function
5321 */
5322 void
5323f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5324{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005325 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005326
5327 if (buf == NULL)
5328 return;
5329 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5330}
5331
5332/*
5333 * "term_getattr(attr, name)" function
5334 */
5335 void
5336f_term_getattr(typval_T *argvars, typval_T *rettv)
5337{
5338 int attr;
5339 size_t i;
5340 char_u *name;
5341
5342 static struct {
5343 char *name;
5344 int attr;
5345 } attrs[] = {
5346 {"bold", HL_BOLD},
5347 {"italic", HL_ITALIC},
5348 {"underline", HL_UNDERLINE},
5349 {"strike", HL_STRIKETHROUGH},
5350 {"reverse", HL_INVERSE},
5351 };
5352
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005353 attr = tv_get_number(&argvars[0]);
5354 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005355 if (name == NULL)
5356 return;
5357
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005358 if (attr > HL_ALL)
5359 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005360 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5361 if (STRCMP(name, attrs[i].name) == 0)
5362 {
5363 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5364 break;
5365 }
5366}
5367
5368/*
5369 * "term_getcursor(buf)" function
5370 */
5371 void
5372f_term_getcursor(typval_T *argvars, typval_T *rettv)
5373{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005374 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005375 term_T *term;
5376 list_T *l;
5377 dict_T *d;
5378
5379 if (rettv_list_alloc(rettv) == FAIL)
5380 return;
5381 if (buf == NULL)
5382 return;
5383 term = buf->b_term;
5384
5385 l = rettv->vval.v_list;
5386 list_append_number(l, term->tl_cursor_pos.row + 1);
5387 list_append_number(l, term->tl_cursor_pos.col + 1);
5388
5389 d = dict_alloc();
5390 if (d != NULL)
5391 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005392 dict_add_number(d, "visible", term->tl_cursor_visible);
5393 dict_add_number(d, "blink", blink_state_is_inverted()
5394 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5395 dict_add_number(d, "shape", term->tl_cursor_shape);
5396 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005397 list_append_dict(l, d);
5398 }
5399}
5400
5401/*
5402 * "term_getjob(buf)" function
5403 */
5404 void
5405f_term_getjob(typval_T *argvars, typval_T *rettv)
5406{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005407 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005408
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005409 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005410 {
5411 rettv->v_type = VAR_SPECIAL;
5412 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005413 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005414 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005415
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005416 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005417 rettv->vval.v_job = buf->b_term->tl_job;
5418 if (rettv->vval.v_job != NULL)
5419 ++rettv->vval.v_job->jv_refcount;
5420}
5421
5422 static int
5423get_row_number(typval_T *tv, term_T *term)
5424{
5425 if (tv->v_type == VAR_STRING
5426 && tv->vval.v_string != NULL
5427 && STRCMP(tv->vval.v_string, ".") == 0)
5428 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005429 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005430}
5431
5432/*
5433 * "term_getline(buf, row)" function
5434 */
5435 void
5436f_term_getline(typval_T *argvars, typval_T *rettv)
5437{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005438 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005439 term_T *term;
5440 int row;
5441
5442 rettv->v_type = VAR_STRING;
5443 if (buf == NULL)
5444 return;
5445 term = buf->b_term;
5446 row = get_row_number(&argvars[1], term);
5447
5448 if (term->tl_vterm == NULL)
5449 {
5450 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5451
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005452 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005453 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5454 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5455 }
5456 else
5457 {
5458 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5459 VTermRect rect;
5460 int len;
5461 char_u *p;
5462
5463 if (row < 0 || row >= term->tl_rows)
5464 return;
5465 len = term->tl_cols * MB_MAXBYTES + 1;
5466 p = alloc(len);
5467 if (p == NULL)
5468 return;
5469 rettv->vval.v_string = p;
5470
5471 rect.start_col = 0;
5472 rect.end_col = term->tl_cols;
5473 rect.start_row = row;
5474 rect.end_row = row + 1;
5475 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5476 }
5477}
5478
5479/*
5480 * "term_getscrolled(buf)" function
5481 */
5482 void
5483f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5484{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005485 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005486
5487 if (buf == NULL)
5488 return;
5489 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5490}
5491
5492/*
5493 * "term_getsize(buf)" function
5494 */
5495 void
5496f_term_getsize(typval_T *argvars, typval_T *rettv)
5497{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005498 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005499 list_T *l;
5500
5501 if (rettv_list_alloc(rettv) == FAIL)
5502 return;
5503 if (buf == NULL)
5504 return;
5505
5506 l = rettv->vval.v_list;
5507 list_append_number(l, buf->b_term->tl_rows);
5508 list_append_number(l, buf->b_term->tl_cols);
5509}
5510
5511/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005512 * "term_setsize(buf, rows, cols)" function
5513 */
5514 void
5515f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5516{
5517 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5518 term_T *term;
5519 varnumber_T rows, cols;
5520
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005521 if (buf == NULL)
5522 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005523 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005524 return;
5525 }
5526 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005527 return;
5528 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005529 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005530 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005531 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005532 cols = cols <= 0 ? term->tl_cols : cols;
5533 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005534 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02005535
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005536 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02005537 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5538 term_report_winsize(term, term->tl_rows, term->tl_cols);
5539}
5540
5541/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005542 * "term_getstatus(buf)" function
5543 */
5544 void
5545f_term_getstatus(typval_T *argvars, typval_T *rettv)
5546{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005547 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005548 term_T *term;
5549 char_u val[100];
5550
5551 rettv->v_type = VAR_STRING;
5552 if (buf == NULL)
5553 return;
5554 term = buf->b_term;
5555
5556 if (term_job_running(term))
5557 STRCPY(val, "running");
5558 else
5559 STRCPY(val, "finished");
5560 if (term->tl_normal_mode)
5561 STRCAT(val, ",normal");
5562 rettv->vval.v_string = vim_strsave(val);
5563}
5564
5565/*
5566 * "term_gettitle(buf)" function
5567 */
5568 void
5569f_term_gettitle(typval_T *argvars, typval_T *rettv)
5570{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005571 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005572
5573 rettv->v_type = VAR_STRING;
5574 if (buf == NULL)
5575 return;
5576
5577 if (buf->b_term->tl_title != NULL)
5578 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5579}
5580
5581/*
5582 * "term_gettty(buf)" function
5583 */
5584 void
5585f_term_gettty(typval_T *argvars, typval_T *rettv)
5586{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005587 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005588 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005589 int num = 0;
5590
5591 rettv->v_type = VAR_STRING;
5592 if (buf == NULL)
5593 return;
5594 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005595 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005596
5597 switch (num)
5598 {
5599 case 0:
5600 if (buf->b_term->tl_job != NULL)
5601 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005602 break;
5603 case 1:
5604 if (buf->b_term->tl_job != NULL)
5605 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005606 break;
5607 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005608 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005609 return;
5610 }
5611 if (p != NULL)
5612 rettv->vval.v_string = vim_strsave(p);
5613}
5614
5615/*
5616 * "term_list()" function
5617 */
5618 void
5619f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5620{
5621 term_T *tp;
5622 list_T *l;
5623
5624 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5625 return;
5626
5627 l = rettv->vval.v_list;
5628 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5629 if (tp != NULL && tp->tl_buffer != NULL)
5630 if (list_append_number(l,
5631 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5632 return;
5633}
5634
5635/*
5636 * "term_scrape(buf, row)" function
5637 */
5638 void
5639f_term_scrape(typval_T *argvars, typval_T *rettv)
5640{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005641 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005642 VTermScreen *screen = NULL;
5643 VTermPos pos;
5644 list_T *l;
5645 term_T *term;
5646 char_u *p;
5647 sb_line_T *line;
5648
5649 if (rettv_list_alloc(rettv) == FAIL)
5650 return;
5651 if (buf == NULL)
5652 return;
5653 term = buf->b_term;
5654
5655 l = rettv->vval.v_list;
5656 pos.row = get_row_number(&argvars[1], term);
5657
5658 if (term->tl_vterm != NULL)
5659 {
5660 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005661 if (screen == NULL) // can't really happen
5662 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005663 p = NULL;
5664 line = NULL;
5665 }
5666 else
5667 {
5668 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5669
5670 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5671 return;
5672 p = ml_get_buf(buf, lnum + 1, FALSE);
5673 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5674 }
5675
5676 for (pos.col = 0; pos.col < term->tl_cols; )
5677 {
5678 dict_T *dcell;
5679 int width;
5680 VTermScreenCellAttrs attrs;
5681 VTermColor fg, bg;
5682 char_u rgb[8];
5683 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5684 int off = 0;
5685 int i;
5686
5687 if (screen == NULL)
5688 {
5689 cellattr_T *cellattr;
5690 int len;
5691
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005692 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005693 if (pos.col >= line->sb_cols)
5694 break;
5695 cellattr = line->sb_cells + pos.col;
5696 width = cellattr->width;
5697 attrs = cellattr->attrs;
5698 fg = cellattr->fg;
5699 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005700 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005701 mch_memmove(mbs, p, len);
5702 mbs[len] = NUL;
5703 p += len;
5704 }
5705 else
5706 {
5707 VTermScreenCell cell;
5708 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5709 break;
5710 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5711 {
5712 if (cell.chars[i] == 0)
5713 break;
5714 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5715 }
5716 mbs[off] = NUL;
5717 width = cell.width;
5718 attrs = cell.attrs;
5719 fg = cell.fg;
5720 bg = cell.bg;
5721 }
5722 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005723 if (dcell == NULL)
5724 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005725 list_append_dict(l, dcell);
5726
Bram Moolenaare0be1672018-07-08 16:50:37 +02005727 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005728
5729 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5730 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005731 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005732 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5733 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005734 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005735
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005736 dict_add_number(dcell, "attr", cell2attr(NULL, attrs, fg, bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02005737 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005738
5739 ++pos.col;
5740 if (width == 2)
5741 ++pos.col;
5742 }
5743}
5744
5745/*
5746 * "term_sendkeys(buf, keys)" function
5747 */
5748 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01005749f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005750{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005751 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005752 char_u *msg;
5753 term_T *term;
5754
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005755 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