blob: 1fdad2aeec310b808069f92db3edb801327429fc [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 Moolenaar83d47902020-03-26 20:34:00 +0100151 char_u *tl_highlight_name; // replaces "Terminal"; allocated
152
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200153 cellattr_T tl_default_color;
154
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100155 linenr_T tl_top_diff_rows; // rows of top diff file or zero
156 linenr_T tl_bot_diff_rows; // rows of bottom diff file
Bram Moolenaard96ff162018-02-18 22:13:29 +0100157
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200158 VTermPos tl_cursor_pos;
159 int tl_cursor_visible;
160 int tl_cursor_blink;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100161 int tl_cursor_shape; // 1: block, 2: underline, 3: bar
162 char_u *tl_cursor_color; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200163
164 int tl_using_altscreen;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200165 garray_T tl_osc_buf; // incomplete OSC string
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200166};
167
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100168#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
169#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200170
171/*
172 * List of all active terminals.
173 */
174static term_T *first_term = NULL;
175
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100176// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200177static term_T *in_terminal_loop = NULL;
178
Bram Moolenaar4f974752019-02-17 17:44:42 +0100179#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100180static BOOL has_winpty = FALSE;
181static BOOL has_conpty = FALSE;
182#endif
183
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100184#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200185#define KEY_BUF_LEN 200
186
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200187#define FOR_ALL_TERMS(term) \
188 for ((term) = first_term; (term) != NULL; (term) = (term)->tl_next)
189
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200190/*
191 * Functions with separate implementation for MS-Windows and Unix-like systems.
192 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200193static 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 +0200194static int create_pty_only(term_T *term, jobopt_T *opt);
195static void term_report_winsize(term_T *term, int rows, int cols);
196static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100197#ifdef FEAT_GUI
198static void update_system_term(term_T *term);
199#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200200
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100201static void handle_postponed_scrollback(term_T *term);
202
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100203// The character that we know (or assume) that the terminal expects for the
204// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200205static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200206
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100207// "Terminal" highlight group colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100208static int term_default_cterm_fg = -1;
209static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200210
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100211// Store the last set and the desired cursor properties, so that we only update
212// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200213static char_u *last_set_cursor_color = NULL;
214static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100215static int last_set_cursor_shape = -1;
216static int desired_cursor_shape = -1;
217static int last_set_cursor_blink = -1;
218static int desired_cursor_blink = -1;
219
220
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100221///////////////////////////////////////
222// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200223
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200224 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200225cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
226{
227 if (lhs_color != NULL && rhs_color != NULL)
228 return STRCMP(lhs_color, rhs_color) == 0;
229 return lhs_color == NULL && rhs_color == NULL;
230}
231
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200232 static void
233cursor_color_copy(char_u **to_color, char_u *from_color)
234{
235 // Avoid a free & alloc if the value is already right.
236 if (cursor_color_equal(*to_color, from_color))
237 return;
238 vim_free(*to_color);
239 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
240}
241
242 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200243cursor_color_get(char_u *color)
244{
245 return (color == NULL) ? (char_u *)"" : color;
246}
247
248
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200249/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200250 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200251 * current window.
252 * Sets "rows" and/or "cols" to zero when it should follow the window size.
253 * Return TRUE if the size is the minimum size: "24*80".
254 */
255 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200256parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200257{
258 int minsize = FALSE;
259
260 *rows = 0;
261 *cols = 0;
262
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200263 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200264 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200265 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200266
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100267 // Syntax of value was already checked when it's set.
Bram Moolenaar498c2562018-04-15 23:45:15 +0200268 if (p == NULL)
269 {
270 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200271 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200272 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200273 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200274 *cols = atoi((char *)p + 1);
275 }
276 return minsize;
277}
278
279/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200280 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200281 */
282 static void
283set_term_and_win_size(term_T *term)
284{
Bram Moolenaar13568252018-03-16 20:46:58 +0100285#ifdef FEAT_GUI
286 if (term->tl_system)
287 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100288 // Use the whole screen for the system command. However, it will start
289 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100290 term->tl_rows = Rows;
291 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200292 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100293 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100294#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200295 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200296 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200297 if (term->tl_rows != 0)
298 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
299 if (term->tl_cols != 0)
300 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200301 }
302 if (term->tl_rows == 0)
303 term->tl_rows = curwin->w_height;
304 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200305 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200306 if (term->tl_cols == 0)
307 term->tl_cols = curwin->w_width;
308 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200309 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200310}
311
312/*
313 * Initialize job options for a terminal job.
314 * Caller may overrule some of them.
315 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100316 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200317init_job_options(jobopt_T *opt)
318{
319 clear_job_options(opt);
320
321 opt->jo_mode = MODE_RAW;
322 opt->jo_out_mode = MODE_RAW;
323 opt->jo_err_mode = MODE_RAW;
324 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
325}
326
327/*
328 * Set job options mandatory for a terminal job.
329 */
330 static void
331setup_job_options(jobopt_T *opt, int rows, int cols)
332{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100333#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100334 // Win32: Redirecting the job output won't work, thus always connect stdout
335 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200336 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200337#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200338 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100339 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200340 opt->jo_io[PART_OUT] = JIO_BUFFER;
341 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
342 opt->jo_modifiable[PART_OUT] = 0;
343 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
344 }
345
Bram Moolenaar4f974752019-02-17 17:44:42 +0100346#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100347 // Win32: Redirecting the job output won't work, thus always connect stderr
348 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200349 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200350#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200351 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100352 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200353 opt->jo_io[PART_ERR] = JIO_BUFFER;
354 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
355 opt->jo_modifiable[PART_ERR] = 0;
356 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
357 }
358
359 opt->jo_pty = TRUE;
360 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
361 opt->jo_term_rows = rows;
362 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
363 opt->jo_term_cols = cols;
364}
365
366/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200367 * Flush messages on channels.
368 */
369 static void
370term_flush_messages()
371{
372 mch_check_messages();
373 parse_queued_messages();
374}
375
376/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100377 * Close a terminal buffer (and its window). Used when creating the terminal
378 * fails.
379 */
380 static void
381term_close_buffer(buf_T *buf, buf_T *old_curbuf)
382{
383 free_terminal(buf);
384 if (old_curbuf != NULL)
385 {
386 --curbuf->b_nwindows;
387 curbuf = old_curbuf;
388 curwin->w_buffer = curbuf;
389 ++curbuf->b_nwindows;
390 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100391 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100392
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100393 // Wiping out the buffer will also close the window and call
394 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100395 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
396}
397
398/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200399 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100400 * Use either "argvar" or "argv", the other must be NULL.
401 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
402 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200403 * Returns NULL when failed.
404 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100405 buf_T *
406term_start(
407 typval_T *argvar,
408 char **argv,
409 jobopt_T *opt,
410 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200411{
412 exarg_T split_ea;
413 win_T *old_curwin = curwin;
414 term_T *term;
415 buf_T *old_curbuf = NULL;
416 int res;
417 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100418 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200419 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200420
421 if (check_restricted() || check_secure())
422 return NULL;
423
424 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
425 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
426 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100427 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
428 || (argvar != NULL
429 && argvar->v_type == VAR_LIST
430 && argvar->vval.v_list != NULL
431 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200432 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100433 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200434 return NULL;
435 }
436
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200437 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200438 if (term == NULL)
439 return NULL;
440 term->tl_dirty_row_end = MAX_ROW;
441 term->tl_cursor_visible = TRUE;
442 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
443 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100444#ifdef FEAT_GUI
445 term->tl_system = (flags & TERM_START_SYSTEM);
446#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200447 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100448 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +0200449 ga_init2(&term->tl_osc_buf, sizeof(char), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200450
Bram Moolenaara80faa82020-04-12 19:37:17 +0200451 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200452 if (opt->jo_curwin)
453 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100454 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100455 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200456 {
457 no_write_message();
458 vim_free(term);
459 return NULL;
460 }
461 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100462 ECMD_HIDE
463 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
464 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200465 {
466 vim_free(term);
467 return NULL;
468 }
469 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100470 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200471 {
472 buf_T *buf;
473
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100474 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100475 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200476 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
477 BLN_NEW | BLN_LISTED);
478 if (buf == NULL || ml_open(buf) == FAIL)
479 {
480 vim_free(term);
481 return NULL;
482 }
483 old_curbuf = curbuf;
484 --curbuf->b_nwindows;
485 curbuf = buf;
486 curwin->w_buffer = buf;
487 ++curbuf->b_nwindows;
488 }
489 else
490 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100491 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200492 split_ea.cmdidx = CMD_new;
493 split_ea.cmd = (char_u *)"new";
494 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100495 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200496 {
497 split_ea.line2 = opt->jo_term_rows;
498 split_ea.addr_count = 1;
499 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100500 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200501 {
502 split_ea.line2 = opt->jo_term_cols;
503 split_ea.addr_count = 1;
504 }
505
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100506 if (vertical)
507 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200508 ex_splitview(&split_ea);
509 if (curwin == old_curwin)
510 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100511 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200512 vim_free(term);
513 return NULL;
514 }
515 }
516 term->tl_buffer = curbuf;
517 curbuf->b_term = term;
518
519 if (!opt->jo_hidden)
520 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100521 // Only one size was taken care of with :new, do the other one. With
522 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100523 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200524 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100525 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200526 win_setwidth(opt->jo_term_cols);
527 }
528
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100529 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200530 term->tl_next = first_term;
531 first_term = term;
532
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100533 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
534
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200535 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100536 {
537 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200538 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100539 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100540 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100541 {
542 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100543 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100544 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200545 else
546 {
547 int i;
548 size_t len;
549 char_u *cmd, *p;
550
551 if (argvar->v_type == VAR_STRING)
552 {
553 cmd = argvar->vval.v_string;
554 if (cmd == NULL)
555 cmd = (char_u *)"";
556 else if (STRCMP(cmd, "NONE") == 0)
557 cmd = (char_u *)"pty";
558 }
559 else if (argvar->v_type != VAR_LIST
560 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100561 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100562 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200563 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
564 cmd = (char_u*)"";
565
566 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200567 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568
569 for (i = 0; p != NULL; ++i)
570 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100571 // Prepend a ! to the command name to avoid the buffer name equals
572 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200573 if (i == 0)
574 vim_snprintf((char *)p, len, "!%s", cmd);
575 else
576 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
577 if (buflist_findname(p) == NULL)
578 {
579 vim_free(curbuf->b_ffname);
580 curbuf->b_ffname = p;
581 break;
582 }
583 }
584 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100585 vim_free(curbuf->b_sfname);
586 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200587 curbuf->b_fname = curbuf->b_ffname;
588
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100589 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
590
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200591 if (opt->jo_term_opencmd != NULL)
592 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
593
594 if (opt->jo_eof_chars != NULL)
595 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
596
597 set_string_option_direct((char_u *)"buftype", -1,
598 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200599 // Avoid that 'buftype' is reset when this buffer is entered.
600 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200601
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100602 // Mark the buffer as not modifiable. It can only be made modifiable after
603 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200604 curbuf->b_p_ma = FALSE;
605
606 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100607#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200608 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
609#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200610 setup_job_options(opt, term->tl_rows, term->tl_cols);
611
Bram Moolenaar13568252018-03-16 20:46:58 +0100612 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100613 return curbuf;
614
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100615#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100616 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100617 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100618 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100619 else if (argvar->v_type == VAR_STRING)
620 {
621 char_u *cmd = argvar->vval.v_string;
622
623 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
624 term->tl_command = vim_strsave(cmd);
625 }
626 else if (argvar->v_type == VAR_LIST
627 && argvar->vval.v_list != NULL
628 && argvar->vval.v_list->lv_len > 0)
629 {
630 garray_T ga;
631 listitem_T *item;
632
633 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200634 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100635 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100636 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100637 char_u *p;
638
639 if (s == NULL)
640 break;
641 p = vim_strsave_fnameescape(s, FALSE);
642 if (p == NULL)
643 break;
644 ga_concat(&ga, p);
645 vim_free(p);
646 ga_append(&ga, ' ');
647 }
648 if (item == NULL)
649 {
650 ga_append(&ga, NUL);
651 term->tl_command = ga.ga_data;
652 }
653 else
654 ga_clear(&ga);
655 }
656#endif
657
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100658 if (opt->jo_term_kill != NULL)
659 {
660 char_u *p = skiptowhite(opt->jo_term_kill);
661
662 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
663 }
664
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200665 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100666 {
667 char_u *p = skiptowhite(opt->jo_term_api);
668
669 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
670 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200671 else
672 term->tl_api = vim_strsave((char_u *)"Tapi_");
673
Bram Moolenaar83d47902020-03-26 20:34:00 +0100674 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
675 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
676
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100677 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100678 if (argv == NULL
679 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200680 && argvar->vval.v_string != NULL
681 && STRCMP(argvar->vval.v_string, "NONE") == 0)
682 res = create_pty_only(term, opt);
683 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200684 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200685
686 newbuf = curbuf;
687 if (res == OK)
688 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100689 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200690 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
691 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100692#ifdef FEAT_GUI
693 if (term->tl_system)
694 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100695 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100696 term->tl_toprow = msg_row + 1;
697 term->tl_dirty_row_end = 0;
698 }
699#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200700
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100701 // Make sure we don't get stuck on sending keys to the job, it leads to
702 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200703 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
704
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200705 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200706 {
707 --curbuf->b_nwindows;
708 curbuf = old_curbuf;
709 curwin->w_buffer = curbuf;
710 ++curbuf->b_nwindows;
711 }
712 }
713 else
714 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100715 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200716 return NULL;
717 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100718
Bram Moolenaar13568252018-03-16 20:46:58 +0100719 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200720 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
721 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200722 return newbuf;
723}
724
725/*
726 * ":terminal": open a terminal window and execute a job in it.
727 */
728 void
729ex_terminal(exarg_T *eap)
730{
731 typval_T argvar[2];
732 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100733 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200734 char_u *cmd;
735 char_u *tofree = NULL;
736
737 init_job_options(&opt);
738
739 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100740 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200741 {
742 char_u *p, *ep;
743
744 cmd += 2;
745 p = skiptowhite(cmd);
746 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200747 if (ep != NULL)
748 {
749 if (ep < p)
750 p = ep;
751 else
752 ep = NULL;
753 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200754
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200755# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
756 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
757 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200758 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200759 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100760 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200761 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200762 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200763 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200764 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200765 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200766 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200767 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100768 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100769 else if (OPTARG_HAS("shell"))
770 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200771 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100772 {
773 opt.jo_set2 |= JO2_TERM_KILL;
774 opt.jo_term_kill = ep + 1;
775 p = skiptowhite(cmd);
776 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200777 else if (OPTARG_HAS("api"))
778 {
779 opt.jo_set2 |= JO2_TERM_API;
780 if (ep != NULL)
781 {
782 opt.jo_term_api = ep + 1;
783 p = skiptowhite(cmd);
784 }
785 else
786 opt.jo_term_api = NULL;
787 }
788 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200789 {
790 opt.jo_set2 |= JO2_TERM_ROWS;
791 opt.jo_term_rows = atoi((char *)ep + 1);
792 p = skiptowhite(cmd);
793 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200794 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200795 {
796 opt.jo_set2 |= JO2_TERM_COLS;
797 opt.jo_term_cols = atoi((char *)ep + 1);
798 p = skiptowhite(cmd);
799 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200800 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200801 {
802 char_u *buf = NULL;
803 char_u *keys;
804
Bram Moolenaar21109272020-01-30 16:27:20 +0100805 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200806 p = skiptowhite(cmd);
807 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200808 keys = replace_termcodes(ep + 1, &buf,
809 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200810 opt.jo_set2 |= JO2_EOF_CHARS;
811 opt.jo_eof_chars = vim_strsave(keys);
812 vim_free(buf);
813 *p = ' ';
814 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100815#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100816 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
817 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100818 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100819 int tty_type = NUL;
820
821 p = skiptowhite(cmd);
822 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
823 tty_type = 'w';
824 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
825 tty_type = 'c';
826 else
827 {
828 semsg(e_invargval, "type");
829 goto theend;
830 }
831 opt.jo_set2 |= JO2_TTY_TYPE;
832 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100833 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100834#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200835 else
836 {
837 if (*p)
838 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100839 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100840 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200841 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200842# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200843 cmd = skipwhite(p);
844 }
845 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100846 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100847 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200848 tofree = cmd = vim_strsave(p_sh);
849
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100850 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100851 if (opt.jo_term_finish == NUL)
Bram Moolenaare2978022020-04-26 14:47:44 +0200852 opt.jo_term_finish = TL_FINISH_CLOSE;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100853 }
854
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200855 if (eap->addr_count > 0)
856 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100857 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200858 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
859 opt.jo_io[PART_IN] = JIO_BUFFER;
860 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
861 opt.jo_in_top = eap->line1;
862 opt.jo_in_bot = eap->line2;
863 }
864
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100865 if (opt_shell && tofree == NULL)
866 {
867#ifdef UNIX
868 char **argv = NULL;
869 char_u *tofree1 = NULL;
870 char_u *tofree2 = NULL;
871
872 // :term ++shell command
873 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
874 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100875 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100876 vim_free(tofree1);
877 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100878 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100879#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100880# ifdef MSWIN
881 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
882 char_u *newcmd;
883
884 newcmd = alloc(cmdlen);
885 if (newcmd == NULL)
886 goto theend;
887 tofree = newcmd;
888 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
889 cmd = newcmd;
890# else
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100891 emsg(_("E279: Sorry, ++shell is not supported on this system"));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100892 goto theend;
893# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100894#endif
895 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100896 argvar[0].v_type = VAR_STRING;
897 argvar[0].vval.v_string = cmd;
898 argvar[1].v_type = VAR_UNKNOWN;
899 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100900
901theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100902 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200903 vim_free(opt.jo_eof_chars);
904}
905
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100906#if defined(FEAT_SESSION) || defined(PROTO)
907/*
908 * Write a :terminal command to the session file to restore the terminal in
909 * window "wp".
910 * Return FAIL if writing fails.
911 */
912 int
913term_write_session(FILE *fd, win_T *wp)
914{
915 term_T *term = wp->w_buffer->b_term;
916
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100917 // Create the terminal and run the command. This is not without
918 // risk, but let's assume the user only creates a session when this
919 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100920 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
921 term->tl_cols, term->tl_rows) < 0)
922 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100923#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100924 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
925 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100926#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100927 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
928 return FAIL;
929
930 return put_eol(fd);
931}
932
933/*
934 * Return TRUE if "buf" has a terminal that should be restored.
935 */
936 int
937term_should_restore(buf_T *buf)
938{
939 term_T *term = buf->b_term;
940
941 return term != NULL && (term->tl_command == NULL
942 || STRCMP(term->tl_command, "NONE") != 0);
943}
944#endif
945
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200946/*
947 * Free the scrollback buffer for "term".
948 */
949 static void
950free_scrollback(term_T *term)
951{
952 int i;
953
954 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
955 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
956 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100957 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
958 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
959 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200960}
961
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100962
963// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200964static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100965
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200966/*
967 * Free a terminal and everything it refers to.
968 * Kills the job if there is one.
969 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100970 * The actual terminal structure is freed later in free_unused_terminals(),
971 * because callbacks may wipe out a buffer while the terminal is still
972 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200973 */
974 void
975free_terminal(buf_T *buf)
976{
977 term_T *term = buf->b_term;
978 term_T *tp;
979
980 if (term == NULL)
981 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100982
983 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200984 if (first_term == term)
985 first_term = term->tl_next;
986 else
987 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
988 if (tp->tl_next == term)
989 {
990 tp->tl_next = term->tl_next;
991 break;
992 }
993
994 if (term->tl_job != NULL)
995 {
996 if (term->tl_job->jv_status != JOB_ENDED
997 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100998 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200999 job_stop(term->tl_job, NULL, "kill");
1000 job_unref(term->tl_job);
1001 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001002 term->tl_next = terminals_to_free;
1003 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001004
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001005 buf->b_term = NULL;
1006 if (in_terminal_loop == term)
1007 in_terminal_loop = NULL;
1008}
1009
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001010 void
1011free_unused_terminals()
1012{
1013 while (terminals_to_free != NULL)
1014 {
1015 term_T *term = terminals_to_free;
1016
1017 terminals_to_free = term->tl_next;
1018
1019 free_scrollback(term);
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02001020 ga_clear(&term->tl_osc_buf);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001021
1022 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001023 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001024 vim_free(term->tl_title);
1025#ifdef FEAT_SESSION
1026 vim_free(term->tl_command);
1027#endif
1028 vim_free(term->tl_kill);
1029 vim_free(term->tl_status_text);
1030 vim_free(term->tl_opencmd);
1031 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001032 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001033#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001034 if (term->tl_out_fd != NULL)
1035 fclose(term->tl_out_fd);
1036#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001037 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001038 vim_free(term->tl_cursor_color);
1039 vim_free(term);
1040 }
1041}
1042
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001043/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001044 * Get the part that is connected to the tty. Normally this is PART_IN, but
1045 * when writing buffer lines to the job it can be another. This makes it
1046 * possible to do "1,5term vim -".
1047 */
1048 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001049get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001050{
1051#ifdef UNIX
1052 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1053 int i;
1054
1055 for (i = 0; i < 3; ++i)
1056 {
1057 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1058
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001059 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001060 return parts[i];
1061 }
1062#endif
1063 return PART_IN;
1064}
1065
1066/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001067 * Write job output "msg[len]" to the vterm.
1068 */
1069 static void
1070term_write_job_output(term_T *term, char_u *msg, size_t len)
1071{
1072 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001073 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001074
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001075 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001076
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001077 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001078 if (prevlen != vterm_output_get_buffer_current(vterm))
1079 {
1080 char buf[KEY_BUF_LEN];
1081 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1082
1083 if (curlen > 0)
1084 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1085 (char_u *)buf, (int)curlen, NULL);
1086 }
1087
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001088 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001089 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1090}
1091
1092 static void
1093update_cursor(term_T *term, int redraw)
1094{
1095 if (term->tl_normal_mode)
1096 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001097#ifdef FEAT_GUI
1098 if (term->tl_system)
1099 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1100 term->tl_cursor_pos.col);
1101 else
1102#endif
1103 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001104 if (redraw)
1105 {
1106 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1107 cursor_on();
1108 out_flush();
1109#ifdef FEAT_GUI
1110 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001111 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001112 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001113 gui_mch_flush();
1114 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001115#endif
1116 }
1117}
1118
1119/*
1120 * Invoked when "msg" output from a job was received. Write it to the terminal
1121 * of "buffer".
1122 */
1123 void
1124write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1125{
1126 size_t len = STRLEN(msg);
1127 term_T *term = buffer->b_term;
1128
Bram Moolenaar4f974752019-02-17 17:44:42 +01001129#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001130 // Win32: Cannot redirect output of the job, intercept it here and write to
1131 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001132 if (term->tl_out_fd != NULL)
1133 {
1134 ch_log(channel, "Writing %d bytes to output file", (int)len);
1135 fwrite(msg, len, 1, term->tl_out_fd);
1136 return;
1137 }
1138#endif
1139
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001140 if (term->tl_vterm == NULL)
1141 {
1142 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1143 return;
1144 }
1145 ch_log(channel, "writing %d bytes to terminal", (int)len);
1146 term_write_job_output(term, msg, len);
1147
Bram Moolenaar13568252018-03-16 20:46:58 +01001148#ifdef FEAT_GUI
1149 if (term->tl_system)
1150 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001151 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001152 update_system_term(term);
1153 update_cursor(term, TRUE);
1154 }
1155 else
1156#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001157 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1158 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001159 if (!term->tl_normal_mode)
1160 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001161 // Don't use update_screen() when editing the command line, it gets
1162 // cleared.
1163 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001164 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001165 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001166 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001167 update_screen(VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001168 // update_screen() can be slow, check the terminal wasn't closed
1169 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001170 if (buffer == curbuf && curbuf->b_term != NULL)
1171 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001172 }
1173 else
1174 redraw_after_callback(TRUE);
1175 }
1176}
1177
1178/*
1179 * Send a mouse position and click to the vterm
1180 */
1181 static int
1182term_send_mouse(VTerm *vterm, int button, int pressed)
1183{
1184 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001185 int row = mouse_row - W_WINROW(curwin);
1186 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001187
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001188#ifdef FEAT_PROP_POPUP
1189 if (popup_is_popup(curwin))
1190 {
1191 row -= popup_top_extra(curwin);
1192 col -= popup_left_extra(curwin);
1193 }
1194#endif
1195 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001196 if (button != 0)
1197 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001198 return TRUE;
1199}
1200
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001201static int enter_mouse_col = -1;
1202static int enter_mouse_row = -1;
1203
1204/*
1205 * Handle a mouse click, drag or release.
1206 * Return TRUE when a mouse event is sent to the terminal.
1207 */
1208 static int
1209term_mouse_click(VTerm *vterm, int key)
1210{
1211#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001212 // For modeless selection mouse drag and release events are ignored, unless
1213 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001214 static int ignore_drag_release = TRUE;
1215 VTermMouseState mouse_state;
1216
1217 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1218 if (mouse_state.flags == 0)
1219 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001220 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001221 switch (key)
1222 {
1223 case K_LEFTDRAG:
1224 case K_LEFTRELEASE:
1225 case K_RIGHTDRAG:
1226 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001227 // Ignore drag and release events when the button-down wasn't
1228 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001229 if (ignore_drag_release)
1230 {
1231 int save_mouse_col, save_mouse_row;
1232
1233 if (enter_mouse_col < 0)
1234 break;
1235
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001236 // mouse click in the window gave us focus, handle that
1237 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001238 save_mouse_col = mouse_col;
1239 save_mouse_row = mouse_row;
1240 mouse_col = enter_mouse_col;
1241 mouse_row = enter_mouse_row;
1242 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1243 mouse_col = save_mouse_col;
1244 mouse_row = save_mouse_row;
1245 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001246 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001247 case K_LEFTMOUSE:
1248 case K_RIGHTMOUSE:
1249 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1250 ignore_drag_release = TRUE;
1251 else
1252 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001253 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001254 if (clip_star.available)
1255 {
1256 int button, is_click, is_drag;
1257
1258 button = get_mouse_button(KEY2TERMCAP1(key),
1259 &is_click, &is_drag);
1260 if (mouse_model_popup() && button == MOUSE_LEFT
1261 && (mod_mask & MOD_MASK_SHIFT))
1262 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001263 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001264 button = MOUSE_RIGHT;
1265 mod_mask &= ~MOD_MASK_SHIFT;
1266 }
1267 clip_modeless(button, is_click, is_drag);
1268 }
1269 break;
1270
1271 case K_MIDDLEMOUSE:
1272 if (clip_star.available)
1273 insert_reg('*', TRUE);
1274 break;
1275 }
1276 enter_mouse_col = -1;
1277 return FALSE;
1278 }
1279#endif
1280 enter_mouse_col = -1;
1281
1282 switch (key)
1283 {
1284 case K_LEFTMOUSE:
1285 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1286 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1287 case K_LEFTRELEASE:
1288 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1289 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1290 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1291 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1292 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1293 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1294 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1295 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1296 }
1297 return TRUE;
1298}
1299
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001300/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001301 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1302 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001303 * Return the number of bytes in "buf".
1304 */
1305 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001306term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001307{
1308 VTerm *vterm = term->tl_vterm;
1309 VTermKey key = VTERM_KEY_NONE;
1310 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001311 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001312
1313 switch (c)
1314 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001315 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001316
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001317 // don't use VTERM_KEY_BACKSPACE, it always
1318 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001319 case K_BS: c = term_backspace_char; break;
1320
1321 case ESC: key = VTERM_KEY_ESCAPE; break;
1322 case K_DEL: key = VTERM_KEY_DEL; break;
1323 case K_DOWN: key = VTERM_KEY_DOWN; break;
1324 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1325 key = VTERM_KEY_DOWN; break;
1326 case K_END: key = VTERM_KEY_END; break;
1327 case K_S_END: mod = VTERM_MOD_SHIFT;
1328 key = VTERM_KEY_END; break;
1329 case K_C_END: mod = VTERM_MOD_CTRL;
1330 key = VTERM_KEY_END; break;
1331 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1332 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1333 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1334 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1335 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1336 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1337 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1338 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1339 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1340 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1341 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1342 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1343 case K_HOME: key = VTERM_KEY_HOME; break;
1344 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1345 key = VTERM_KEY_HOME; break;
1346 case K_C_HOME: mod = VTERM_MOD_CTRL;
1347 key = VTERM_KEY_HOME; break;
1348 case K_INS: key = VTERM_KEY_INS; break;
1349 case K_K0: key = VTERM_KEY_KP_0; break;
1350 case K_K1: key = VTERM_KEY_KP_1; break;
1351 case K_K2: key = VTERM_KEY_KP_2; break;
1352 case K_K3: key = VTERM_KEY_KP_3; break;
1353 case K_K4: key = VTERM_KEY_KP_4; break;
1354 case K_K5: key = VTERM_KEY_KP_5; break;
1355 case K_K6: key = VTERM_KEY_KP_6; break;
1356 case K_K7: key = VTERM_KEY_KP_7; break;
1357 case K_K8: key = VTERM_KEY_KP_8; break;
1358 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001359 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001360 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001361 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001362 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001363 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1364 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001365 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1366 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001367 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1368 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001369 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1370 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1371 case K_LEFT: key = VTERM_KEY_LEFT; break;
1372 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1373 key = VTERM_KEY_LEFT; break;
1374 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1375 key = VTERM_KEY_LEFT; break;
1376 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1377 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1378 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1379 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1380 key = VTERM_KEY_RIGHT; break;
1381 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1382 key = VTERM_KEY_RIGHT; break;
1383 case K_UP: key = VTERM_KEY_UP; break;
1384 case K_S_UP: mod = VTERM_MOD_SHIFT;
1385 key = VTERM_KEY_UP; break;
1386 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001387 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1388 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001389
Bram Moolenaara42ad572017-11-16 13:08:04 +01001390 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1391 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001392 case K_MOUSELEFT: /* TODO */ return 0;
1393 case K_MOUSERIGHT: /* TODO */ return 0;
1394
1395 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001396 case K_LEFTMOUSE_NM:
1397 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001398 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001399 case K_LEFTRELEASE_NM:
1400 case K_MOUSEMOVE:
1401 case K_MIDDLEMOUSE:
1402 case K_MIDDLEDRAG:
1403 case K_MIDDLERELEASE:
1404 case K_RIGHTMOUSE:
1405 case K_RIGHTDRAG:
1406 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1407 return 0;
1408 other = TRUE;
1409 break;
1410
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001411 case K_X1MOUSE: /* TODO */ return 0;
1412 case K_X1DRAG: /* TODO */ return 0;
1413 case K_X1RELEASE: /* TODO */ return 0;
1414 case K_X2MOUSE: /* TODO */ return 0;
1415 case K_X2DRAG: /* TODO */ return 0;
1416 case K_X2RELEASE: /* TODO */ return 0;
1417
1418 case K_IGNORE: return 0;
1419 case K_NOP: return 0;
1420 case K_UNDO: return 0;
1421 case K_HELP: return 0;
1422 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1423 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1424 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1425 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1426 case K_SELECT: return 0;
1427#ifdef FEAT_GUI
1428 case K_VER_SCROLLBAR: return 0;
1429 case K_HOR_SCROLLBAR: return 0;
1430#endif
1431#ifdef FEAT_GUI_TABLINE
1432 case K_TABLINE: return 0;
1433 case K_TABMENU: return 0;
1434#endif
1435#ifdef FEAT_NETBEANS_INTG
1436 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1437#endif
1438#ifdef FEAT_DND
1439 case K_DROP: return 0;
1440#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001441 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001442 case K_PS: vterm_keyboard_start_paste(vterm);
1443 other = TRUE;
1444 break;
1445 case K_PE: vterm_keyboard_end_paste(vterm);
1446 other = TRUE;
1447 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001448 }
1449
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001450 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001451 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001452 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001453 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001454 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001455 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001456 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001457
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001458 /*
1459 * Convert special keys to vterm keys:
1460 * - Write keys to vterm: vterm_keyboard_key()
1461 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001462 */
1463 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001464 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001465 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001466 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001467 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001468 vterm_keyboard_unichar(vterm, c, mod);
1469
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001470 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001471 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1472}
1473
1474/*
1475 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001476 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001477 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001478 */
1479 static int
1480term_job_running_check(term_T *term, int check_job_status)
1481{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001482 // Also consider the job finished when the channel is closed, to avoid a
1483 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001484 if (term != NULL
1485 && term->tl_job != NULL
1486 && channel_is_open(term->tl_job->jv_channel))
1487 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001488 job_T *job = term->tl_job;
1489
1490 // Careful: Checking the job status may invoked callbacks, which close
1491 // the buffer and terminate "term". However, "job" will not be freed
1492 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001493 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001494 job_status(job);
1495 return (job->jv_status == JOB_STARTED
1496 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001497 }
1498 return FALSE;
1499}
1500
1501/*
1502 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001503 */
1504 int
1505term_job_running(term_T *term)
1506{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001507 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001508}
1509
1510/*
1511 * Return TRUE if "term" has an active channel and used ":term NONE".
1512 */
1513 int
1514term_none_open(term_T *term)
1515{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001516 // Also consider the job finished when the channel is closed, to avoid a
1517 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001518 return term != NULL
1519 && term->tl_job != NULL
1520 && channel_is_open(term->tl_job->jv_channel)
1521 && term->tl_job->jv_channel->ch_keep_open;
1522}
1523
1524/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001525 * Used when exiting: kill the job in "buf" if so desired.
1526 * Return OK when the job finished.
1527 * Return FAIL when the job is still running.
1528 */
1529 int
1530term_try_stop_job(buf_T *buf)
1531{
1532 int count;
1533 char *how = (char *)buf->b_term->tl_kill;
1534
1535#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1536 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1537 {
1538 char_u buff[DIALOG_MSG_SIZE];
1539 int ret;
1540
1541 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1542 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1543 if (ret == VIM_YES)
1544 how = "kill";
1545 else if (ret == VIM_CANCEL)
1546 return FAIL;
1547 }
1548#endif
1549 if (how == NULL || *how == NUL)
1550 return FAIL;
1551
1552 job_stop(buf->b_term->tl_job, NULL, how);
1553
Bram Moolenaar9172d232019-01-29 23:06:54 +01001554 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001555 for (count = 0; count < 100; ++count)
1556 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001557 job_T *job;
1558
1559 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001560 if (!buf_valid(buf)
1561 || buf->b_term == NULL
1562 || buf->b_term->tl_job == NULL)
1563 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001564 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001565
Bram Moolenaar9172d232019-01-29 23:06:54 +01001566 // Call job_status() to update jv_status. It may cause the job to be
1567 // cleaned up but it won't be freed.
1568 job_status(job);
1569 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001570 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001571
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001572 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001573 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001574 }
1575 return FAIL;
1576}
1577
1578/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001579 * Add the last line of the scrollback buffer to the buffer in the window.
1580 */
1581 static void
1582add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1583{
1584 buf_T *buf = term->tl_buffer;
1585 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1586 linenr_T lnum = buf->b_ml.ml_line_count;
1587
Bram Moolenaar4f974752019-02-17 17:44:42 +01001588#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001589 if (!enc_utf8 && enc_codepage > 0)
1590 {
1591 WCHAR *ret = NULL;
1592 int length = 0;
1593
1594 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1595 &ret, &length);
1596 if (ret != NULL)
1597 {
1598 WideCharToMultiByte_alloc(enc_codepage, 0,
1599 ret, length, (char **)&text, &len, 0, 0);
1600 vim_free(ret);
1601 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1602 vim_free(text);
1603 }
1604 }
1605 else
1606#endif
1607 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1608 if (empty)
1609 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001610 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001611 curbuf = buf;
1612 ml_delete(1, FALSE);
1613 curbuf = curwin->w_buffer;
1614 }
1615}
1616
1617 static void
1618cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1619{
1620 attr->width = cell->width;
1621 attr->attrs = cell->attrs;
1622 attr->fg = cell->fg;
1623 attr->bg = cell->bg;
1624}
1625
1626 static int
1627equal_celattr(cellattr_T *a, cellattr_T *b)
1628{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001629 // Comparing the colors should be sufficient.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001630 return a->fg.red == b->fg.red
1631 && a->fg.green == b->fg.green
1632 && a->fg.blue == b->fg.blue
1633 && a->bg.red == b->bg.red
1634 && a->bg.green == b->bg.green
1635 && a->bg.blue == b->bg.blue;
1636}
1637
Bram Moolenaard96ff162018-02-18 22:13:29 +01001638/*
1639 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1640 * line at this position. Otherwise at the end.
1641 */
1642 static int
1643add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1644{
1645 if (ga_grow(&term->tl_scrollback, 1) == OK)
1646 {
1647 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1648 + term->tl_scrollback.ga_len;
1649
1650 if (lnum > 0)
1651 {
1652 int i;
1653
1654 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1655 {
1656 *line = *(line - 1);
1657 --line;
1658 }
1659 }
1660 line->sb_cols = 0;
1661 line->sb_cells = NULL;
1662 line->sb_fill_attr = *fill_attr;
1663 ++term->tl_scrollback.ga_len;
1664 return OK;
1665 }
1666 return FALSE;
1667}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001668
1669/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001670 * Remove the terminal contents from the scrollback and the buffer.
1671 * Used before adding a new scrollback line or updating the buffer for lines
1672 * displayed in the terminal.
1673 */
1674 static void
1675cleanup_scrollback(term_T *term)
1676{
1677 sb_line_T *line;
1678 garray_T *gap;
1679
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001680 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001681 gap = &term->tl_scrollback;
1682 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1683 && gap->ga_len > 0)
1684 {
1685 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1686 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1687 vim_free(line->sb_cells);
1688 --gap->ga_len;
1689 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001690 curbuf = curwin->w_buffer;
1691 if (curbuf == term->tl_buffer)
1692 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001693}
1694
1695/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001696 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001697 */
1698 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001699update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001700{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001701 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001702 int len;
1703 int lines_skipped = 0;
1704 VTermPos pos;
1705 VTermScreenCell cell;
1706 cellattr_T fill_attr, new_fill_attr;
1707 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001708
1709 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1710 "Adding terminal window snapshot to buffer");
1711
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001712 // First remove the lines that were appended before, they might be
1713 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001714 cleanup_scrollback(term);
1715
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001716 screen = vterm_obtain_screen(term->tl_vterm);
1717 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001718 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1719 {
1720 len = 0;
1721 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1722 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1723 && cell.chars[0] != NUL)
1724 {
1725 len = pos.col + 1;
1726 new_fill_attr = term->tl_default_color;
1727 }
1728 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001729 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001730 cell2cellattr(&cell, &new_fill_attr);
1731
1732 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1733 ++lines_skipped;
1734 else
1735 {
1736 while (lines_skipped > 0)
1737 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001738 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001739 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001740 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001741 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001742 }
1743
1744 if (len == 0)
1745 p = NULL;
1746 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001747 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001748 if ((p != NULL || len == 0)
1749 && ga_grow(&term->tl_scrollback, 1) == OK)
1750 {
1751 garray_T ga;
1752 int width;
1753 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1754 + term->tl_scrollback.ga_len;
1755
1756 ga_init2(&ga, 1, 100);
1757 for (pos.col = 0; pos.col < len; pos.col += width)
1758 {
1759 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1760 {
1761 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02001762 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001763 if (ga_grow(&ga, 1) == OK)
1764 ga.ga_len += utf_char2bytes(' ',
1765 (char_u *)ga.ga_data + ga.ga_len);
1766 }
1767 else
1768 {
1769 width = cell.width;
1770
1771 cell2cellattr(&cell, &p[pos.col]);
1772
Bram Moolenaara79fd562018-12-20 20:47:32 +01001773 // Each character can be up to 6 bytes.
1774 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001775 {
1776 int i;
1777 int c;
1778
1779 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1780 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1781 (char_u *)ga.ga_data + ga.ga_len);
1782 }
1783 }
1784 }
1785 line->sb_cols = len;
1786 line->sb_cells = p;
1787 line->sb_fill_attr = new_fill_attr;
1788 fill_attr = new_fill_attr;
1789 ++term->tl_scrollback.ga_len;
1790
1791 if (ga_grow(&ga, 1) == FAIL)
1792 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1793 else
1794 {
1795 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1796 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1797 }
1798 ga_clear(&ga);
1799 }
1800 else
1801 vim_free(p);
1802 }
1803 }
1804
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001805 // Add trailing empty lines.
1806 for (pos.row = term->tl_scrollback.ga_len;
1807 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1808 ++pos.row)
1809 {
1810 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1811 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1812 }
1813
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001814 term->tl_dirty_snapshot = FALSE;
1815#ifdef FEAT_TIMERS
1816 term->tl_timer_set = FALSE;
1817#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001818}
1819
1820/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001821 * Loop over all windows in the current tab, and also curwin, which is not
1822 * encountered when using a terminal in a popup window.
1823 * Return TRUE if "*wp" was set to the next window.
1824 */
1825 static int
1826for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1827{
1828 if (*wp == NULL)
1829 *wp = firstwin;
1830 else if ((*wp)->w_next != NULL)
1831 *wp = (*wp)->w_next;
1832 else if (!*did_curwin)
1833 *wp = curwin;
1834 else
1835 return FALSE;
1836 if (*wp == curwin)
1837 *did_curwin = TRUE;
1838 return TRUE;
1839}
1840
1841/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001842 * If needed, add the current lines of the terminal to scrollback and to the
1843 * buffer. Called after the job has ended and when switching to
1844 * Terminal-Normal mode.
1845 * When "redraw" is TRUE redraw the windows that show the terminal.
1846 */
1847 static void
1848may_move_terminal_to_buffer(term_T *term, int redraw)
1849{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001850 if (term->tl_vterm == NULL)
1851 return;
1852
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001853 // Update the snapshot only if something changes or the buffer does not
1854 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001855 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1856 <= term->tl_scrollback_scrolled)
1857 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001858
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001859 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001860 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1861 &term->tl_default_color.fg, &term->tl_default_color.bg);
1862
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001863 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001864 {
1865 win_T *wp = NULL;
1866 int did_curwin = FALSE;
1867
1868 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001869 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001870 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001871 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001872 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1873 wp->w_cursor.col = 0;
1874 wp->w_valid = 0;
1875 if (wp->w_cursor.lnum >= wp->w_height)
1876 {
1877 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001878
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001879 if (wp->w_topline < min_topline)
1880 wp->w_topline = min_topline;
1881 }
1882 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001883 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001884 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001885 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001886}
1887
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001888#if defined(FEAT_TIMERS) || defined(PROTO)
1889/*
1890 * Check if any terminal timer expired. If so, copy text from the terminal to
1891 * the buffer.
1892 * Return the time until the next timer will expire.
1893 */
1894 int
1895term_check_timers(int next_due_arg, proftime_T *now)
1896{
1897 term_T *term;
1898 int next_due = next_due_arg;
1899
Bram Moolenaaraeea7212020-04-02 18:50:46 +02001900 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001901 {
1902 if (term->tl_timer_set && !term->tl_normal_mode)
1903 {
1904 long this_due = proftime_time_left(&term->tl_timer_due, now);
1905
1906 if (this_due <= 1)
1907 {
1908 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001909 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001910 }
1911 else if (next_due == -1 || next_due > this_due)
1912 next_due = this_due;
1913 }
1914 }
1915
1916 return next_due;
1917}
1918#endif
1919
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001920/*
1921 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1922 * otherwise end it.
1923 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001924 static void
1925set_terminal_mode(term_T *term, int normal_mode)
1926{
1927 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001928 if (!normal_mode)
1929 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001930 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001931 if (term->tl_buffer == curbuf)
1932 maketitle();
1933}
1934
1935/*
Bram Moolenaare2978022020-04-26 14:47:44 +02001936 * Called after the job is finished and Terminal mode is not active:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001937 * Move the vterm contents into the scrollback buffer and free the vterm.
1938 */
1939 static void
1940cleanup_vterm(term_T *term)
1941{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001942 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001943 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001944 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001945 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001946}
1947
1948/*
1949 * Switch from Terminal-Job mode to Terminal-Normal mode.
1950 * Suspends updating the terminal window.
1951 */
1952 static void
1953term_enter_normal_mode(void)
1954{
1955 term_T *term = curbuf->b_term;
1956
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001957 set_terminal_mode(term, TRUE);
1958
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001959 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001960 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001961
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001962 // Move the window cursor to the position of the cursor in the
1963 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001964 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1965 + term->tl_cursor_pos.row + 1;
1966 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001967 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1968 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001969 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001970
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001971 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001972 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1973}
1974
1975/*
1976 * Returns TRUE if the current window contains a terminal and we are in
1977 * Terminal-Normal mode.
1978 */
1979 int
1980term_in_normal_mode(void)
1981{
1982 term_T *term = curbuf->b_term;
1983
1984 return term != NULL && term->tl_normal_mode;
1985}
1986
1987/*
1988 * Switch from Terminal-Normal mode to Terminal-Job mode.
1989 * Restores updating the terminal window.
1990 */
1991 void
1992term_enter_job_mode()
1993{
1994 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001995
1996 set_terminal_mode(term, FALSE);
1997
1998 if (term->tl_channel_closed)
1999 cleanup_vterm(term);
2000 redraw_buf_and_status_later(curbuf, NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002001#ifdef FEAT_PROP_POPUP
2002 if (WIN_IS_POPUP(curwin))
Bram Moolenaard5bc32d2020-03-22 19:25:50 +01002003 redraw_later(NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002004#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002005}
2006
2007/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002008 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002009 * Note: while waiting a terminal may be closed and freed if the channel is
2010 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 */
2012 static int
2013term_vgetc()
2014{
2015 int c;
2016 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002017 int modify_other_keys =
2018 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002019
2020 State = TERMINAL;
2021 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002022#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002023 ctrl_break_was_pressed = FALSE;
2024#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002025 if (modify_other_keys)
2026 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002027 c = vgetc();
2028 got_int = FALSE;
2029 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002030 if (modify_other_keys)
2031 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002032 return c;
2033}
2034
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002035static int mouse_was_outside = FALSE;
2036
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002037/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002038 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002039 * Return FAIL when the key needs to be handled in Normal mode.
2040 * Return OK when the key was dropped or sent to the terminal.
2041 */
2042 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002043send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002044{
2045 char msg[KEY_BUF_LEN];
2046 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002047 int dragging_outside = FALSE;
2048
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002049 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002050 switch (c)
2051 {
2052 case NUL:
2053 case K_ZERO:
2054 if (typed)
2055 stuffcharReadbuff(c);
2056 return FAIL;
2057
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002058 case K_TABLINE:
2059 stuffcharReadbuff(c);
2060 return FAIL;
2061
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002062 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002063 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002064 return FAIL;
2065
2066 case K_LEFTDRAG:
2067 case K_MIDDLEDRAG:
2068 case K_RIGHTDRAG:
2069 case K_X1DRAG:
2070 case K_X2DRAG:
2071 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002072 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002073 case K_LEFTMOUSE:
2074 case K_LEFTMOUSE_NM:
2075 case K_LEFTRELEASE:
2076 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002077 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002078 case K_MIDDLEMOUSE:
2079 case K_MIDDLERELEASE:
2080 case K_RIGHTMOUSE:
2081 case K_RIGHTRELEASE:
2082 case K_X1MOUSE:
2083 case K_X1RELEASE:
2084 case K_X2MOUSE:
2085 case K_X2RELEASE:
2086
2087 case K_MOUSEUP:
2088 case K_MOUSEDOWN:
2089 case K_MOUSELEFT:
2090 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002091 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002092 int row = mouse_row;
2093 int col = mouse_col;
2094
2095#ifdef FEAT_PROP_POPUP
2096 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002097 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002098 row -= popup_top_extra(curwin);
2099 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002100 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002101#endif
2102 if (row < W_WINROW(curwin)
2103 || row >= (W_WINROW(curwin) + curwin->w_height)
2104 || col < curwin->w_wincol
2105 || col >= W_ENDCOL(curwin)
2106 || dragging_outside)
2107 {
2108 // click or scroll outside the current window or on status
2109 // line or vertical separator
2110 if (typed)
2111 {
2112 stuffcharReadbuff(c);
2113 mouse_was_outside = TRUE;
2114 }
2115 return FAIL;
2116 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002117 }
2118 }
2119 if (typed)
2120 mouse_was_outside = FALSE;
2121
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002122 // Convert the typed key to a sequence of bytes for the job.
2123 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002124 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002125 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002126 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2127 (char_u *)msg, (int)len, NULL);
2128
2129 return OK;
2130}
2131
2132 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002133position_cursor(win_T *wp, VTermPos *pos, int add_off UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002134{
2135 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2136 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002137#ifdef FEAT_PROP_POPUP
2138 if (add_off && popup_is_popup(curwin))
2139 {
2140 wp->w_wrow += popup_top_extra(curwin);
2141 wp->w_wcol += popup_left_extra(curwin);
2142 }
2143#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002144 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2145}
2146
2147/*
2148 * Handle CTRL-W "": send register contents to the job.
2149 */
2150 static void
2151term_paste_register(int prev_c UNUSED)
2152{
2153 int c;
2154 list_T *l;
2155 listitem_T *item;
2156 long reglen = 0;
2157 int type;
2158
2159#ifdef FEAT_CMDL_INFO
2160 if (add_to_showcmd(prev_c))
2161 if (add_to_showcmd('"'))
2162 out_flush();
2163#endif
2164 c = term_vgetc();
2165#ifdef FEAT_CMDL_INFO
2166 clear_showcmd();
2167#endif
2168 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002169 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002170 return;
2171
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002172 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002173 if (c == '=' && get_expr_register() != '=')
2174 return;
2175 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002176 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002177 return;
2178
2179 l = (list_T *)get_reg_contents(c, GREG_LIST);
2180 if (l != NULL)
2181 {
2182 type = get_reg_type(c, &reglen);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002183 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002184 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002185 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002186#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002187 char_u *tmp = s;
2188
2189 if (!enc_utf8 && enc_codepage > 0)
2190 {
2191 WCHAR *ret = NULL;
2192 int length = 0;
2193
2194 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2195 (int)STRLEN(s), &ret, &length);
2196 if (ret != NULL)
2197 {
2198 WideCharToMultiByte_alloc(CP_UTF8, 0,
2199 ret, length, (char **)&s, &length, 0, 0);
2200 vim_free(ret);
2201 }
2202 }
2203#endif
2204 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2205 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002206#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002207 if (tmp != s)
2208 vim_free(s);
2209#endif
2210
2211 if (item->li_next != NULL || type == MLINE)
2212 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2213 (char_u *)"\r", 1, NULL);
2214 }
2215 list_free(l);
2216 }
2217}
2218
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002219/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002220 * Return TRUE when waiting for a character in the terminal, the cursor of the
2221 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002222 */
2223 int
2224terminal_is_active()
2225{
2226 return in_terminal_loop != NULL;
2227}
2228
Bram Moolenaar83d47902020-03-26 20:34:00 +01002229/*
2230 * Return the highight group name for the terminal; "Terminal" if not set.
2231 */
2232 static char_u *
2233term_get_highlight_name(term_T *term)
2234{
2235 if (term->tl_highlight_name == NULL)
2236 return (char_u *)"Terminal";
2237 return term->tl_highlight_name;
2238}
2239
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002240#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002241 cursorentry_T *
2242term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2243{
2244 term_T *term = in_terminal_loop;
2245 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002246 int id;
2247 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002248
Bram Moolenaara80faa82020-04-12 19:37:17 +02002249 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002250 entry.shape = entry.mshape =
2251 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2252 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2253 SHAPE_BLOCK;
2254 entry.percentage = 20;
2255 if (term->tl_cursor_blink)
2256 {
2257 entry.blinkwait = 700;
2258 entry.blinkon = 400;
2259 entry.blinkoff = 250;
2260 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002261
Bram Moolenaar83d47902020-03-26 20:34:00 +01002262 // The highlight group overrules the defaults.
2263 id = syn_name2id(term_get_highlight_name(term));
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002264 if (id != 0)
2265 {
2266 syn_id2colors(id, &term_fg, &term_bg);
2267 *fg = term_bg;
2268 }
2269 else
2270 *fg = gui.back_pixel;
2271
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002272 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002273 {
2274 if (id != 0)
2275 *bg = term_fg;
2276 else
2277 *bg = gui.norm_pixel;
2278 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002279 else
2280 *bg = color_name2handle(term->tl_cursor_color);
2281 entry.name = "n";
2282 entry.used_for = SHAPE_CURSOR;
2283
2284 return &entry;
2285}
2286#endif
2287
Bram Moolenaard317b382018-02-08 22:33:31 +01002288 static void
2289may_output_cursor_props(void)
2290{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002291 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002292 || last_set_cursor_shape != desired_cursor_shape
2293 || last_set_cursor_blink != desired_cursor_blink)
2294 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002295 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002296 last_set_cursor_shape = desired_cursor_shape;
2297 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002298 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002299 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002300 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002301 ui_cursor_shape_forced(TRUE);
2302 else
2303 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2304 }
2305}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002306
Bram Moolenaard317b382018-02-08 22:33:31 +01002307/*
2308 * Set the cursor color and shape, if not last set to these.
2309 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002310 static void
2311may_set_cursor_props(term_T *term)
2312{
2313#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002314 // For the GUI the cursor properties are obtained with
2315 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002316 if (gui.in_use)
2317 return;
2318#endif
2319 if (in_terminal_loop == term)
2320 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002321 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002322 desired_cursor_shape = term->tl_cursor_shape;
2323 desired_cursor_blink = term->tl_cursor_blink;
2324 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002325 }
2326}
2327
Bram Moolenaard317b382018-02-08 22:33:31 +01002328/*
2329 * Reset the desired cursor properties and restore them when needed.
2330 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002331 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002332prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002333{
2334#ifdef FEAT_GUI
2335 if (gui.in_use)
2336 return;
2337#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002338 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002339 desired_cursor_shape = -1;
2340 desired_cursor_blink = -1;
2341 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002342}
2343
2344/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002345 * Returns TRUE if the current window contains a terminal and we are sending
2346 * keys to the job.
2347 * If "check_job_status" is TRUE update the job status.
2348 */
2349 static int
2350term_use_loop_check(int check_job_status)
2351{
2352 term_T *term = curbuf->b_term;
2353
2354 return term != NULL
2355 && !term->tl_normal_mode
2356 && term->tl_vterm != NULL
2357 && term_job_running_check(term, check_job_status);
2358}
2359
2360/*
2361 * Returns TRUE if the current window contains a terminal and we are sending
2362 * keys to the job.
2363 */
2364 int
2365term_use_loop(void)
2366{
2367 return term_use_loop_check(FALSE);
2368}
2369
2370/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002371 * Called when entering a window with the mouse. If this is a terminal window
2372 * we may want to change state.
2373 */
2374 void
2375term_win_entered()
2376{
2377 term_T *term = curbuf->b_term;
2378
2379 if (term != NULL)
2380 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002381 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002382 {
2383 reset_VIsual_and_resel();
2384 if (State & INSERT)
2385 stop_insert_mode = TRUE;
2386 }
2387 mouse_was_outside = FALSE;
2388 enter_mouse_col = mouse_col;
2389 enter_mouse_row = mouse_row;
2390 }
2391}
2392
2393/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002394 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2395 * Return the Ctrl-key value in that case.
2396 */
2397 static int
2398raw_c_to_ctrl(int c)
2399{
2400 if ((mod_mask & MOD_MASK_CTRL)
2401 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2402 return c & 0x1f;
2403 return c;
2404}
2405
2406/*
2407 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2408 * May set "mod_mask".
2409 */
2410 static int
2411ctrl_to_raw_c(int c)
2412{
2413 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2414 {
2415 mod_mask |= MOD_MASK_CTRL;
2416 return c + '@';
2417 }
2418 return c;
2419}
2420
2421/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002422 * Wait for input and send it to the job.
2423 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2424 * when there is no more typahead.
2425 * Return when the start of a CTRL-W command is typed or anything else that
2426 * should be handled as a Normal mode command.
2427 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2428 * the terminal was closed.
2429 */
2430 int
2431terminal_loop(int blocking)
2432{
2433 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002434 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002435 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002436 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002437#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002438 int tty_fd = curbuf->b_term->tl_job->jv_channel
2439 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002440#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002441 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002442
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002443 // Remember the terminal we are sending keys to. However, the terminal
2444 // might be closed while waiting for a character, e.g. typing "exit" in a
2445 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2446 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002447 in_terminal_loop = curbuf->b_term;
2448
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002449 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002450 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002451 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002452 if (termwinkey == Ctrl_W)
2453 termwinkey = 0;
2454 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002455 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002456 may_set_cursor_props(curbuf->b_term);
2457
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002458 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002459 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002460#ifdef FEAT_GUI
2461 if (!curbuf->b_term->tl_system)
2462#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002463 // TODO: skip screen update when handling a sequence of keys.
2464 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002465 while (must_redraw != 0)
2466 if (update_screen(0) == FAIL)
2467 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002468 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002469 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002470 break;
2471
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002472 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002473 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002474
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002475 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002476 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002477 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002478 // Job finished while waiting for a character. Push back the
2479 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002480 if (raw_c != K_IGNORE)
2481 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002482 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002483 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002484 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002485 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002486 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002487
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002488#ifdef UNIX
2489 /*
2490 * The shell or another program may change the tty settings. Getting
2491 * them for every typed character is a bit of overhead, but it's needed
2492 * for the first character typed, e.g. when Vim starts in a shell.
2493 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002494 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002495 {
2496 ttyinfo_T info;
2497
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002498 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002499 if (get_tty_info(tty_fd, &info) == OK)
2500 term_backspace_char = info.backspace;
2501 }
2502#endif
2503
Bram Moolenaar4f974752019-02-17 17:44:42 +01002504#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002505 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2506 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002507 if (ctrl_break_was_pressed)
2508 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2509#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002510 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2511 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002512 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002513#ifdef FEAT_GUI
2514 && !curbuf->b_term->tl_system
2515#endif
2516 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002517 {
2518 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002519 int prev_raw_c = raw_c;
2520 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002521
2522#ifdef FEAT_CMDL_INFO
2523 if (add_to_showcmd(c))
2524 out_flush();
2525#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002526 raw_c = term_vgetc();
2527 c = raw_c_to_ctrl(raw_c);
2528
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002529#ifdef FEAT_CMDL_INFO
2530 clear_showcmd();
2531#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002532 if (!term_use_loop_check(TRUE)
2533 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002534 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002535 break;
2536
2537 if (prev_c == Ctrl_BSL)
2538 {
2539 if (c == Ctrl_N)
2540 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002541 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002542 term_enter_normal_mode();
2543 ret = FAIL;
2544 goto theend;
2545 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002546 // Send both keys to the terminal, first one here, second one
2547 // below.
2548 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2549 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002550 }
2551 else if (c == Ctrl_C)
2552 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002553 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002554 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2555 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002556 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002557 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002558 // "CTRL-W .": send CTRL-W to the job
2559 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002560 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002561 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002562 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002563 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002564 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002565 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002566 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002567 else if (c == 'N')
2568 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002569 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002570 term_enter_normal_mode();
2571 ret = FAIL;
2572 goto theend;
2573 }
2574 else if (c == '"')
2575 {
2576 term_paste_register(prev_c);
2577 continue;
2578 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002579 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002580 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002581 char_u buf[MB_MAXBYTES + 2];
2582
2583 // Put the command into the typeahead buffer, when using the
2584 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2585 buf[0] = Ctrl_W;
2586 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2587 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002588 ret = OK;
2589 goto theend;
2590 }
2591 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002592# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002593 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002594 {
2595 WCHAR wc;
2596 char_u mb[3];
2597
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002598 mb[0] = (unsigned)raw_c >> 8;
2599 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002600 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002601 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002602 }
2603# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002604 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002605 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002606 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002607 // We are sure to come back here, don't reset the cursor color
2608 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002609 restore_cursor = FALSE;
2610
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002611 ret = OK;
2612 goto theend;
2613 }
2614 }
2615 ret = FAIL;
2616
2617theend:
2618 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002619 if (restore_cursor)
2620 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002621
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002622 // Move a snapshot of the screen contents to the buffer, so that completion
2623 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002624 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2625 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002626
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002627 return ret;
2628}
2629
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002630 static void
2631may_toggle_cursor(term_T *term)
2632{
2633 if (in_terminal_loop == term)
2634 {
2635 if (term->tl_cursor_visible)
2636 cursor_on();
2637 else
2638 cursor_off();
2639 }
2640}
2641
2642/*
Bram Moolenaar83d47902020-03-26 20:34:00 +01002643 * Cache "Terminal" highlight group colors.
2644 */
2645 void
2646set_terminal_default_colors(int cterm_fg, int cterm_bg)
2647{
2648 term_default_cterm_fg = cterm_fg - 1;
2649 term_default_cterm_bg = cterm_bg - 1;
2650}
2651
2652 static int
2653get_default_cterm_fg(term_T *term)
2654{
2655 if (term->tl_highlight_name != NULL)
2656 {
2657 int id = syn_name2id(term->tl_highlight_name);
2658 int fg = -1;
2659 int bg = -1;
2660
2661 if (id > 0)
2662 syn_id2cterm_bg(id, &fg, &bg);
2663 return fg;
2664 }
2665 return term_default_cterm_fg;
2666}
2667
2668 static int
2669get_default_cterm_bg(term_T *term)
2670{
2671 if (term->tl_highlight_name != NULL)
2672 {
2673 int id = syn_name2id(term->tl_highlight_name);
2674 int fg = -1;
2675 int bg = -1;
2676
2677 if (id > 0)
2678 syn_id2cterm_bg(id, &fg, &bg);
2679 return bg;
2680 }
2681 return term_default_cterm_bg;
2682}
2683
2684/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002685 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002686 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002687 */
2688 static int
2689color2index(VTermColor *color, int fg, int *boldp)
2690{
2691 int red = color->red;
2692 int blue = color->blue;
2693 int green = color->green;
2694
Bram Moolenaar46359e12017-11-29 22:33:38 +01002695 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002696 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002697 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002698 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002699 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002700 case 0: return 0;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002701 case 1: return lookup_color( 0, fg, boldp) + 1; // black
2702 case 2: return lookup_color( 4, fg, boldp) + 1; // dark red
2703 case 3: return lookup_color( 2, fg, boldp) + 1; // dark green
Bram Moolenaare2978022020-04-26 14:47:44 +02002704 case 4: return lookup_color( 7, fg, boldp) + 1; // dark yellow
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002705 case 5: return lookup_color( 1, fg, boldp) + 1; // dark blue
2706 case 6: return lookup_color( 5, fg, boldp) + 1; // dark magenta
2707 case 7: return lookup_color( 3, fg, boldp) + 1; // dark cyan
2708 case 8: return lookup_color( 8, fg, boldp) + 1; // light grey
2709 case 9: return lookup_color(12, fg, boldp) + 1; // dark grey
2710 case 10: return lookup_color(20, fg, boldp) + 1; // red
2711 case 11: return lookup_color(16, fg, boldp) + 1; // green
2712 case 12: return lookup_color(24, fg, boldp) + 1; // yellow
2713 case 13: return lookup_color(14, fg, boldp) + 1; // blue
2714 case 14: return lookup_color(22, fg, boldp) + 1; // magenta
2715 case 15: return lookup_color(18, fg, boldp) + 1; // cyan
2716 case 16: return lookup_color(26, fg, boldp) + 1; // white
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002717 }
2718 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002719
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002720 if (t_colors >= 256)
2721 {
2722 if (red == blue && red == green)
2723 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002724 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002725 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002726 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2727 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2728 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002729 int i;
2730
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002731 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002732 return 17; // 00/00/00
2733 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002734 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002735 for (i = 0; i < 23; ++i)
2736 if (red < cutoff[i])
2737 return i + 233;
2738 return 256;
2739 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002740 {
2741 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2742 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002743
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002744 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002745 for (ri = 0; ri < 5; ++ri)
2746 if (red < cutoff[ri])
2747 break;
2748 for (gi = 0; gi < 5; ++gi)
2749 if (green < cutoff[gi])
2750 break;
2751 for (bi = 0; bi < 5; ++bi)
2752 if (blue < cutoff[bi])
2753 break;
2754 return 17 + ri * 36 + gi * 6 + bi;
2755 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002756 }
2757 return 0;
2758}
2759
2760/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002761 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002762 */
2763 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002764vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002765{
2766 int attr = 0;
2767
2768 if (cellattrs.bold)
2769 attr |= HL_BOLD;
2770 if (cellattrs.underline)
2771 attr |= HL_UNDERLINE;
2772 if (cellattrs.italic)
2773 attr |= HL_ITALIC;
2774 if (cellattrs.strike)
2775 attr |= HL_STRIKETHROUGH;
2776 if (cellattrs.reverse)
2777 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002778 return attr;
2779}
2780
2781/*
2782 * Store Vterm attributes in "cell" from highlight flags.
2783 */
2784 static void
2785hl2vtermAttr(int attr, cellattr_T *cell)
2786{
Bram Moolenaara80faa82020-04-12 19:37:17 +02002787 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002788 if (attr & HL_BOLD)
2789 cell->attrs.bold = 1;
2790 if (attr & HL_UNDERLINE)
2791 cell->attrs.underline = 1;
2792 if (attr & HL_ITALIC)
2793 cell->attrs.italic = 1;
2794 if (attr & HL_STRIKETHROUGH)
2795 cell->attrs.strike = 1;
2796 if (attr & HL_INVERSE)
2797 cell->attrs.reverse = 1;
2798}
2799
2800/*
2801 * Convert the attributes of a vterm cell into an attribute index.
2802 */
2803 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002804cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01002805 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002806 win_T *wp,
2807 VTermScreenCellAttrs cellattrs,
2808 VTermColor cellfg,
2809 VTermColor cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002810{
2811 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002812
2813#ifdef FEAT_GUI
2814 if (gui.in_use)
2815 {
2816 guicolor_T fg, bg;
2817
2818 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2819 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2820 return get_gui_attr_idx(attr, fg, bg);
2821 }
2822 else
2823#endif
2824#ifdef FEAT_TERMGUICOLORS
2825 if (p_tgc)
2826 {
2827 guicolor_T fg, bg;
2828
2829 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2830 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2831
2832 return get_tgc_attr_idx(attr, fg, bg);
2833 }
2834 else
2835#endif
2836 {
2837 int bold = MAYBE;
2838 int fg = color2index(&cellfg, TRUE, &bold);
2839 int bg = color2index(&cellbg, FALSE, &bold);
2840
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002841 // Use the 'wincolor' or "Terminal" highlighting for the default
2842 // colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002843 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002844 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002845 int wincolor_fg = -1;
2846 int wincolor_bg = -1;
2847
2848 if (wp != NULL && *wp->w_p_wcr != NUL)
2849 {
2850 int id = syn_name2id(curwin->w_p_wcr);
2851
2852 // Get the 'wincolor' group colors.
2853 if (id > 0)
2854 syn_id2cterm_bg(id, &wincolor_fg, &wincolor_bg);
2855 }
2856 if (fg == 0)
2857 {
2858 if (wincolor_fg >= 0)
2859 fg = wincolor_fg + 1;
Bram Moolenaar83d47902020-03-26 20:34:00 +01002860 else
2861 {
2862 int cterm_fg = get_default_cterm_fg(term);
2863
2864 if (cterm_fg >= 0)
2865 fg = cterm_fg + 1;
2866 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002867 }
2868 if (bg == 0)
2869 {
2870 if (wincolor_bg >= 0)
2871 bg = wincolor_bg + 1;
Bram Moolenaar83d47902020-03-26 20:34:00 +01002872 else
2873 {
2874 int cterm_bg = get_default_cterm_bg(term);
2875
2876 if (cterm_bg >= 0)
2877 bg = cterm_bg + 1;
2878 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002879 }
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002880 }
2881
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002882 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002883 if (bold == TRUE)
2884 attr |= HL_BOLD;
2885 return get_cterm_attr_idx(attr, fg, bg);
2886 }
2887 return 0;
2888}
2889
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002890 static void
2891set_dirty_snapshot(term_T *term)
2892{
2893 term->tl_dirty_snapshot = TRUE;
2894#ifdef FEAT_TIMERS
2895 if (!term->tl_normal_mode)
2896 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002897 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002898 profile_setlimit(100L, &term->tl_timer_due);
2899 term->tl_timer_set = TRUE;
2900 }
2901#endif
2902}
2903
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002904 static int
2905handle_damage(VTermRect rect, void *user)
2906{
2907 term_T *term = (term_T *)user;
2908
2909 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2910 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002911 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002912 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002913 return 1;
2914}
2915
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002916 static void
2917term_scroll_up(term_T *term, int start_row, int count)
2918{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002919 win_T *wp = NULL;
2920 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002921 VTermColor fg, bg;
2922 VTermScreenCellAttrs attr;
2923 int clear_attr;
2924
Bram Moolenaara80faa82020-04-12 19:37:17 +02002925 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002926
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002927 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002928 {
2929 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002930 {
2931 // Set the color to clear lines with.
2932 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2933 &fg, &bg);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002934 clear_attr = cell2attr(term, wp, attr, fg, bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002935 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002936 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002937 }
2938}
2939
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002940 static int
2941handle_moverect(VTermRect dest, VTermRect src, void *user)
2942{
2943 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002944 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002945
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002946 // Scrolling up is done much more efficiently by deleting lines instead of
2947 // redrawing the text. But avoid doing this multiple times, postpone until
2948 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002949 if (dest.start_col == src.start_col
2950 && dest.end_col == src.end_col
2951 && dest.start_row < src.start_row)
2952 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002953 if (dest.start_row == 0)
2954 term->tl_postponed_scroll += count;
2955 else
2956 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002957 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002958
2959 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2960 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002961 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002962
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002963 // Note sure if the scrolling will work correctly, let's do a complete
2964 // redraw later.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002965 redraw_buf_later(term->tl_buffer, NOT_VALID);
2966 return 1;
2967}
2968
2969 static int
2970handle_movecursor(
2971 VTermPos pos,
2972 VTermPos oldpos UNUSED,
2973 int visible,
2974 void *user)
2975{
2976 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002977 win_T *wp = NULL;
2978 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002979
2980 term->tl_cursor_pos = pos;
2981 term->tl_cursor_visible = visible;
2982
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002983 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002984 {
2985 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002986 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002987 }
2988 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2989 {
2990 may_toggle_cursor(term);
2991 update_cursor(term, term->tl_cursor_visible);
2992 }
2993
2994 return 1;
2995}
2996
2997 static int
2998handle_settermprop(
2999 VTermProp prop,
3000 VTermValue *value,
3001 void *user)
3002{
3003 term_T *term = (term_T *)user;
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003004 char_u *strval = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003005
3006 switch (prop)
3007 {
3008 case VTERM_PROP_TITLE:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003009 strval = vim_strnsave((char_u *)value->string.str,
3010 (int)value->string.len);
3011 if (strval == NULL)
3012 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003013 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003014 // a blank title isn't useful, make it empty, so that "running" is
3015 // displayed
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003016 if (*skipwhite(strval) == NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003017 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003018 // Same as blank
3019 else if (term->tl_arg0_cmd != NULL
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003020 && STRNCMP(term->tl_arg0_cmd, strval,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003021 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3022 term->tl_title = NULL;
3023 // Empty corrupted data of winpty
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003024 else if (STRNCMP(" - ", strval, 4) == 0)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003025 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003026#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003027 else if (!enc_utf8 && enc_codepage > 0)
3028 {
3029 WCHAR *ret = NULL;
3030 int length = 0;
3031
3032 MultiByteToWideChar_alloc(CP_UTF8, 0,
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003033 (char*)value->string.str,
3034 (int)value->string.len, &ret, &length);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003035 if (ret != NULL)
3036 {
3037 WideCharToMultiByte_alloc(enc_codepage, 0,
3038 ret, length, (char**)&term->tl_title,
3039 &length, 0, 0);
3040 vim_free(ret);
3041 }
3042 }
3043#endif
3044 else
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003045 {
3046 term->tl_title = vim_strsave(strval);
3047 strval = NULL;
3048 }
Bram Moolenaard23a8232018-02-10 18:45:26 +01003049 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003050 if (term == curbuf->b_term)
3051 maketitle();
3052 break;
3053
3054 case VTERM_PROP_CURSORVISIBLE:
3055 term->tl_cursor_visible = value->boolean;
3056 may_toggle_cursor(term);
3057 out_flush();
3058 break;
3059
3060 case VTERM_PROP_CURSORBLINK:
3061 term->tl_cursor_blink = value->boolean;
3062 may_set_cursor_props(term);
3063 break;
3064
3065 case VTERM_PROP_CURSORSHAPE:
3066 term->tl_cursor_shape = value->number;
3067 may_set_cursor_props(term);
3068 break;
3069
3070 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003071 strval = vim_strnsave((char_u *)value->string.str,
3072 (int)value->string.len);
3073 if (strval == NULL)
3074 break;
3075 cursor_color_copy(&term->tl_cursor_color, strval);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003076 may_set_cursor_props(term);
3077 break;
3078
3079 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003080 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003081 term->tl_using_altscreen = value->boolean;
3082 break;
3083
3084 default:
3085 break;
3086 }
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02003087 vim_free(strval);
3088
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003089 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003090 return 1;
3091}
3092
3093/*
3094 * The job running in the terminal resized the terminal.
3095 */
3096 static int
3097handle_resize(int rows, int cols, void *user)
3098{
3099 term_T *term = (term_T *)user;
3100 win_T *wp;
3101
3102 term->tl_rows = rows;
3103 term->tl_cols = cols;
3104 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003105 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003106 term->tl_vterm_size_changed = FALSE;
3107 else
3108 {
3109 FOR_ALL_WINDOWS(wp)
3110 {
3111 if (wp->w_buffer == term->tl_buffer)
3112 {
3113 win_setheight_win(rows, wp);
3114 win_setwidth_win(cols, wp);
3115 }
3116 }
3117 redraw_buf_later(term->tl_buffer, NOT_VALID);
3118 }
3119 return 1;
3120}
3121
3122/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003123 * If the number of lines that are stored goes over 'termscrollback' then
3124 * delete the first 10%.
3125 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3126 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003127 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003128 static void
3129limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003131 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003132 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003133 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003134 int i;
3135
3136 curbuf = term->tl_buffer;
3137 for (i = 0; i < todo; ++i)
3138 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003139 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3140 if (update_buffer)
3141 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003142 }
3143 curbuf = curwin->w_buffer;
3144
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003145 gap->ga_len -= todo;
3146 mch_memmove(gap->ga_data,
3147 (sb_line_T *)gap->ga_data + todo,
3148 sizeof(sb_line_T) * gap->ga_len);
3149 if (update_buffer)
3150 term->tl_scrollback_scrolled -= todo;
3151 }
3152}
3153
3154/*
3155 * Handle a line that is pushed off the top of the screen.
3156 */
3157 static int
3158handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3159{
3160 term_T *term = (term_T *)user;
3161 garray_T *gap;
3162 int update_buffer;
3163
3164 if (term->tl_normal_mode)
3165 {
3166 // In Terminal-Normal mode the user interacts with the buffer, thus we
3167 // must not change it. Postpone adding the scrollback lines.
3168 gap = &term->tl_scrollback_postponed;
3169 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003170 }
3171 else
3172 {
3173 // First remove the lines that were appended before, the pushed line
3174 // goes above it.
3175 cleanup_scrollback(term);
3176 gap = &term->tl_scrollback;
3177 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003178 }
3179
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003180 limit_scrollback(term, gap, update_buffer);
3181
3182 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003183 {
3184 cellattr_T *p = NULL;
3185 int len = 0;
3186 int i;
3187 int c;
3188 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003189 int text_len;
3190 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003191 sb_line_T *line;
3192 garray_T ga;
3193 cellattr_T fill_attr = term->tl_default_color;
3194
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003195 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003196 for (i = 0; i < cols; ++i)
3197 if (cells[i].chars[0] != 0)
3198 len = i + 1;
3199 else
3200 cell2cellattr(&cells[i], &fill_attr);
3201
3202 ga_init2(&ga, 1, 100);
3203 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003204 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003205 if (p != NULL)
3206 {
3207 for (col = 0; col < len; col += cells[col].width)
3208 {
3209 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3210 {
3211 ga.ga_len = 0;
3212 break;
3213 }
3214 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3215 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3216 (char_u *)ga.ga_data + ga.ga_len);
3217 cell2cellattr(&cells[col], &p[col]);
3218 }
3219 }
3220 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003221 {
3222 if (update_buffer)
3223 text = (char_u *)"";
3224 else
3225 text = vim_strsave((char_u *)"");
3226 text_len = 0;
3227 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003228 else
3229 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003230 text = ga.ga_data;
3231 text_len = ga.ga_len;
3232 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003233 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003234 if (update_buffer)
3235 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003236
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003237 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003238 line->sb_cols = len;
3239 line->sb_cells = p;
3240 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003241 if (update_buffer)
3242 {
3243 line->sb_text = NULL;
3244 ++term->tl_scrollback_scrolled;
3245 ga_clear(&ga); // free the text
3246 }
3247 else
3248 {
3249 line->sb_text = text;
3250 ga_init(&ga); // text is kept in tl_scrollback_postponed
3251 }
3252 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003253 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003254 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003255}
3256
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003257/*
3258 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3259 * received and stored in tl_scrollback_postponed.
3260 */
3261 static void
3262handle_postponed_scrollback(term_T *term)
3263{
3264 int i;
3265
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003266 if (term->tl_scrollback_postponed.ga_len == 0)
3267 return;
3268 ch_log(NULL, "Moving postponed scrollback to scrollback");
3269
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003270 // First remove the lines that were appended before, the pushed lines go
3271 // above it.
3272 cleanup_scrollback(term);
3273
3274 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3275 {
3276 char_u *text;
3277 sb_line_T *pp_line;
3278 sb_line_T *line;
3279
3280 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3281 break;
3282 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3283
3284 text = pp_line->sb_text;
3285 if (text == NULL)
3286 text = (char_u *)"";
3287 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3288 vim_free(pp_line->sb_text);
3289
3290 line = (sb_line_T *)term->tl_scrollback.ga_data
3291 + term->tl_scrollback.ga_len;
3292 line->sb_cols = pp_line->sb_cols;
3293 line->sb_cells = pp_line->sb_cells;
3294 line->sb_fill_attr = pp_line->sb_fill_attr;
3295 line->sb_text = NULL;
3296 ++term->tl_scrollback_scrolled;
3297 ++term->tl_scrollback.ga_len;
3298 }
3299
3300 ga_clear(&term->tl_scrollback_postponed);
3301 limit_scrollback(term, &term->tl_scrollback, TRUE);
3302}
3303
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003304static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003305 handle_damage, // damage
3306 handle_moverect, // moverect
3307 handle_movecursor, // movecursor
3308 handle_settermprop, // settermprop
3309 NULL, // bell
3310 handle_resize, // resize
3311 handle_pushline, // sb_pushline
3312 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003313};
3314
3315/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003316 * Do the work after the channel of a terminal was closed.
3317 * Must be called only when updating_screen is FALSE.
3318 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3319 */
3320 static int
3321term_after_channel_closed(term_T *term)
3322{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003323 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003324 if (!term->tl_normal_mode)
3325 {
3326 int fnum = term->tl_buffer->b_fnum;
3327
3328 cleanup_vterm(term);
3329
3330 if (term->tl_finish == TL_FINISH_CLOSE)
3331 {
3332 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003333 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003334#ifdef FEAT_PROP_POPUP
3335 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003336
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003337 // If this was a terminal in a popup window, go back to the
3338 // previous window.
3339 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3340 {
3341 pwin = curwin;
3342 if (win_valid(prevwin))
3343 win_enter(prevwin, FALSE);
3344 }
3345 else
3346#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003347 // If this is the last normal window: exit Vim.
3348 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3349 {
3350 exarg_T ea;
3351
Bram Moolenaara80faa82020-04-12 19:37:17 +02003352 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003353 ex_quit(&ea);
3354 return TRUE;
3355 }
3356
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003357 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003358 ch_log(NULL, "terminal job finished, closing window");
3359 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003360 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003361 if (curwin == aucmd_win)
3362 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003363 if (do_set_w_closing)
3364 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003365 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003366 if (do_set_w_closing)
3367 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003368 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003369#ifdef FEAT_PROP_POPUP
3370 if (pwin != NULL)
3371 popup_close_with_retval(pwin, 0);
3372#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003373 return TRUE;
3374 }
3375 if (term->tl_finish == TL_FINISH_OPEN
3376 && term->tl_buffer->b_nwindows == 0)
3377 {
3378 char buf[50];
3379
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003380 // TODO: use term_opencmd
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003381 ch_log(NULL, "terminal job finished, opening window");
3382 vim_snprintf(buf, sizeof(buf),
3383 term->tl_opencmd == NULL
3384 ? "botright sbuf %d"
3385 : (char *)term->tl_opencmd, fnum);
3386 do_cmdline_cmd((char_u *)buf);
3387 }
3388 else
3389 ch_log(NULL, "terminal job finished");
3390 }
3391
3392 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3393 return FALSE;
3394}
3395
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003396#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3397/*
3398 * If the current window is a terminal in a popup window and the job has
3399 * finished, close the popup window and to back to the previous window.
3400 * Otherwise return FAIL.
3401 */
3402 int
3403may_close_term_popup(void)
3404{
3405 if (popup_is_popup(curwin) && curbuf->b_term != NULL
3406 && !term_job_running(curbuf->b_term))
3407 {
3408 win_T *pwin = curwin;
3409
3410 if (win_valid(prevwin))
3411 win_enter(prevwin, FALSE);
3412 popup_close_with_retval(pwin, 0);
3413 return OK;
3414 }
3415 return FAIL;
3416}
3417#endif
3418
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003419/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003420 * Called when a channel has been closed.
3421 * If this was a channel for a terminal window then finish it up.
3422 */
3423 void
3424term_channel_closed(channel_T *ch)
3425{
3426 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003427 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003428 int did_one = FALSE;
3429
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003430 for (term = first_term; term != NULL; term = next_term)
3431 {
3432 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003433 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003434 {
3435 term->tl_channel_closed = TRUE;
3436 did_one = TRUE;
3437
Bram Moolenaard23a8232018-02-10 18:45:26 +01003438 VIM_CLEAR(term->tl_title);
3439 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003440#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003441 if (term->tl_out_fd != NULL)
3442 {
3443 fclose(term->tl_out_fd);
3444 term->tl_out_fd = NULL;
3445 }
3446#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003447
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003448 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003449 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003450 // Cannot open or close windows now. Can happen when
3451 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003452 term->tl_channel_recently_closed = TRUE;
3453 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003454 }
3455
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003456 if (term_after_channel_closed(term))
3457 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003458 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003459 }
3460
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003461 if (did_one)
3462 {
3463 redraw_statuslines();
3464
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003465 // Need to break out of vgetc().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003466 ins_char_typebuf(K_IGNORE);
3467 typebuf_was_filled = TRUE;
3468
3469 term = curbuf->b_term;
3470 if (term != NULL)
3471 {
3472 if (term->tl_job == ch->ch_job)
3473 maketitle();
3474 update_cursor(term, term->tl_cursor_visible);
3475 }
3476 }
3477}
3478
3479/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003480 * To be called after resetting updating_screen: handle any terminal where the
3481 * channel was closed.
3482 */
3483 void
3484term_check_channel_closed_recently()
3485{
3486 term_T *term;
3487 term_T *next_term;
3488
3489 for (term = first_term; term != NULL; term = next_term)
3490 {
3491 next_term = term->tl_next;
3492 if (term->tl_channel_recently_closed)
3493 {
3494 term->tl_channel_recently_closed = FALSE;
3495 if (term_after_channel_closed(term))
3496 // start over, the list may have changed
3497 next_term = first_term;
3498 }
3499 }
3500}
3501
3502/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003503 * Fill one screen line from a line of the terminal.
3504 * Advances "pos" to past the last column.
3505 */
3506 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003507term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003508 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003509 win_T *wp,
3510 VTermScreen *screen,
3511 VTermPos *pos,
3512 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003513{
3514 int off = screen_get_current_line_off();
3515
3516 for (pos->col = 0; pos->col < max_col; )
3517 {
3518 VTermScreenCell cell;
3519 int c;
3520
3521 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003522 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003523
3524 c = cell.chars[0];
3525 if (c == NUL)
3526 {
3527 ScreenLines[off] = ' ';
3528 if (enc_utf8)
3529 ScreenLinesUC[off] = NUL;
3530 }
3531 else
3532 {
3533 if (enc_utf8)
3534 {
3535 int i;
3536
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003537 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003538 for (i = 0; i < Screen_mco
3539 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3540 {
3541 ScreenLinesC[i][off] = cell.chars[i + 1];
3542 if (cell.chars[i + 1] == 0)
3543 break;
3544 }
3545 if (c >= 0x80 || (Screen_mco > 0
3546 && ScreenLinesC[0][off] != 0))
3547 {
3548 ScreenLines[off] = ' ';
3549 ScreenLinesUC[off] = c;
3550 }
3551 else
3552 {
3553 ScreenLines[off] = c;
3554 ScreenLinesUC[off] = NUL;
3555 }
3556 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003557#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003558 else if (has_mbyte && c >= 0x80)
3559 {
3560 char_u mb[MB_MAXBYTES+1];
3561 WCHAR wc = c;
3562
3563 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3564 (char*)mb, 2, 0, 0) > 1)
3565 {
3566 ScreenLines[off] = mb[0];
3567 ScreenLines[off + 1] = mb[1];
3568 cell.width = mb_ptr2cells(mb);
3569 }
3570 else
3571 ScreenLines[off] = c;
3572 }
3573#endif
3574 else
3575 ScreenLines[off] = c;
3576 }
Bram Moolenaar83d47902020-03-26 20:34:00 +01003577 ScreenAttrs[off] = cell2attr(term, wp, cell.attrs, cell.fg, cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003578
3579 ++pos->col;
3580 ++off;
3581 if (cell.width == 2)
3582 {
3583 if (enc_utf8)
3584 ScreenLinesUC[off] = NUL;
3585
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003586 // don't set the second byte to NUL for a DBCS encoding, it
3587 // has been set above
Bram Moolenaar13568252018-03-16 20:46:58 +01003588 if (enc_utf8 || !has_mbyte)
3589 ScreenLines[off] = NUL;
3590
3591 ++pos->col;
3592 ++off;
3593 }
3594 }
3595}
3596
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003597#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003598 static void
3599update_system_term(term_T *term)
3600{
3601 VTermPos pos;
3602 VTermScreen *screen;
3603
3604 if (term->tl_vterm == NULL)
3605 return;
3606 screen = vterm_obtain_screen(term->tl_vterm);
3607
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003608 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003609 while (term->tl_toprow > 0
3610 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3611 {
3612 int save_p_more = p_more;
3613
3614 p_more = FALSE;
3615 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003616 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003617 p_more = save_p_more;
3618 --term->tl_toprow;
3619 }
3620
3621 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3622 && pos.row < Rows; ++pos.row)
3623 {
3624 if (pos.row < term->tl_rows)
3625 {
3626 int max_col = MIN(Columns, term->tl_cols);
3627
Bram Moolenaar83d47902020-03-26 20:34:00 +01003628 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003629 }
3630 else
3631 pos.col = 0;
3632
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003633 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003634 }
3635
3636 term->tl_dirty_row_start = MAX_ROW;
3637 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003638}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003639#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003640
3641/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003642 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3643 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003644 * Terminal-Normal mode.
3645 */
3646 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003647term_do_update_window(win_T *wp)
3648{
3649 term_T *term = wp->w_buffer->b_term;
3650
3651 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3652}
3653
3654/*
3655 * Called to update a window that contains an active terminal.
3656 */
3657 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003658term_update_window(win_T *wp)
3659{
3660 term_T *term = wp->w_buffer->b_term;
3661 VTerm *vterm;
3662 VTermScreen *screen;
3663 VTermState *state;
3664 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003665 int rows, cols;
3666 int newrows, newcols;
3667 int minsize;
3668 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003669
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003670 vterm = term->tl_vterm;
3671 screen = vterm_obtain_screen(vterm);
3672 state = vterm_obtain_state(vterm);
3673
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003674 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3675 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003676 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003677 {
3678 term->tl_dirty_row_start = 0;
3679 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003680
3681 if (term->tl_postponed_scroll > 0
3682 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003683 // Scrolling is usually faster than redrawing, when there are only
3684 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003685 term_scroll_up(term, 0, term->tl_postponed_scroll);
3686 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003687 }
3688
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003689 /*
3690 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003691 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003692 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003693 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003694
Bram Moolenaar498c2562018-04-15 23:45:15 +02003695 newrows = 99999;
3696 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003697 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003698 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003699 // Always use curwin, it may be a popup window.
3700 win_T *wwp = twp == NULL ? curwin : twp;
3701
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003702 // When more than one window shows the same terminal, use the
3703 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003704 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003705 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003706 newrows = MIN(newrows, wwp->w_height);
3707 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003708 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003709 if (twp == NULL)
3710 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003711 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003712 if (newrows == 99999 || newcols == 99999)
3713 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003714 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3715 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3716
3717 if (term->tl_rows != newrows || term->tl_cols != newcols)
3718 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003719 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003720 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003721 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003722 newrows);
3723 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003724
3725 // Updating the terminal size will cause the snapshot to be cleared.
3726 // When not in terminal_loop() we need to restore it.
3727 if (term != in_terminal_loop)
3728 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003729 }
3730
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003731 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003732 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003733 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003734
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003735 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3736 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003737 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003738 if (pos.row < term->tl_rows)
3739 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003740 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003741
Bram Moolenaar83d47902020-03-26 20:34:00 +01003742 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003743 }
3744 else
3745 pos.col = 0;
3746
Bram Moolenaarf118d482018-03-13 13:14:00 +01003747 screen_line(wp->w_winrow + pos.row
3748#ifdef FEAT_MENU
3749 + winbar_height(wp)
3750#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003751 , wp->w_wincol, pos.col, wp->w_width,
3752#ifdef FEAT_PROP_POPUP
3753 popup_is_popup(wp) ? SLF_POPUP :
3754#endif
3755 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003756 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003757 term->tl_dirty_row_start = MAX_ROW;
3758 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003759}
3760
3761/*
3762 * Return TRUE if "wp" is a terminal window where the job has finished.
3763 */
3764 int
3765term_is_finished(buf_T *buf)
3766{
3767 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3768}
3769
3770/*
3771 * Return TRUE if "wp" is a terminal window where the job has finished or we
3772 * are in Terminal-Normal mode, thus we show the buffer contents.
3773 */
3774 int
3775term_show_buffer(buf_T *buf)
3776{
3777 term_T *term = buf->b_term;
3778
3779 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3780}
3781
3782/*
3783 * The current buffer is going to be changed. If there is terminal
3784 * highlighting remove it now.
3785 */
3786 void
3787term_change_in_curbuf(void)
3788{
3789 term_T *term = curbuf->b_term;
3790
3791 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3792 {
3793 free_scrollback(term);
3794 redraw_buf_later(term->tl_buffer, NOT_VALID);
3795
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003796 // The buffer is now like a normal buffer, it cannot be easily
3797 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003798 set_string_option_direct((char_u *)"buftype", -1,
3799 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3800 }
3801}
3802
3803/*
3804 * Get the screen attribute for a position in the buffer.
3805 * Use a negative "col" to get the filler background color.
3806 */
3807 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003808term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003809{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003810 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003811 term_T *term = buf->b_term;
3812 sb_line_T *line;
3813 cellattr_T *cellattr;
3814
3815 if (lnum > term->tl_scrollback.ga_len)
3816 cellattr = &term->tl_default_color;
3817 else
3818 {
3819 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3820 if (col < 0 || col >= line->sb_cols)
3821 cellattr = &line->sb_fill_attr;
3822 else
3823 cellattr = line->sb_cells + col;
3824 }
Bram Moolenaar83d47902020-03-26 20:34:00 +01003825 return cell2attr(term, wp, cellattr->attrs, cellattr->fg, cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003826}
3827
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003828/*
3829 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003830 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003831 */
3832 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003833cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003834{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003835 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003836}
3837
3838/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003839 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003840 */
3841 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003842init_default_colors(term_T *term, win_T *wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003843{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003844 VTermColor *fg, *bg;
3845 int fgval, bgval;
3846 int id;
3847
Bram Moolenaara80faa82020-04-12 19:37:17 +02003848 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003849 term->tl_default_color.width = 1;
3850 fg = &term->tl_default_color.fg;
3851 bg = &term->tl_default_color.bg;
3852
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003853 // Vterm uses a default black background. Set it to white when
3854 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003855 if (*p_bg == 'l')
3856 {
3857 fgval = 0;
3858 bgval = 255;
3859 }
3860 else
3861 {
3862 fgval = 255;
3863 bgval = 0;
3864 }
3865 fg->red = fg->green = fg->blue = fgval;
3866 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003867 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003868
Bram Moolenaar83d47902020-03-26 20:34:00 +01003869 // The 'wincolor' or the highlight group overrules the defaults.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003870 if (wp != NULL && *wp->w_p_wcr != NUL)
3871 id = syn_name2id(wp->w_p_wcr);
3872 else
Bram Moolenaar83d47902020-03-26 20:34:00 +01003873 id = syn_name2id(term_get_highlight_name(term));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003874
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003875 // Use the actual color for the GUI and when 'termguicolors' is set.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003876#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3877 if (0
3878# ifdef FEAT_GUI
3879 || gui.in_use
3880# endif
3881# ifdef FEAT_TERMGUICOLORS
3882 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003883# ifdef FEAT_VTP
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003884 // Finally get INVALCOLOR on this execution path
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003885 || (!p_tgc && t_colors >= 256)
3886# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003887# endif
3888 )
3889 {
3890 guicolor_T fg_rgb = INVALCOLOR;
3891 guicolor_T bg_rgb = INVALCOLOR;
3892
3893 if (id != 0)
3894 syn_id2colors(id, &fg_rgb, &bg_rgb);
3895
3896# ifdef FEAT_GUI
3897 if (gui.in_use)
3898 {
3899 if (fg_rgb == INVALCOLOR)
3900 fg_rgb = gui.norm_pixel;
3901 if (bg_rgb == INVALCOLOR)
3902 bg_rgb = gui.back_pixel;
3903 }
3904# ifdef FEAT_TERMGUICOLORS
3905 else
3906# endif
3907# endif
3908# ifdef FEAT_TERMGUICOLORS
3909 {
3910 if (fg_rgb == INVALCOLOR)
3911 fg_rgb = cterm_normal_fg_gui_color;
3912 if (bg_rgb == INVALCOLOR)
3913 bg_rgb = cterm_normal_bg_gui_color;
3914 }
3915# endif
3916 if (fg_rgb != INVALCOLOR)
3917 {
3918 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3919
3920 fg->red = (unsigned)(rgb >> 16);
3921 fg->green = (unsigned)(rgb >> 8) & 255;
3922 fg->blue = (unsigned)rgb & 255;
3923 }
3924 if (bg_rgb != INVALCOLOR)
3925 {
3926 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3927
3928 bg->red = (unsigned)(rgb >> 16);
3929 bg->green = (unsigned)(rgb >> 8) & 255;
3930 bg->blue = (unsigned)rgb & 255;
3931 }
3932 }
3933 else
3934#endif
3935 if (id != 0 && t_colors >= 16)
3936 {
Bram Moolenaar83d47902020-03-26 20:34:00 +01003937 int cterm_fg = get_default_cterm_fg(term);
3938 int cterm_bg = get_default_cterm_bg(term);
3939
3940 if (cterm_fg >= 0)
3941 cterm_color2vterm(cterm_fg, fg);
3942 if (cterm_bg >= 0)
3943 cterm_color2vterm(cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003944 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003945 else
3946 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003947#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003948 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003949#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003950
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003951 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003952 if (cterm_normal_fg_color > 0)
3953 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003954 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003955# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3956# ifdef VIMDLL
3957 if (!gui.in_use)
3958# endif
3959 {
3960 tmp = fg->red;
3961 fg->red = fg->blue;
3962 fg->blue = tmp;
3963 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003964# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003965 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003966# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003967 else
3968 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003969# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003970
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003971 if (cterm_normal_bg_color > 0)
3972 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003973 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003974# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3975# ifdef VIMDLL
3976 if (!gui.in_use)
3977# endif
3978 {
3979 tmp = fg->red;
3980 fg->red = fg->blue;
3981 fg->blue = tmp;
3982 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003983# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003984 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003985# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003986 else
3987 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003988# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003989 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003990}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003991
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003992#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3993/*
3994 * Set the 16 ANSI colors from array of RGB values
3995 */
3996 static void
3997set_vterm_palette(VTerm *vterm, long_u *rgb)
3998{
3999 int index = 0;
4000 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004001
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004002 for (; index < 16; index++)
4003 {
4004 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02004005
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004006 color.red = (unsigned)(rgb[index] >> 16);
4007 color.green = (unsigned)(rgb[index] >> 8) & 255;
4008 color.blue = (unsigned)rgb[index] & 255;
4009 vterm_state_set_palette_color(state, index, &color);
4010 }
4011}
4012
4013/*
4014 * Set the ANSI color palette from a list of colors
4015 */
4016 static int
4017set_ansi_colors_list(VTerm *vterm, list_T *list)
4018{
4019 int n = 0;
4020 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004021 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004022
Bram Moolenaarb0992022020-01-30 14:55:42 +01004023 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004024 {
4025 char_u *color_name;
4026 guicolor_T guicolor;
4027
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004028 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004029 if (color_name == NULL)
4030 return FAIL;
4031
4032 guicolor = GUI_GET_COLOR(color_name);
4033 if (guicolor == INVALCOLOR)
4034 return FAIL;
4035
4036 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4037 }
4038
4039 if (n != 16 || li != NULL)
4040 return FAIL;
4041
4042 set_vterm_palette(vterm, rgb);
4043
4044 return OK;
4045}
4046
4047/*
4048 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4049 */
4050 static void
4051init_vterm_ansi_colors(VTerm *vterm)
4052{
4053 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4054
4055 if (var != NULL
4056 && (var->di_tv.v_type != VAR_LIST
4057 || var->di_tv.vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +01004058 || var->di_tv.vval.v_list->lv_first == &range_list_item
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004059 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004060 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004061}
4062#endif
4063
Bram Moolenaar52acb112018-03-18 19:20:22 +01004064/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004065 * Handles a "drop" command from the job in the terminal.
4066 * "item" is the file name, "item->li_next" may have options.
4067 */
4068 static void
4069handle_drop_command(listitem_T *item)
4070{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004071 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004072 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004073 int bufnr;
4074 win_T *wp;
4075 tabpage_T *tp;
4076 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004077 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004078
4079 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4080 FOR_ALL_TAB_WINDOWS(tp, wp)
4081 {
4082 if (wp->w_buffer->b_fnum == bufnr)
4083 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004084 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004085 goto_tabpage_win(tp, wp);
4086 return;
4087 }
4088 }
4089
Bram Moolenaara80faa82020-04-12 19:37:17 +02004090 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004091
4092 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4093 && opt_item->li_tv.vval.v_dict != NULL)
4094 {
4095 dict_T *dict = opt_item->li_tv.vval.v_dict;
4096 char_u *p;
4097
Bram Moolenaar8f667172018-12-14 15:38:31 +01004098 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004099 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004100 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004101 if (p != NULL)
4102 {
4103 if (check_ff_value(p) == FAIL)
4104 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4105 else
4106 ea.force_ff = *p;
4107 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01004108 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004109 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004110 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004111 if (p != NULL)
4112 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004113 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004114 if (ea.cmd != NULL)
4115 {
4116 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4117 ea.force_enc = 11;
4118 tofree = ea.cmd;
4119 }
4120 }
4121
Bram Moolenaar8f667172018-12-14 15:38:31 +01004122 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004123 if (p != NULL)
4124 get_bad_opt(p, &ea);
4125
4126 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
4127 ea.force_bin = FORCE_BIN;
4128 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
4129 ea.force_bin = FORCE_BIN;
4130 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
4131 ea.force_bin = FORCE_NOBIN;
4132 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
4133 ea.force_bin = FORCE_NOBIN;
4134 }
4135
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004136 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004137 if (ea.cmd == NULL)
4138 ea.cmd = (char_u *)"split";
4139 ea.arg = fname;
4140 ea.cmdidx = CMD_split;
4141 ex_splitview(&ea);
4142
4143 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004144}
4145
4146/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004147 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4148 */
4149 static int
4150is_permitted_term_api(char_u *func, char_u *pat)
4151{
4152 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4153}
4154
4155/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004156 * Handles a function call from the job running in a terminal.
4157 * "item" is the function name, "item->li_next" has the arguments.
4158 */
4159 static void
4160handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4161{
4162 char_u *func;
4163 typval_T argvars[2];
4164 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004165 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004166
4167 if (item->li_next == NULL)
4168 {
4169 ch_log(channel, "Missing function arguments for call");
4170 return;
4171 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004172 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004173
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004174 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004175 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004176 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004177 return;
4178 }
4179
4180 argvars[0].v_type = VAR_NUMBER;
4181 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4182 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004183 CLEAR_FIELD(funcexe);
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004184 funcexe.firstline = 1L;
4185 funcexe.lastline = 1L;
4186 funcexe.evaluate = TRUE;
4187 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004188 {
4189 clear_tv(&rettv);
4190 ch_log(channel, "Function %s called", func);
4191 }
4192 else
4193 ch_log(channel, "Calling function %s failed", func);
4194}
4195
4196/*
4197 * Called by libvterm when it cannot recognize an OSC sequence.
4198 * We recognize a terminal API command.
4199 */
4200 static int
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004201parse_osc(int command, VTermStringFragment frag, void *user)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004202{
4203 term_T *term = (term_T *)user;
4204 js_read_T reader;
4205 typval_T tv;
4206 channel_T *channel = term->tl_job == NULL ? NULL
4207 : term->tl_job->jv_channel;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004208 garray_T *gap = &term->tl_osc_buf;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004209
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004210 // We recognize only OSC 5 1 ; {command}
Bram Moolenaarbe593bf2020-05-19 21:20:04 +02004211 if (command != 51)
4212 return 0;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004213
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004214 // Concatenate what was received until the final piece is found.
4215 if (ga_grow(gap, (int)frag.len + 1) == FAIL)
4216 {
4217 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004218 return 1;
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004219 }
4220 mch_memmove((char *)gap->ga_data + gap->ga_len, frag.str, frag.len);
4221 gap->ga_len += frag.len;
4222 if (!frag.final)
4223 return 1;
4224
4225 ((char *)gap->ga_data)[gap->ga_len] = 0;
4226 reader.js_buf = gap->ga_data;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004227 reader.js_fill = NULL;
4228 reader.js_used = 0;
4229 if (json_decode(&reader, &tv, 0) == OK
4230 && tv.v_type == VAR_LIST
4231 && tv.vval.v_list != NULL)
4232 {
4233 listitem_T *item = tv.vval.v_list->lv_first;
4234
4235 if (item == NULL)
4236 ch_log(channel, "Missing command");
4237 else
4238 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004239 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004240
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004241 // Make sure an invoked command doesn't delete the buffer (and the
4242 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004243 ++term->tl_buffer->b_locked;
4244
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004245 item = item->li_next;
4246 if (item == NULL)
4247 ch_log(channel, "Missing argument for %s", cmd);
4248 else if (STRCMP(cmd, "drop") == 0)
4249 handle_drop_command(item);
4250 else if (STRCMP(cmd, "call") == 0)
4251 handle_call_command(term, channel, item);
4252 else
4253 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004254 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004255 }
4256 }
4257 else
4258 ch_log(channel, "Invalid JSON received");
4259
Bram Moolenaareaa3e0d2020-05-19 23:11:00 +02004260 ga_clear(gap);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004261 clear_tv(&tv);
4262 return 1;
4263}
4264
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004265/*
4266 * Called by libvterm when it cannot recognize a CSI sequence.
4267 * We recognize the window position report.
4268 */
4269 static int
4270parse_csi(
4271 const char *leader UNUSED,
4272 const long args[],
4273 int argcount,
4274 const char *intermed UNUSED,
4275 char command,
4276 void *user)
4277{
4278 term_T *term = (term_T *)user;
4279 char buf[100];
4280 int len;
4281 int x = 0;
4282 int y = 0;
4283 win_T *wp;
4284
4285 // We recognize only CSI 13 t
4286 if (command != 't' || argcount != 1 || args[0] != 13)
4287 return 0; // not handled
4288
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004289 // When getting the window position is not possible or it fails it results
4290 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004291#if defined(FEAT_GUI) \
4292 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4293 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004294 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004295#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004296
4297 FOR_ALL_WINDOWS(wp)
4298 if (wp->w_buffer == term->tl_buffer)
4299 break;
4300 if (wp != NULL)
4301 {
4302#ifdef FEAT_GUI
4303 if (gui.in_use)
4304 {
4305 x += wp->w_wincol * gui.char_width;
4306 y += W_WINROW(wp) * gui.char_height;
4307 }
4308 else
4309#endif
4310 {
4311 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004312 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004313 x += wp->w_wincol * 7;
4314 y += W_WINROW(wp) * 10;
4315 }
4316 }
4317
4318 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4319 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4320 (char_u *)buf, len, NULL);
4321 return 1;
4322}
4323
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004324static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004325 NULL, // text
4326 NULL, // control
4327 NULL, // escape
4328 parse_csi, // csi
4329 parse_osc, // osc
4330 NULL, // dcs
4331 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004332};
4333
4334/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004335 * Use Vim's allocation functions for vterm so profiling works.
4336 */
4337 static void *
4338vterm_malloc(size_t size, void *data UNUSED)
4339{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004340 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004341}
4342
4343 static void
4344vterm_memfree(void *ptr, void *data UNUSED)
4345{
4346 vim_free(ptr);
4347}
4348
4349static VTermAllocatorFunctions vterm_allocator = {
4350 &vterm_malloc,
4351 &vterm_memfree
4352};
4353
4354/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004355 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004356 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004357 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004358 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004359create_vterm(term_T *term, int rows, int cols)
4360{
4361 VTerm *vterm;
4362 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004363 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004364 VTermValue value;
4365
Bram Moolenaar756ef112018-04-10 12:04:27 +02004366 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004367 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004368 if (vterm == NULL)
4369 return FAIL;
4370
4371 // Allocate screen and state here, so we can bail out if that fails.
4372 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004373 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004374 if (state == NULL || screen == NULL)
4375 {
4376 vterm_free(vterm);
4377 return FAIL;
4378 }
4379
Bram Moolenaar52acb112018-03-18 19:20:22 +01004380 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004381 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004382 vterm_set_utf8(vterm, 1);
4383
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004384 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004385
4386 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004387 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004388 &term->tl_default_color.fg,
4389 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004390
Bram Moolenaar9e587872019-05-13 20:27:23 +02004391 if (t_colors < 16)
4392 // Less than 16 colors: assume that bold means using a bright color for
4393 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004394 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4395
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004396 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004397 vterm_screen_reset(screen, 1 /* hard */);
4398
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004399 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004400 vterm_screen_enable_altscreen(screen, 1);
4401
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004402 // For unix do not use a blinking cursor. In an xterm this causes the
4403 // cursor to blink if it's blinking in the xterm.
4404 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004405#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004406 if (GetCaretBlinkTime() == INFINITE)
4407 value.boolean = 0;
4408 else
4409 value.boolean = 1;
4410#else
4411 value.boolean = 0;
4412#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004413 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4414 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004415
4416 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004417}
4418
4419/*
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004420 * Called when 'wincolor' was set.
4421 */
4422 void
4423term_update_colors(void)
4424{
4425 term_T *term = curwin->w_buffer->b_term;
4426
Bram Moolenaar7ba3b912020-02-10 20:34:04 +01004427 if (term->tl_vterm == NULL)
4428 return;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004429 init_default_colors(term, curwin);
4430 vterm_state_set_default_colors(
4431 vterm_obtain_state(term->tl_vterm),
4432 &term->tl_default_color.fg,
4433 &term->tl_default_color.bg);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +01004434
4435 redraw_later(NOT_VALID);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004436}
4437
4438/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004439 * Return the text to show for the buffer name and status.
4440 */
4441 char_u *
4442term_get_status_text(term_T *term)
4443{
4444 if (term->tl_status_text == NULL)
4445 {
4446 char_u *txt;
4447 size_t len;
4448
4449 if (term->tl_normal_mode)
4450 {
4451 if (term_job_running(term))
4452 txt = (char_u *)_("Terminal");
4453 else
4454 txt = (char_u *)_("Terminal-finished");
4455 }
4456 else if (term->tl_title != NULL)
4457 txt = term->tl_title;
4458 else if (term_none_open(term))
4459 txt = (char_u *)_("active");
4460 else if (term_job_running(term))
4461 txt = (char_u *)_("running");
4462 else
4463 txt = (char_u *)_("finished");
4464 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004465 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004466 if (term->tl_status_text != NULL)
4467 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4468 term->tl_buffer->b_fname, txt);
4469 }
4470 return term->tl_status_text;
4471}
4472
4473/*
4474 * Mark references in jobs of terminals.
4475 */
4476 int
4477set_ref_in_term(int copyID)
4478{
4479 int abort = FALSE;
4480 term_T *term;
4481 typval_T tv;
4482
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004483 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004484 if (term->tl_job != NULL)
4485 {
4486 tv.v_type = VAR_JOB;
4487 tv.vval.v_job = term->tl_job;
4488 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4489 }
4490 return abort;
4491}
4492
4493/*
4494 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004495 * Returns NULL when the buffer is not for a terminal window and logs a message
4496 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004497 */
4498 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004499term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004500{
4501 buf_T *buf;
4502
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004503 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004504 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004505 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004506 --emsg_off;
4507 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004508 {
4509 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004510 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004511 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004512 return buf;
4513}
4514
Bram Moolenaard96ff162018-02-18 22:13:29 +01004515 static int
4516same_color(VTermColor *a, VTermColor *b)
4517{
4518 return a->red == b->red
4519 && a->green == b->green
4520 && a->blue == b->blue
4521 && a->ansi_index == b->ansi_index;
4522}
4523
4524 static void
4525dump_term_color(FILE *fd, VTermColor *color)
4526{
4527 fprintf(fd, "%02x%02x%02x%d",
4528 (int)color->red, (int)color->green, (int)color->blue,
4529 (int)color->ansi_index);
4530}
4531
4532/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004533 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004534 *
4535 * Each screen cell in full is:
4536 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4537 * {characters} is a space for an empty cell
4538 * For a double-width character "+" is changed to "*" and the next cell is
4539 * skipped.
4540 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4541 * when "&" use the same as the previous cell.
4542 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4543 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4544 * {color-idx} is a number from 0 to 255
4545 *
4546 * Screen cell with same width, attributes and color as the previous one:
4547 * |{characters}
4548 *
4549 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4550 *
4551 * Repeating the previous screen cell:
4552 * @{count}
4553 */
4554 void
4555f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4556{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004557 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004558 term_T *term;
4559 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004560 int max_height = 0;
4561 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004562 stat_T st;
4563 FILE *fd;
4564 VTermPos pos;
4565 VTermScreen *screen;
4566 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004567 VTermState *state;
4568 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004569
4570 if (check_restricted() || check_secure())
4571 return;
4572 if (buf == NULL)
4573 return;
4574 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004575 if (term->tl_vterm == NULL)
4576 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004577 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004578 return;
4579 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004580
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004581 if (argvars[2].v_type != VAR_UNKNOWN)
4582 {
4583 dict_T *d;
4584
4585 if (argvars[2].v_type != VAR_DICT)
4586 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004587 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004588 return;
4589 }
4590 d = argvars[2].vval.v_dict;
4591 if (d != NULL)
4592 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004593 max_height = dict_get_number(d, (char_u *)"rows");
4594 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004595 }
4596 }
4597
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004598 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004599 if (fname == NULL)
4600 return;
4601 if (mch_stat((char *)fname, &st) >= 0)
4602 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004603 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004604 return;
4605 }
4606
Bram Moolenaard96ff162018-02-18 22:13:29 +01004607 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4608 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004609 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004610 return;
4611 }
4612
Bram Moolenaara80faa82020-04-12 19:37:17 +02004613 CLEAR_FIELD(prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004614
4615 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004616 state = vterm_obtain_state(term->tl_vterm);
4617 vterm_state_get_cursorpos(state, &cursor_pos);
4618
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004619 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4620 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004621 {
4622 int repeat = 0;
4623
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004624 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4625 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004626 {
4627 VTermScreenCell cell;
4628 int same_attr;
4629 int same_chars = TRUE;
4630 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004631 int is_cursor_pos = (pos.col == cursor_pos.col
4632 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004633
4634 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02004635 CLEAR_FIELD(cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004636
4637 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4638 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004639 int c = cell.chars[i];
4640 int pc = prev_cell.chars[i];
4641
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004642 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01004643 if (i == 0)
4644 {
4645 c = (c == NUL) ? ' ' : c;
4646 pc = (pc == NUL) ? ' ' : pc;
4647 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004648 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004649 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004650 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004651 break;
4652 }
4653 same_attr = vtermAttr2hl(cell.attrs)
4654 == vtermAttr2hl(prev_cell.attrs)
4655 && same_color(&cell.fg, &prev_cell.fg)
4656 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004657 if (same_chars && cell.width == prev_cell.width && same_attr
4658 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004659 {
4660 ++repeat;
4661 }
4662 else
4663 {
4664 if (repeat > 0)
4665 {
4666 fprintf(fd, "@%d", repeat);
4667 repeat = 0;
4668 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004669 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004670
4671 if (cell.chars[0] == NUL)
4672 fputs(" ", fd);
4673 else
4674 {
4675 char_u charbuf[10];
4676 int len;
4677
4678 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4679 && cell.chars[i] != NUL; ++i)
4680 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004681 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004682 fwrite(charbuf, len, 1, fd);
4683 }
4684 }
4685
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004686 // When only the characters differ we don't write anything, the
4687 // following "|", "@" or NL will indicate using the same
4688 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004689 if (cell.width != prev_cell.width || !same_attr)
4690 {
4691 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004692 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004693 else
4694 fputs("+", fd);
4695
4696 if (same_attr)
4697 {
4698 fputs("&", fd);
4699 }
4700 else
4701 {
4702 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4703 if (same_color(&cell.fg, &prev_cell.fg))
4704 fputs("&", fd);
4705 else
4706 {
4707 fputs("#", fd);
4708 dump_term_color(fd, &cell.fg);
4709 }
4710 if (same_color(&cell.bg, &prev_cell.bg))
4711 fputs("&", fd);
4712 else
4713 {
4714 fputs("#", fd);
4715 dump_term_color(fd, &cell.bg);
4716 }
4717 }
4718 }
4719
4720 prev_cell = cell;
4721 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004722
4723 if (cell.width == 2)
4724 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004725 }
4726 if (repeat > 0)
4727 fprintf(fd, "@%d", repeat);
4728 fputs("\n", fd);
4729 }
4730
4731 fclose(fd);
4732}
4733
4734/*
4735 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4736 */
4737 static void
4738dump_is_corrupt(garray_T *gap)
4739{
4740 ga_concat(gap, (char_u *)"CORRUPT");
4741}
4742
4743 static void
4744append_cell(garray_T *gap, cellattr_T *cell)
4745{
4746 if (ga_grow(gap, 1) == OK)
4747 {
4748 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4749 ++gap->ga_len;
4750 }
4751}
4752
4753/*
4754 * Read the dump file from "fd" and append lines to the current buffer.
4755 * Return the cell width of the longest line.
4756 */
4757 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004758read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004759{
4760 int c;
4761 garray_T ga_text;
4762 garray_T ga_cell;
4763 char_u *prev_char = NULL;
4764 int attr = 0;
4765 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004766 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004767 term_T *term = curbuf->b_term;
4768 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004769 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004770
4771 ga_init2(&ga_text, 1, 90);
4772 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaara80faa82020-04-12 19:37:17 +02004773 CLEAR_FIELD(cell);
4774 CLEAR_FIELD(empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004775 cursor_pos->row = -1;
4776 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004777
4778 c = fgetc(fd);
4779 for (;;)
4780 {
4781 if (c == EOF)
4782 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004783 if (c == '\r')
4784 {
4785 // DOS line endings? Ignore.
4786 c = fgetc(fd);
4787 }
4788 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004789 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004790 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004791 if (ga_text.ga_data == NULL)
4792 dump_is_corrupt(&ga_text);
4793 if (ga_grow(&term->tl_scrollback, 1) == OK)
4794 {
4795 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4796 + term->tl_scrollback.ga_len;
4797
4798 if (max_cells < ga_cell.ga_len)
4799 max_cells = ga_cell.ga_len;
4800 line->sb_cols = ga_cell.ga_len;
4801 line->sb_cells = ga_cell.ga_data;
4802 line->sb_fill_attr = term->tl_default_color;
4803 ++term->tl_scrollback.ga_len;
4804 ga_init(&ga_cell);
4805
4806 ga_append(&ga_text, NUL);
4807 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4808 ga_text.ga_len, FALSE);
4809 }
4810 else
4811 ga_clear(&ga_cell);
4812 ga_text.ga_len = 0;
4813
4814 c = fgetc(fd);
4815 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004816 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004817 {
4818 int prev_len = ga_text.ga_len;
4819
Bram Moolenaar9271d052018-02-25 21:39:46 +01004820 if (c == '>')
4821 {
4822 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004823 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004824 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4825 cursor_pos->col = ga_cell.ga_len;
4826 }
4827
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004828 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004829 c = fgetc(fd);
4830 if (c != EOF)
4831 ga_append(&ga_text, c);
4832 for (;;)
4833 {
4834 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004835 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004836 || c == EOF || c == '\n')
4837 break;
4838 ga_append(&ga_text, c);
4839 }
4840
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004841 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01004842 vim_free(prev_char);
4843 if (ga_text.ga_data != NULL)
4844 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4845 ga_text.ga_len - prev_len);
4846
Bram Moolenaar9271d052018-02-25 21:39:46 +01004847 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004848 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004849 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004850 }
4851 else if (c == '+' || c == '*')
4852 {
4853 int is_bg;
4854
4855 cell.width = c == '+' ? 1 : 2;
4856
4857 c = fgetc(fd);
4858 if (c == '&')
4859 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004860 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004861 c = fgetc(fd);
4862 }
4863 else if (isdigit(c))
4864 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004865 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01004866 attr = 0;
4867 while (isdigit(c))
4868 {
4869 attr = attr * 10 + (c - '0');
4870 c = fgetc(fd);
4871 }
4872 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004873
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004874 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004875 for (is_bg = 0; is_bg <= 1; ++is_bg)
4876 {
4877 if (c == '&')
4878 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004879 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004880 c = fgetc(fd);
4881 }
4882 else if (c == '#')
4883 {
4884 int red, green, blue, index = 0;
4885
4886 c = fgetc(fd);
4887 red = hex2nr(c);
4888 c = fgetc(fd);
4889 red = (red << 4) + hex2nr(c);
4890 c = fgetc(fd);
4891 green = hex2nr(c);
4892 c = fgetc(fd);
4893 green = (green << 4) + hex2nr(c);
4894 c = fgetc(fd);
4895 blue = hex2nr(c);
4896 c = fgetc(fd);
4897 blue = (blue << 4) + hex2nr(c);
4898 c = fgetc(fd);
4899 if (!isdigit(c))
4900 dump_is_corrupt(&ga_text);
4901 while (isdigit(c))
4902 {
4903 index = index * 10 + (c - '0');
4904 c = fgetc(fd);
4905 }
4906
4907 if (is_bg)
4908 {
4909 cell.bg.red = red;
4910 cell.bg.green = green;
4911 cell.bg.blue = blue;
4912 cell.bg.ansi_index = index;
4913 }
4914 else
4915 {
4916 cell.fg.red = red;
4917 cell.fg.green = green;
4918 cell.fg.blue = blue;
4919 cell.fg.ansi_index = index;
4920 }
4921 }
4922 else
4923 dump_is_corrupt(&ga_text);
4924 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004925 }
4926 else
4927 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004928 }
4929 else
4930 dump_is_corrupt(&ga_text);
4931
4932 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004933 if (cell.width == 2)
4934 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004935 }
4936 else if (c == '@')
4937 {
4938 if (prev_char == NULL)
4939 dump_is_corrupt(&ga_text);
4940 else
4941 {
4942 int count = 0;
4943
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004944 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01004945 for (;;)
4946 {
4947 c = fgetc(fd);
4948 if (!isdigit(c))
4949 break;
4950 count = count * 10 + (c - '0');
4951 }
4952
4953 while (count-- > 0)
4954 {
4955 ga_concat(&ga_text, prev_char);
4956 append_cell(&ga_cell, &cell);
4957 }
4958 }
4959 }
4960 else
4961 {
4962 dump_is_corrupt(&ga_text);
4963 c = fgetc(fd);
4964 }
4965 }
4966
4967 if (ga_text.ga_len > 0)
4968 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004969 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004970 dump_is_corrupt(&ga_text);
4971 ga_append(&ga_text, NUL);
4972 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4973 ga_text.ga_len, FALSE);
4974 }
4975
4976 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004977 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004978 vim_free(prev_char);
4979
4980 return max_cells;
4981}
4982
4983/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004984 * Return an allocated string with at least "text_width" "=" characters and
4985 * "fname" inserted in the middle.
4986 */
4987 static char_u *
4988get_separator(int text_width, char_u *fname)
4989{
4990 int width = MAX(text_width, curwin->w_width);
4991 char_u *textline;
4992 int fname_size;
4993 char_u *p = fname;
4994 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004995 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004996
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004997 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004998 if (textline == NULL)
4999 return NULL;
5000
5001 fname_size = vim_strsize(fname);
5002 if (fname_size < width - 8)
5003 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005004 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02005005 width = MAX(text_width, fname_size + 8);
5006 }
5007 else if (fname_size > width - 8)
5008 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005009 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02005010 p = gettail(fname);
5011 fname_size = vim_strsize(p);
5012 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005013 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02005014 while (fname_size > width - 8)
5015 {
5016 p += (*mb_ptr2len)(p);
5017 fname_size = vim_strsize(p);
5018 }
5019
5020 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
5021 textline[i] = '=';
5022 textline[i++] = ' ';
5023
5024 STRCPY(textline + i, p);
5025 off = STRLEN(textline);
5026 textline[off] = ' ';
5027 for (i = 1; i < (width - fname_size) / 2; ++i)
5028 textline[off + i] = '=';
5029 textline[off + i] = NUL;
5030
5031 return textline;
5032}
5033
5034/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005035 * Common for "term_dumpdiff()" and "term_dumpload()".
5036 */
5037 static void
5038term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5039{
5040 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005041 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005042 char_u buf1[NUMBUFLEN];
5043 char_u buf2[NUMBUFLEN];
5044 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005045 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005046 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005047 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005048 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005049 char_u *textline = NULL;
5050
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005051 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005052 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005053 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005054 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005055 if (fname1 == NULL || (do_diff && fname2 == NULL))
5056 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005057 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005058 return;
5059 }
5060 fd1 = mch_fopen((char *)fname1, READBIN);
5061 if (fd1 == NULL)
5062 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005063 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005064 return;
5065 }
5066 if (do_diff)
5067 {
5068 fd2 = mch_fopen((char *)fname2, READBIN);
5069 if (fd2 == NULL)
5070 {
5071 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005072 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005073 return;
5074 }
5075 }
5076
5077 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005078 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5079 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5080 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5081 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5082 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005083
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005084 if (opt.jo_term_name == NULL)
5085 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005086 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005087
Bram Moolenaar51e14382019-05-25 20:21:28 +02005088 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005089 if (fname_tofree != NULL)
5090 {
5091 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5092 opt.jo_term_name = fname_tofree;
5093 }
5094 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005095
Bram Moolenaar87abab92019-06-03 21:14:59 +02005096 if (opt.jo_bufnr_buf != NULL)
5097 {
5098 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5099
5100 // With "bufnr" argument: enter the window with this buffer and make it
5101 // empty.
5102 if (wp == NULL)
5103 semsg(_(e_invarg2), "bufnr");
5104 else
5105 {
5106 buf = curbuf;
5107 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
5108 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02005109 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005110 redraw_later(NOT_VALID);
5111 }
5112 }
5113 else
5114 // Create a new terminal window.
5115 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5116
Bram Moolenaard96ff162018-02-18 22:13:29 +01005117 if (buf != NULL && buf->b_term != NULL)
5118 {
5119 int i;
5120 linenr_T bot_lnum;
5121 linenr_T lnum;
5122 term_T *term = buf->b_term;
5123 int width;
5124 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005125 VTermPos cursor_pos1;
5126 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005127
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005128 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005129
Bram Moolenaard96ff162018-02-18 22:13:29 +01005130 rettv->vval.v_number = buf->b_fnum;
5131
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005132 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005133 width = read_dump_file(fd1, &cursor_pos1);
5134
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005135 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005136 if (cursor_pos1.row >= 0)
5137 {
5138 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5139 coladvance(cursor_pos1.col);
5140 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005141
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005142 // Delete the empty line that was in the empty buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005143 ml_delete(1, FALSE);
5144
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005145 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005146 if (!do_diff)
5147 goto theend;
5148
5149 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5150
Bram Moolenaar4a696342018-04-05 18:45:26 +02005151 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005152 if (textline == NULL)
5153 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005154 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5155 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5156 vim_free(textline);
5157
5158 textline = get_separator(width, fname2);
5159 if (textline == NULL)
5160 goto theend;
5161 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5162 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005163 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005164
5165 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005166 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005167 if (width2 > width)
5168 {
5169 vim_free(textline);
5170 textline = alloc(width2 + 1);
5171 if (textline == NULL)
5172 goto theend;
5173 width = width2;
5174 textline[width] = NUL;
5175 }
5176 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5177
5178 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5179 {
5180 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5181 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005182 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005183 for (i = 0; i < width; ++i)
5184 textline[i] = '-';
5185 }
5186 else
5187 {
5188 char_u *line1;
5189 char_u *line2;
5190 char_u *p1;
5191 char_u *p2;
5192 int col;
5193 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5194 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5195 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5196 ->sb_cells;
5197
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005198 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005199 line1 = vim_strsave(ml_get(lnum));
5200 if (line1 == NULL)
5201 break;
5202 p1 = line1;
5203
5204 line2 = ml_get(lnum + bot_lnum);
5205 p2 = line2;
5206 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5207 {
5208 int len1 = utfc_ptr2len(p1);
5209 int len2 = utfc_ptr2len(p2);
5210
5211 textline[col] = ' ';
5212 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005213 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005214 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005215 else if (lnum == cursor_pos1.row + 1
5216 && col == cursor_pos1.col
5217 && (cursor_pos1.row != cursor_pos2.row
5218 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005219 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005220 textline[col] = '>';
5221 else if (lnum == cursor_pos2.row + 1
5222 && col == cursor_pos2.col
5223 && (cursor_pos1.row != cursor_pos2.row
5224 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005225 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005226 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005227 else if (cellattr1 != NULL && cellattr2 != NULL)
5228 {
5229 if ((cellattr1 + col)->width
5230 != (cellattr2 + col)->width)
5231 textline[col] = 'w';
5232 else if (!same_color(&(cellattr1 + col)->fg,
5233 &(cellattr2 + col)->fg))
5234 textline[col] = 'f';
5235 else if (!same_color(&(cellattr1 + col)->bg,
5236 &(cellattr2 + col)->bg))
5237 textline[col] = 'b';
5238 else if (vtermAttr2hl((cellattr1 + col)->attrs)
5239 != vtermAttr2hl(((cellattr2 + col)->attrs)))
5240 textline[col] = 'a';
5241 }
5242 p1 += len1;
5243 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005244 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005245 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005246
5247 while (col < width)
5248 {
5249 if (*p1 == NUL && *p2 == NUL)
5250 textline[col] = '?';
5251 else if (*p1 == NUL)
5252 {
5253 textline[col] = '+';
5254 p2 += utfc_ptr2len(p2);
5255 }
5256 else
5257 {
5258 textline[col] = '-';
5259 p1 += utfc_ptr2len(p1);
5260 }
5261 ++col;
5262 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005263
5264 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005265 }
5266 if (add_empty_scrollback(term, &term->tl_default_color,
5267 term->tl_top_diff_rows) == OK)
5268 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5269 ++bot_lnum;
5270 }
5271
5272 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5273 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005274 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005275 for (i = 0; i < width; ++i)
5276 textline[i] = '+';
5277 if (add_empty_scrollback(term, &term->tl_default_color,
5278 term->tl_top_diff_rows) == OK)
5279 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5280 ++lnum;
5281 ++bot_lnum;
5282 }
5283
5284 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005285
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005286 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005287 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005288 }
5289
5290theend:
5291 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005292 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005293 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005294 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005295 fclose(fd2);
5296}
5297
5298/*
5299 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5300 * bottom files.
5301 * Return FAIL when this is not possible.
5302 */
5303 int
5304term_swap_diff()
5305{
5306 term_T *term = curbuf->b_term;
5307 linenr_T line_count;
5308 linenr_T top_rows;
5309 linenr_T bot_rows;
5310 linenr_T bot_start;
5311 linenr_T lnum;
5312 char_u *p;
5313 sb_line_T *sb_line;
5314
5315 if (term == NULL
5316 || !term_is_finished(curbuf)
5317 || term->tl_top_diff_rows == 0
5318 || term->tl_scrollback.ga_len == 0)
5319 return FAIL;
5320
5321 line_count = curbuf->b_ml.ml_line_count;
5322 top_rows = term->tl_top_diff_rows;
5323 bot_rows = term->tl_bot_diff_rows;
5324 bot_start = line_count - bot_rows;
5325 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5326
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005327 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005328 for (lnum = 1; lnum <= top_rows; ++lnum)
5329 {
5330 p = vim_strsave(ml_get(1));
5331 if (p == NULL)
5332 return OK;
5333 ml_append(bot_start, p, 0, FALSE);
5334 ml_delete(1, FALSE);
5335 vim_free(p);
5336 }
5337
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005338 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005339 for (lnum = 1; lnum <= bot_rows; ++lnum)
5340 {
5341 p = vim_strsave(ml_get(bot_start + lnum));
5342 if (p == NULL)
5343 return OK;
5344 ml_delete(bot_start + lnum, FALSE);
5345 ml_append(lnum - 1, p, 0, FALSE);
5346 vim_free(p);
5347 }
5348
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005349 // move top title to bottom
5350 p = vim_strsave(ml_get(bot_rows + 1));
5351 if (p == NULL)
5352 return OK;
5353 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5354 ml_delete(bot_rows + 1, FALSE);
5355 vim_free(p);
5356
5357 // move bottom title to top
5358 p = vim_strsave(ml_get(line_count - top_rows));
5359 if (p == NULL)
5360 return OK;
5361 ml_delete(line_count - top_rows, FALSE);
5362 ml_append(bot_rows, p, 0, FALSE);
5363 vim_free(p);
5364
Bram Moolenaard96ff162018-02-18 22:13:29 +01005365 if (top_rows == bot_rows)
5366 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005367 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005368 for (lnum = 0; lnum < top_rows; ++lnum)
5369 {
5370 sb_line_T temp;
5371
5372 temp = *(sb_line + lnum);
5373 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5374 *(sb_line + bot_start + lnum) = temp;
5375 }
5376 }
5377 else
5378 {
5379 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005380 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005381
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005382 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005383 if (temp != NULL)
5384 {
5385 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5386 mch_memmove(term->tl_scrollback.ga_data,
5387 temp + bot_start,
5388 sizeof(sb_line_T) * bot_rows);
5389 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5390 temp + top_rows,
5391 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5392 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5393 + line_count - top_rows,
5394 temp,
5395 sizeof(sb_line_T) * top_rows);
5396 vim_free(temp);
5397 }
5398 }
5399
5400 term->tl_top_diff_rows = bot_rows;
5401 term->tl_bot_diff_rows = top_rows;
5402
5403 update_screen(NOT_VALID);
5404 return OK;
5405}
5406
5407/*
5408 * "term_dumpdiff(filename, filename, options)" function
5409 */
5410 void
5411f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5412{
5413 term_load_dump(argvars, rettv, TRUE);
5414}
5415
5416/*
5417 * "term_dumpload(filename, options)" function
5418 */
5419 void
5420f_term_dumpload(typval_T *argvars, typval_T *rettv)
5421{
5422 term_load_dump(argvars, rettv, FALSE);
5423}
5424
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005425/*
5426 * "term_getaltscreen(buf)" function
5427 */
5428 void
5429f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5430{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005431 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005432
5433 if (buf == NULL)
5434 return;
5435 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5436}
5437
5438/*
5439 * "term_getattr(attr, name)" function
5440 */
5441 void
5442f_term_getattr(typval_T *argvars, typval_T *rettv)
5443{
5444 int attr;
5445 size_t i;
5446 char_u *name;
5447
5448 static struct {
5449 char *name;
5450 int attr;
5451 } attrs[] = {
5452 {"bold", HL_BOLD},
5453 {"italic", HL_ITALIC},
5454 {"underline", HL_UNDERLINE},
5455 {"strike", HL_STRIKETHROUGH},
5456 {"reverse", HL_INVERSE},
5457 };
5458
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005459 attr = tv_get_number(&argvars[0]);
5460 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005461 if (name == NULL)
5462 return;
5463
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005464 if (attr > HL_ALL)
5465 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005466 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5467 if (STRCMP(name, attrs[i].name) == 0)
5468 {
5469 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5470 break;
5471 }
5472}
5473
5474/*
5475 * "term_getcursor(buf)" function
5476 */
5477 void
5478f_term_getcursor(typval_T *argvars, typval_T *rettv)
5479{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005480 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005481 term_T *term;
5482 list_T *l;
5483 dict_T *d;
5484
5485 if (rettv_list_alloc(rettv) == FAIL)
5486 return;
5487 if (buf == NULL)
5488 return;
5489 term = buf->b_term;
5490
5491 l = rettv->vval.v_list;
5492 list_append_number(l, term->tl_cursor_pos.row + 1);
5493 list_append_number(l, term->tl_cursor_pos.col + 1);
5494
5495 d = dict_alloc();
5496 if (d != NULL)
5497 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005498 dict_add_number(d, "visible", term->tl_cursor_visible);
5499 dict_add_number(d, "blink", blink_state_is_inverted()
5500 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5501 dict_add_number(d, "shape", term->tl_cursor_shape);
5502 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005503 list_append_dict(l, d);
5504 }
5505}
5506
5507/*
5508 * "term_getjob(buf)" function
5509 */
5510 void
5511f_term_getjob(typval_T *argvars, typval_T *rettv)
5512{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005513 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005514
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005515 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005516 {
5517 rettv->v_type = VAR_SPECIAL;
5518 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005519 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005520 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005521
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005522 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005523 rettv->vval.v_job = buf->b_term->tl_job;
5524 if (rettv->vval.v_job != NULL)
5525 ++rettv->vval.v_job->jv_refcount;
5526}
5527
5528 static int
5529get_row_number(typval_T *tv, term_T *term)
5530{
5531 if (tv->v_type == VAR_STRING
5532 && tv->vval.v_string != NULL
5533 && STRCMP(tv->vval.v_string, ".") == 0)
5534 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005535 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005536}
5537
5538/*
5539 * "term_getline(buf, row)" function
5540 */
5541 void
5542f_term_getline(typval_T *argvars, typval_T *rettv)
5543{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005544 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005545 term_T *term;
5546 int row;
5547
5548 rettv->v_type = VAR_STRING;
5549 if (buf == NULL)
5550 return;
5551 term = buf->b_term;
5552 row = get_row_number(&argvars[1], term);
5553
5554 if (term->tl_vterm == NULL)
5555 {
5556 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5557
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005558 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005559 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5560 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5561 }
5562 else
5563 {
5564 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5565 VTermRect rect;
5566 int len;
5567 char_u *p;
5568
5569 if (row < 0 || row >= term->tl_rows)
5570 return;
5571 len = term->tl_cols * MB_MAXBYTES + 1;
5572 p = alloc(len);
5573 if (p == NULL)
5574 return;
5575 rettv->vval.v_string = p;
5576
5577 rect.start_col = 0;
5578 rect.end_col = term->tl_cols;
5579 rect.start_row = row;
5580 rect.end_row = row + 1;
5581 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5582 }
5583}
5584
5585/*
5586 * "term_getscrolled(buf)" function
5587 */
5588 void
5589f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5590{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005591 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005592
5593 if (buf == NULL)
5594 return;
5595 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5596}
5597
5598/*
5599 * "term_getsize(buf)" function
5600 */
5601 void
5602f_term_getsize(typval_T *argvars, typval_T *rettv)
5603{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005604 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005605 list_T *l;
5606
5607 if (rettv_list_alloc(rettv) == FAIL)
5608 return;
5609 if (buf == NULL)
5610 return;
5611
5612 l = rettv->vval.v_list;
5613 list_append_number(l, buf->b_term->tl_rows);
5614 list_append_number(l, buf->b_term->tl_cols);
5615}
5616
5617/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005618 * "term_setsize(buf, rows, cols)" function
5619 */
5620 void
5621f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5622{
5623 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5624 term_T *term;
5625 varnumber_T rows, cols;
5626
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005627 if (buf == NULL)
5628 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005629 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005630 return;
5631 }
5632 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005633 return;
5634 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005635 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005636 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005637 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005638 cols = cols <= 0 ? term->tl_cols : cols;
5639 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005640 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02005641
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005642 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02005643 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5644 term_report_winsize(term, term->tl_rows, term->tl_cols);
5645}
5646
5647/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005648 * "term_getstatus(buf)" function
5649 */
5650 void
5651f_term_getstatus(typval_T *argvars, typval_T *rettv)
5652{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005653 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005654 term_T *term;
5655 char_u val[100];
5656
5657 rettv->v_type = VAR_STRING;
5658 if (buf == NULL)
5659 return;
5660 term = buf->b_term;
5661
5662 if (term_job_running(term))
5663 STRCPY(val, "running");
5664 else
5665 STRCPY(val, "finished");
5666 if (term->tl_normal_mode)
5667 STRCAT(val, ",normal");
5668 rettv->vval.v_string = vim_strsave(val);
5669}
5670
5671/*
5672 * "term_gettitle(buf)" function
5673 */
5674 void
5675f_term_gettitle(typval_T *argvars, typval_T *rettv)
5676{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005677 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005678
5679 rettv->v_type = VAR_STRING;
5680 if (buf == NULL)
5681 return;
5682
5683 if (buf->b_term->tl_title != NULL)
5684 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5685}
5686
5687/*
5688 * "term_gettty(buf)" function
5689 */
5690 void
5691f_term_gettty(typval_T *argvars, typval_T *rettv)
5692{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005693 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005694 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005695 int num = 0;
5696
5697 rettv->v_type = VAR_STRING;
5698 if (buf == NULL)
5699 return;
5700 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005701 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005702
5703 switch (num)
5704 {
5705 case 0:
5706 if (buf->b_term->tl_job != NULL)
5707 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005708 break;
5709 case 1:
5710 if (buf->b_term->tl_job != NULL)
5711 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005712 break;
5713 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005714 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005715 return;
5716 }
5717 if (p != NULL)
5718 rettv->vval.v_string = vim_strsave(p);
5719}
5720
5721/*
5722 * "term_list()" function
5723 */
5724 void
5725f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5726{
5727 term_T *tp;
5728 list_T *l;
5729
5730 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5731 return;
5732
5733 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02005734 FOR_ALL_TERMS(tp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005735 if (tp != NULL && tp->tl_buffer != NULL)
5736 if (list_append_number(l,
5737 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5738 return;
5739}
5740
5741/*
5742 * "term_scrape(buf, row)" function
5743 */
5744 void
5745f_term_scrape(typval_T *argvars, typval_T *rettv)
5746{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005747 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005748 VTermScreen *screen = NULL;
5749 VTermPos pos;
5750 list_T *l;
5751 term_T *term;
5752 char_u *p;
5753 sb_line_T *line;
5754
5755 if (rettv_list_alloc(rettv) == FAIL)
5756 return;
5757 if (buf == NULL)
5758 return;
5759 term = buf->b_term;
5760
5761 l = rettv->vval.v_list;
5762 pos.row = get_row_number(&argvars[1], term);
5763
5764 if (term->tl_vterm != NULL)
5765 {
5766 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005767 if (screen == NULL) // can't really happen
5768 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005769 p = NULL;
5770 line = NULL;
5771 }
5772 else
5773 {
5774 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5775
5776 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5777 return;
5778 p = ml_get_buf(buf, lnum + 1, FALSE);
5779 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5780 }
5781
5782 for (pos.col = 0; pos.col < term->tl_cols; )
5783 {
5784 dict_T *dcell;
5785 int width;
5786 VTermScreenCellAttrs attrs;
5787 VTermColor fg, bg;
5788 char_u rgb[8];
5789 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5790 int off = 0;
5791 int i;
5792
5793 if (screen == NULL)
5794 {
5795 cellattr_T *cellattr;
5796 int len;
5797
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005798 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005799 if (pos.col >= line->sb_cols)
5800 break;
5801 cellattr = line->sb_cells + pos.col;
5802 width = cellattr->width;
5803 attrs = cellattr->attrs;
5804 fg = cellattr->fg;
5805 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005806 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005807 mch_memmove(mbs, p, len);
5808 mbs[len] = NUL;
5809 p += len;
5810 }
5811 else
5812 {
5813 VTermScreenCell cell;
5814 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5815 break;
5816 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5817 {
5818 if (cell.chars[i] == 0)
5819 break;
5820 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5821 }
5822 mbs[off] = NUL;
5823 width = cell.width;
5824 attrs = cell.attrs;
5825 fg = cell.fg;
5826 bg = cell.bg;
5827 }
5828 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005829 if (dcell == NULL)
5830 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005831 list_append_dict(l, dcell);
5832
Bram Moolenaare0be1672018-07-08 16:50:37 +02005833 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005834
5835 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5836 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005837 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005838 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5839 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005840 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005841
Bram Moolenaar83d47902020-03-26 20:34:00 +01005842 dict_add_number(dcell, "attr", cell2attr(term, NULL, attrs, fg, bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02005843 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005844
5845 ++pos.col;
5846 if (width == 2)
5847 ++pos.col;
5848 }
5849}
5850
5851/*
5852 * "term_sendkeys(buf, keys)" function
5853 */
5854 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01005855f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005856{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005857 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005858 char_u *msg;
5859 term_T *term;
5860
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005861 if (buf == NULL)
5862 return;
5863
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005864 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005865 if (msg == NULL)
5866 return;
5867 term = buf->b_term;
5868 if (term->tl_vterm == NULL)
5869 return;
5870
5871 while (*msg != NUL)
5872 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005873 int c;
5874
5875 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5876 {
5877 c = TO_SPECIAL(msg[1], msg[2]);
5878 msg += 3;
5879 }
5880 else
5881 {
5882 c = PTR2CHAR(msg);
5883 msg += MB_CPTR2LEN(msg);
5884 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005885 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005886 }
5887}
5888
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005889#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5890/*
5891 * "term_getansicolors(buf)" function
5892 */
5893 void
5894f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5895{
5896 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5897 term_T *term;
5898 VTermState *state;
5899 VTermColor color;
5900 char_u hexbuf[10];
5901 int index;
5902 list_T *list;
5903
5904 if (rettv_list_alloc(rettv) == FAIL)
5905 return;
5906
5907 if (buf == NULL)
5908 return;
5909 term = buf->b_term;
5910 if (term->tl_vterm == NULL)
5911 return;
5912
5913 list = rettv->vval.v_list;
5914 state = vterm_obtain_state(term->tl_vterm);
5915 for (index = 0; index < 16; index++)
5916 {
5917 vterm_state_get_palette_color(state, index, &color);
5918 sprintf((char *)hexbuf, "#%02x%02x%02x",
5919 color.red, color.green, color.blue);
5920 if (list_append_string(list, hexbuf, 7) == FAIL)
5921 return;
5922 }
5923}
5924
5925/*
5926 * "term_setansicolors(buf, list)" function
5927 */
5928 void
5929f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5930{
5931 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5932 term_T *term;
5933
5934 if (buf == NULL)
5935 return;
5936 term = buf->b_term;
5937 if (term->tl_vterm == NULL)
5938 return;
5939
5940 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5941 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005942 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005943 return;
5944 }
5945
5946 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005947 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005948}
5949#endif
5950
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005951/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005952 * "term_setapi(buf, api)" function
5953 */
5954 void
5955f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5956{
5957 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5958 term_T *term;
5959 char_u *api;
5960
5961 if (buf == NULL)
5962 return;
5963 term = buf->b_term;
5964 vim_free(term->tl_api);
5965 api = tv_get_string_chk(&argvars[1]);
5966 if (api != NULL)
5967 term->tl_api = vim_strsave(api);
5968 else
5969 term->tl_api = NULL;
5970}
5971
5972/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005973 * "term_setrestore(buf, command)" function
5974 */
5975 void
5976f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5977{
5978#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005979 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005980 term_T *term;
5981 char_u *cmd;
5982
5983 if (buf == NULL)
5984 return;
5985 term = buf->b_term;
5986 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005987 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005988 if (cmd != NULL)
5989 term->tl_command = vim_strsave(cmd);
5990 else
5991 term->tl_command = NULL;
5992#endif
5993}
5994
5995/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005996 * "term_setkill(buf, how)" function
5997 */
5998 void
5999f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
6000{
6001 buf_T *buf = term_get_buf(argvars, "term_setkill()");
6002 term_T *term;
6003 char_u *how;
6004
6005 if (buf == NULL)
6006 return;
6007 term = buf->b_term;
6008 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006009 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006010 if (how != NULL)
6011 term->tl_kill = vim_strsave(how);
6012 else
6013 term->tl_kill = NULL;
6014}
6015
6016/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006017 * "term_start(command, options)" function
6018 */
6019 void
6020f_term_start(typval_T *argvars, typval_T *rettv)
6021{
6022 jobopt_T opt;
6023 buf_T *buf;
6024
6025 init_job_options(&opt);
6026 if (argvars[1].v_type != VAR_UNKNOWN
6027 && get_job_options(&argvars[1], &opt,
6028 JO_TIMEOUT_ALL + JO_STOPONEXIT
6029 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6030 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6031 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6032 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006033 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006034 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006035 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006036 return;
6037
Bram Moolenaar13568252018-03-16 20:46:58 +01006038 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006039
6040 if (buf != NULL && buf->b_term != NULL)
6041 rettv->vval.v_number = buf->b_fnum;
6042}
6043
6044/*
6045 * "term_wait" function
6046 */
6047 void
6048f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6049{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006050 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006051
6052 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006053 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006054 if (buf->b_term->tl_job == NULL)
6055 {
6056 ch_log(NULL, "term_wait(): no job to wait for");
6057 return;
6058 }
6059 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006060 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006061 return;
6062
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006063 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006064 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006065 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6066 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006067 // The job is dead, keep reading channel I/O until the channel is
6068 // closed. buf->b_term may become NULL if the terminal was closed while
6069 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006070 ch_log(NULL, "term_wait(): waiting for channel to close");
6071 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6072 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006073 term_flush_messages();
6074
Bram Moolenaard45aa552018-05-21 22:50:29 +02006075 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006076 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006077 // If the terminal is closed when the channel is closed the
6078 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006079 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006080 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006081
6082 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006083 }
6084 else
6085 {
6086 long wait = 10L;
6087
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006088 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006089
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006090 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006091 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006092 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006093 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006094
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006095 // Flushing messages on channels is hopefully sufficient.
6096 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006097 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006098 }
6099}
6100
6101/*
6102 * Called when a channel has sent all the lines to a terminal.
6103 * Send a CTRL-D to mark the end of the text.
6104 */
6105 void
6106term_send_eof(channel_T *ch)
6107{
6108 term_T *term;
6109
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006110 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006111 if (term->tl_job == ch->ch_job)
6112 {
6113 if (term->tl_eof_chars != NULL)
6114 {
6115 channel_send(ch, PART_IN, term->tl_eof_chars,
6116 (int)STRLEN(term->tl_eof_chars), NULL);
6117 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6118 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006119# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006120 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006121 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006122 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6123# endif
6124 }
6125}
6126
Bram Moolenaar113e1072019-01-20 15:30:40 +01006127#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006128 job_T *
6129term_getjob(term_T *term)
6130{
6131 return term != NULL ? term->tl_job : NULL;
6132}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006133#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006134
Bram Moolenaar4f974752019-02-17 17:44:42 +01006135# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006136
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006137///////////////////////////////////////
6138// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006139#ifdef PROTO
6140typedef int COORD;
6141typedef int DWORD;
6142typedef int HANDLE;
6143typedef int *DWORD_PTR;
6144typedef int HPCON;
6145typedef int HRESULT;
6146typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006147typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006148typedef int PSIZE_T;
6149typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006150typedef int BOOL;
6151# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006152#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006153
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006154HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6155HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6156HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006157BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6158BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6159void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006160
6161 static int
6162dyn_conpty_init(int verbose)
6163{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006164 static HMODULE hKerneldll = NULL;
6165 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006166 static struct
6167 {
6168 char *name;
6169 FARPROC *ptr;
6170 } conpty_entry[] =
6171 {
6172 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6173 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6174 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6175 {"InitializeProcThreadAttributeList",
6176 (FARPROC*)&pInitializeProcThreadAttributeList},
6177 {"UpdateProcThreadAttribute",
6178 (FARPROC*)&pUpdateProcThreadAttribute},
6179 {"DeleteProcThreadAttributeList",
6180 (FARPROC*)&pDeleteProcThreadAttributeList},
6181 {NULL, NULL}
6182 };
6183
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006184 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006185 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006186 if (verbose)
6187 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006188 return FAIL;
6189 }
6190
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006191 // No need to initialize twice.
6192 if (hKerneldll)
6193 return OK;
6194
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006195 hKerneldll = vimLoadLib("kernel32.dll");
6196 for (i = 0; conpty_entry[i].name != NULL
6197 && conpty_entry[i].ptr != NULL; ++i)
6198 {
6199 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6200 conpty_entry[i].name)) == NULL)
6201 {
6202 if (verbose)
6203 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006204 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006205 return FAIL;
6206 }
6207 }
6208
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006209 return OK;
6210}
6211
6212 static int
6213conpty_term_and_job_init(
6214 term_T *term,
6215 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006216 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006217 jobopt_T *opt,
6218 jobopt_T *orig_opt)
6219{
6220 WCHAR *cmd_wchar = NULL;
6221 WCHAR *cmd_wchar_copy = NULL;
6222 WCHAR *cwd_wchar = NULL;
6223 WCHAR *env_wchar = NULL;
6224 channel_T *channel = NULL;
6225 job_T *job = NULL;
6226 HANDLE jo = NULL;
6227 garray_T ga_cmd, ga_env;
6228 char_u *cmd = NULL;
6229 HRESULT hr;
6230 COORD consize;
6231 SIZE_T breq;
6232 PROCESS_INFORMATION proc_info;
6233 HANDLE i_theirs = NULL;
6234 HANDLE o_theirs = NULL;
6235 HANDLE i_ours = NULL;
6236 HANDLE o_ours = NULL;
6237
6238 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6239 ga_init2(&ga_env, (int)sizeof(char*), 20);
6240
6241 if (argvar->v_type == VAR_STRING)
6242 {
6243 cmd = argvar->vval.v_string;
6244 }
6245 else if (argvar->v_type == VAR_LIST)
6246 {
6247 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6248 goto failed;
6249 cmd = ga_cmd.ga_data;
6250 }
6251 if (cmd == NULL || *cmd == NUL)
6252 {
6253 emsg(_(e_invarg));
6254 goto failed;
6255 }
6256
6257 term->tl_arg0_cmd = vim_strsave(cmd);
6258
6259 cmd_wchar = enc_to_utf16(cmd, NULL);
6260
6261 if (cmd_wchar != NULL)
6262 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006263 // Request by CreateProcessW
6264 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006265 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006266 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6267 }
6268
6269 ga_clear(&ga_cmd);
6270 if (cmd_wchar == NULL)
6271 goto failed;
6272 if (opt->jo_cwd != NULL)
6273 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6274
6275 win32_build_env(opt->jo_env, &ga_env, TRUE);
6276 env_wchar = ga_env.ga_data;
6277
6278 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6279 goto failed;
6280 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6281 goto failed;
6282
6283 consize.X = term->tl_cols;
6284 consize.Y = term->tl_rows;
6285 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6286 &term->tl_conpty);
6287 if (FAILED(hr))
6288 goto failed;
6289
6290 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6291
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006292 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006293 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006294 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006295 if (!term->tl_siex.lpAttributeList)
6296 goto failed;
6297 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6298 0, &breq))
6299 goto failed;
6300 if (!pUpdateProcThreadAttribute(
6301 term->tl_siex.lpAttributeList, 0,
6302 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6303 sizeof(HPCON), NULL, NULL))
6304 goto failed;
6305
6306 channel = add_channel();
6307 if (channel == NULL)
6308 goto failed;
6309
6310 job = job_alloc();
6311 if (job == NULL)
6312 goto failed;
6313 if (argvar->v_type == VAR_STRING)
6314 {
6315 int argc;
6316
6317 build_argv_from_string(cmd, &job->jv_argv, &argc);
6318 }
6319 else
6320 {
6321 int argc;
6322
6323 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6324 }
6325
6326 if (opt->jo_set & JO_IN_BUF)
6327 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6328
6329 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6330 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
Bram Moolenaar07b761a2020-04-26 16:06:01 +02006331 | CREATE_SUSPENDED | CREATE_DEFAULT_ERROR_MODE,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006332 env_wchar, cwd_wchar,
6333 &term->tl_siex.StartupInfo, &proc_info))
6334 goto failed;
6335
6336 CloseHandle(i_theirs);
6337 CloseHandle(o_theirs);
6338
6339 channel_set_pipes(channel,
6340 (sock_T)i_ours,
6341 (sock_T)o_ours,
6342 (sock_T)o_ours);
6343
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006344 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006345 channel->ch_write_text_mode = TRUE;
6346
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006347 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006348 channel->ch_anonymous_pipe = TRUE;
6349
6350 jo = CreateJobObject(NULL, NULL);
6351 if (jo == NULL)
6352 goto failed;
6353
6354 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6355 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006356 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006357 CloseHandle(jo);
6358 jo = NULL;
6359 }
6360
6361 ResumeThread(proc_info.hThread);
6362 CloseHandle(proc_info.hThread);
6363
6364 vim_free(cmd_wchar);
6365 vim_free(cmd_wchar_copy);
6366 vim_free(cwd_wchar);
6367 vim_free(env_wchar);
6368
6369 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6370 goto failed;
6371
6372#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6373 if (opt->jo_set2 & JO2_ANSI_COLORS)
6374 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6375 else
6376 init_vterm_ansi_colors(term->tl_vterm);
6377#endif
6378
6379 channel_set_job(channel, job, opt);
6380 job_set_options(job, opt);
6381
6382 job->jv_channel = channel;
6383 job->jv_proc_info = proc_info;
6384 job->jv_job_object = jo;
6385 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006386 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006387 ++job->jv_refcount;
6388 term->tl_job = job;
6389
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006390 // Redirecting stdout and stderr doesn't work at the job level. Instead
6391 // open the file here and handle it in. opt->jo_io was changed in
6392 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006393 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6394 {
6395 char_u *fname = opt->jo_io_name[PART_OUT];
6396
6397 ch_log(channel, "Opening output file %s", fname);
6398 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6399 if (term->tl_out_fd == NULL)
6400 semsg(_(e_notopen), fname);
6401 }
6402
6403 return OK;
6404
6405failed:
6406 ga_clear(&ga_cmd);
6407 ga_clear(&ga_env);
6408 vim_free(cmd_wchar);
6409 vim_free(cmd_wchar_copy);
6410 vim_free(cwd_wchar);
6411 if (channel != NULL)
6412 channel_clear(channel);
6413 if (job != NULL)
6414 {
6415 job->jv_channel = NULL;
6416 job_cleanup(job);
6417 }
6418 term->tl_job = NULL;
6419 if (jo != NULL)
6420 CloseHandle(jo);
6421
6422 if (term->tl_siex.lpAttributeList != NULL)
6423 {
6424 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6425 vim_free(term->tl_siex.lpAttributeList);
6426 }
6427 term->tl_siex.lpAttributeList = NULL;
6428 if (o_theirs != NULL)
6429 CloseHandle(o_theirs);
6430 if (o_ours != NULL)
6431 CloseHandle(o_ours);
6432 if (i_ours != NULL)
6433 CloseHandle(i_ours);
6434 if (i_theirs != NULL)
6435 CloseHandle(i_theirs);
6436 if (term->tl_conpty != NULL)
6437 pClosePseudoConsole(term->tl_conpty);
6438 term->tl_conpty = NULL;
6439 return FAIL;
6440}
6441
6442 static void
6443conpty_term_report_winsize(term_T *term, int rows, int cols)
6444{
6445 COORD consize;
6446
6447 consize.X = cols;
6448 consize.Y = rows;
6449 pResizePseudoConsole(term->tl_conpty, consize);
6450}
6451
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006452 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006453term_free_conpty(term_T *term)
6454{
6455 if (term->tl_siex.lpAttributeList != NULL)
6456 {
6457 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6458 vim_free(term->tl_siex.lpAttributeList);
6459 }
6460 term->tl_siex.lpAttributeList = NULL;
6461 if (term->tl_conpty != NULL)
6462 pClosePseudoConsole(term->tl_conpty);
6463 term->tl_conpty = NULL;
6464}
6465
6466 int
6467use_conpty(void)
6468{
6469 return has_conpty;
6470}
6471
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006472# ifndef PROTO
6473
6474#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6475#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006476#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006477
6478void* (*winpty_config_new)(UINT64, void*);
6479void* (*winpty_open)(void*, void*);
6480void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6481BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6482void (*winpty_config_set_mouse_mode)(void*, int);
6483void (*winpty_config_set_initial_size)(void*, int, int);
6484LPCWSTR (*winpty_conin_name)(void*);
6485LPCWSTR (*winpty_conout_name)(void*);
6486LPCWSTR (*winpty_conerr_name)(void*);
6487void (*winpty_free)(void*);
6488void (*winpty_config_free)(void*);
6489void (*winpty_spawn_config_free)(void*);
6490void (*winpty_error_free)(void*);
6491LPCWSTR (*winpty_error_msg)(void*);
6492BOOL (*winpty_set_size)(void*, int, int, void*);
6493HANDLE (*winpty_agent_process)(void*);
6494
6495#define WINPTY_DLL "winpty.dll"
6496
6497static HINSTANCE hWinPtyDLL = NULL;
6498# endif
6499
6500 static int
6501dyn_winpty_init(int verbose)
6502{
6503 int i;
6504 static struct
6505 {
6506 char *name;
6507 FARPROC *ptr;
6508 } winpty_entry[] =
6509 {
6510 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6511 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6512 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6513 {"winpty_config_set_mouse_mode",
6514 (FARPROC*)&winpty_config_set_mouse_mode},
6515 {"winpty_config_set_initial_size",
6516 (FARPROC*)&winpty_config_set_initial_size},
6517 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6518 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6519 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6520 {"winpty_free", (FARPROC*)&winpty_free},
6521 {"winpty_open", (FARPROC*)&winpty_open},
6522 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6523 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6524 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6525 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6526 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6527 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6528 {NULL, NULL}
6529 };
6530
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006531 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006532 if (hWinPtyDLL)
6533 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006534 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6535 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006536 if (*p_winptydll != NUL)
6537 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6538 if (!hWinPtyDLL)
6539 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6540 if (!hWinPtyDLL)
6541 {
6542 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006543 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006544 : (char_u *)WINPTY_DLL);
6545 return FAIL;
6546 }
6547 for (i = 0; winpty_entry[i].name != NULL
6548 && winpty_entry[i].ptr != NULL; ++i)
6549 {
6550 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6551 winpty_entry[i].name)) == NULL)
6552 {
6553 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006554 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006555 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006556 return FAIL;
6557 }
6558 }
6559
6560 return OK;
6561}
6562
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006563 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006564winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006565 term_T *term,
6566 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006567 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006568 jobopt_T *opt,
6569 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006570{
6571 WCHAR *cmd_wchar = NULL;
6572 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006573 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006574 channel_T *channel = NULL;
6575 job_T *job = NULL;
6576 DWORD error;
6577 HANDLE jo = NULL;
6578 HANDLE child_process_handle;
6579 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006580 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006581 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006582 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006583 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006584
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006585 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6586 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006587
6588 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006589 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006590 cmd = argvar->vval.v_string;
6591 }
6592 else if (argvar->v_type == VAR_LIST)
6593 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006594 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006595 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006596 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006597 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006598 if (cmd == NULL || *cmd == NUL)
6599 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006600 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006601 goto failed;
6602 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006603
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006604 term->tl_arg0_cmd = vim_strsave(cmd);
6605
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006606 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006607 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006608 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006609 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006610 if (opt->jo_cwd != NULL)
6611 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006612
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006613 win32_build_env(opt->jo_env, &ga_env, TRUE);
6614 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006615
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006616 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6617 if (term->tl_winpty_config == NULL)
6618 goto failed;
6619
6620 winpty_config_set_mouse_mode(term->tl_winpty_config,
6621 WINPTY_MOUSE_MODE_FORCE);
6622 winpty_config_set_initial_size(term->tl_winpty_config,
6623 term->tl_cols, term->tl_rows);
6624 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6625 if (term->tl_winpty == NULL)
6626 goto failed;
6627
6628 spawn_config = winpty_spawn_config_new(
6629 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6630 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6631 NULL,
6632 cmd_wchar,
6633 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006634 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006635 &winpty_err);
6636 if (spawn_config == NULL)
6637 goto failed;
6638
6639 channel = add_channel();
6640 if (channel == NULL)
6641 goto failed;
6642
6643 job = job_alloc();
6644 if (job == NULL)
6645 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006646 if (argvar->v_type == VAR_STRING)
6647 {
6648 int argc;
6649
6650 build_argv_from_string(cmd, &job->jv_argv, &argc);
6651 }
6652 else
6653 {
6654 int argc;
6655
6656 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6657 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006658
6659 if (opt->jo_set & JO_IN_BUF)
6660 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6661
6662 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6663 &child_thread_handle, &error, &winpty_err))
6664 goto failed;
6665
6666 channel_set_pipes(channel,
6667 (sock_T)CreateFileW(
6668 winpty_conin_name(term->tl_winpty),
6669 GENERIC_WRITE, 0, NULL,
6670 OPEN_EXISTING, 0, NULL),
6671 (sock_T)CreateFileW(
6672 winpty_conout_name(term->tl_winpty),
6673 GENERIC_READ, 0, NULL,
6674 OPEN_EXISTING, 0, NULL),
6675 (sock_T)CreateFileW(
6676 winpty_conerr_name(term->tl_winpty),
6677 GENERIC_READ, 0, NULL,
6678 OPEN_EXISTING, 0, NULL));
6679
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006680 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006681 channel->ch_write_text_mode = TRUE;
6682
6683 jo = CreateJobObject(NULL, NULL);
6684 if (jo == NULL)
6685 goto failed;
6686
6687 if (!AssignProcessToJobObject(jo, child_process_handle))
6688 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006689 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006690 CloseHandle(jo);
6691 jo = NULL;
6692 }
6693
6694 winpty_spawn_config_free(spawn_config);
6695 vim_free(cmd_wchar);
6696 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006697 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006698
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006699 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6700 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006701
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006702#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6703 if (opt->jo_set2 & JO2_ANSI_COLORS)
6704 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6705 else
6706 init_vterm_ansi_colors(term->tl_vterm);
6707#endif
6708
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006709 channel_set_job(channel, job, opt);
6710 job_set_options(job, opt);
6711
6712 job->jv_channel = channel;
6713 job->jv_proc_info.hProcess = child_process_handle;
6714 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6715 job->jv_job_object = jo;
6716 job->jv_status = JOB_STARTED;
6717 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006718 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006719 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006720 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006721 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006722 ++job->jv_refcount;
6723 term->tl_job = job;
6724
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006725 // Redirecting stdout and stderr doesn't work at the job level. Instead
6726 // open the file here and handle it in. opt->jo_io was changed in
6727 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006728 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6729 {
6730 char_u *fname = opt->jo_io_name[PART_OUT];
6731
6732 ch_log(channel, "Opening output file %s", fname);
6733 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6734 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006735 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006736 }
6737
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006738 return OK;
6739
6740failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006741 ga_clear(&ga_cmd);
6742 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006743 vim_free(cmd_wchar);
6744 vim_free(cwd_wchar);
6745 if (spawn_config != NULL)
6746 winpty_spawn_config_free(spawn_config);
6747 if (channel != NULL)
6748 channel_clear(channel);
6749 if (job != NULL)
6750 {
6751 job->jv_channel = NULL;
6752 job_cleanup(job);
6753 }
6754 term->tl_job = NULL;
6755 if (jo != NULL)
6756 CloseHandle(jo);
6757 if (term->tl_winpty != NULL)
6758 winpty_free(term->tl_winpty);
6759 term->tl_winpty = NULL;
6760 if (term->tl_winpty_config != NULL)
6761 winpty_config_free(term->tl_winpty_config);
6762 term->tl_winpty_config = NULL;
6763 if (winpty_err != NULL)
6764 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006765 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006766 (short_u *)winpty_error_msg(winpty_err), NULL);
6767
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006768 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006769 winpty_error_free(winpty_err);
6770 }
6771 return FAIL;
6772}
6773
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006774/*
6775 * Create a new terminal of "rows" by "cols" cells.
6776 * Store a reference in "term".
6777 * Return OK or FAIL.
6778 */
6779 static int
6780term_and_job_init(
6781 term_T *term,
6782 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01006783 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006784 jobopt_T *opt,
6785 jobopt_T *orig_opt)
6786{
6787 int use_winpty = FALSE;
6788 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006789 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006790
6791 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6792 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6793
6794 if (!has_winpty && !has_conpty)
6795 // If neither is available give the errors for winpty, since when
6796 // conpty is not available it can't be installed either.
6797 return dyn_winpty_init(TRUE);
6798
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006799 if (opt->jo_tty_type != NUL)
6800 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006801
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006802 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006803 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006804 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006805 use_conpty = TRUE;
6806 else if (has_winpty)
6807 use_winpty = TRUE;
6808 // else: error
6809 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006810 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006811 {
6812 if (has_winpty)
6813 use_winpty = TRUE;
6814 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006815 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006816 {
6817 if (has_conpty)
6818 use_conpty = TRUE;
6819 else
6820 return dyn_conpty_init(TRUE);
6821 }
6822
6823 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006824 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006825
6826 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006827 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006828
6829 // error
6830 return dyn_winpty_init(TRUE);
6831}
6832
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006833 static int
6834create_pty_only(term_T *term, jobopt_T *options)
6835{
6836 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6837 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6838 char in_name[80], out_name[80];
6839 channel_T *channel = NULL;
6840
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006841 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6842 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006843
6844 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6845 GetCurrentProcessId(),
6846 curbuf->b_fnum);
6847 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6848 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6849 PIPE_UNLIMITED_INSTANCES,
6850 0, 0, NMPWAIT_NOWAIT, NULL);
6851 if (hPipeIn == INVALID_HANDLE_VALUE)
6852 goto failed;
6853
6854 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6855 GetCurrentProcessId(),
6856 curbuf->b_fnum);
6857 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6858 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6859 PIPE_UNLIMITED_INSTANCES,
6860 0, 0, 0, NULL);
6861 if (hPipeOut == INVALID_HANDLE_VALUE)
6862 goto failed;
6863
6864 ConnectNamedPipe(hPipeIn, NULL);
6865 ConnectNamedPipe(hPipeOut, NULL);
6866
6867 term->tl_job = job_alloc();
6868 if (term->tl_job == NULL)
6869 goto failed;
6870 ++term->tl_job->jv_refcount;
6871
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006872 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006873 term->tl_job->jv_status = JOB_FINISHED;
6874
6875 channel = add_channel();
6876 if (channel == NULL)
6877 goto failed;
6878 term->tl_job->jv_channel = channel;
6879 channel->ch_keep_open = TRUE;
6880 channel->ch_named_pipe = TRUE;
6881
6882 channel_set_pipes(channel,
6883 (sock_T)hPipeIn,
6884 (sock_T)hPipeOut,
6885 (sock_T)hPipeOut);
6886 channel_set_job(channel, term->tl_job, options);
6887 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6888 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6889
6890 return OK;
6891
6892failed:
6893 if (hPipeIn != NULL)
6894 CloseHandle(hPipeIn);
6895 if (hPipeOut != NULL)
6896 CloseHandle(hPipeOut);
6897 return FAIL;
6898}
6899
6900/*
6901 * Free the terminal emulator part of "term".
6902 */
6903 static void
6904term_free_vterm(term_T *term)
6905{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006906 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006907 if (term->tl_winpty != NULL)
6908 winpty_free(term->tl_winpty);
6909 term->tl_winpty = NULL;
6910 if (term->tl_winpty_config != NULL)
6911 winpty_config_free(term->tl_winpty_config);
6912 term->tl_winpty_config = NULL;
6913 if (term->tl_vterm != NULL)
6914 vterm_free(term->tl_vterm);
6915 term->tl_vterm = NULL;
6916}
6917
6918/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006919 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006920 */
6921 static void
6922term_report_winsize(term_T *term, int rows, int cols)
6923{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006924 if (term->tl_conpty)
6925 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006926 if (term->tl_winpty)
6927 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6928}
6929
6930 int
6931terminal_enabled(void)
6932{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006933 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006934}
6935
6936# else
6937
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006938///////////////////////////////////////
6939// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006940
6941/*
6942 * Create a new terminal of "rows" by "cols" cells.
6943 * Start job for "cmd".
6944 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006945 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006946 * Return OK or FAIL.
6947 */
6948 static int
6949term_and_job_init(
6950 term_T *term,
6951 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006952 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006953 jobopt_T *opt,
6954 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006955{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006956 term->tl_arg0_cmd = NULL;
6957
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006958 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6959 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006960
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006961#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6962 if (opt->jo_set2 & JO2_ANSI_COLORS)
6963 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6964 else
6965 init_vterm_ansi_colors(term->tl_vterm);
6966#endif
6967
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006968 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01006969 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006970 if (term->tl_job != NULL)
6971 ++term->tl_job->jv_refcount;
6972
6973 return term->tl_job != NULL
6974 && term->tl_job->jv_channel != NULL
6975 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6976}
6977
6978 static int
6979create_pty_only(term_T *term, jobopt_T *opt)
6980{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006981 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6982 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006983
6984 term->tl_job = job_alloc();
6985 if (term->tl_job == NULL)
6986 return FAIL;
6987 ++term->tl_job->jv_refcount;
6988
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006989 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006990 term->tl_job->jv_status = JOB_FINISHED;
6991
6992 return mch_create_pty_channel(term->tl_job, opt);
6993}
6994
6995/*
6996 * Free the terminal emulator part of "term".
6997 */
6998 static void
6999term_free_vterm(term_T *term)
7000{
7001 if (term->tl_vterm != NULL)
7002 vterm_free(term->tl_vterm);
7003 term->tl_vterm = NULL;
7004}
7005
7006/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02007007 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007008 */
7009 static void
7010term_report_winsize(term_T *term, int rows, int cols)
7011{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007012 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007013 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
7014 {
7015 int fd = -1;
7016 int part;
7017
7018 for (part = PART_OUT; part < PART_COUNT; ++part)
7019 {
7020 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01007021 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02007022 break;
7023 }
7024 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
7025 mch_signal_job(term->tl_job, (char_u *)"winch");
7026 }
7027}
7028
7029# endif
7030
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007031#endif // FEAT_TERMINAL