blob: 2ff697acfa0d05d3798e186367ce3924a44f091f [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;
165};
166
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100167#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
168#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200169
170/*
171 * List of all active terminals.
172 */
173static term_T *first_term = NULL;
174
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100175// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200176static term_T *in_terminal_loop = NULL;
177
Bram Moolenaar4f974752019-02-17 17:44:42 +0100178#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100179static BOOL has_winpty = FALSE;
180static BOOL has_conpty = FALSE;
181#endif
182
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100183#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200184#define KEY_BUF_LEN 200
185
186/*
187 * Functions with separate implementation for MS-Windows and Unix-like systems.
188 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200189static 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 +0200190static int create_pty_only(term_T *term, jobopt_T *opt);
191static void term_report_winsize(term_T *term, int rows, int cols);
192static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100193#ifdef FEAT_GUI
194static void update_system_term(term_T *term);
195#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200196
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100197static void handle_postponed_scrollback(term_T *term);
198
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100199// The character that we know (or assume) that the terminal expects for the
200// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200201static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200202
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100203// "Terminal" highlight group colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100204static int term_default_cterm_fg = -1;
205static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200206
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100207// Store the last set and the desired cursor properties, so that we only update
208// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200209static char_u *last_set_cursor_color = NULL;
210static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100211static int last_set_cursor_shape = -1;
212static int desired_cursor_shape = -1;
213static int last_set_cursor_blink = -1;
214static int desired_cursor_blink = -1;
215
216
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100217///////////////////////////////////////
218// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200219
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200220 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200221cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
222{
223 if (lhs_color != NULL && rhs_color != NULL)
224 return STRCMP(lhs_color, rhs_color) == 0;
225 return lhs_color == NULL && rhs_color == NULL;
226}
227
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200228 static void
229cursor_color_copy(char_u **to_color, char_u *from_color)
230{
231 // Avoid a free & alloc if the value is already right.
232 if (cursor_color_equal(*to_color, from_color))
233 return;
234 vim_free(*to_color);
235 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
236}
237
238 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200239cursor_color_get(char_u *color)
240{
241 return (color == NULL) ? (char_u *)"" : color;
242}
243
244
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200245/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200246 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200247 * current window.
248 * Sets "rows" and/or "cols" to zero when it should follow the window size.
249 * Return TRUE if the size is the minimum size: "24*80".
250 */
251 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200252parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200253{
254 int minsize = FALSE;
255
256 *rows = 0;
257 *cols = 0;
258
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200259 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200260 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200261 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200262
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100263 // Syntax of value was already checked when it's set.
Bram Moolenaar498c2562018-04-15 23:45:15 +0200264 if (p == NULL)
265 {
266 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200267 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200268 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200269 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200270 *cols = atoi((char *)p + 1);
271 }
272 return minsize;
273}
274
275/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200276 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200277 */
278 static void
279set_term_and_win_size(term_T *term)
280{
Bram Moolenaar13568252018-03-16 20:46:58 +0100281#ifdef FEAT_GUI
282 if (term->tl_system)
283 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100284 // Use the whole screen for the system command. However, it will start
285 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100286 term->tl_rows = Rows;
287 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200288 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100289 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100290#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200291 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200292 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200293 if (term->tl_rows != 0)
294 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
295 if (term->tl_cols != 0)
296 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200297 }
298 if (term->tl_rows == 0)
299 term->tl_rows = curwin->w_height;
300 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200301 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200302 if (term->tl_cols == 0)
303 term->tl_cols = curwin->w_width;
304 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200305 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200306}
307
308/*
309 * Initialize job options for a terminal job.
310 * Caller may overrule some of them.
311 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100312 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200313init_job_options(jobopt_T *opt)
314{
315 clear_job_options(opt);
316
317 opt->jo_mode = MODE_RAW;
318 opt->jo_out_mode = MODE_RAW;
319 opt->jo_err_mode = MODE_RAW;
320 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
321}
322
323/*
324 * Set job options mandatory for a terminal job.
325 */
326 static void
327setup_job_options(jobopt_T *opt, int rows, int cols)
328{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100329#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100330 // Win32: Redirecting the job output won't work, thus always connect stdout
331 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200332 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200333#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200334 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100335 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200336 opt->jo_io[PART_OUT] = JIO_BUFFER;
337 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
338 opt->jo_modifiable[PART_OUT] = 0;
339 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
340 }
341
Bram Moolenaar4f974752019-02-17 17:44:42 +0100342#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100343 // Win32: Redirecting the job output won't work, thus always connect stderr
344 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200345 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200346#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200347 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100348 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200349 opt->jo_io[PART_ERR] = JIO_BUFFER;
350 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
351 opt->jo_modifiable[PART_ERR] = 0;
352 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
353 }
354
355 opt->jo_pty = TRUE;
356 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
357 opt->jo_term_rows = rows;
358 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
359 opt->jo_term_cols = cols;
360}
361
362/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200363 * Flush messages on channels.
364 */
365 static void
366term_flush_messages()
367{
368 mch_check_messages();
369 parse_queued_messages();
370}
371
372/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100373 * Close a terminal buffer (and its window). Used when creating the terminal
374 * fails.
375 */
376 static void
377term_close_buffer(buf_T *buf, buf_T *old_curbuf)
378{
379 free_terminal(buf);
380 if (old_curbuf != NULL)
381 {
382 --curbuf->b_nwindows;
383 curbuf = old_curbuf;
384 curwin->w_buffer = curbuf;
385 ++curbuf->b_nwindows;
386 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100387 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100388
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100389 // Wiping out the buffer will also close the window and call
390 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100391 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
392}
393
394/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200395 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100396 * Use either "argvar" or "argv", the other must be NULL.
397 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
398 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200399 * Returns NULL when failed.
400 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100401 buf_T *
402term_start(
403 typval_T *argvar,
404 char **argv,
405 jobopt_T *opt,
406 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200407{
408 exarg_T split_ea;
409 win_T *old_curwin = curwin;
410 term_T *term;
411 buf_T *old_curbuf = NULL;
412 int res;
413 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100414 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200415 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200416
417 if (check_restricted() || check_secure())
418 return NULL;
419
420 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
421 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
422 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100423 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
424 || (argvar != NULL
425 && argvar->v_type == VAR_LIST
426 && argvar->vval.v_list != NULL
427 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100429 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200430 return NULL;
431 }
432
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200433 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200434 if (term == NULL)
435 return NULL;
436 term->tl_dirty_row_end = MAX_ROW;
437 term->tl_cursor_visible = TRUE;
438 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
439 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100440#ifdef FEAT_GUI
441 term->tl_system = (flags & TERM_START_SYSTEM);
442#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200443 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100444 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200445
446 vim_memset(&split_ea, 0, sizeof(split_ea));
447 if (opt->jo_curwin)
448 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100449 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100450 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200451 {
452 no_write_message();
453 vim_free(term);
454 return NULL;
455 }
456 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100457 ECMD_HIDE
458 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
459 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200460 {
461 vim_free(term);
462 return NULL;
463 }
464 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100465 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200466 {
467 buf_T *buf;
468
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100469 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100470 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200471 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
472 BLN_NEW | BLN_LISTED);
473 if (buf == NULL || ml_open(buf) == FAIL)
474 {
475 vim_free(term);
476 return NULL;
477 }
478 old_curbuf = curbuf;
479 --curbuf->b_nwindows;
480 curbuf = buf;
481 curwin->w_buffer = buf;
482 ++curbuf->b_nwindows;
483 }
484 else
485 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100486 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200487 split_ea.cmdidx = CMD_new;
488 split_ea.cmd = (char_u *)"new";
489 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100490 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200491 {
492 split_ea.line2 = opt->jo_term_rows;
493 split_ea.addr_count = 1;
494 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100495 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200496 {
497 split_ea.line2 = opt->jo_term_cols;
498 split_ea.addr_count = 1;
499 }
500
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100501 if (vertical)
502 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200503 ex_splitview(&split_ea);
504 if (curwin == old_curwin)
505 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100506 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200507 vim_free(term);
508 return NULL;
509 }
510 }
511 term->tl_buffer = curbuf;
512 curbuf->b_term = term;
513
514 if (!opt->jo_hidden)
515 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100516 // Only one size was taken care of with :new, do the other one. With
517 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100518 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200519 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100520 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200521 win_setwidth(opt->jo_term_cols);
522 }
523
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100524 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200525 term->tl_next = first_term;
526 first_term = term;
527
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100528 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
529
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200530 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100531 {
532 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200533 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100534 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100535 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100536 {
537 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100538 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100539 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200540 else
541 {
542 int i;
543 size_t len;
544 char_u *cmd, *p;
545
546 if (argvar->v_type == VAR_STRING)
547 {
548 cmd = argvar->vval.v_string;
549 if (cmd == NULL)
550 cmd = (char_u *)"";
551 else if (STRCMP(cmd, "NONE") == 0)
552 cmd = (char_u *)"pty";
553 }
554 else if (argvar->v_type != VAR_LIST
555 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100556 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100557 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200558 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
559 cmd = (char_u*)"";
560
561 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200562 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200563
564 for (i = 0; p != NULL; ++i)
565 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100566 // Prepend a ! to the command name to avoid the buffer name equals
567 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 if (i == 0)
569 vim_snprintf((char *)p, len, "!%s", cmd);
570 else
571 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
572 if (buflist_findname(p) == NULL)
573 {
574 vim_free(curbuf->b_ffname);
575 curbuf->b_ffname = p;
576 break;
577 }
578 }
579 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100580 vim_free(curbuf->b_sfname);
581 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200582 curbuf->b_fname = curbuf->b_ffname;
583
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100584 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
585
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200586 if (opt->jo_term_opencmd != NULL)
587 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
588
589 if (opt->jo_eof_chars != NULL)
590 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
591
592 set_string_option_direct((char_u *)"buftype", -1,
593 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200594 // Avoid that 'buftype' is reset when this buffer is entered.
595 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200596
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100597 // Mark the buffer as not modifiable. It can only be made modifiable after
598 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200599 curbuf->b_p_ma = FALSE;
600
601 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100602#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200603 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
604#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200605 setup_job_options(opt, term->tl_rows, term->tl_cols);
606
Bram Moolenaar13568252018-03-16 20:46:58 +0100607 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100608 return curbuf;
609
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100610#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100611 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100612 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100613 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100614 else if (argvar->v_type == VAR_STRING)
615 {
616 char_u *cmd = argvar->vval.v_string;
617
618 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
619 term->tl_command = vim_strsave(cmd);
620 }
621 else if (argvar->v_type == VAR_LIST
622 && argvar->vval.v_list != NULL
623 && argvar->vval.v_list->lv_len > 0)
624 {
625 garray_T ga;
626 listitem_T *item;
627
628 ga_init2(&ga, 1, 100);
629 for (item = argvar->vval.v_list->lv_first;
630 item != NULL; item = item->li_next)
631 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100632 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100633 char_u *p;
634
635 if (s == NULL)
636 break;
637 p = vim_strsave_fnameescape(s, FALSE);
638 if (p == NULL)
639 break;
640 ga_concat(&ga, p);
641 vim_free(p);
642 ga_append(&ga, ' ');
643 }
644 if (item == NULL)
645 {
646 ga_append(&ga, NUL);
647 term->tl_command = ga.ga_data;
648 }
649 else
650 ga_clear(&ga);
651 }
652#endif
653
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100654 if (opt->jo_term_kill != NULL)
655 {
656 char_u *p = skiptowhite(opt->jo_term_kill);
657
658 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
659 }
660
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200661 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100662 {
663 char_u *p = skiptowhite(opt->jo_term_api);
664
665 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
666 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200667 else
668 term->tl_api = vim_strsave((char_u *)"Tapi_");
669
Bram Moolenaar83d47902020-03-26 20:34:00 +0100670 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
671 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
672
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100673 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100674 if (argv == NULL
675 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200676 && argvar->vval.v_string != NULL
677 && STRCMP(argvar->vval.v_string, "NONE") == 0)
678 res = create_pty_only(term, opt);
679 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200680 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200681
682 newbuf = curbuf;
683 if (res == OK)
684 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100685 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200686 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
687 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100688#ifdef FEAT_GUI
689 if (term->tl_system)
690 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100691 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100692 term->tl_toprow = msg_row + 1;
693 term->tl_dirty_row_end = 0;
694 }
695#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200696
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100697 // Make sure we don't get stuck on sending keys to the job, it leads to
698 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200699 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
700
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200701 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200702 {
703 --curbuf->b_nwindows;
704 curbuf = old_curbuf;
705 curwin->w_buffer = curbuf;
706 ++curbuf->b_nwindows;
707 }
708 }
709 else
710 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100711 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200712 return NULL;
713 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100714
Bram Moolenaar13568252018-03-16 20:46:58 +0100715 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200716 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
717 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200718 return newbuf;
719}
720
721/*
722 * ":terminal": open a terminal window and execute a job in it.
723 */
724 void
725ex_terminal(exarg_T *eap)
726{
727 typval_T argvar[2];
728 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100729 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200730 char_u *cmd;
731 char_u *tofree = NULL;
732
733 init_job_options(&opt);
734
735 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100736 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200737 {
738 char_u *p, *ep;
739
740 cmd += 2;
741 p = skiptowhite(cmd);
742 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200743 if (ep != NULL)
744 {
745 if (ep < p)
746 p = ep;
747 else
748 ep = NULL;
749 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200750
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200751# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
752 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
753 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200754 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200755 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100756 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200757 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200758 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200759 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200760 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200761 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200762 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200763 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100764 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100765 else if (OPTARG_HAS("shell"))
766 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200767 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100768 {
769 opt.jo_set2 |= JO2_TERM_KILL;
770 opt.jo_term_kill = ep + 1;
771 p = skiptowhite(cmd);
772 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200773 else if (OPTARG_HAS("api"))
774 {
775 opt.jo_set2 |= JO2_TERM_API;
776 if (ep != NULL)
777 {
778 opt.jo_term_api = ep + 1;
779 p = skiptowhite(cmd);
780 }
781 else
782 opt.jo_term_api = NULL;
783 }
784 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200785 {
786 opt.jo_set2 |= JO2_TERM_ROWS;
787 opt.jo_term_rows = atoi((char *)ep + 1);
788 p = skiptowhite(cmd);
789 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200790 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200791 {
792 opt.jo_set2 |= JO2_TERM_COLS;
793 opt.jo_term_cols = atoi((char *)ep + 1);
794 p = skiptowhite(cmd);
795 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200796 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200797 {
798 char_u *buf = NULL;
799 char_u *keys;
800
Bram Moolenaar21109272020-01-30 16:27:20 +0100801 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200802 p = skiptowhite(cmd);
803 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200804 keys = replace_termcodes(ep + 1, &buf,
805 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200806 opt.jo_set2 |= JO2_EOF_CHARS;
807 opt.jo_eof_chars = vim_strsave(keys);
808 vim_free(buf);
809 *p = ' ';
810 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100811#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100812 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
813 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100814 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100815 int tty_type = NUL;
816
817 p = skiptowhite(cmd);
818 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
819 tty_type = 'w';
820 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
821 tty_type = 'c';
822 else
823 {
824 semsg(e_invargval, "type");
825 goto theend;
826 }
827 opt.jo_set2 |= JO2_TTY_TYPE;
828 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100829 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100830#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200831 else
832 {
833 if (*p)
834 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100835 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100836 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200837 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200838# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200839 cmd = skipwhite(p);
840 }
841 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100842 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100843 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200844 tofree = cmd = vim_strsave(p_sh);
845
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100846 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100847 if (opt.jo_term_finish == NUL)
848 opt.jo_term_finish = 'c';
849 }
850
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200851 if (eap->addr_count > 0)
852 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100853 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200854 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
855 opt.jo_io[PART_IN] = JIO_BUFFER;
856 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
857 opt.jo_in_top = eap->line1;
858 opt.jo_in_bot = eap->line2;
859 }
860
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100861 if (opt_shell && tofree == NULL)
862 {
863#ifdef UNIX
864 char **argv = NULL;
865 char_u *tofree1 = NULL;
866 char_u *tofree2 = NULL;
867
868 // :term ++shell command
869 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
870 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100871 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100872 vim_free(tofree1);
873 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100874 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100875#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100876# ifdef MSWIN
877 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
878 char_u *newcmd;
879
880 newcmd = alloc(cmdlen);
881 if (newcmd == NULL)
882 goto theend;
883 tofree = newcmd;
884 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
885 cmd = newcmd;
886# else
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100887 emsg(_("E279: Sorry, ++shell is not supported on this system"));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100888 goto theend;
889# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100890#endif
891 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100892 argvar[0].v_type = VAR_STRING;
893 argvar[0].vval.v_string = cmd;
894 argvar[1].v_type = VAR_UNKNOWN;
895 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100896
897theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100898 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200899 vim_free(opt.jo_eof_chars);
900}
901
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100902#if defined(FEAT_SESSION) || defined(PROTO)
903/*
904 * Write a :terminal command to the session file to restore the terminal in
905 * window "wp".
906 * Return FAIL if writing fails.
907 */
908 int
909term_write_session(FILE *fd, win_T *wp)
910{
911 term_T *term = wp->w_buffer->b_term;
912
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100913 // Create the terminal and run the command. This is not without
914 // risk, but let's assume the user only creates a session when this
915 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100916 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
917 term->tl_cols, term->tl_rows) < 0)
918 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100919#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100920 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
921 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100922#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100923 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
924 return FAIL;
925
926 return put_eol(fd);
927}
928
929/*
930 * Return TRUE if "buf" has a terminal that should be restored.
931 */
932 int
933term_should_restore(buf_T *buf)
934{
935 term_T *term = buf->b_term;
936
937 return term != NULL && (term->tl_command == NULL
938 || STRCMP(term->tl_command, "NONE") != 0);
939}
940#endif
941
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200942/*
943 * Free the scrollback buffer for "term".
944 */
945 static void
946free_scrollback(term_T *term)
947{
948 int i;
949
950 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
951 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
952 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100953 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
954 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
955 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200956}
957
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100958
959// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200960static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100961
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200962/*
963 * Free a terminal and everything it refers to.
964 * Kills the job if there is one.
965 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100966 * The actual terminal structure is freed later in free_unused_terminals(),
967 * because callbacks may wipe out a buffer while the terminal is still
968 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200969 */
970 void
971free_terminal(buf_T *buf)
972{
973 term_T *term = buf->b_term;
974 term_T *tp;
975
976 if (term == NULL)
977 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100978
979 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200980 if (first_term == term)
981 first_term = term->tl_next;
982 else
983 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
984 if (tp->tl_next == term)
985 {
986 tp->tl_next = term->tl_next;
987 break;
988 }
989
990 if (term->tl_job != NULL)
991 {
992 if (term->tl_job->jv_status != JOB_ENDED
993 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100994 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200995 job_stop(term->tl_job, NULL, "kill");
996 job_unref(term->tl_job);
997 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100998 term->tl_next = terminals_to_free;
999 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001000
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001001 buf->b_term = NULL;
1002 if (in_terminal_loop == term)
1003 in_terminal_loop = NULL;
1004}
1005
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001006 void
1007free_unused_terminals()
1008{
1009 while (terminals_to_free != NULL)
1010 {
1011 term_T *term = terminals_to_free;
1012
1013 terminals_to_free = term->tl_next;
1014
1015 free_scrollback(term);
1016
1017 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001018 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001019 vim_free(term->tl_title);
1020#ifdef FEAT_SESSION
1021 vim_free(term->tl_command);
1022#endif
1023 vim_free(term->tl_kill);
1024 vim_free(term->tl_status_text);
1025 vim_free(term->tl_opencmd);
1026 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001027 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001028#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001029 if (term->tl_out_fd != NULL)
1030 fclose(term->tl_out_fd);
1031#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001032 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001033 vim_free(term->tl_cursor_color);
1034 vim_free(term);
1035 }
1036}
1037
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001038/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001039 * Get the part that is connected to the tty. Normally this is PART_IN, but
1040 * when writing buffer lines to the job it can be another. This makes it
1041 * possible to do "1,5term vim -".
1042 */
1043 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001044get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001045{
1046#ifdef UNIX
1047 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1048 int i;
1049
1050 for (i = 0; i < 3; ++i)
1051 {
1052 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1053
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001054 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001055 return parts[i];
1056 }
1057#endif
1058 return PART_IN;
1059}
1060
1061/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001062 * Write job output "msg[len]" to the vterm.
1063 */
1064 static void
1065term_write_job_output(term_T *term, char_u *msg, size_t len)
1066{
1067 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001068 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001069
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001070 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001071
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001072 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001073 if (prevlen != vterm_output_get_buffer_current(vterm))
1074 {
1075 char buf[KEY_BUF_LEN];
1076 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1077
1078 if (curlen > 0)
1079 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1080 (char_u *)buf, (int)curlen, NULL);
1081 }
1082
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001083 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001084 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1085}
1086
1087 static void
1088update_cursor(term_T *term, int redraw)
1089{
1090 if (term->tl_normal_mode)
1091 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001092#ifdef FEAT_GUI
1093 if (term->tl_system)
1094 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1095 term->tl_cursor_pos.col);
1096 else
1097#endif
1098 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001099 if (redraw)
1100 {
1101 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1102 cursor_on();
1103 out_flush();
1104#ifdef FEAT_GUI
1105 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001106 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001107 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001108 gui_mch_flush();
1109 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001110#endif
1111 }
1112}
1113
1114/*
1115 * Invoked when "msg" output from a job was received. Write it to the terminal
1116 * of "buffer".
1117 */
1118 void
1119write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1120{
1121 size_t len = STRLEN(msg);
1122 term_T *term = buffer->b_term;
1123
Bram Moolenaar4f974752019-02-17 17:44:42 +01001124#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001125 // Win32: Cannot redirect output of the job, intercept it here and write to
1126 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001127 if (term->tl_out_fd != NULL)
1128 {
1129 ch_log(channel, "Writing %d bytes to output file", (int)len);
1130 fwrite(msg, len, 1, term->tl_out_fd);
1131 return;
1132 }
1133#endif
1134
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001135 if (term->tl_vterm == NULL)
1136 {
1137 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1138 return;
1139 }
1140 ch_log(channel, "writing %d bytes to terminal", (int)len);
1141 term_write_job_output(term, msg, len);
1142
Bram Moolenaar13568252018-03-16 20:46:58 +01001143#ifdef FEAT_GUI
1144 if (term->tl_system)
1145 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001146 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001147 update_system_term(term);
1148 update_cursor(term, TRUE);
1149 }
1150 else
1151#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001152 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1153 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001154 if (!term->tl_normal_mode)
1155 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001156 // Don't use update_screen() when editing the command line, it gets
1157 // cleared.
1158 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001159 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001160 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001161 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001162 update_screen(VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001163 // update_screen() can be slow, check the terminal wasn't closed
1164 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001165 if (buffer == curbuf && curbuf->b_term != NULL)
1166 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001167 }
1168 else
1169 redraw_after_callback(TRUE);
1170 }
1171}
1172
1173/*
1174 * Send a mouse position and click to the vterm
1175 */
1176 static int
1177term_send_mouse(VTerm *vterm, int button, int pressed)
1178{
1179 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001180 int row = mouse_row - W_WINROW(curwin);
1181 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001182
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001183#ifdef FEAT_PROP_POPUP
1184 if (popup_is_popup(curwin))
1185 {
1186 row -= popup_top_extra(curwin);
1187 col -= popup_left_extra(curwin);
1188 }
1189#endif
1190 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001191 if (button != 0)
1192 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001193 return TRUE;
1194}
1195
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001196static int enter_mouse_col = -1;
1197static int enter_mouse_row = -1;
1198
1199/*
1200 * Handle a mouse click, drag or release.
1201 * Return TRUE when a mouse event is sent to the terminal.
1202 */
1203 static int
1204term_mouse_click(VTerm *vterm, int key)
1205{
1206#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001207 // For modeless selection mouse drag and release events are ignored, unless
1208 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001209 static int ignore_drag_release = TRUE;
1210 VTermMouseState mouse_state;
1211
1212 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1213 if (mouse_state.flags == 0)
1214 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001215 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001216 switch (key)
1217 {
1218 case K_LEFTDRAG:
1219 case K_LEFTRELEASE:
1220 case K_RIGHTDRAG:
1221 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001222 // Ignore drag and release events when the button-down wasn't
1223 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001224 if (ignore_drag_release)
1225 {
1226 int save_mouse_col, save_mouse_row;
1227
1228 if (enter_mouse_col < 0)
1229 break;
1230
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001231 // mouse click in the window gave us focus, handle that
1232 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001233 save_mouse_col = mouse_col;
1234 save_mouse_row = mouse_row;
1235 mouse_col = enter_mouse_col;
1236 mouse_row = enter_mouse_row;
1237 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1238 mouse_col = save_mouse_col;
1239 mouse_row = save_mouse_row;
1240 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001241 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001242 case K_LEFTMOUSE:
1243 case K_RIGHTMOUSE:
1244 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1245 ignore_drag_release = TRUE;
1246 else
1247 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001248 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001249 if (clip_star.available)
1250 {
1251 int button, is_click, is_drag;
1252
1253 button = get_mouse_button(KEY2TERMCAP1(key),
1254 &is_click, &is_drag);
1255 if (mouse_model_popup() && button == MOUSE_LEFT
1256 && (mod_mask & MOD_MASK_SHIFT))
1257 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001258 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001259 button = MOUSE_RIGHT;
1260 mod_mask &= ~MOD_MASK_SHIFT;
1261 }
1262 clip_modeless(button, is_click, is_drag);
1263 }
1264 break;
1265
1266 case K_MIDDLEMOUSE:
1267 if (clip_star.available)
1268 insert_reg('*', TRUE);
1269 break;
1270 }
1271 enter_mouse_col = -1;
1272 return FALSE;
1273 }
1274#endif
1275 enter_mouse_col = -1;
1276
1277 switch (key)
1278 {
1279 case K_LEFTMOUSE:
1280 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1281 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1282 case K_LEFTRELEASE:
1283 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1284 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1285 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1286 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1287 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1288 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1289 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1290 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1291 }
1292 return TRUE;
1293}
1294
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001295/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001296 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1297 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001298 * Return the number of bytes in "buf".
1299 */
1300 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001301term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001302{
1303 VTerm *vterm = term->tl_vterm;
1304 VTermKey key = VTERM_KEY_NONE;
1305 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001306 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001307
1308 switch (c)
1309 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001310 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001311
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001312 // don't use VTERM_KEY_BACKSPACE, it always
1313 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001314 case K_BS: c = term_backspace_char; break;
1315
1316 case ESC: key = VTERM_KEY_ESCAPE; break;
1317 case K_DEL: key = VTERM_KEY_DEL; break;
1318 case K_DOWN: key = VTERM_KEY_DOWN; break;
1319 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1320 key = VTERM_KEY_DOWN; break;
1321 case K_END: key = VTERM_KEY_END; break;
1322 case K_S_END: mod = VTERM_MOD_SHIFT;
1323 key = VTERM_KEY_END; break;
1324 case K_C_END: mod = VTERM_MOD_CTRL;
1325 key = VTERM_KEY_END; break;
1326 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1327 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1328 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1329 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1330 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1331 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1332 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1333 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1334 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1335 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1336 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1337 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1338 case K_HOME: key = VTERM_KEY_HOME; break;
1339 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1340 key = VTERM_KEY_HOME; break;
1341 case K_C_HOME: mod = VTERM_MOD_CTRL;
1342 key = VTERM_KEY_HOME; break;
1343 case K_INS: key = VTERM_KEY_INS; break;
1344 case K_K0: key = VTERM_KEY_KP_0; break;
1345 case K_K1: key = VTERM_KEY_KP_1; break;
1346 case K_K2: key = VTERM_KEY_KP_2; break;
1347 case K_K3: key = VTERM_KEY_KP_3; break;
1348 case K_K4: key = VTERM_KEY_KP_4; break;
1349 case K_K5: key = VTERM_KEY_KP_5; break;
1350 case K_K6: key = VTERM_KEY_KP_6; break;
1351 case K_K7: key = VTERM_KEY_KP_7; break;
1352 case K_K8: key = VTERM_KEY_KP_8; break;
1353 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001354 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001355 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001356 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001357 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001358 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1359 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001360 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1361 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001362 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1363 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001364 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1365 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1366 case K_LEFT: key = VTERM_KEY_LEFT; break;
1367 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1368 key = VTERM_KEY_LEFT; break;
1369 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1370 key = VTERM_KEY_LEFT; break;
1371 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1372 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1373 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1374 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1375 key = VTERM_KEY_RIGHT; break;
1376 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1377 key = VTERM_KEY_RIGHT; break;
1378 case K_UP: key = VTERM_KEY_UP; break;
1379 case K_S_UP: mod = VTERM_MOD_SHIFT;
1380 key = VTERM_KEY_UP; break;
1381 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001382 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1383 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001384
Bram Moolenaara42ad572017-11-16 13:08:04 +01001385 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1386 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001387 case K_MOUSELEFT: /* TODO */ return 0;
1388 case K_MOUSERIGHT: /* TODO */ return 0;
1389
1390 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001391 case K_LEFTMOUSE_NM:
1392 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001393 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001394 case K_LEFTRELEASE_NM:
1395 case K_MOUSEMOVE:
1396 case K_MIDDLEMOUSE:
1397 case K_MIDDLEDRAG:
1398 case K_MIDDLERELEASE:
1399 case K_RIGHTMOUSE:
1400 case K_RIGHTDRAG:
1401 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1402 return 0;
1403 other = TRUE;
1404 break;
1405
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001406 case K_X1MOUSE: /* TODO */ return 0;
1407 case K_X1DRAG: /* TODO */ return 0;
1408 case K_X1RELEASE: /* TODO */ return 0;
1409 case K_X2MOUSE: /* TODO */ return 0;
1410 case K_X2DRAG: /* TODO */ return 0;
1411 case K_X2RELEASE: /* TODO */ return 0;
1412
1413 case K_IGNORE: return 0;
1414 case K_NOP: return 0;
1415 case K_UNDO: return 0;
1416 case K_HELP: return 0;
1417 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1418 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1419 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1420 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1421 case K_SELECT: return 0;
1422#ifdef FEAT_GUI
1423 case K_VER_SCROLLBAR: return 0;
1424 case K_HOR_SCROLLBAR: return 0;
1425#endif
1426#ifdef FEAT_GUI_TABLINE
1427 case K_TABLINE: return 0;
1428 case K_TABMENU: return 0;
1429#endif
1430#ifdef FEAT_NETBEANS_INTG
1431 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1432#endif
1433#ifdef FEAT_DND
1434 case K_DROP: return 0;
1435#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001436 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001437 case K_PS: vterm_keyboard_start_paste(vterm);
1438 other = TRUE;
1439 break;
1440 case K_PE: vterm_keyboard_end_paste(vterm);
1441 other = TRUE;
1442 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001443 }
1444
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001445 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001446 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001447 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001448 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001449 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001450 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001451 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001452
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001453 /*
1454 * Convert special keys to vterm keys:
1455 * - Write keys to vterm: vterm_keyboard_key()
1456 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001457 */
1458 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001459 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001460 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001461 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001462 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001463 vterm_keyboard_unichar(vterm, c, mod);
1464
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001465 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001466 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1467}
1468
1469/*
1470 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001471 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001472 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001473 */
1474 static int
1475term_job_running_check(term_T *term, int check_job_status)
1476{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001477 // Also consider the job finished when the channel is closed, to avoid a
1478 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001479 if (term != NULL
1480 && term->tl_job != NULL
1481 && channel_is_open(term->tl_job->jv_channel))
1482 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001483 job_T *job = term->tl_job;
1484
1485 // Careful: Checking the job status may invoked callbacks, which close
1486 // the buffer and terminate "term". However, "job" will not be freed
1487 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001488 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001489 job_status(job);
1490 return (job->jv_status == JOB_STARTED
1491 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001492 }
1493 return FALSE;
1494}
1495
1496/*
1497 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001498 */
1499 int
1500term_job_running(term_T *term)
1501{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001502 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001503}
1504
1505/*
1506 * Return TRUE if "term" has an active channel and used ":term NONE".
1507 */
1508 int
1509term_none_open(term_T *term)
1510{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001511 // Also consider the job finished when the channel is closed, to avoid a
1512 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001513 return term != NULL
1514 && term->tl_job != NULL
1515 && channel_is_open(term->tl_job->jv_channel)
1516 && term->tl_job->jv_channel->ch_keep_open;
1517}
1518
1519/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001520 * Used when exiting: kill the job in "buf" if so desired.
1521 * Return OK when the job finished.
1522 * Return FAIL when the job is still running.
1523 */
1524 int
1525term_try_stop_job(buf_T *buf)
1526{
1527 int count;
1528 char *how = (char *)buf->b_term->tl_kill;
1529
1530#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1531 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1532 {
1533 char_u buff[DIALOG_MSG_SIZE];
1534 int ret;
1535
1536 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1537 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1538 if (ret == VIM_YES)
1539 how = "kill";
1540 else if (ret == VIM_CANCEL)
1541 return FAIL;
1542 }
1543#endif
1544 if (how == NULL || *how == NUL)
1545 return FAIL;
1546
1547 job_stop(buf->b_term->tl_job, NULL, how);
1548
Bram Moolenaar9172d232019-01-29 23:06:54 +01001549 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001550 for (count = 0; count < 100; ++count)
1551 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001552 job_T *job;
1553
1554 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001555 if (!buf_valid(buf)
1556 || buf->b_term == NULL
1557 || buf->b_term->tl_job == NULL)
1558 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001559 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001560
Bram Moolenaar9172d232019-01-29 23:06:54 +01001561 // Call job_status() to update jv_status. It may cause the job to be
1562 // cleaned up but it won't be freed.
1563 job_status(job);
1564 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001565 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001566
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001567 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001568 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001569 }
1570 return FAIL;
1571}
1572
1573/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001574 * Add the last line of the scrollback buffer to the buffer in the window.
1575 */
1576 static void
1577add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1578{
1579 buf_T *buf = term->tl_buffer;
1580 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1581 linenr_T lnum = buf->b_ml.ml_line_count;
1582
Bram Moolenaar4f974752019-02-17 17:44:42 +01001583#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001584 if (!enc_utf8 && enc_codepage > 0)
1585 {
1586 WCHAR *ret = NULL;
1587 int length = 0;
1588
1589 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1590 &ret, &length);
1591 if (ret != NULL)
1592 {
1593 WideCharToMultiByte_alloc(enc_codepage, 0,
1594 ret, length, (char **)&text, &len, 0, 0);
1595 vim_free(ret);
1596 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1597 vim_free(text);
1598 }
1599 }
1600 else
1601#endif
1602 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1603 if (empty)
1604 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001605 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001606 curbuf = buf;
1607 ml_delete(1, FALSE);
1608 curbuf = curwin->w_buffer;
1609 }
1610}
1611
1612 static void
1613cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1614{
1615 attr->width = cell->width;
1616 attr->attrs = cell->attrs;
1617 attr->fg = cell->fg;
1618 attr->bg = cell->bg;
1619}
1620
1621 static int
1622equal_celattr(cellattr_T *a, cellattr_T *b)
1623{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001624 // Comparing the colors should be sufficient.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001625 return a->fg.red == b->fg.red
1626 && a->fg.green == b->fg.green
1627 && a->fg.blue == b->fg.blue
1628 && a->bg.red == b->bg.red
1629 && a->bg.green == b->bg.green
1630 && a->bg.blue == b->bg.blue;
1631}
1632
Bram Moolenaard96ff162018-02-18 22:13:29 +01001633/*
1634 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1635 * line at this position. Otherwise at the end.
1636 */
1637 static int
1638add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1639{
1640 if (ga_grow(&term->tl_scrollback, 1) == OK)
1641 {
1642 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1643 + term->tl_scrollback.ga_len;
1644
1645 if (lnum > 0)
1646 {
1647 int i;
1648
1649 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1650 {
1651 *line = *(line - 1);
1652 --line;
1653 }
1654 }
1655 line->sb_cols = 0;
1656 line->sb_cells = NULL;
1657 line->sb_fill_attr = *fill_attr;
1658 ++term->tl_scrollback.ga_len;
1659 return OK;
1660 }
1661 return FALSE;
1662}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001663
1664/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001665 * Remove the terminal contents from the scrollback and the buffer.
1666 * Used before adding a new scrollback line or updating the buffer for lines
1667 * displayed in the terminal.
1668 */
1669 static void
1670cleanup_scrollback(term_T *term)
1671{
1672 sb_line_T *line;
1673 garray_T *gap;
1674
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001675 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001676 gap = &term->tl_scrollback;
1677 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1678 && gap->ga_len > 0)
1679 {
1680 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1681 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1682 vim_free(line->sb_cells);
1683 --gap->ga_len;
1684 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001685 curbuf = curwin->w_buffer;
1686 if (curbuf == term->tl_buffer)
1687 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001688}
1689
1690/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001691 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001692 */
1693 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001694update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001695{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001696 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001697 int len;
1698 int lines_skipped = 0;
1699 VTermPos pos;
1700 VTermScreenCell cell;
1701 cellattr_T fill_attr, new_fill_attr;
1702 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001703
1704 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1705 "Adding terminal window snapshot to buffer");
1706
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001707 // First remove the lines that were appended before, they might be
1708 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001709 cleanup_scrollback(term);
1710
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001711 screen = vterm_obtain_screen(term->tl_vterm);
1712 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001713 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1714 {
1715 len = 0;
1716 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1717 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1718 && cell.chars[0] != NUL)
1719 {
1720 len = pos.col + 1;
1721 new_fill_attr = term->tl_default_color;
1722 }
1723 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001724 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001725 cell2cellattr(&cell, &new_fill_attr);
1726
1727 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1728 ++lines_skipped;
1729 else
1730 {
1731 while (lines_skipped > 0)
1732 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001733 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001735 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001736 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001737 }
1738
1739 if (len == 0)
1740 p = NULL;
1741 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001742 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001743 if ((p != NULL || len == 0)
1744 && ga_grow(&term->tl_scrollback, 1) == OK)
1745 {
1746 garray_T ga;
1747 int width;
1748 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1749 + term->tl_scrollback.ga_len;
1750
1751 ga_init2(&ga, 1, 100);
1752 for (pos.col = 0; pos.col < len; pos.col += width)
1753 {
1754 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1755 {
1756 width = 1;
1757 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1758 if (ga_grow(&ga, 1) == OK)
1759 ga.ga_len += utf_char2bytes(' ',
1760 (char_u *)ga.ga_data + ga.ga_len);
1761 }
1762 else
1763 {
1764 width = cell.width;
1765
1766 cell2cellattr(&cell, &p[pos.col]);
1767
Bram Moolenaara79fd562018-12-20 20:47:32 +01001768 // Each character can be up to 6 bytes.
1769 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001770 {
1771 int i;
1772 int c;
1773
1774 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1775 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1776 (char_u *)ga.ga_data + ga.ga_len);
1777 }
1778 }
1779 }
1780 line->sb_cols = len;
1781 line->sb_cells = p;
1782 line->sb_fill_attr = new_fill_attr;
1783 fill_attr = new_fill_attr;
1784 ++term->tl_scrollback.ga_len;
1785
1786 if (ga_grow(&ga, 1) == FAIL)
1787 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1788 else
1789 {
1790 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1791 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1792 }
1793 ga_clear(&ga);
1794 }
1795 else
1796 vim_free(p);
1797 }
1798 }
1799
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001800 // Add trailing empty lines.
1801 for (pos.row = term->tl_scrollback.ga_len;
1802 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1803 ++pos.row)
1804 {
1805 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1806 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1807 }
1808
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001809 term->tl_dirty_snapshot = FALSE;
1810#ifdef FEAT_TIMERS
1811 term->tl_timer_set = FALSE;
1812#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001813}
1814
1815/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001816 * Loop over all windows in the current tab, and also curwin, which is not
1817 * encountered when using a terminal in a popup window.
1818 * Return TRUE if "*wp" was set to the next window.
1819 */
1820 static int
1821for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1822{
1823 if (*wp == NULL)
1824 *wp = firstwin;
1825 else if ((*wp)->w_next != NULL)
1826 *wp = (*wp)->w_next;
1827 else if (!*did_curwin)
1828 *wp = curwin;
1829 else
1830 return FALSE;
1831 if (*wp == curwin)
1832 *did_curwin = TRUE;
1833 return TRUE;
1834}
1835
1836/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001837 * If needed, add the current lines of the terminal to scrollback and to the
1838 * buffer. Called after the job has ended and when switching to
1839 * Terminal-Normal mode.
1840 * When "redraw" is TRUE redraw the windows that show the terminal.
1841 */
1842 static void
1843may_move_terminal_to_buffer(term_T *term, int redraw)
1844{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001845 if (term->tl_vterm == NULL)
1846 return;
1847
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001848 // Update the snapshot only if something changes or the buffer does not
1849 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001850 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1851 <= term->tl_scrollback_scrolled)
1852 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001853
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001854 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001855 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1856 &term->tl_default_color.fg, &term->tl_default_color.bg);
1857
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001858 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001859 {
1860 win_T *wp = NULL;
1861 int did_curwin = FALSE;
1862
1863 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001864 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001865 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001866 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001867 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1868 wp->w_cursor.col = 0;
1869 wp->w_valid = 0;
1870 if (wp->w_cursor.lnum >= wp->w_height)
1871 {
1872 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001873
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001874 if (wp->w_topline < min_topline)
1875 wp->w_topline = min_topline;
1876 }
1877 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001878 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001879 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001880 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001881}
1882
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001883#if defined(FEAT_TIMERS) || defined(PROTO)
1884/*
1885 * Check if any terminal timer expired. If so, copy text from the terminal to
1886 * the buffer.
1887 * Return the time until the next timer will expire.
1888 */
1889 int
1890term_check_timers(int next_due_arg, proftime_T *now)
1891{
1892 term_T *term;
1893 int next_due = next_due_arg;
1894
1895 for (term = first_term; term != NULL; term = term->tl_next)
1896 {
1897 if (term->tl_timer_set && !term->tl_normal_mode)
1898 {
1899 long this_due = proftime_time_left(&term->tl_timer_due, now);
1900
1901 if (this_due <= 1)
1902 {
1903 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001904 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001905 }
1906 else if (next_due == -1 || next_due > this_due)
1907 next_due = this_due;
1908 }
1909 }
1910
1911 return next_due;
1912}
1913#endif
1914
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001915/*
1916 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1917 * otherwise end it.
1918 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001919 static void
1920set_terminal_mode(term_T *term, int normal_mode)
1921{
1922 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001923 if (!normal_mode)
1924 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001925 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001926 if (term->tl_buffer == curbuf)
1927 maketitle();
1928}
1929
1930/*
1931 * Called after the job if finished and Terminal mode is not active:
1932 * Move the vterm contents into the scrollback buffer and free the vterm.
1933 */
1934 static void
1935cleanup_vterm(term_T *term)
1936{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001937 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001938 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001939 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001940 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001941}
1942
1943/*
1944 * Switch from Terminal-Job mode to Terminal-Normal mode.
1945 * Suspends updating the terminal window.
1946 */
1947 static void
1948term_enter_normal_mode(void)
1949{
1950 term_T *term = curbuf->b_term;
1951
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001952 set_terminal_mode(term, TRUE);
1953
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001954 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001955 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001956
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001957 // Move the window cursor to the position of the cursor in the
1958 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001959 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1960 + term->tl_cursor_pos.row + 1;
1961 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001962 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1963 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001964 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001965
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001966 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001967 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1968}
1969
1970/*
1971 * Returns TRUE if the current window contains a terminal and we are in
1972 * Terminal-Normal mode.
1973 */
1974 int
1975term_in_normal_mode(void)
1976{
1977 term_T *term = curbuf->b_term;
1978
1979 return term != NULL && term->tl_normal_mode;
1980}
1981
1982/*
1983 * Switch from Terminal-Normal mode to Terminal-Job mode.
1984 * Restores updating the terminal window.
1985 */
1986 void
1987term_enter_job_mode()
1988{
1989 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001990
1991 set_terminal_mode(term, FALSE);
1992
1993 if (term->tl_channel_closed)
1994 cleanup_vterm(term);
1995 redraw_buf_and_status_later(curbuf, NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001996#ifdef FEAT_PROP_POPUP
1997 if (WIN_IS_POPUP(curwin))
Bram Moolenaard5bc32d2020-03-22 19:25:50 +01001998 redraw_later(NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001999#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002000}
2001
2002/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002003 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002004 * Note: while waiting a terminal may be closed and freed if the channel is
2005 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002006 */
2007 static int
2008term_vgetc()
2009{
2010 int c;
2011 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002012 int modify_other_keys =
2013 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002014
2015 State = TERMINAL;
2016 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002017#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002018 ctrl_break_was_pressed = FALSE;
2019#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002020 if (modify_other_keys)
2021 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022 c = vgetc();
2023 got_int = FALSE;
2024 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002025 if (modify_other_keys)
2026 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002027 return c;
2028}
2029
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002030static int mouse_was_outside = FALSE;
2031
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002032/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002033 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002034 * Return FAIL when the key needs to be handled in Normal mode.
2035 * Return OK when the key was dropped or sent to the terminal.
2036 */
2037 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002038send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002039{
2040 char msg[KEY_BUF_LEN];
2041 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002042 int dragging_outside = FALSE;
2043
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002044 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002045 switch (c)
2046 {
2047 case NUL:
2048 case K_ZERO:
2049 if (typed)
2050 stuffcharReadbuff(c);
2051 return FAIL;
2052
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002053 case K_TABLINE:
2054 stuffcharReadbuff(c);
2055 return FAIL;
2056
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002057 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002058 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002059 return FAIL;
2060
2061 case K_LEFTDRAG:
2062 case K_MIDDLEDRAG:
2063 case K_RIGHTDRAG:
2064 case K_X1DRAG:
2065 case K_X2DRAG:
2066 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002067 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002068 case K_LEFTMOUSE:
2069 case K_LEFTMOUSE_NM:
2070 case K_LEFTRELEASE:
2071 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002072 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002073 case K_MIDDLEMOUSE:
2074 case K_MIDDLERELEASE:
2075 case K_RIGHTMOUSE:
2076 case K_RIGHTRELEASE:
2077 case K_X1MOUSE:
2078 case K_X1RELEASE:
2079 case K_X2MOUSE:
2080 case K_X2RELEASE:
2081
2082 case K_MOUSEUP:
2083 case K_MOUSEDOWN:
2084 case K_MOUSELEFT:
2085 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002086 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002087 int row = mouse_row;
2088 int col = mouse_col;
2089
2090#ifdef FEAT_PROP_POPUP
2091 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002092 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002093 row -= popup_top_extra(curwin);
2094 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002095 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002096#endif
2097 if (row < W_WINROW(curwin)
2098 || row >= (W_WINROW(curwin) + curwin->w_height)
2099 || col < curwin->w_wincol
2100 || col >= W_ENDCOL(curwin)
2101 || dragging_outside)
2102 {
2103 // click or scroll outside the current window or on status
2104 // line or vertical separator
2105 if (typed)
2106 {
2107 stuffcharReadbuff(c);
2108 mouse_was_outside = TRUE;
2109 }
2110 return FAIL;
2111 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002112 }
2113 }
2114 if (typed)
2115 mouse_was_outside = FALSE;
2116
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002117 // Convert the typed key to a sequence of bytes for the job.
2118 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002119 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002120 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002121 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2122 (char_u *)msg, (int)len, NULL);
2123
2124 return OK;
2125}
2126
2127 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002128position_cursor(win_T *wp, VTermPos *pos, int add_off UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002129{
2130 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2131 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002132#ifdef FEAT_PROP_POPUP
2133 if (add_off && popup_is_popup(curwin))
2134 {
2135 wp->w_wrow += popup_top_extra(curwin);
2136 wp->w_wcol += popup_left_extra(curwin);
2137 }
2138#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002139 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2140}
2141
2142/*
2143 * Handle CTRL-W "": send register contents to the job.
2144 */
2145 static void
2146term_paste_register(int prev_c UNUSED)
2147{
2148 int c;
2149 list_T *l;
2150 listitem_T *item;
2151 long reglen = 0;
2152 int type;
2153
2154#ifdef FEAT_CMDL_INFO
2155 if (add_to_showcmd(prev_c))
2156 if (add_to_showcmd('"'))
2157 out_flush();
2158#endif
2159 c = term_vgetc();
2160#ifdef FEAT_CMDL_INFO
2161 clear_showcmd();
2162#endif
2163 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002164 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002165 return;
2166
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002167 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002168 if (c == '=' && get_expr_register() != '=')
2169 return;
2170 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002171 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002172 return;
2173
2174 l = (list_T *)get_reg_contents(c, GREG_LIST);
2175 if (l != NULL)
2176 {
2177 type = get_reg_type(c, &reglen);
2178 for (item = l->lv_first; item != NULL; item = item->li_next)
2179 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002180 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002181#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002182 char_u *tmp = s;
2183
2184 if (!enc_utf8 && enc_codepage > 0)
2185 {
2186 WCHAR *ret = NULL;
2187 int length = 0;
2188
2189 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2190 (int)STRLEN(s), &ret, &length);
2191 if (ret != NULL)
2192 {
2193 WideCharToMultiByte_alloc(CP_UTF8, 0,
2194 ret, length, (char **)&s, &length, 0, 0);
2195 vim_free(ret);
2196 }
2197 }
2198#endif
2199 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2200 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002201#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002202 if (tmp != s)
2203 vim_free(s);
2204#endif
2205
2206 if (item->li_next != NULL || type == MLINE)
2207 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2208 (char_u *)"\r", 1, NULL);
2209 }
2210 list_free(l);
2211 }
2212}
2213
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002214/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002215 * Return TRUE when waiting for a character in the terminal, the cursor of the
2216 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002217 */
2218 int
2219terminal_is_active()
2220{
2221 return in_terminal_loop != NULL;
2222}
2223
Bram Moolenaar83d47902020-03-26 20:34:00 +01002224/*
2225 * Return the highight group name for the terminal; "Terminal" if not set.
2226 */
2227 static char_u *
2228term_get_highlight_name(term_T *term)
2229{
2230 if (term->tl_highlight_name == NULL)
2231 return (char_u *)"Terminal";
2232 return term->tl_highlight_name;
2233}
2234
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002235#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 cursorentry_T *
2237term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2238{
2239 term_T *term = in_terminal_loop;
2240 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002241 int id;
2242 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002243
2244 vim_memset(&entry, 0, sizeof(entry));
2245 entry.shape = entry.mshape =
2246 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2247 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2248 SHAPE_BLOCK;
2249 entry.percentage = 20;
2250 if (term->tl_cursor_blink)
2251 {
2252 entry.blinkwait = 700;
2253 entry.blinkon = 400;
2254 entry.blinkoff = 250;
2255 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002256
Bram Moolenaar83d47902020-03-26 20:34:00 +01002257 // The highlight group overrules the defaults.
2258 id = syn_name2id(term_get_highlight_name(term));
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002259 if (id != 0)
2260 {
2261 syn_id2colors(id, &term_fg, &term_bg);
2262 *fg = term_bg;
2263 }
2264 else
2265 *fg = gui.back_pixel;
2266
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002267 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002268 {
2269 if (id != 0)
2270 *bg = term_fg;
2271 else
2272 *bg = gui.norm_pixel;
2273 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002274 else
2275 *bg = color_name2handle(term->tl_cursor_color);
2276 entry.name = "n";
2277 entry.used_for = SHAPE_CURSOR;
2278
2279 return &entry;
2280}
2281#endif
2282
Bram Moolenaard317b382018-02-08 22:33:31 +01002283 static void
2284may_output_cursor_props(void)
2285{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002286 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002287 || last_set_cursor_shape != desired_cursor_shape
2288 || last_set_cursor_blink != desired_cursor_blink)
2289 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002290 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002291 last_set_cursor_shape = desired_cursor_shape;
2292 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002293 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002294 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002295 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002296 ui_cursor_shape_forced(TRUE);
2297 else
2298 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2299 }
2300}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002301
Bram Moolenaard317b382018-02-08 22:33:31 +01002302/*
2303 * Set the cursor color and shape, if not last set to these.
2304 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002305 static void
2306may_set_cursor_props(term_T *term)
2307{
2308#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002309 // For the GUI the cursor properties are obtained with
2310 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002311 if (gui.in_use)
2312 return;
2313#endif
2314 if (in_terminal_loop == term)
2315 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002316 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002317 desired_cursor_shape = term->tl_cursor_shape;
2318 desired_cursor_blink = term->tl_cursor_blink;
2319 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002320 }
2321}
2322
Bram Moolenaard317b382018-02-08 22:33:31 +01002323/*
2324 * Reset the desired cursor properties and restore them when needed.
2325 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002326 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002327prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002328{
2329#ifdef FEAT_GUI
2330 if (gui.in_use)
2331 return;
2332#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002333 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002334 desired_cursor_shape = -1;
2335 desired_cursor_blink = -1;
2336 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002337}
2338
2339/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002340 * Returns TRUE if the current window contains a terminal and we are sending
2341 * keys to the job.
2342 * If "check_job_status" is TRUE update the job status.
2343 */
2344 static int
2345term_use_loop_check(int check_job_status)
2346{
2347 term_T *term = curbuf->b_term;
2348
2349 return term != NULL
2350 && !term->tl_normal_mode
2351 && term->tl_vterm != NULL
2352 && term_job_running_check(term, check_job_status);
2353}
2354
2355/*
2356 * Returns TRUE if the current window contains a terminal and we are sending
2357 * keys to the job.
2358 */
2359 int
2360term_use_loop(void)
2361{
2362 return term_use_loop_check(FALSE);
2363}
2364
2365/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002366 * Called when entering a window with the mouse. If this is a terminal window
2367 * we may want to change state.
2368 */
2369 void
2370term_win_entered()
2371{
2372 term_T *term = curbuf->b_term;
2373
2374 if (term != NULL)
2375 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002376 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002377 {
2378 reset_VIsual_and_resel();
2379 if (State & INSERT)
2380 stop_insert_mode = TRUE;
2381 }
2382 mouse_was_outside = FALSE;
2383 enter_mouse_col = mouse_col;
2384 enter_mouse_row = mouse_row;
2385 }
2386}
2387
2388/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002389 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2390 * Return the Ctrl-key value in that case.
2391 */
2392 static int
2393raw_c_to_ctrl(int c)
2394{
2395 if ((mod_mask & MOD_MASK_CTRL)
2396 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2397 return c & 0x1f;
2398 return c;
2399}
2400
2401/*
2402 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2403 * May set "mod_mask".
2404 */
2405 static int
2406ctrl_to_raw_c(int c)
2407{
2408 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2409 {
2410 mod_mask |= MOD_MASK_CTRL;
2411 return c + '@';
2412 }
2413 return c;
2414}
2415
2416/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002417 * Wait for input and send it to the job.
2418 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2419 * when there is no more typahead.
2420 * Return when the start of a CTRL-W command is typed or anything else that
2421 * should be handled as a Normal mode command.
2422 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2423 * the terminal was closed.
2424 */
2425 int
2426terminal_loop(int blocking)
2427{
2428 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002429 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002430 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002431 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002432#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002433 int tty_fd = curbuf->b_term->tl_job->jv_channel
2434 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002435#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002436 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002437
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002438 // Remember the terminal we are sending keys to. However, the terminal
2439 // might be closed while waiting for a character, e.g. typing "exit" in a
2440 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2441 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002442 in_terminal_loop = curbuf->b_term;
2443
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002444 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002445 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002446 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002447 if (termwinkey == Ctrl_W)
2448 termwinkey = 0;
2449 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002450 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002451 may_set_cursor_props(curbuf->b_term);
2452
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002453 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002454 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002455#ifdef FEAT_GUI
2456 if (!curbuf->b_term->tl_system)
2457#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002458 // TODO: skip screen update when handling a sequence of keys.
2459 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002460 while (must_redraw != 0)
2461 if (update_screen(0) == FAIL)
2462 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002463 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002464 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002465 break;
2466
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002467 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002468 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002469
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002470 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002471 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002472 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002473 // Job finished while waiting for a character. Push back the
2474 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002475 if (raw_c != K_IGNORE)
2476 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002477 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002478 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002479 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002480 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002481 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002482
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002483#ifdef UNIX
2484 /*
2485 * The shell or another program may change the tty settings. Getting
2486 * them for every typed character is a bit of overhead, but it's needed
2487 * for the first character typed, e.g. when Vim starts in a shell.
2488 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002489 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002490 {
2491 ttyinfo_T info;
2492
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002493 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002494 if (get_tty_info(tty_fd, &info) == OK)
2495 term_backspace_char = info.backspace;
2496 }
2497#endif
2498
Bram Moolenaar4f974752019-02-17 17:44:42 +01002499#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002500 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2501 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002502 if (ctrl_break_was_pressed)
2503 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2504#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002505 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2506 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002507 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002508#ifdef FEAT_GUI
2509 && !curbuf->b_term->tl_system
2510#endif
2511 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002512 {
2513 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002514 int prev_raw_c = raw_c;
2515 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002516
2517#ifdef FEAT_CMDL_INFO
2518 if (add_to_showcmd(c))
2519 out_flush();
2520#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002521 raw_c = term_vgetc();
2522 c = raw_c_to_ctrl(raw_c);
2523
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002524#ifdef FEAT_CMDL_INFO
2525 clear_showcmd();
2526#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002527 if (!term_use_loop_check(TRUE)
2528 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002529 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002530 break;
2531
2532 if (prev_c == Ctrl_BSL)
2533 {
2534 if (c == Ctrl_N)
2535 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002536 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002537 term_enter_normal_mode();
2538 ret = FAIL;
2539 goto theend;
2540 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002541 // Send both keys to the terminal, first one here, second one
2542 // below.
2543 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2544 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002545 }
2546 else if (c == Ctrl_C)
2547 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002548 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002549 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2550 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002551 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002552 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002553 // "CTRL-W .": send CTRL-W to the job
2554 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002555 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002556 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002557 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002558 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002559 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002560 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002561 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002562 else if (c == 'N')
2563 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002564 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002565 term_enter_normal_mode();
2566 ret = FAIL;
2567 goto theend;
2568 }
2569 else if (c == '"')
2570 {
2571 term_paste_register(prev_c);
2572 continue;
2573 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002574 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002575 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002576 char_u buf[MB_MAXBYTES + 2];
2577
2578 // Put the command into the typeahead buffer, when using the
2579 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2580 buf[0] = Ctrl_W;
2581 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2582 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002583 ret = OK;
2584 goto theend;
2585 }
2586 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002587# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002588 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002589 {
2590 WCHAR wc;
2591 char_u mb[3];
2592
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002593 mb[0] = (unsigned)raw_c >> 8;
2594 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002595 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002596 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002597 }
2598# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002599 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002600 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002601 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002602 // We are sure to come back here, don't reset the cursor color
2603 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002604 restore_cursor = FALSE;
2605
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002606 ret = OK;
2607 goto theend;
2608 }
2609 }
2610 ret = FAIL;
2611
2612theend:
2613 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002614 if (restore_cursor)
2615 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002616
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002617 // Move a snapshot of the screen contents to the buffer, so that completion
2618 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002619 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2620 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002621
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002622 return ret;
2623}
2624
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002625 static void
2626may_toggle_cursor(term_T *term)
2627{
2628 if (in_terminal_loop == term)
2629 {
2630 if (term->tl_cursor_visible)
2631 cursor_on();
2632 else
2633 cursor_off();
2634 }
2635}
2636
2637/*
Bram Moolenaar83d47902020-03-26 20:34:00 +01002638 * Cache "Terminal" highlight group colors.
2639 */
2640 void
2641set_terminal_default_colors(int cterm_fg, int cterm_bg)
2642{
2643 term_default_cterm_fg = cterm_fg - 1;
2644 term_default_cterm_bg = cterm_bg - 1;
2645}
2646
2647 static int
2648get_default_cterm_fg(term_T *term)
2649{
2650 if (term->tl_highlight_name != NULL)
2651 {
2652 int id = syn_name2id(term->tl_highlight_name);
2653 int fg = -1;
2654 int bg = -1;
2655
2656 if (id > 0)
2657 syn_id2cterm_bg(id, &fg, &bg);
2658 return fg;
2659 }
2660 return term_default_cterm_fg;
2661}
2662
2663 static int
2664get_default_cterm_bg(term_T *term)
2665{
2666 if (term->tl_highlight_name != NULL)
2667 {
2668 int id = syn_name2id(term->tl_highlight_name);
2669 int fg = -1;
2670 int bg = -1;
2671
2672 if (id > 0)
2673 syn_id2cterm_bg(id, &fg, &bg);
2674 return bg;
2675 }
2676 return term_default_cterm_bg;
2677}
2678
2679/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002680 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002681 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002682 */
2683 static int
2684color2index(VTermColor *color, int fg, int *boldp)
2685{
2686 int red = color->red;
2687 int blue = color->blue;
2688 int green = color->green;
2689
Bram Moolenaar46359e12017-11-29 22:33:38 +01002690 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002691 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002692 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002693 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002694 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002695 case 0: return 0;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002696 case 1: return lookup_color( 0, fg, boldp) + 1; // black
2697 case 2: return lookup_color( 4, fg, boldp) + 1; // dark red
2698 case 3: return lookup_color( 2, fg, boldp) + 1; // dark green
2699 case 4: return lookup_color( 6, fg, boldp) + 1; // brown
2700 case 5: return lookup_color( 1, fg, boldp) + 1; // dark blue
2701 case 6: return lookup_color( 5, fg, boldp) + 1; // dark magenta
2702 case 7: return lookup_color( 3, fg, boldp) + 1; // dark cyan
2703 case 8: return lookup_color( 8, fg, boldp) + 1; // light grey
2704 case 9: return lookup_color(12, fg, boldp) + 1; // dark grey
2705 case 10: return lookup_color(20, fg, boldp) + 1; // red
2706 case 11: return lookup_color(16, fg, boldp) + 1; // green
2707 case 12: return lookup_color(24, fg, boldp) + 1; // yellow
2708 case 13: return lookup_color(14, fg, boldp) + 1; // blue
2709 case 14: return lookup_color(22, fg, boldp) + 1; // magenta
2710 case 15: return lookup_color(18, fg, boldp) + 1; // cyan
2711 case 16: return lookup_color(26, fg, boldp) + 1; // white
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002712 }
2713 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002714
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002715 if (t_colors >= 256)
2716 {
2717 if (red == blue && red == green)
2718 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002719 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002720 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002721 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2722 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2723 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002724 int i;
2725
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002726 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002727 return 17; // 00/00/00
2728 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002729 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002730 for (i = 0; i < 23; ++i)
2731 if (red < cutoff[i])
2732 return i + 233;
2733 return 256;
2734 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002735 {
2736 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2737 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002738
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002739 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002740 for (ri = 0; ri < 5; ++ri)
2741 if (red < cutoff[ri])
2742 break;
2743 for (gi = 0; gi < 5; ++gi)
2744 if (green < cutoff[gi])
2745 break;
2746 for (bi = 0; bi < 5; ++bi)
2747 if (blue < cutoff[bi])
2748 break;
2749 return 17 + ri * 36 + gi * 6 + bi;
2750 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002751 }
2752 return 0;
2753}
2754
2755/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002756 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002757 */
2758 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002759vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002760{
2761 int attr = 0;
2762
2763 if (cellattrs.bold)
2764 attr |= HL_BOLD;
2765 if (cellattrs.underline)
2766 attr |= HL_UNDERLINE;
2767 if (cellattrs.italic)
2768 attr |= HL_ITALIC;
2769 if (cellattrs.strike)
2770 attr |= HL_STRIKETHROUGH;
2771 if (cellattrs.reverse)
2772 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002773 return attr;
2774}
2775
2776/*
2777 * Store Vterm attributes in "cell" from highlight flags.
2778 */
2779 static void
2780hl2vtermAttr(int attr, cellattr_T *cell)
2781{
2782 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2783 if (attr & HL_BOLD)
2784 cell->attrs.bold = 1;
2785 if (attr & HL_UNDERLINE)
2786 cell->attrs.underline = 1;
2787 if (attr & HL_ITALIC)
2788 cell->attrs.italic = 1;
2789 if (attr & HL_STRIKETHROUGH)
2790 cell->attrs.strike = 1;
2791 if (attr & HL_INVERSE)
2792 cell->attrs.reverse = 1;
2793}
2794
2795/*
2796 * Convert the attributes of a vterm cell into an attribute index.
2797 */
2798 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002799cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01002800 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002801 win_T *wp,
2802 VTermScreenCellAttrs cellattrs,
2803 VTermColor cellfg,
2804 VTermColor cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002805{
2806 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002807
2808#ifdef FEAT_GUI
2809 if (gui.in_use)
2810 {
2811 guicolor_T fg, bg;
2812
2813 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2814 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2815 return get_gui_attr_idx(attr, fg, bg);
2816 }
2817 else
2818#endif
2819#ifdef FEAT_TERMGUICOLORS
2820 if (p_tgc)
2821 {
2822 guicolor_T fg, bg;
2823
2824 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2825 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2826
2827 return get_tgc_attr_idx(attr, fg, bg);
2828 }
2829 else
2830#endif
2831 {
2832 int bold = MAYBE;
2833 int fg = color2index(&cellfg, TRUE, &bold);
2834 int bg = color2index(&cellbg, FALSE, &bold);
2835
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002836 // Use the 'wincolor' or "Terminal" highlighting for the default
2837 // colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002838 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002839 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002840 int wincolor_fg = -1;
2841 int wincolor_bg = -1;
2842
2843 if (wp != NULL && *wp->w_p_wcr != NUL)
2844 {
2845 int id = syn_name2id(curwin->w_p_wcr);
2846
2847 // Get the 'wincolor' group colors.
2848 if (id > 0)
2849 syn_id2cterm_bg(id, &wincolor_fg, &wincolor_bg);
2850 }
2851 if (fg == 0)
2852 {
2853 if (wincolor_fg >= 0)
2854 fg = wincolor_fg + 1;
Bram Moolenaar83d47902020-03-26 20:34:00 +01002855 else
2856 {
2857 int cterm_fg = get_default_cterm_fg(term);
2858
2859 if (cterm_fg >= 0)
2860 fg = cterm_fg + 1;
2861 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002862 }
2863 if (bg == 0)
2864 {
2865 if (wincolor_bg >= 0)
2866 bg = wincolor_bg + 1;
Bram Moolenaar83d47902020-03-26 20:34:00 +01002867 else
2868 {
2869 int cterm_bg = get_default_cterm_bg(term);
2870
2871 if (cterm_bg >= 0)
2872 bg = cterm_bg + 1;
2873 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002874 }
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002875 }
2876
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002877 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002878 if (bold == TRUE)
2879 attr |= HL_BOLD;
2880 return get_cterm_attr_idx(attr, fg, bg);
2881 }
2882 return 0;
2883}
2884
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002885 static void
2886set_dirty_snapshot(term_T *term)
2887{
2888 term->tl_dirty_snapshot = TRUE;
2889#ifdef FEAT_TIMERS
2890 if (!term->tl_normal_mode)
2891 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002892 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002893 profile_setlimit(100L, &term->tl_timer_due);
2894 term->tl_timer_set = TRUE;
2895 }
2896#endif
2897}
2898
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002899 static int
2900handle_damage(VTermRect rect, void *user)
2901{
2902 term_T *term = (term_T *)user;
2903
2904 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2905 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002906 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002907 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002908 return 1;
2909}
2910
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002911 static void
2912term_scroll_up(term_T *term, int start_row, int count)
2913{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002914 win_T *wp = NULL;
2915 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002916 VTermColor fg, bg;
2917 VTermScreenCellAttrs attr;
2918 int clear_attr;
2919
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002920 vim_memset(&attr, 0, sizeof(attr));
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002921
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002922 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002923 {
2924 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002925 {
2926 // Set the color to clear lines with.
2927 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2928 &fg, &bg);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002929 clear_attr = cell2attr(term, wp, attr, fg, bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002930 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002931 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002932 }
2933}
2934
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002935 static int
2936handle_moverect(VTermRect dest, VTermRect src, void *user)
2937{
2938 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002939 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002940
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002941 // Scrolling up is done much more efficiently by deleting lines instead of
2942 // redrawing the text. But avoid doing this multiple times, postpone until
2943 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002944 if (dest.start_col == src.start_col
2945 && dest.end_col == src.end_col
2946 && dest.start_row < src.start_row)
2947 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002948 if (dest.start_row == 0)
2949 term->tl_postponed_scroll += count;
2950 else
2951 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002952 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002953
2954 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2955 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002956 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002957
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002958 // Note sure if the scrolling will work correctly, let's do a complete
2959 // redraw later.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002960 redraw_buf_later(term->tl_buffer, NOT_VALID);
2961 return 1;
2962}
2963
2964 static int
2965handle_movecursor(
2966 VTermPos pos,
2967 VTermPos oldpos UNUSED,
2968 int visible,
2969 void *user)
2970{
2971 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002972 win_T *wp = NULL;
2973 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002974
2975 term->tl_cursor_pos = pos;
2976 term->tl_cursor_visible = visible;
2977
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002978 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002979 {
2980 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002981 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002982 }
2983 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2984 {
2985 may_toggle_cursor(term);
2986 update_cursor(term, term->tl_cursor_visible);
2987 }
2988
2989 return 1;
2990}
2991
2992 static int
2993handle_settermprop(
2994 VTermProp prop,
2995 VTermValue *value,
2996 void *user)
2997{
2998 term_T *term = (term_T *)user;
2999
3000 switch (prop)
3001 {
3002 case VTERM_PROP_TITLE:
3003 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003004 // a blank title isn't useful, make it empty, so that "running" is
3005 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003006 if (*skipwhite((char_u *)value->string) == NUL)
3007 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003008 // Same as blank
3009 else if (term->tl_arg0_cmd != NULL
3010 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
3011 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3012 term->tl_title = NULL;
3013 // Empty corrupted data of winpty
3014 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
3015 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003016#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003017 else if (!enc_utf8 && enc_codepage > 0)
3018 {
3019 WCHAR *ret = NULL;
3020 int length = 0;
3021
3022 MultiByteToWideChar_alloc(CP_UTF8, 0,
3023 (char*)value->string, (int)STRLEN(value->string),
3024 &ret, &length);
3025 if (ret != NULL)
3026 {
3027 WideCharToMultiByte_alloc(enc_codepage, 0,
3028 ret, length, (char**)&term->tl_title,
3029 &length, 0, 0);
3030 vim_free(ret);
3031 }
3032 }
3033#endif
3034 else
3035 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01003036 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003037 if (term == curbuf->b_term)
3038 maketitle();
3039 break;
3040
3041 case VTERM_PROP_CURSORVISIBLE:
3042 term->tl_cursor_visible = value->boolean;
3043 may_toggle_cursor(term);
3044 out_flush();
3045 break;
3046
3047 case VTERM_PROP_CURSORBLINK:
3048 term->tl_cursor_blink = value->boolean;
3049 may_set_cursor_props(term);
3050 break;
3051
3052 case VTERM_PROP_CURSORSHAPE:
3053 term->tl_cursor_shape = value->number;
3054 may_set_cursor_props(term);
3055 break;
3056
3057 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02003058 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003059 may_set_cursor_props(term);
3060 break;
3061
3062 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003063 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003064 term->tl_using_altscreen = value->boolean;
3065 break;
3066
3067 default:
3068 break;
3069 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003070 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003071 return 1;
3072}
3073
3074/*
3075 * The job running in the terminal resized the terminal.
3076 */
3077 static int
3078handle_resize(int rows, int cols, void *user)
3079{
3080 term_T *term = (term_T *)user;
3081 win_T *wp;
3082
3083 term->tl_rows = rows;
3084 term->tl_cols = cols;
3085 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003086 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003087 term->tl_vterm_size_changed = FALSE;
3088 else
3089 {
3090 FOR_ALL_WINDOWS(wp)
3091 {
3092 if (wp->w_buffer == term->tl_buffer)
3093 {
3094 win_setheight_win(rows, wp);
3095 win_setwidth_win(cols, wp);
3096 }
3097 }
3098 redraw_buf_later(term->tl_buffer, NOT_VALID);
3099 }
3100 return 1;
3101}
3102
3103/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003104 * If the number of lines that are stored goes over 'termscrollback' then
3105 * delete the first 10%.
3106 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3107 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003108 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003109 static void
3110limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003111{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003112 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003113 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003114 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003115 int i;
3116
3117 curbuf = term->tl_buffer;
3118 for (i = 0; i < todo; ++i)
3119 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003120 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3121 if (update_buffer)
3122 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003123 }
3124 curbuf = curwin->w_buffer;
3125
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003126 gap->ga_len -= todo;
3127 mch_memmove(gap->ga_data,
3128 (sb_line_T *)gap->ga_data + todo,
3129 sizeof(sb_line_T) * gap->ga_len);
3130 if (update_buffer)
3131 term->tl_scrollback_scrolled -= todo;
3132 }
3133}
3134
3135/*
3136 * Handle a line that is pushed off the top of the screen.
3137 */
3138 static int
3139handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3140{
3141 term_T *term = (term_T *)user;
3142 garray_T *gap;
3143 int update_buffer;
3144
3145 if (term->tl_normal_mode)
3146 {
3147 // In Terminal-Normal mode the user interacts with the buffer, thus we
3148 // must not change it. Postpone adding the scrollback lines.
3149 gap = &term->tl_scrollback_postponed;
3150 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003151 }
3152 else
3153 {
3154 // First remove the lines that were appended before, the pushed line
3155 // goes above it.
3156 cleanup_scrollback(term);
3157 gap = &term->tl_scrollback;
3158 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003159 }
3160
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003161 limit_scrollback(term, gap, update_buffer);
3162
3163 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003164 {
3165 cellattr_T *p = NULL;
3166 int len = 0;
3167 int i;
3168 int c;
3169 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003170 int text_len;
3171 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003172 sb_line_T *line;
3173 garray_T ga;
3174 cellattr_T fill_attr = term->tl_default_color;
3175
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003176 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003177 for (i = 0; i < cols; ++i)
3178 if (cells[i].chars[0] != 0)
3179 len = i + 1;
3180 else
3181 cell2cellattr(&cells[i], &fill_attr);
3182
3183 ga_init2(&ga, 1, 100);
3184 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003185 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003186 if (p != NULL)
3187 {
3188 for (col = 0; col < len; col += cells[col].width)
3189 {
3190 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3191 {
3192 ga.ga_len = 0;
3193 break;
3194 }
3195 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3196 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3197 (char_u *)ga.ga_data + ga.ga_len);
3198 cell2cellattr(&cells[col], &p[col]);
3199 }
3200 }
3201 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003202 {
3203 if (update_buffer)
3204 text = (char_u *)"";
3205 else
3206 text = vim_strsave((char_u *)"");
3207 text_len = 0;
3208 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003209 else
3210 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003211 text = ga.ga_data;
3212 text_len = ga.ga_len;
3213 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003214 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003215 if (update_buffer)
3216 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003217
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003218 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003219 line->sb_cols = len;
3220 line->sb_cells = p;
3221 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003222 if (update_buffer)
3223 {
3224 line->sb_text = NULL;
3225 ++term->tl_scrollback_scrolled;
3226 ga_clear(&ga); // free the text
3227 }
3228 else
3229 {
3230 line->sb_text = text;
3231 ga_init(&ga); // text is kept in tl_scrollback_postponed
3232 }
3233 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003234 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003235 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003236}
3237
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003238/*
3239 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3240 * received and stored in tl_scrollback_postponed.
3241 */
3242 static void
3243handle_postponed_scrollback(term_T *term)
3244{
3245 int i;
3246
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003247 if (term->tl_scrollback_postponed.ga_len == 0)
3248 return;
3249 ch_log(NULL, "Moving postponed scrollback to scrollback");
3250
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003251 // First remove the lines that were appended before, the pushed lines go
3252 // above it.
3253 cleanup_scrollback(term);
3254
3255 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3256 {
3257 char_u *text;
3258 sb_line_T *pp_line;
3259 sb_line_T *line;
3260
3261 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3262 break;
3263 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3264
3265 text = pp_line->sb_text;
3266 if (text == NULL)
3267 text = (char_u *)"";
3268 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3269 vim_free(pp_line->sb_text);
3270
3271 line = (sb_line_T *)term->tl_scrollback.ga_data
3272 + term->tl_scrollback.ga_len;
3273 line->sb_cols = pp_line->sb_cols;
3274 line->sb_cells = pp_line->sb_cells;
3275 line->sb_fill_attr = pp_line->sb_fill_attr;
3276 line->sb_text = NULL;
3277 ++term->tl_scrollback_scrolled;
3278 ++term->tl_scrollback.ga_len;
3279 }
3280
3281 ga_clear(&term->tl_scrollback_postponed);
3282 limit_scrollback(term, &term->tl_scrollback, TRUE);
3283}
3284
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003285static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003286 handle_damage, // damage
3287 handle_moverect, // moverect
3288 handle_movecursor, // movecursor
3289 handle_settermprop, // settermprop
3290 NULL, // bell
3291 handle_resize, // resize
3292 handle_pushline, // sb_pushline
3293 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003294};
3295
3296/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003297 * Do the work after the channel of a terminal was closed.
3298 * Must be called only when updating_screen is FALSE.
3299 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3300 */
3301 static int
3302term_after_channel_closed(term_T *term)
3303{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003304 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003305 if (!term->tl_normal_mode)
3306 {
3307 int fnum = term->tl_buffer->b_fnum;
3308
3309 cleanup_vterm(term);
3310
3311 if (term->tl_finish == TL_FINISH_CLOSE)
3312 {
3313 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003314 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003315#ifdef FEAT_PROP_POPUP
3316 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003317
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003318 // If this was a terminal in a popup window, go back to the
3319 // previous window.
3320 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3321 {
3322 pwin = curwin;
3323 if (win_valid(prevwin))
3324 win_enter(prevwin, FALSE);
3325 }
3326 else
3327#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003328 // If this is the last normal window: exit Vim.
3329 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3330 {
3331 exarg_T ea;
3332
3333 vim_memset(&ea, 0, sizeof(ea));
3334 ex_quit(&ea);
3335 return TRUE;
3336 }
3337
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003338 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003339 ch_log(NULL, "terminal job finished, closing window");
3340 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003341 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003342 if (curwin == aucmd_win)
3343 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003344 if (do_set_w_closing)
3345 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003346 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003347 if (do_set_w_closing)
3348 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003349 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003350#ifdef FEAT_PROP_POPUP
3351 if (pwin != NULL)
3352 popup_close_with_retval(pwin, 0);
3353#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003354 return TRUE;
3355 }
3356 if (term->tl_finish == TL_FINISH_OPEN
3357 && term->tl_buffer->b_nwindows == 0)
3358 {
3359 char buf[50];
3360
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003361 // TODO: use term_opencmd
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003362 ch_log(NULL, "terminal job finished, opening window");
3363 vim_snprintf(buf, sizeof(buf),
3364 term->tl_opencmd == NULL
3365 ? "botright sbuf %d"
3366 : (char *)term->tl_opencmd, fnum);
3367 do_cmdline_cmd((char_u *)buf);
3368 }
3369 else
3370 ch_log(NULL, "terminal job finished");
3371 }
3372
3373 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3374 return FALSE;
3375}
3376
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003377#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3378/*
3379 * If the current window is a terminal in a popup window and the job has
3380 * finished, close the popup window and to back to the previous window.
3381 * Otherwise return FAIL.
3382 */
3383 int
3384may_close_term_popup(void)
3385{
3386 if (popup_is_popup(curwin) && curbuf->b_term != NULL
3387 && !term_job_running(curbuf->b_term))
3388 {
3389 win_T *pwin = curwin;
3390
3391 if (win_valid(prevwin))
3392 win_enter(prevwin, FALSE);
3393 popup_close_with_retval(pwin, 0);
3394 return OK;
3395 }
3396 return FAIL;
3397}
3398#endif
3399
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003400/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003401 * Called when a channel has been closed.
3402 * If this was a channel for a terminal window then finish it up.
3403 */
3404 void
3405term_channel_closed(channel_T *ch)
3406{
3407 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003408 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003409 int did_one = FALSE;
3410
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003411 for (term = first_term; term != NULL; term = next_term)
3412 {
3413 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003414 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003415 {
3416 term->tl_channel_closed = TRUE;
3417 did_one = TRUE;
3418
Bram Moolenaard23a8232018-02-10 18:45:26 +01003419 VIM_CLEAR(term->tl_title);
3420 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003421#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003422 if (term->tl_out_fd != NULL)
3423 {
3424 fclose(term->tl_out_fd);
3425 term->tl_out_fd = NULL;
3426 }
3427#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003428
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003429 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003430 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003431 // Cannot open or close windows now. Can happen when
3432 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003433 term->tl_channel_recently_closed = TRUE;
3434 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003435 }
3436
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003437 if (term_after_channel_closed(term))
3438 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003439 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003440 }
3441
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003442 if (did_one)
3443 {
3444 redraw_statuslines();
3445
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003446 // Need to break out of vgetc().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003447 ins_char_typebuf(K_IGNORE);
3448 typebuf_was_filled = TRUE;
3449
3450 term = curbuf->b_term;
3451 if (term != NULL)
3452 {
3453 if (term->tl_job == ch->ch_job)
3454 maketitle();
3455 update_cursor(term, term->tl_cursor_visible);
3456 }
3457 }
3458}
3459
3460/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003461 * To be called after resetting updating_screen: handle any terminal where the
3462 * channel was closed.
3463 */
3464 void
3465term_check_channel_closed_recently()
3466{
3467 term_T *term;
3468 term_T *next_term;
3469
3470 for (term = first_term; term != NULL; term = next_term)
3471 {
3472 next_term = term->tl_next;
3473 if (term->tl_channel_recently_closed)
3474 {
3475 term->tl_channel_recently_closed = FALSE;
3476 if (term_after_channel_closed(term))
3477 // start over, the list may have changed
3478 next_term = first_term;
3479 }
3480 }
3481}
3482
3483/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003484 * Fill one screen line from a line of the terminal.
3485 * Advances "pos" to past the last column.
3486 */
3487 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003488term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003489 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003490 win_T *wp,
3491 VTermScreen *screen,
3492 VTermPos *pos,
3493 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003494{
3495 int off = screen_get_current_line_off();
3496
3497 for (pos->col = 0; pos->col < max_col; )
3498 {
3499 VTermScreenCell cell;
3500 int c;
3501
3502 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3503 vim_memset(&cell, 0, sizeof(cell));
3504
3505 c = cell.chars[0];
3506 if (c == NUL)
3507 {
3508 ScreenLines[off] = ' ';
3509 if (enc_utf8)
3510 ScreenLinesUC[off] = NUL;
3511 }
3512 else
3513 {
3514 if (enc_utf8)
3515 {
3516 int i;
3517
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003518 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003519 for (i = 0; i < Screen_mco
3520 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3521 {
3522 ScreenLinesC[i][off] = cell.chars[i + 1];
3523 if (cell.chars[i + 1] == 0)
3524 break;
3525 }
3526 if (c >= 0x80 || (Screen_mco > 0
3527 && ScreenLinesC[0][off] != 0))
3528 {
3529 ScreenLines[off] = ' ';
3530 ScreenLinesUC[off] = c;
3531 }
3532 else
3533 {
3534 ScreenLines[off] = c;
3535 ScreenLinesUC[off] = NUL;
3536 }
3537 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003538#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003539 else if (has_mbyte && c >= 0x80)
3540 {
3541 char_u mb[MB_MAXBYTES+1];
3542 WCHAR wc = c;
3543
3544 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3545 (char*)mb, 2, 0, 0) > 1)
3546 {
3547 ScreenLines[off] = mb[0];
3548 ScreenLines[off + 1] = mb[1];
3549 cell.width = mb_ptr2cells(mb);
3550 }
3551 else
3552 ScreenLines[off] = c;
3553 }
3554#endif
3555 else
3556 ScreenLines[off] = c;
3557 }
Bram Moolenaar83d47902020-03-26 20:34:00 +01003558 ScreenAttrs[off] = cell2attr(term, wp, cell.attrs, cell.fg, cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003559
3560 ++pos->col;
3561 ++off;
3562 if (cell.width == 2)
3563 {
3564 if (enc_utf8)
3565 ScreenLinesUC[off] = NUL;
3566
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003567 // don't set the second byte to NUL for a DBCS encoding, it
3568 // has been set above
Bram Moolenaar13568252018-03-16 20:46:58 +01003569 if (enc_utf8 || !has_mbyte)
3570 ScreenLines[off] = NUL;
3571
3572 ++pos->col;
3573 ++off;
3574 }
3575 }
3576}
3577
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003578#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003579 static void
3580update_system_term(term_T *term)
3581{
3582 VTermPos pos;
3583 VTermScreen *screen;
3584
3585 if (term->tl_vterm == NULL)
3586 return;
3587 screen = vterm_obtain_screen(term->tl_vterm);
3588
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003589 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003590 while (term->tl_toprow > 0
3591 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3592 {
3593 int save_p_more = p_more;
3594
3595 p_more = FALSE;
3596 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003597 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003598 p_more = save_p_more;
3599 --term->tl_toprow;
3600 }
3601
3602 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3603 && pos.row < Rows; ++pos.row)
3604 {
3605 if (pos.row < term->tl_rows)
3606 {
3607 int max_col = MIN(Columns, term->tl_cols);
3608
Bram Moolenaar83d47902020-03-26 20:34:00 +01003609 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003610 }
3611 else
3612 pos.col = 0;
3613
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003614 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003615 }
3616
3617 term->tl_dirty_row_start = MAX_ROW;
3618 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003619}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003620#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003621
3622/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003623 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3624 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003625 * Terminal-Normal mode.
3626 */
3627 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003628term_do_update_window(win_T *wp)
3629{
3630 term_T *term = wp->w_buffer->b_term;
3631
3632 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3633}
3634
3635/*
3636 * Called to update a window that contains an active terminal.
3637 */
3638 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003639term_update_window(win_T *wp)
3640{
3641 term_T *term = wp->w_buffer->b_term;
3642 VTerm *vterm;
3643 VTermScreen *screen;
3644 VTermState *state;
3645 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003646 int rows, cols;
3647 int newrows, newcols;
3648 int minsize;
3649 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003650
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003651 vterm = term->tl_vterm;
3652 screen = vterm_obtain_screen(vterm);
3653 state = vterm_obtain_state(vterm);
3654
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003655 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3656 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003657 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003658 {
3659 term->tl_dirty_row_start = 0;
3660 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003661
3662 if (term->tl_postponed_scroll > 0
3663 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003664 // Scrolling is usually faster than redrawing, when there are only
3665 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003666 term_scroll_up(term, 0, term->tl_postponed_scroll);
3667 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003668 }
3669
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003670 /*
3671 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003672 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003673 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003674 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003675
Bram Moolenaar498c2562018-04-15 23:45:15 +02003676 newrows = 99999;
3677 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003678 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003679 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003680 // Always use curwin, it may be a popup window.
3681 win_T *wwp = twp == NULL ? curwin : twp;
3682
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003683 // When more than one window shows the same terminal, use the
3684 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003685 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003686 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003687 newrows = MIN(newrows, wwp->w_height);
3688 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003689 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003690 if (twp == NULL)
3691 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003692 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003693 if (newrows == 99999 || newcols == 99999)
3694 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003695 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3696 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3697
3698 if (term->tl_rows != newrows || term->tl_cols != newcols)
3699 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003700 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003701 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003702 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003703 newrows);
3704 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003705
3706 // Updating the terminal size will cause the snapshot to be cleared.
3707 // When not in terminal_loop() we need to restore it.
3708 if (term != in_terminal_loop)
3709 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003710 }
3711
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003712 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003713 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003714 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003715
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003716 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3717 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003718 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003719 if (pos.row < term->tl_rows)
3720 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003721 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003722
Bram Moolenaar83d47902020-03-26 20:34:00 +01003723 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003724 }
3725 else
3726 pos.col = 0;
3727
Bram Moolenaarf118d482018-03-13 13:14:00 +01003728 screen_line(wp->w_winrow + pos.row
3729#ifdef FEAT_MENU
3730 + winbar_height(wp)
3731#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003732 , wp->w_wincol, pos.col, wp->w_width,
3733#ifdef FEAT_PROP_POPUP
3734 popup_is_popup(wp) ? SLF_POPUP :
3735#endif
3736 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003737 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003738 term->tl_dirty_row_start = MAX_ROW;
3739 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003740}
3741
3742/*
3743 * Return TRUE if "wp" is a terminal window where the job has finished.
3744 */
3745 int
3746term_is_finished(buf_T *buf)
3747{
3748 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3749}
3750
3751/*
3752 * Return TRUE if "wp" is a terminal window where the job has finished or we
3753 * are in Terminal-Normal mode, thus we show the buffer contents.
3754 */
3755 int
3756term_show_buffer(buf_T *buf)
3757{
3758 term_T *term = buf->b_term;
3759
3760 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3761}
3762
3763/*
3764 * The current buffer is going to be changed. If there is terminal
3765 * highlighting remove it now.
3766 */
3767 void
3768term_change_in_curbuf(void)
3769{
3770 term_T *term = curbuf->b_term;
3771
3772 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3773 {
3774 free_scrollback(term);
3775 redraw_buf_later(term->tl_buffer, NOT_VALID);
3776
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003777 // The buffer is now like a normal buffer, it cannot be easily
3778 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003779 set_string_option_direct((char_u *)"buftype", -1,
3780 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3781 }
3782}
3783
3784/*
3785 * Get the screen attribute for a position in the buffer.
3786 * Use a negative "col" to get the filler background color.
3787 */
3788 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003789term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003790{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003791 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003792 term_T *term = buf->b_term;
3793 sb_line_T *line;
3794 cellattr_T *cellattr;
3795
3796 if (lnum > term->tl_scrollback.ga_len)
3797 cellattr = &term->tl_default_color;
3798 else
3799 {
3800 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3801 if (col < 0 || col >= line->sb_cols)
3802 cellattr = &line->sb_fill_attr;
3803 else
3804 cellattr = line->sb_cells + col;
3805 }
Bram Moolenaar83d47902020-03-26 20:34:00 +01003806 return cell2attr(term, wp, cellattr->attrs, cellattr->fg, cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003807}
3808
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003809/*
3810 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003811 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003812 */
3813 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003814cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003815{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003816 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003817}
3818
3819/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003820 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003821 */
3822 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003823init_default_colors(term_T *term, win_T *wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003824{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003825 VTermColor *fg, *bg;
3826 int fgval, bgval;
3827 int id;
3828
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003829 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3830 term->tl_default_color.width = 1;
3831 fg = &term->tl_default_color.fg;
3832 bg = &term->tl_default_color.bg;
3833
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003834 // Vterm uses a default black background. Set it to white when
3835 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003836 if (*p_bg == 'l')
3837 {
3838 fgval = 0;
3839 bgval = 255;
3840 }
3841 else
3842 {
3843 fgval = 255;
3844 bgval = 0;
3845 }
3846 fg->red = fg->green = fg->blue = fgval;
3847 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003848 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003849
Bram Moolenaar83d47902020-03-26 20:34:00 +01003850 // The 'wincolor' or the highlight group overrules the defaults.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003851 if (wp != NULL && *wp->w_p_wcr != NUL)
3852 id = syn_name2id(wp->w_p_wcr);
3853 else
Bram Moolenaar83d47902020-03-26 20:34:00 +01003854 id = syn_name2id(term_get_highlight_name(term));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003855
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003856 // Use the actual color for the GUI and when 'termguicolors' is set.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003857#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3858 if (0
3859# ifdef FEAT_GUI
3860 || gui.in_use
3861# endif
3862# ifdef FEAT_TERMGUICOLORS
3863 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003864# ifdef FEAT_VTP
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003865 // Finally get INVALCOLOR on this execution path
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003866 || (!p_tgc && t_colors >= 256)
3867# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003868# endif
3869 )
3870 {
3871 guicolor_T fg_rgb = INVALCOLOR;
3872 guicolor_T bg_rgb = INVALCOLOR;
3873
3874 if (id != 0)
3875 syn_id2colors(id, &fg_rgb, &bg_rgb);
3876
3877# ifdef FEAT_GUI
3878 if (gui.in_use)
3879 {
3880 if (fg_rgb == INVALCOLOR)
3881 fg_rgb = gui.norm_pixel;
3882 if (bg_rgb == INVALCOLOR)
3883 bg_rgb = gui.back_pixel;
3884 }
3885# ifdef FEAT_TERMGUICOLORS
3886 else
3887# endif
3888# endif
3889# ifdef FEAT_TERMGUICOLORS
3890 {
3891 if (fg_rgb == INVALCOLOR)
3892 fg_rgb = cterm_normal_fg_gui_color;
3893 if (bg_rgb == INVALCOLOR)
3894 bg_rgb = cterm_normal_bg_gui_color;
3895 }
3896# endif
3897 if (fg_rgb != INVALCOLOR)
3898 {
3899 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3900
3901 fg->red = (unsigned)(rgb >> 16);
3902 fg->green = (unsigned)(rgb >> 8) & 255;
3903 fg->blue = (unsigned)rgb & 255;
3904 }
3905 if (bg_rgb != INVALCOLOR)
3906 {
3907 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3908
3909 bg->red = (unsigned)(rgb >> 16);
3910 bg->green = (unsigned)(rgb >> 8) & 255;
3911 bg->blue = (unsigned)rgb & 255;
3912 }
3913 }
3914 else
3915#endif
3916 if (id != 0 && t_colors >= 16)
3917 {
Bram Moolenaar83d47902020-03-26 20:34:00 +01003918 int cterm_fg = get_default_cterm_fg(term);
3919 int cterm_bg = get_default_cterm_bg(term);
3920
3921 if (cterm_fg >= 0)
3922 cterm_color2vterm(cterm_fg, fg);
3923 if (cterm_bg >= 0)
3924 cterm_color2vterm(cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003925 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003926 else
3927 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003928#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003929 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003930#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003931
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003932 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003933 if (cterm_normal_fg_color > 0)
3934 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003935 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003936# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3937# ifdef VIMDLL
3938 if (!gui.in_use)
3939# endif
3940 {
3941 tmp = fg->red;
3942 fg->red = fg->blue;
3943 fg->blue = tmp;
3944 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003945# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003946 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003947# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003948 else
3949 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003950# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003951
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003952 if (cterm_normal_bg_color > 0)
3953 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003954 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
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_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003969# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003970 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003971}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003972
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003973#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3974/*
3975 * Set the 16 ANSI colors from array of RGB values
3976 */
3977 static void
3978set_vterm_palette(VTerm *vterm, long_u *rgb)
3979{
3980 int index = 0;
3981 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003982
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003983 for (; index < 16; index++)
3984 {
3985 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003986
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003987 color.red = (unsigned)(rgb[index] >> 16);
3988 color.green = (unsigned)(rgb[index] >> 8) & 255;
3989 color.blue = (unsigned)rgb[index] & 255;
3990 vterm_state_set_palette_color(state, index, &color);
3991 }
3992}
3993
3994/*
3995 * Set the ANSI color palette from a list of colors
3996 */
3997 static int
3998set_ansi_colors_list(VTerm *vterm, list_T *list)
3999{
4000 int n = 0;
4001 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004002 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004003
Bram Moolenaarb0992022020-01-30 14:55:42 +01004004 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004005 {
4006 char_u *color_name;
4007 guicolor_T guicolor;
4008
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004009 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004010 if (color_name == NULL)
4011 return FAIL;
4012
4013 guicolor = GUI_GET_COLOR(color_name);
4014 if (guicolor == INVALCOLOR)
4015 return FAIL;
4016
4017 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4018 }
4019
4020 if (n != 16 || li != NULL)
4021 return FAIL;
4022
4023 set_vterm_palette(vterm, rgb);
4024
4025 return OK;
4026}
4027
4028/*
4029 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4030 */
4031 static void
4032init_vterm_ansi_colors(VTerm *vterm)
4033{
4034 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4035
4036 if (var != NULL
4037 && (var->di_tv.v_type != VAR_LIST
4038 || var->di_tv.vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +01004039 || var->di_tv.vval.v_list->lv_first == &range_list_item
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004040 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004041 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004042}
4043#endif
4044
Bram Moolenaar52acb112018-03-18 19:20:22 +01004045/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004046 * Handles a "drop" command from the job in the terminal.
4047 * "item" is the file name, "item->li_next" may have options.
4048 */
4049 static void
4050handle_drop_command(listitem_T *item)
4051{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004052 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004053 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004054 int bufnr;
4055 win_T *wp;
4056 tabpage_T *tp;
4057 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004058 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004059
4060 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4061 FOR_ALL_TAB_WINDOWS(tp, wp)
4062 {
4063 if (wp->w_buffer->b_fnum == bufnr)
4064 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004065 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004066 goto_tabpage_win(tp, wp);
4067 return;
4068 }
4069 }
4070
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004071 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004072
4073 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4074 && opt_item->li_tv.vval.v_dict != NULL)
4075 {
4076 dict_T *dict = opt_item->li_tv.vval.v_dict;
4077 char_u *p;
4078
Bram Moolenaar8f667172018-12-14 15:38:31 +01004079 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004080 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004081 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004082 if (p != NULL)
4083 {
4084 if (check_ff_value(p) == FAIL)
4085 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4086 else
4087 ea.force_ff = *p;
4088 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01004089 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004090 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004091 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004092 if (p != NULL)
4093 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004094 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004095 if (ea.cmd != NULL)
4096 {
4097 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4098 ea.force_enc = 11;
4099 tofree = ea.cmd;
4100 }
4101 }
4102
Bram Moolenaar8f667172018-12-14 15:38:31 +01004103 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004104 if (p != NULL)
4105 get_bad_opt(p, &ea);
4106
4107 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
4108 ea.force_bin = FORCE_BIN;
4109 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
4110 ea.force_bin = FORCE_BIN;
4111 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
4112 ea.force_bin = FORCE_NOBIN;
4113 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
4114 ea.force_bin = FORCE_NOBIN;
4115 }
4116
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004117 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004118 if (ea.cmd == NULL)
4119 ea.cmd = (char_u *)"split";
4120 ea.arg = fname;
4121 ea.cmdidx = CMD_split;
4122 ex_splitview(&ea);
4123
4124 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004125}
4126
4127/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004128 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4129 */
4130 static int
4131is_permitted_term_api(char_u *func, char_u *pat)
4132{
4133 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4134}
4135
4136/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004137 * Handles a function call from the job running in a terminal.
4138 * "item" is the function name, "item->li_next" has the arguments.
4139 */
4140 static void
4141handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4142{
4143 char_u *func;
4144 typval_T argvars[2];
4145 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004146 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004147
4148 if (item->li_next == NULL)
4149 {
4150 ch_log(channel, "Missing function arguments for call");
4151 return;
4152 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004153 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004154
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004155 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004156 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004157 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004158 return;
4159 }
4160
4161 argvars[0].v_type = VAR_NUMBER;
4162 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4163 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004164 vim_memset(&funcexe, 0, sizeof(funcexe));
4165 funcexe.firstline = 1L;
4166 funcexe.lastline = 1L;
4167 funcexe.evaluate = TRUE;
4168 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004169 {
4170 clear_tv(&rettv);
4171 ch_log(channel, "Function %s called", func);
4172 }
4173 else
4174 ch_log(channel, "Calling function %s failed", func);
4175}
4176
4177/*
4178 * Called by libvterm when it cannot recognize an OSC sequence.
4179 * We recognize a terminal API command.
4180 */
4181 static int
4182parse_osc(const char *command, size_t cmdlen, void *user)
4183{
4184 term_T *term = (term_T *)user;
4185 js_read_T reader;
4186 typval_T tv;
4187 channel_T *channel = term->tl_job == NULL ? NULL
4188 : term->tl_job->jv_channel;
4189
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004190 // We recognize only OSC 5 1 ; {command}
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004191 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004192 return 0; // not handled
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004193
Bram Moolenaar878c96d2018-04-04 23:00:06 +02004194 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004195 if (reader.js_buf == NULL)
4196 return 1;
4197 reader.js_fill = NULL;
4198 reader.js_used = 0;
4199 if (json_decode(&reader, &tv, 0) == OK
4200 && tv.v_type == VAR_LIST
4201 && tv.vval.v_list != NULL)
4202 {
4203 listitem_T *item = tv.vval.v_list->lv_first;
4204
4205 if (item == NULL)
4206 ch_log(channel, "Missing command");
4207 else
4208 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004209 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004210
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004211 // Make sure an invoked command doesn't delete the buffer (and the
4212 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004213 ++term->tl_buffer->b_locked;
4214
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004215 item = item->li_next;
4216 if (item == NULL)
4217 ch_log(channel, "Missing argument for %s", cmd);
4218 else if (STRCMP(cmd, "drop") == 0)
4219 handle_drop_command(item);
4220 else if (STRCMP(cmd, "call") == 0)
4221 handle_call_command(term, channel, item);
4222 else
4223 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004224 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004225 }
4226 }
4227 else
4228 ch_log(channel, "Invalid JSON received");
4229
4230 vim_free(reader.js_buf);
4231 clear_tv(&tv);
4232 return 1;
4233}
4234
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004235/*
4236 * Called by libvterm when it cannot recognize a CSI sequence.
4237 * We recognize the window position report.
4238 */
4239 static int
4240parse_csi(
4241 const char *leader UNUSED,
4242 const long args[],
4243 int argcount,
4244 const char *intermed UNUSED,
4245 char command,
4246 void *user)
4247{
4248 term_T *term = (term_T *)user;
4249 char buf[100];
4250 int len;
4251 int x = 0;
4252 int y = 0;
4253 win_T *wp;
4254
4255 // We recognize only CSI 13 t
4256 if (command != 't' || argcount != 1 || args[0] != 13)
4257 return 0; // not handled
4258
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004259 // When getting the window position is not possible or it fails it results
4260 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004261#if defined(FEAT_GUI) \
4262 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4263 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004264 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004265#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004266
4267 FOR_ALL_WINDOWS(wp)
4268 if (wp->w_buffer == term->tl_buffer)
4269 break;
4270 if (wp != NULL)
4271 {
4272#ifdef FEAT_GUI
4273 if (gui.in_use)
4274 {
4275 x += wp->w_wincol * gui.char_width;
4276 y += W_WINROW(wp) * gui.char_height;
4277 }
4278 else
4279#endif
4280 {
4281 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004282 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004283 x += wp->w_wincol * 7;
4284 y += W_WINROW(wp) * 10;
4285 }
4286 }
4287
4288 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4289 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4290 (char_u *)buf, len, NULL);
4291 return 1;
4292}
4293
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004294static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004295 NULL, // text
4296 NULL, // control
4297 NULL, // escape
4298 parse_csi, // csi
4299 parse_osc, // osc
4300 NULL, // dcs
4301 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004302};
4303
4304/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004305 * Use Vim's allocation functions for vterm so profiling works.
4306 */
4307 static void *
4308vterm_malloc(size_t size, void *data UNUSED)
4309{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004310 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004311}
4312
4313 static void
4314vterm_memfree(void *ptr, void *data UNUSED)
4315{
4316 vim_free(ptr);
4317}
4318
4319static VTermAllocatorFunctions vterm_allocator = {
4320 &vterm_malloc,
4321 &vterm_memfree
4322};
4323
4324/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004325 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004326 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004327 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004328 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004329create_vterm(term_T *term, int rows, int cols)
4330{
4331 VTerm *vterm;
4332 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004333 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004334 VTermValue value;
4335
Bram Moolenaar756ef112018-04-10 12:04:27 +02004336 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004337 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004338 if (vterm == NULL)
4339 return FAIL;
4340
4341 // Allocate screen and state here, so we can bail out if that fails.
4342 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004343 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004344 if (state == NULL || screen == NULL)
4345 {
4346 vterm_free(vterm);
4347 return FAIL;
4348 }
4349
Bram Moolenaar52acb112018-03-18 19:20:22 +01004350 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004351 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004352 vterm_set_utf8(vterm, 1);
4353
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004354 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004355
4356 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004357 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004358 &term->tl_default_color.fg,
4359 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004360
Bram Moolenaar9e587872019-05-13 20:27:23 +02004361 if (t_colors < 16)
4362 // Less than 16 colors: assume that bold means using a bright color for
4363 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004364 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4365
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004366 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004367 vterm_screen_reset(screen, 1 /* hard */);
4368
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004369 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004370 vterm_screen_enable_altscreen(screen, 1);
4371
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004372 // For unix do not use a blinking cursor. In an xterm this causes the
4373 // cursor to blink if it's blinking in the xterm.
4374 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004375#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004376 if (GetCaretBlinkTime() == INFINITE)
4377 value.boolean = 0;
4378 else
4379 value.boolean = 1;
4380#else
4381 value.boolean = 0;
4382#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004383 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4384 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004385
4386 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004387}
4388
4389/*
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004390 * Called when 'wincolor' was set.
4391 */
4392 void
4393term_update_colors(void)
4394{
4395 term_T *term = curwin->w_buffer->b_term;
4396
Bram Moolenaar7ba3b912020-02-10 20:34:04 +01004397 if (term->tl_vterm == NULL)
4398 return;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004399 init_default_colors(term, curwin);
4400 vterm_state_set_default_colors(
4401 vterm_obtain_state(term->tl_vterm),
4402 &term->tl_default_color.fg,
4403 &term->tl_default_color.bg);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +01004404
4405 redraw_later(NOT_VALID);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004406}
4407
4408/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004409 * Return the text to show for the buffer name and status.
4410 */
4411 char_u *
4412term_get_status_text(term_T *term)
4413{
4414 if (term->tl_status_text == NULL)
4415 {
4416 char_u *txt;
4417 size_t len;
4418
4419 if (term->tl_normal_mode)
4420 {
4421 if (term_job_running(term))
4422 txt = (char_u *)_("Terminal");
4423 else
4424 txt = (char_u *)_("Terminal-finished");
4425 }
4426 else if (term->tl_title != NULL)
4427 txt = term->tl_title;
4428 else if (term_none_open(term))
4429 txt = (char_u *)_("active");
4430 else if (term_job_running(term))
4431 txt = (char_u *)_("running");
4432 else
4433 txt = (char_u *)_("finished");
4434 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004435 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004436 if (term->tl_status_text != NULL)
4437 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4438 term->tl_buffer->b_fname, txt);
4439 }
4440 return term->tl_status_text;
4441}
4442
4443/*
4444 * Mark references in jobs of terminals.
4445 */
4446 int
4447set_ref_in_term(int copyID)
4448{
4449 int abort = FALSE;
4450 term_T *term;
4451 typval_T tv;
4452
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004453 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004454 if (term->tl_job != NULL)
4455 {
4456 tv.v_type = VAR_JOB;
4457 tv.vval.v_job = term->tl_job;
4458 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4459 }
4460 return abort;
4461}
4462
4463/*
4464 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004465 * Returns NULL when the buffer is not for a terminal window and logs a message
4466 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004467 */
4468 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004469term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004470{
4471 buf_T *buf;
4472
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004473 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004474 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004475 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004476 --emsg_off;
4477 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004478 {
4479 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004480 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004481 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004482 return buf;
4483}
4484
Bram Moolenaard96ff162018-02-18 22:13:29 +01004485 static int
4486same_color(VTermColor *a, VTermColor *b)
4487{
4488 return a->red == b->red
4489 && a->green == b->green
4490 && a->blue == b->blue
4491 && a->ansi_index == b->ansi_index;
4492}
4493
4494 static void
4495dump_term_color(FILE *fd, VTermColor *color)
4496{
4497 fprintf(fd, "%02x%02x%02x%d",
4498 (int)color->red, (int)color->green, (int)color->blue,
4499 (int)color->ansi_index);
4500}
4501
4502/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004503 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004504 *
4505 * Each screen cell in full is:
4506 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4507 * {characters} is a space for an empty cell
4508 * For a double-width character "+" is changed to "*" and the next cell is
4509 * skipped.
4510 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4511 * when "&" use the same as the previous cell.
4512 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4513 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4514 * {color-idx} is a number from 0 to 255
4515 *
4516 * Screen cell with same width, attributes and color as the previous one:
4517 * |{characters}
4518 *
4519 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4520 *
4521 * Repeating the previous screen cell:
4522 * @{count}
4523 */
4524 void
4525f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4526{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004527 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004528 term_T *term;
4529 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004530 int max_height = 0;
4531 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004532 stat_T st;
4533 FILE *fd;
4534 VTermPos pos;
4535 VTermScreen *screen;
4536 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004537 VTermState *state;
4538 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004539
4540 if (check_restricted() || check_secure())
4541 return;
4542 if (buf == NULL)
4543 return;
4544 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004545 if (term->tl_vterm == NULL)
4546 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004547 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004548 return;
4549 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004550
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004551 if (argvars[2].v_type != VAR_UNKNOWN)
4552 {
4553 dict_T *d;
4554
4555 if (argvars[2].v_type != VAR_DICT)
4556 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004557 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004558 return;
4559 }
4560 d = argvars[2].vval.v_dict;
4561 if (d != NULL)
4562 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004563 max_height = dict_get_number(d, (char_u *)"rows");
4564 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004565 }
4566 }
4567
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004568 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004569 if (fname == NULL)
4570 return;
4571 if (mch_stat((char *)fname, &st) >= 0)
4572 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004573 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004574 return;
4575 }
4576
Bram Moolenaard96ff162018-02-18 22:13:29 +01004577 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4578 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004579 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004580 return;
4581 }
4582
4583 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4584
4585 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004586 state = vterm_obtain_state(term->tl_vterm);
4587 vterm_state_get_cursorpos(state, &cursor_pos);
4588
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004589 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4590 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004591 {
4592 int repeat = 0;
4593
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004594 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4595 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004596 {
4597 VTermScreenCell cell;
4598 int same_attr;
4599 int same_chars = TRUE;
4600 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004601 int is_cursor_pos = (pos.col == cursor_pos.col
4602 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004603
4604 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4605 vim_memset(&cell, 0, sizeof(cell));
4606
4607 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4608 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004609 int c = cell.chars[i];
4610 int pc = prev_cell.chars[i];
4611
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004612 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01004613 if (i == 0)
4614 {
4615 c = (c == NUL) ? ' ' : c;
4616 pc = (pc == NUL) ? ' ' : pc;
4617 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004618 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004619 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004620 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004621 break;
4622 }
4623 same_attr = vtermAttr2hl(cell.attrs)
4624 == vtermAttr2hl(prev_cell.attrs)
4625 && same_color(&cell.fg, &prev_cell.fg)
4626 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004627 if (same_chars && cell.width == prev_cell.width && same_attr
4628 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004629 {
4630 ++repeat;
4631 }
4632 else
4633 {
4634 if (repeat > 0)
4635 {
4636 fprintf(fd, "@%d", repeat);
4637 repeat = 0;
4638 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004639 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004640
4641 if (cell.chars[0] == NUL)
4642 fputs(" ", fd);
4643 else
4644 {
4645 char_u charbuf[10];
4646 int len;
4647
4648 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4649 && cell.chars[i] != NUL; ++i)
4650 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004651 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004652 fwrite(charbuf, len, 1, fd);
4653 }
4654 }
4655
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004656 // When only the characters differ we don't write anything, the
4657 // following "|", "@" or NL will indicate using the same
4658 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004659 if (cell.width != prev_cell.width || !same_attr)
4660 {
4661 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004662 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004663 else
4664 fputs("+", fd);
4665
4666 if (same_attr)
4667 {
4668 fputs("&", fd);
4669 }
4670 else
4671 {
4672 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4673 if (same_color(&cell.fg, &prev_cell.fg))
4674 fputs("&", fd);
4675 else
4676 {
4677 fputs("#", fd);
4678 dump_term_color(fd, &cell.fg);
4679 }
4680 if (same_color(&cell.bg, &prev_cell.bg))
4681 fputs("&", fd);
4682 else
4683 {
4684 fputs("#", fd);
4685 dump_term_color(fd, &cell.bg);
4686 }
4687 }
4688 }
4689
4690 prev_cell = cell;
4691 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004692
4693 if (cell.width == 2)
4694 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004695 }
4696 if (repeat > 0)
4697 fprintf(fd, "@%d", repeat);
4698 fputs("\n", fd);
4699 }
4700
4701 fclose(fd);
4702}
4703
4704/*
4705 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4706 */
4707 static void
4708dump_is_corrupt(garray_T *gap)
4709{
4710 ga_concat(gap, (char_u *)"CORRUPT");
4711}
4712
4713 static void
4714append_cell(garray_T *gap, cellattr_T *cell)
4715{
4716 if (ga_grow(gap, 1) == OK)
4717 {
4718 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4719 ++gap->ga_len;
4720 }
4721}
4722
4723/*
4724 * Read the dump file from "fd" and append lines to the current buffer.
4725 * Return the cell width of the longest line.
4726 */
4727 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004728read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004729{
4730 int c;
4731 garray_T ga_text;
4732 garray_T ga_cell;
4733 char_u *prev_char = NULL;
4734 int attr = 0;
4735 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004736 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004737 term_T *term = curbuf->b_term;
4738 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004739 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004740
4741 ga_init2(&ga_text, 1, 90);
4742 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4743 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004744 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004745 cursor_pos->row = -1;
4746 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004747
4748 c = fgetc(fd);
4749 for (;;)
4750 {
4751 if (c == EOF)
4752 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004753 if (c == '\r')
4754 {
4755 // DOS line endings? Ignore.
4756 c = fgetc(fd);
4757 }
4758 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004759 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004760 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004761 if (ga_text.ga_data == NULL)
4762 dump_is_corrupt(&ga_text);
4763 if (ga_grow(&term->tl_scrollback, 1) == OK)
4764 {
4765 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4766 + term->tl_scrollback.ga_len;
4767
4768 if (max_cells < ga_cell.ga_len)
4769 max_cells = ga_cell.ga_len;
4770 line->sb_cols = ga_cell.ga_len;
4771 line->sb_cells = ga_cell.ga_data;
4772 line->sb_fill_attr = term->tl_default_color;
4773 ++term->tl_scrollback.ga_len;
4774 ga_init(&ga_cell);
4775
4776 ga_append(&ga_text, NUL);
4777 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4778 ga_text.ga_len, FALSE);
4779 }
4780 else
4781 ga_clear(&ga_cell);
4782 ga_text.ga_len = 0;
4783
4784 c = fgetc(fd);
4785 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004786 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004787 {
4788 int prev_len = ga_text.ga_len;
4789
Bram Moolenaar9271d052018-02-25 21:39:46 +01004790 if (c == '>')
4791 {
4792 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004793 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004794 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4795 cursor_pos->col = ga_cell.ga_len;
4796 }
4797
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004798 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004799 c = fgetc(fd);
4800 if (c != EOF)
4801 ga_append(&ga_text, c);
4802 for (;;)
4803 {
4804 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004805 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004806 || c == EOF || c == '\n')
4807 break;
4808 ga_append(&ga_text, c);
4809 }
4810
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004811 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01004812 vim_free(prev_char);
4813 if (ga_text.ga_data != NULL)
4814 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4815 ga_text.ga_len - prev_len);
4816
Bram Moolenaar9271d052018-02-25 21:39:46 +01004817 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004818 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004819 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004820 }
4821 else if (c == '+' || c == '*')
4822 {
4823 int is_bg;
4824
4825 cell.width = c == '+' ? 1 : 2;
4826
4827 c = fgetc(fd);
4828 if (c == '&')
4829 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004830 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004831 c = fgetc(fd);
4832 }
4833 else if (isdigit(c))
4834 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004835 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01004836 attr = 0;
4837 while (isdigit(c))
4838 {
4839 attr = attr * 10 + (c - '0');
4840 c = fgetc(fd);
4841 }
4842 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004843
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004844 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004845 for (is_bg = 0; is_bg <= 1; ++is_bg)
4846 {
4847 if (c == '&')
4848 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004849 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004850 c = fgetc(fd);
4851 }
4852 else if (c == '#')
4853 {
4854 int red, green, blue, index = 0;
4855
4856 c = fgetc(fd);
4857 red = hex2nr(c);
4858 c = fgetc(fd);
4859 red = (red << 4) + hex2nr(c);
4860 c = fgetc(fd);
4861 green = hex2nr(c);
4862 c = fgetc(fd);
4863 green = (green << 4) + hex2nr(c);
4864 c = fgetc(fd);
4865 blue = hex2nr(c);
4866 c = fgetc(fd);
4867 blue = (blue << 4) + hex2nr(c);
4868 c = fgetc(fd);
4869 if (!isdigit(c))
4870 dump_is_corrupt(&ga_text);
4871 while (isdigit(c))
4872 {
4873 index = index * 10 + (c - '0');
4874 c = fgetc(fd);
4875 }
4876
4877 if (is_bg)
4878 {
4879 cell.bg.red = red;
4880 cell.bg.green = green;
4881 cell.bg.blue = blue;
4882 cell.bg.ansi_index = index;
4883 }
4884 else
4885 {
4886 cell.fg.red = red;
4887 cell.fg.green = green;
4888 cell.fg.blue = blue;
4889 cell.fg.ansi_index = index;
4890 }
4891 }
4892 else
4893 dump_is_corrupt(&ga_text);
4894 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004895 }
4896 else
4897 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004898 }
4899 else
4900 dump_is_corrupt(&ga_text);
4901
4902 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004903 if (cell.width == 2)
4904 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004905 }
4906 else if (c == '@')
4907 {
4908 if (prev_char == NULL)
4909 dump_is_corrupt(&ga_text);
4910 else
4911 {
4912 int count = 0;
4913
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004914 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01004915 for (;;)
4916 {
4917 c = fgetc(fd);
4918 if (!isdigit(c))
4919 break;
4920 count = count * 10 + (c - '0');
4921 }
4922
4923 while (count-- > 0)
4924 {
4925 ga_concat(&ga_text, prev_char);
4926 append_cell(&ga_cell, &cell);
4927 }
4928 }
4929 }
4930 else
4931 {
4932 dump_is_corrupt(&ga_text);
4933 c = fgetc(fd);
4934 }
4935 }
4936
4937 if (ga_text.ga_len > 0)
4938 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004939 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004940 dump_is_corrupt(&ga_text);
4941 ga_append(&ga_text, NUL);
4942 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4943 ga_text.ga_len, FALSE);
4944 }
4945
4946 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004947 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004948 vim_free(prev_char);
4949
4950 return max_cells;
4951}
4952
4953/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004954 * Return an allocated string with at least "text_width" "=" characters and
4955 * "fname" inserted in the middle.
4956 */
4957 static char_u *
4958get_separator(int text_width, char_u *fname)
4959{
4960 int width = MAX(text_width, curwin->w_width);
4961 char_u *textline;
4962 int fname_size;
4963 char_u *p = fname;
4964 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004965 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004966
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004967 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004968 if (textline == NULL)
4969 return NULL;
4970
4971 fname_size = vim_strsize(fname);
4972 if (fname_size < width - 8)
4973 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004974 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02004975 width = MAX(text_width, fname_size + 8);
4976 }
4977 else if (fname_size > width - 8)
4978 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004979 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02004980 p = gettail(fname);
4981 fname_size = vim_strsize(p);
4982 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004983 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02004984 while (fname_size > width - 8)
4985 {
4986 p += (*mb_ptr2len)(p);
4987 fname_size = vim_strsize(p);
4988 }
4989
4990 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4991 textline[i] = '=';
4992 textline[i++] = ' ';
4993
4994 STRCPY(textline + i, p);
4995 off = STRLEN(textline);
4996 textline[off] = ' ';
4997 for (i = 1; i < (width - fname_size) / 2; ++i)
4998 textline[off + i] = '=';
4999 textline[off + i] = NUL;
5000
5001 return textline;
5002}
5003
5004/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005005 * Common for "term_dumpdiff()" and "term_dumpload()".
5006 */
5007 static void
5008term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5009{
5010 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005011 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005012 char_u buf1[NUMBUFLEN];
5013 char_u buf2[NUMBUFLEN];
5014 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005015 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005016 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005017 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005018 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005019 char_u *textline = NULL;
5020
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005021 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005022 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005023 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005024 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005025 if (fname1 == NULL || (do_diff && fname2 == NULL))
5026 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005027 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005028 return;
5029 }
5030 fd1 = mch_fopen((char *)fname1, READBIN);
5031 if (fd1 == NULL)
5032 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005033 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005034 return;
5035 }
5036 if (do_diff)
5037 {
5038 fd2 = mch_fopen((char *)fname2, READBIN);
5039 if (fd2 == NULL)
5040 {
5041 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005042 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005043 return;
5044 }
5045 }
5046
5047 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005048 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5049 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5050 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5051 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5052 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005053
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005054 if (opt.jo_term_name == NULL)
5055 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005056 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005057
Bram Moolenaar51e14382019-05-25 20:21:28 +02005058 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005059 if (fname_tofree != NULL)
5060 {
5061 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5062 opt.jo_term_name = fname_tofree;
5063 }
5064 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005065
Bram Moolenaar87abab92019-06-03 21:14:59 +02005066 if (opt.jo_bufnr_buf != NULL)
5067 {
5068 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5069
5070 // With "bufnr" argument: enter the window with this buffer and make it
5071 // empty.
5072 if (wp == NULL)
5073 semsg(_(e_invarg2), "bufnr");
5074 else
5075 {
5076 buf = curbuf;
5077 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
5078 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02005079 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005080 redraw_later(NOT_VALID);
5081 }
5082 }
5083 else
5084 // Create a new terminal window.
5085 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5086
Bram Moolenaard96ff162018-02-18 22:13:29 +01005087 if (buf != NULL && buf->b_term != NULL)
5088 {
5089 int i;
5090 linenr_T bot_lnum;
5091 linenr_T lnum;
5092 term_T *term = buf->b_term;
5093 int width;
5094 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005095 VTermPos cursor_pos1;
5096 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005097
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005098 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005099
Bram Moolenaard96ff162018-02-18 22:13:29 +01005100 rettv->vval.v_number = buf->b_fnum;
5101
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005102 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005103 width = read_dump_file(fd1, &cursor_pos1);
5104
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005105 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005106 if (cursor_pos1.row >= 0)
5107 {
5108 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5109 coladvance(cursor_pos1.col);
5110 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005111
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005112 // Delete the empty line that was in the empty buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005113 ml_delete(1, FALSE);
5114
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005115 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005116 if (!do_diff)
5117 goto theend;
5118
5119 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5120
Bram Moolenaar4a696342018-04-05 18:45:26 +02005121 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005122 if (textline == NULL)
5123 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005124 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5125 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5126 vim_free(textline);
5127
5128 textline = get_separator(width, fname2);
5129 if (textline == NULL)
5130 goto theend;
5131 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5132 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005133 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005134
5135 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005136 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005137 if (width2 > width)
5138 {
5139 vim_free(textline);
5140 textline = alloc(width2 + 1);
5141 if (textline == NULL)
5142 goto theend;
5143 width = width2;
5144 textline[width] = NUL;
5145 }
5146 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5147
5148 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5149 {
5150 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5151 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005152 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005153 for (i = 0; i < width; ++i)
5154 textline[i] = '-';
5155 }
5156 else
5157 {
5158 char_u *line1;
5159 char_u *line2;
5160 char_u *p1;
5161 char_u *p2;
5162 int col;
5163 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5164 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5165 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5166 ->sb_cells;
5167
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005168 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005169 line1 = vim_strsave(ml_get(lnum));
5170 if (line1 == NULL)
5171 break;
5172 p1 = line1;
5173
5174 line2 = ml_get(lnum + bot_lnum);
5175 p2 = line2;
5176 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5177 {
5178 int len1 = utfc_ptr2len(p1);
5179 int len2 = utfc_ptr2len(p2);
5180
5181 textline[col] = ' ';
5182 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005183 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005184 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005185 else if (lnum == cursor_pos1.row + 1
5186 && col == cursor_pos1.col
5187 && (cursor_pos1.row != cursor_pos2.row
5188 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005189 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005190 textline[col] = '>';
5191 else if (lnum == cursor_pos2.row + 1
5192 && col == cursor_pos2.col
5193 && (cursor_pos1.row != cursor_pos2.row
5194 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005195 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005196 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005197 else if (cellattr1 != NULL && cellattr2 != NULL)
5198 {
5199 if ((cellattr1 + col)->width
5200 != (cellattr2 + col)->width)
5201 textline[col] = 'w';
5202 else if (!same_color(&(cellattr1 + col)->fg,
5203 &(cellattr2 + col)->fg))
5204 textline[col] = 'f';
5205 else if (!same_color(&(cellattr1 + col)->bg,
5206 &(cellattr2 + col)->bg))
5207 textline[col] = 'b';
5208 else if (vtermAttr2hl((cellattr1 + col)->attrs)
5209 != vtermAttr2hl(((cellattr2 + col)->attrs)))
5210 textline[col] = 'a';
5211 }
5212 p1 += len1;
5213 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005214 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005215 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005216
5217 while (col < width)
5218 {
5219 if (*p1 == NUL && *p2 == NUL)
5220 textline[col] = '?';
5221 else if (*p1 == NUL)
5222 {
5223 textline[col] = '+';
5224 p2 += utfc_ptr2len(p2);
5225 }
5226 else
5227 {
5228 textline[col] = '-';
5229 p1 += utfc_ptr2len(p1);
5230 }
5231 ++col;
5232 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005233
5234 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005235 }
5236 if (add_empty_scrollback(term, &term->tl_default_color,
5237 term->tl_top_diff_rows) == OK)
5238 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5239 ++bot_lnum;
5240 }
5241
5242 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5243 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005244 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005245 for (i = 0; i < width; ++i)
5246 textline[i] = '+';
5247 if (add_empty_scrollback(term, &term->tl_default_color,
5248 term->tl_top_diff_rows) == OK)
5249 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5250 ++lnum;
5251 ++bot_lnum;
5252 }
5253
5254 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005255
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005256 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005257 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005258 }
5259
5260theend:
5261 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005262 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005263 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005264 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005265 fclose(fd2);
5266}
5267
5268/*
5269 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5270 * bottom files.
5271 * Return FAIL when this is not possible.
5272 */
5273 int
5274term_swap_diff()
5275{
5276 term_T *term = curbuf->b_term;
5277 linenr_T line_count;
5278 linenr_T top_rows;
5279 linenr_T bot_rows;
5280 linenr_T bot_start;
5281 linenr_T lnum;
5282 char_u *p;
5283 sb_line_T *sb_line;
5284
5285 if (term == NULL
5286 || !term_is_finished(curbuf)
5287 || term->tl_top_diff_rows == 0
5288 || term->tl_scrollback.ga_len == 0)
5289 return FAIL;
5290
5291 line_count = curbuf->b_ml.ml_line_count;
5292 top_rows = term->tl_top_diff_rows;
5293 bot_rows = term->tl_bot_diff_rows;
5294 bot_start = line_count - bot_rows;
5295 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5296
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005297 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005298 for (lnum = 1; lnum <= top_rows; ++lnum)
5299 {
5300 p = vim_strsave(ml_get(1));
5301 if (p == NULL)
5302 return OK;
5303 ml_append(bot_start, p, 0, FALSE);
5304 ml_delete(1, FALSE);
5305 vim_free(p);
5306 }
5307
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005308 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005309 for (lnum = 1; lnum <= bot_rows; ++lnum)
5310 {
5311 p = vim_strsave(ml_get(bot_start + lnum));
5312 if (p == NULL)
5313 return OK;
5314 ml_delete(bot_start + lnum, FALSE);
5315 ml_append(lnum - 1, p, 0, FALSE);
5316 vim_free(p);
5317 }
5318
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005319 // move top title to bottom
5320 p = vim_strsave(ml_get(bot_rows + 1));
5321 if (p == NULL)
5322 return OK;
5323 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5324 ml_delete(bot_rows + 1, FALSE);
5325 vim_free(p);
5326
5327 // move bottom title to top
5328 p = vim_strsave(ml_get(line_count - top_rows));
5329 if (p == NULL)
5330 return OK;
5331 ml_delete(line_count - top_rows, FALSE);
5332 ml_append(bot_rows, p, 0, FALSE);
5333 vim_free(p);
5334
Bram Moolenaard96ff162018-02-18 22:13:29 +01005335 if (top_rows == bot_rows)
5336 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005337 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005338 for (lnum = 0; lnum < top_rows; ++lnum)
5339 {
5340 sb_line_T temp;
5341
5342 temp = *(sb_line + lnum);
5343 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5344 *(sb_line + bot_start + lnum) = temp;
5345 }
5346 }
5347 else
5348 {
5349 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005350 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005351
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005352 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005353 if (temp != NULL)
5354 {
5355 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5356 mch_memmove(term->tl_scrollback.ga_data,
5357 temp + bot_start,
5358 sizeof(sb_line_T) * bot_rows);
5359 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5360 temp + top_rows,
5361 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5362 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5363 + line_count - top_rows,
5364 temp,
5365 sizeof(sb_line_T) * top_rows);
5366 vim_free(temp);
5367 }
5368 }
5369
5370 term->tl_top_diff_rows = bot_rows;
5371 term->tl_bot_diff_rows = top_rows;
5372
5373 update_screen(NOT_VALID);
5374 return OK;
5375}
5376
5377/*
5378 * "term_dumpdiff(filename, filename, options)" function
5379 */
5380 void
5381f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5382{
5383 term_load_dump(argvars, rettv, TRUE);
5384}
5385
5386/*
5387 * "term_dumpload(filename, options)" function
5388 */
5389 void
5390f_term_dumpload(typval_T *argvars, typval_T *rettv)
5391{
5392 term_load_dump(argvars, rettv, FALSE);
5393}
5394
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005395/*
5396 * "term_getaltscreen(buf)" function
5397 */
5398 void
5399f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5400{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005401 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005402
5403 if (buf == NULL)
5404 return;
5405 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5406}
5407
5408/*
5409 * "term_getattr(attr, name)" function
5410 */
5411 void
5412f_term_getattr(typval_T *argvars, typval_T *rettv)
5413{
5414 int attr;
5415 size_t i;
5416 char_u *name;
5417
5418 static struct {
5419 char *name;
5420 int attr;
5421 } attrs[] = {
5422 {"bold", HL_BOLD},
5423 {"italic", HL_ITALIC},
5424 {"underline", HL_UNDERLINE},
5425 {"strike", HL_STRIKETHROUGH},
5426 {"reverse", HL_INVERSE},
5427 };
5428
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005429 attr = tv_get_number(&argvars[0]);
5430 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005431 if (name == NULL)
5432 return;
5433
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005434 if (attr > HL_ALL)
5435 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005436 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5437 if (STRCMP(name, attrs[i].name) == 0)
5438 {
5439 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5440 break;
5441 }
5442}
5443
5444/*
5445 * "term_getcursor(buf)" function
5446 */
5447 void
5448f_term_getcursor(typval_T *argvars, typval_T *rettv)
5449{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005450 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005451 term_T *term;
5452 list_T *l;
5453 dict_T *d;
5454
5455 if (rettv_list_alloc(rettv) == FAIL)
5456 return;
5457 if (buf == NULL)
5458 return;
5459 term = buf->b_term;
5460
5461 l = rettv->vval.v_list;
5462 list_append_number(l, term->tl_cursor_pos.row + 1);
5463 list_append_number(l, term->tl_cursor_pos.col + 1);
5464
5465 d = dict_alloc();
5466 if (d != NULL)
5467 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005468 dict_add_number(d, "visible", term->tl_cursor_visible);
5469 dict_add_number(d, "blink", blink_state_is_inverted()
5470 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5471 dict_add_number(d, "shape", term->tl_cursor_shape);
5472 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005473 list_append_dict(l, d);
5474 }
5475}
5476
5477/*
5478 * "term_getjob(buf)" function
5479 */
5480 void
5481f_term_getjob(typval_T *argvars, typval_T *rettv)
5482{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005483 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005484
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005485 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005486 {
5487 rettv->v_type = VAR_SPECIAL;
5488 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005489 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005490 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005491
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005492 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005493 rettv->vval.v_job = buf->b_term->tl_job;
5494 if (rettv->vval.v_job != NULL)
5495 ++rettv->vval.v_job->jv_refcount;
5496}
5497
5498 static int
5499get_row_number(typval_T *tv, term_T *term)
5500{
5501 if (tv->v_type == VAR_STRING
5502 && tv->vval.v_string != NULL
5503 && STRCMP(tv->vval.v_string, ".") == 0)
5504 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005505 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005506}
5507
5508/*
5509 * "term_getline(buf, row)" function
5510 */
5511 void
5512f_term_getline(typval_T *argvars, typval_T *rettv)
5513{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005514 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005515 term_T *term;
5516 int row;
5517
5518 rettv->v_type = VAR_STRING;
5519 if (buf == NULL)
5520 return;
5521 term = buf->b_term;
5522 row = get_row_number(&argvars[1], term);
5523
5524 if (term->tl_vterm == NULL)
5525 {
5526 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5527
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005528 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005529 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5530 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5531 }
5532 else
5533 {
5534 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5535 VTermRect rect;
5536 int len;
5537 char_u *p;
5538
5539 if (row < 0 || row >= term->tl_rows)
5540 return;
5541 len = term->tl_cols * MB_MAXBYTES + 1;
5542 p = alloc(len);
5543 if (p == NULL)
5544 return;
5545 rettv->vval.v_string = p;
5546
5547 rect.start_col = 0;
5548 rect.end_col = term->tl_cols;
5549 rect.start_row = row;
5550 rect.end_row = row + 1;
5551 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5552 }
5553}
5554
5555/*
5556 * "term_getscrolled(buf)" function
5557 */
5558 void
5559f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5560{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005561 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005562
5563 if (buf == NULL)
5564 return;
5565 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5566}
5567
5568/*
5569 * "term_getsize(buf)" function
5570 */
5571 void
5572f_term_getsize(typval_T *argvars, typval_T *rettv)
5573{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005574 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005575 list_T *l;
5576
5577 if (rettv_list_alloc(rettv) == FAIL)
5578 return;
5579 if (buf == NULL)
5580 return;
5581
5582 l = rettv->vval.v_list;
5583 list_append_number(l, buf->b_term->tl_rows);
5584 list_append_number(l, buf->b_term->tl_cols);
5585}
5586
5587/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005588 * "term_setsize(buf, rows, cols)" function
5589 */
5590 void
5591f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5592{
5593 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5594 term_T *term;
5595 varnumber_T rows, cols;
5596
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005597 if (buf == NULL)
5598 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005599 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005600 return;
5601 }
5602 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005603 return;
5604 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005605 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005606 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005607 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005608 cols = cols <= 0 ? term->tl_cols : cols;
5609 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005610 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02005611
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005612 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02005613 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5614 term_report_winsize(term, term->tl_rows, term->tl_cols);
5615}
5616
5617/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005618 * "term_getstatus(buf)" function
5619 */
5620 void
5621f_term_getstatus(typval_T *argvars, typval_T *rettv)
5622{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005623 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005624 term_T *term;
5625 char_u val[100];
5626
5627 rettv->v_type = VAR_STRING;
5628 if (buf == NULL)
5629 return;
5630 term = buf->b_term;
5631
5632 if (term_job_running(term))
5633 STRCPY(val, "running");
5634 else
5635 STRCPY(val, "finished");
5636 if (term->tl_normal_mode)
5637 STRCAT(val, ",normal");
5638 rettv->vval.v_string = vim_strsave(val);
5639}
5640
5641/*
5642 * "term_gettitle(buf)" function
5643 */
5644 void
5645f_term_gettitle(typval_T *argvars, typval_T *rettv)
5646{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005647 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005648
5649 rettv->v_type = VAR_STRING;
5650 if (buf == NULL)
5651 return;
5652
5653 if (buf->b_term->tl_title != NULL)
5654 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5655}
5656
5657/*
5658 * "term_gettty(buf)" function
5659 */
5660 void
5661f_term_gettty(typval_T *argvars, typval_T *rettv)
5662{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005663 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005664 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005665 int num = 0;
5666
5667 rettv->v_type = VAR_STRING;
5668 if (buf == NULL)
5669 return;
5670 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005671 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005672
5673 switch (num)
5674 {
5675 case 0:
5676 if (buf->b_term->tl_job != NULL)
5677 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005678 break;
5679 case 1:
5680 if (buf->b_term->tl_job != NULL)
5681 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005682 break;
5683 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005684 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005685 return;
5686 }
5687 if (p != NULL)
5688 rettv->vval.v_string = vim_strsave(p);
5689}
5690
5691/*
5692 * "term_list()" function
5693 */
5694 void
5695f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5696{
5697 term_T *tp;
5698 list_T *l;
5699
5700 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5701 return;
5702
5703 l = rettv->vval.v_list;
5704 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5705 if (tp != NULL && tp->tl_buffer != NULL)
5706 if (list_append_number(l,
5707 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5708 return;
5709}
5710
5711/*
5712 * "term_scrape(buf, row)" function
5713 */
5714 void
5715f_term_scrape(typval_T *argvars, typval_T *rettv)
5716{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005717 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005718 VTermScreen *screen = NULL;
5719 VTermPos pos;
5720 list_T *l;
5721 term_T *term;
5722 char_u *p;
5723 sb_line_T *line;
5724
5725 if (rettv_list_alloc(rettv) == FAIL)
5726 return;
5727 if (buf == NULL)
5728 return;
5729 term = buf->b_term;
5730
5731 l = rettv->vval.v_list;
5732 pos.row = get_row_number(&argvars[1], term);
5733
5734 if (term->tl_vterm != NULL)
5735 {
5736 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005737 if (screen == NULL) // can't really happen
5738 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005739 p = NULL;
5740 line = NULL;
5741 }
5742 else
5743 {
5744 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5745
5746 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5747 return;
5748 p = ml_get_buf(buf, lnum + 1, FALSE);
5749 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5750 }
5751
5752 for (pos.col = 0; pos.col < term->tl_cols; )
5753 {
5754 dict_T *dcell;
5755 int width;
5756 VTermScreenCellAttrs attrs;
5757 VTermColor fg, bg;
5758 char_u rgb[8];
5759 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5760 int off = 0;
5761 int i;
5762
5763 if (screen == NULL)
5764 {
5765 cellattr_T *cellattr;
5766 int len;
5767
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005768 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005769 if (pos.col >= line->sb_cols)
5770 break;
5771 cellattr = line->sb_cells + pos.col;
5772 width = cellattr->width;
5773 attrs = cellattr->attrs;
5774 fg = cellattr->fg;
5775 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005776 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005777 mch_memmove(mbs, p, len);
5778 mbs[len] = NUL;
5779 p += len;
5780 }
5781 else
5782 {
5783 VTermScreenCell cell;
5784 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5785 break;
5786 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5787 {
5788 if (cell.chars[i] == 0)
5789 break;
5790 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5791 }
5792 mbs[off] = NUL;
5793 width = cell.width;
5794 attrs = cell.attrs;
5795 fg = cell.fg;
5796 bg = cell.bg;
5797 }
5798 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005799 if (dcell == NULL)
5800 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005801 list_append_dict(l, dcell);
5802
Bram Moolenaare0be1672018-07-08 16:50:37 +02005803 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005804
5805 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5806 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005807 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005808 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5809 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005810 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005811
Bram Moolenaar83d47902020-03-26 20:34:00 +01005812 dict_add_number(dcell, "attr", cell2attr(term, NULL, attrs, fg, bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02005813 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005814
5815 ++pos.col;
5816 if (width == 2)
5817 ++pos.col;
5818 }
5819}
5820
5821/*
5822 * "term_sendkeys(buf, keys)" function
5823 */
5824 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01005825f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005826{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005827 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005828 char_u *msg;
5829 term_T *term;
5830
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005831 if (buf == NULL)
5832 return;
5833
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005834 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005835 if (msg == NULL)
5836 return;
5837 term = buf->b_term;
5838 if (term->tl_vterm == NULL)
5839 return;
5840
5841 while (*msg != NUL)
5842 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005843 int c;
5844
5845 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5846 {
5847 c = TO_SPECIAL(msg[1], msg[2]);
5848 msg += 3;
5849 }
5850 else
5851 {
5852 c = PTR2CHAR(msg);
5853 msg += MB_CPTR2LEN(msg);
5854 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005855 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005856 }
5857}
5858
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005859#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5860/*
5861 * "term_getansicolors(buf)" function
5862 */
5863 void
5864f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5865{
5866 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5867 term_T *term;
5868 VTermState *state;
5869 VTermColor color;
5870 char_u hexbuf[10];
5871 int index;
5872 list_T *list;
5873
5874 if (rettv_list_alloc(rettv) == FAIL)
5875 return;
5876
5877 if (buf == NULL)
5878 return;
5879 term = buf->b_term;
5880 if (term->tl_vterm == NULL)
5881 return;
5882
5883 list = rettv->vval.v_list;
5884 state = vterm_obtain_state(term->tl_vterm);
5885 for (index = 0; index < 16; index++)
5886 {
5887 vterm_state_get_palette_color(state, index, &color);
5888 sprintf((char *)hexbuf, "#%02x%02x%02x",
5889 color.red, color.green, color.blue);
5890 if (list_append_string(list, hexbuf, 7) == FAIL)
5891 return;
5892 }
5893}
5894
5895/*
5896 * "term_setansicolors(buf, list)" function
5897 */
5898 void
5899f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5900{
5901 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5902 term_T *term;
5903
5904 if (buf == NULL)
5905 return;
5906 term = buf->b_term;
5907 if (term->tl_vterm == NULL)
5908 return;
5909
5910 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5911 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005912 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005913 return;
5914 }
5915
5916 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005917 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005918}
5919#endif
5920
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005921/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005922 * "term_setapi(buf, api)" function
5923 */
5924 void
5925f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5926{
5927 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5928 term_T *term;
5929 char_u *api;
5930
5931 if (buf == NULL)
5932 return;
5933 term = buf->b_term;
5934 vim_free(term->tl_api);
5935 api = tv_get_string_chk(&argvars[1]);
5936 if (api != NULL)
5937 term->tl_api = vim_strsave(api);
5938 else
5939 term->tl_api = NULL;
5940}
5941
5942/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005943 * "term_setrestore(buf, command)" function
5944 */
5945 void
5946f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5947{
5948#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005949 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005950 term_T *term;
5951 char_u *cmd;
5952
5953 if (buf == NULL)
5954 return;
5955 term = buf->b_term;
5956 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005957 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005958 if (cmd != NULL)
5959 term->tl_command = vim_strsave(cmd);
5960 else
5961 term->tl_command = NULL;
5962#endif
5963}
5964
5965/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005966 * "term_setkill(buf, how)" function
5967 */
5968 void
5969f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5970{
5971 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5972 term_T *term;
5973 char_u *how;
5974
5975 if (buf == NULL)
5976 return;
5977 term = buf->b_term;
5978 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005979 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005980 if (how != NULL)
5981 term->tl_kill = vim_strsave(how);
5982 else
5983 term->tl_kill = NULL;
5984}
5985
5986/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005987 * "term_start(command, options)" function
5988 */
5989 void
5990f_term_start(typval_T *argvars, typval_T *rettv)
5991{
5992 jobopt_T opt;
5993 buf_T *buf;
5994
5995 init_job_options(&opt);
5996 if (argvars[1].v_type != VAR_UNKNOWN
5997 && get_job_options(&argvars[1], &opt,
5998 JO_TIMEOUT_ALL + JO_STOPONEXIT
5999 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6000 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6001 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6002 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006003 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006004 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006005 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006006 return;
6007
Bram Moolenaar13568252018-03-16 20:46:58 +01006008 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006009
6010 if (buf != NULL && buf->b_term != NULL)
6011 rettv->vval.v_number = buf->b_fnum;
6012}
6013
6014/*
6015 * "term_wait" function
6016 */
6017 void
6018f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6019{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006020 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006021
6022 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006023 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006024 if (buf->b_term->tl_job == NULL)
6025 {
6026 ch_log(NULL, "term_wait(): no job to wait for");
6027 return;
6028 }
6029 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006030 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006031 return;
6032
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006033 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006034 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006035 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6036 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006037 // The job is dead, keep reading channel I/O until the channel is
6038 // closed. buf->b_term may become NULL if the terminal was closed while
6039 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006040 ch_log(NULL, "term_wait(): waiting for channel to close");
6041 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6042 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006043 term_flush_messages();
6044
Bram Moolenaard45aa552018-05-21 22:50:29 +02006045 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006046 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006047 // If the terminal is closed when the channel is closed the
6048 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006049 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006050 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006051
6052 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006053 }
6054 else
6055 {
6056 long wait = 10L;
6057
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006058 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006059
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006060 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006061 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006062 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006063 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006064
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006065 // Flushing messages on channels is hopefully sufficient.
6066 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006067 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006068 }
6069}
6070
6071/*
6072 * Called when a channel has sent all the lines to a terminal.
6073 * Send a CTRL-D to mark the end of the text.
6074 */
6075 void
6076term_send_eof(channel_T *ch)
6077{
6078 term_T *term;
6079
6080 for (term = first_term; term != NULL; term = term->tl_next)
6081 if (term->tl_job == ch->ch_job)
6082 {
6083 if (term->tl_eof_chars != NULL)
6084 {
6085 channel_send(ch, PART_IN, term->tl_eof_chars,
6086 (int)STRLEN(term->tl_eof_chars), NULL);
6087 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6088 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006089# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006090 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006091 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006092 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6093# endif
6094 }
6095}
6096
Bram Moolenaar113e1072019-01-20 15:30:40 +01006097#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006098 job_T *
6099term_getjob(term_T *term)
6100{
6101 return term != NULL ? term->tl_job : NULL;
6102}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006103#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006104
Bram Moolenaar4f974752019-02-17 17:44:42 +01006105# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006106
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006107///////////////////////////////////////
6108// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006109#ifdef PROTO
6110typedef int COORD;
6111typedef int DWORD;
6112typedef int HANDLE;
6113typedef int *DWORD_PTR;
6114typedef int HPCON;
6115typedef int HRESULT;
6116typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006117typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006118typedef int PSIZE_T;
6119typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006120typedef int BOOL;
6121# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006122#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006123
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006124HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6125HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6126HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006127BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6128BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6129void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006130
6131 static int
6132dyn_conpty_init(int verbose)
6133{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006134 static HMODULE hKerneldll = NULL;
6135 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006136 static struct
6137 {
6138 char *name;
6139 FARPROC *ptr;
6140 } conpty_entry[] =
6141 {
6142 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6143 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6144 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6145 {"InitializeProcThreadAttributeList",
6146 (FARPROC*)&pInitializeProcThreadAttributeList},
6147 {"UpdateProcThreadAttribute",
6148 (FARPROC*)&pUpdateProcThreadAttribute},
6149 {"DeleteProcThreadAttributeList",
6150 (FARPROC*)&pDeleteProcThreadAttributeList},
6151 {NULL, NULL}
6152 };
6153
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006154 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006155 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006156 if (verbose)
6157 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006158 return FAIL;
6159 }
6160
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006161 // No need to initialize twice.
6162 if (hKerneldll)
6163 return OK;
6164
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006165 hKerneldll = vimLoadLib("kernel32.dll");
6166 for (i = 0; conpty_entry[i].name != NULL
6167 && conpty_entry[i].ptr != NULL; ++i)
6168 {
6169 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6170 conpty_entry[i].name)) == NULL)
6171 {
6172 if (verbose)
6173 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006174 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006175 return FAIL;
6176 }
6177 }
6178
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006179 return OK;
6180}
6181
6182 static int
6183conpty_term_and_job_init(
6184 term_T *term,
6185 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006186 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006187 jobopt_T *opt,
6188 jobopt_T *orig_opt)
6189{
6190 WCHAR *cmd_wchar = NULL;
6191 WCHAR *cmd_wchar_copy = NULL;
6192 WCHAR *cwd_wchar = NULL;
6193 WCHAR *env_wchar = NULL;
6194 channel_T *channel = NULL;
6195 job_T *job = NULL;
6196 HANDLE jo = NULL;
6197 garray_T ga_cmd, ga_env;
6198 char_u *cmd = NULL;
6199 HRESULT hr;
6200 COORD consize;
6201 SIZE_T breq;
6202 PROCESS_INFORMATION proc_info;
6203 HANDLE i_theirs = NULL;
6204 HANDLE o_theirs = NULL;
6205 HANDLE i_ours = NULL;
6206 HANDLE o_ours = NULL;
6207
6208 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6209 ga_init2(&ga_env, (int)sizeof(char*), 20);
6210
6211 if (argvar->v_type == VAR_STRING)
6212 {
6213 cmd = argvar->vval.v_string;
6214 }
6215 else if (argvar->v_type == VAR_LIST)
6216 {
6217 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6218 goto failed;
6219 cmd = ga_cmd.ga_data;
6220 }
6221 if (cmd == NULL || *cmd == NUL)
6222 {
6223 emsg(_(e_invarg));
6224 goto failed;
6225 }
6226
6227 term->tl_arg0_cmd = vim_strsave(cmd);
6228
6229 cmd_wchar = enc_to_utf16(cmd, NULL);
6230
6231 if (cmd_wchar != NULL)
6232 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006233 // Request by CreateProcessW
6234 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006235 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006236 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6237 }
6238
6239 ga_clear(&ga_cmd);
6240 if (cmd_wchar == NULL)
6241 goto failed;
6242 if (opt->jo_cwd != NULL)
6243 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6244
6245 win32_build_env(opt->jo_env, &ga_env, TRUE);
6246 env_wchar = ga_env.ga_data;
6247
6248 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6249 goto failed;
6250 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6251 goto failed;
6252
6253 consize.X = term->tl_cols;
6254 consize.Y = term->tl_rows;
6255 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6256 &term->tl_conpty);
6257 if (FAILED(hr))
6258 goto failed;
6259
6260 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6261
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006262 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006263 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006264 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006265 if (!term->tl_siex.lpAttributeList)
6266 goto failed;
6267 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6268 0, &breq))
6269 goto failed;
6270 if (!pUpdateProcThreadAttribute(
6271 term->tl_siex.lpAttributeList, 0,
6272 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6273 sizeof(HPCON), NULL, NULL))
6274 goto failed;
6275
6276 channel = add_channel();
6277 if (channel == NULL)
6278 goto failed;
6279
6280 job = job_alloc();
6281 if (job == NULL)
6282 goto failed;
6283 if (argvar->v_type == VAR_STRING)
6284 {
6285 int argc;
6286
6287 build_argv_from_string(cmd, &job->jv_argv, &argc);
6288 }
6289 else
6290 {
6291 int argc;
6292
6293 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6294 }
6295
6296 if (opt->jo_set & JO_IN_BUF)
6297 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6298
6299 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6300 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
6301 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
6302 | CREATE_DEFAULT_ERROR_MODE,
6303 env_wchar, cwd_wchar,
6304 &term->tl_siex.StartupInfo, &proc_info))
6305 goto failed;
6306
6307 CloseHandle(i_theirs);
6308 CloseHandle(o_theirs);
6309
6310 channel_set_pipes(channel,
6311 (sock_T)i_ours,
6312 (sock_T)o_ours,
6313 (sock_T)o_ours);
6314
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006315 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006316 channel->ch_write_text_mode = TRUE;
6317
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006318 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006319 channel->ch_anonymous_pipe = TRUE;
6320
6321 jo = CreateJobObject(NULL, NULL);
6322 if (jo == NULL)
6323 goto failed;
6324
6325 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6326 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006327 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006328 CloseHandle(jo);
6329 jo = NULL;
6330 }
6331
6332 ResumeThread(proc_info.hThread);
6333 CloseHandle(proc_info.hThread);
6334
6335 vim_free(cmd_wchar);
6336 vim_free(cmd_wchar_copy);
6337 vim_free(cwd_wchar);
6338 vim_free(env_wchar);
6339
6340 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6341 goto failed;
6342
6343#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6344 if (opt->jo_set2 & JO2_ANSI_COLORS)
6345 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6346 else
6347 init_vterm_ansi_colors(term->tl_vterm);
6348#endif
6349
6350 channel_set_job(channel, job, opt);
6351 job_set_options(job, opt);
6352
6353 job->jv_channel = channel;
6354 job->jv_proc_info = proc_info;
6355 job->jv_job_object = jo;
6356 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006357 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006358 ++job->jv_refcount;
6359 term->tl_job = job;
6360
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006361 // Redirecting stdout and stderr doesn't work at the job level. Instead
6362 // open the file here and handle it in. opt->jo_io was changed in
6363 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006364 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6365 {
6366 char_u *fname = opt->jo_io_name[PART_OUT];
6367
6368 ch_log(channel, "Opening output file %s", fname);
6369 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6370 if (term->tl_out_fd == NULL)
6371 semsg(_(e_notopen), fname);
6372 }
6373
6374 return OK;
6375
6376failed:
6377 ga_clear(&ga_cmd);
6378 ga_clear(&ga_env);
6379 vim_free(cmd_wchar);
6380 vim_free(cmd_wchar_copy);
6381 vim_free(cwd_wchar);
6382 if (channel != NULL)
6383 channel_clear(channel);
6384 if (job != NULL)
6385 {
6386 job->jv_channel = NULL;
6387 job_cleanup(job);
6388 }
6389 term->tl_job = NULL;
6390 if (jo != NULL)
6391 CloseHandle(jo);
6392
6393 if (term->tl_siex.lpAttributeList != NULL)
6394 {
6395 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6396 vim_free(term->tl_siex.lpAttributeList);
6397 }
6398 term->tl_siex.lpAttributeList = NULL;
6399 if (o_theirs != NULL)
6400 CloseHandle(o_theirs);
6401 if (o_ours != NULL)
6402 CloseHandle(o_ours);
6403 if (i_ours != NULL)
6404 CloseHandle(i_ours);
6405 if (i_theirs != NULL)
6406 CloseHandle(i_theirs);
6407 if (term->tl_conpty != NULL)
6408 pClosePseudoConsole(term->tl_conpty);
6409 term->tl_conpty = NULL;
6410 return FAIL;
6411}
6412
6413 static void
6414conpty_term_report_winsize(term_T *term, int rows, int cols)
6415{
6416 COORD consize;
6417
6418 consize.X = cols;
6419 consize.Y = rows;
6420 pResizePseudoConsole(term->tl_conpty, consize);
6421}
6422
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006423 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006424term_free_conpty(term_T *term)
6425{
6426 if (term->tl_siex.lpAttributeList != NULL)
6427 {
6428 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6429 vim_free(term->tl_siex.lpAttributeList);
6430 }
6431 term->tl_siex.lpAttributeList = NULL;
6432 if (term->tl_conpty != NULL)
6433 pClosePseudoConsole(term->tl_conpty);
6434 term->tl_conpty = NULL;
6435}
6436
6437 int
6438use_conpty(void)
6439{
6440 return has_conpty;
6441}
6442
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006443# ifndef PROTO
6444
6445#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6446#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006447#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006448
6449void* (*winpty_config_new)(UINT64, void*);
6450void* (*winpty_open)(void*, void*);
6451void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6452BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6453void (*winpty_config_set_mouse_mode)(void*, int);
6454void (*winpty_config_set_initial_size)(void*, int, int);
6455LPCWSTR (*winpty_conin_name)(void*);
6456LPCWSTR (*winpty_conout_name)(void*);
6457LPCWSTR (*winpty_conerr_name)(void*);
6458void (*winpty_free)(void*);
6459void (*winpty_config_free)(void*);
6460void (*winpty_spawn_config_free)(void*);
6461void (*winpty_error_free)(void*);
6462LPCWSTR (*winpty_error_msg)(void*);
6463BOOL (*winpty_set_size)(void*, int, int, void*);
6464HANDLE (*winpty_agent_process)(void*);
6465
6466#define WINPTY_DLL "winpty.dll"
6467
6468static HINSTANCE hWinPtyDLL = NULL;
6469# endif
6470
6471 static int
6472dyn_winpty_init(int verbose)
6473{
6474 int i;
6475 static struct
6476 {
6477 char *name;
6478 FARPROC *ptr;
6479 } winpty_entry[] =
6480 {
6481 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6482 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6483 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6484 {"winpty_config_set_mouse_mode",
6485 (FARPROC*)&winpty_config_set_mouse_mode},
6486 {"winpty_config_set_initial_size",
6487 (FARPROC*)&winpty_config_set_initial_size},
6488 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6489 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6490 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6491 {"winpty_free", (FARPROC*)&winpty_free},
6492 {"winpty_open", (FARPROC*)&winpty_open},
6493 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6494 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6495 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6496 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6497 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6498 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6499 {NULL, NULL}
6500 };
6501
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006502 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006503 if (hWinPtyDLL)
6504 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006505 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6506 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006507 if (*p_winptydll != NUL)
6508 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6509 if (!hWinPtyDLL)
6510 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6511 if (!hWinPtyDLL)
6512 {
6513 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006514 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006515 : (char_u *)WINPTY_DLL);
6516 return FAIL;
6517 }
6518 for (i = 0; winpty_entry[i].name != NULL
6519 && winpty_entry[i].ptr != NULL; ++i)
6520 {
6521 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6522 winpty_entry[i].name)) == NULL)
6523 {
6524 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006525 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006526 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006527 return FAIL;
6528 }
6529 }
6530
6531 return OK;
6532}
6533
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006534 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006535winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006536 term_T *term,
6537 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006538 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006539 jobopt_T *opt,
6540 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006541{
6542 WCHAR *cmd_wchar = NULL;
6543 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006544 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006545 channel_T *channel = NULL;
6546 job_T *job = NULL;
6547 DWORD error;
6548 HANDLE jo = NULL;
6549 HANDLE child_process_handle;
6550 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006551 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006552 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006553 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006554 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006555
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006556 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6557 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006558
6559 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006560 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006561 cmd = argvar->vval.v_string;
6562 }
6563 else if (argvar->v_type == VAR_LIST)
6564 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006565 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006566 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006567 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006568 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006569 if (cmd == NULL || *cmd == NUL)
6570 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006571 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006572 goto failed;
6573 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006574
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006575 term->tl_arg0_cmd = vim_strsave(cmd);
6576
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006577 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006578 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006579 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006580 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006581 if (opt->jo_cwd != NULL)
6582 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006583
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006584 win32_build_env(opt->jo_env, &ga_env, TRUE);
6585 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006586
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006587 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6588 if (term->tl_winpty_config == NULL)
6589 goto failed;
6590
6591 winpty_config_set_mouse_mode(term->tl_winpty_config,
6592 WINPTY_MOUSE_MODE_FORCE);
6593 winpty_config_set_initial_size(term->tl_winpty_config,
6594 term->tl_cols, term->tl_rows);
6595 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6596 if (term->tl_winpty == NULL)
6597 goto failed;
6598
6599 spawn_config = winpty_spawn_config_new(
6600 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6601 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6602 NULL,
6603 cmd_wchar,
6604 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006605 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006606 &winpty_err);
6607 if (spawn_config == NULL)
6608 goto failed;
6609
6610 channel = add_channel();
6611 if (channel == NULL)
6612 goto failed;
6613
6614 job = job_alloc();
6615 if (job == NULL)
6616 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006617 if (argvar->v_type == VAR_STRING)
6618 {
6619 int argc;
6620
6621 build_argv_from_string(cmd, &job->jv_argv, &argc);
6622 }
6623 else
6624 {
6625 int argc;
6626
6627 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6628 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006629
6630 if (opt->jo_set & JO_IN_BUF)
6631 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6632
6633 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6634 &child_thread_handle, &error, &winpty_err))
6635 goto failed;
6636
6637 channel_set_pipes(channel,
6638 (sock_T)CreateFileW(
6639 winpty_conin_name(term->tl_winpty),
6640 GENERIC_WRITE, 0, NULL,
6641 OPEN_EXISTING, 0, NULL),
6642 (sock_T)CreateFileW(
6643 winpty_conout_name(term->tl_winpty),
6644 GENERIC_READ, 0, NULL,
6645 OPEN_EXISTING, 0, NULL),
6646 (sock_T)CreateFileW(
6647 winpty_conerr_name(term->tl_winpty),
6648 GENERIC_READ, 0, NULL,
6649 OPEN_EXISTING, 0, NULL));
6650
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006651 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006652 channel->ch_write_text_mode = TRUE;
6653
6654 jo = CreateJobObject(NULL, NULL);
6655 if (jo == NULL)
6656 goto failed;
6657
6658 if (!AssignProcessToJobObject(jo, child_process_handle))
6659 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006660 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006661 CloseHandle(jo);
6662 jo = NULL;
6663 }
6664
6665 winpty_spawn_config_free(spawn_config);
6666 vim_free(cmd_wchar);
6667 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006668 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006669
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006670 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6671 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006672
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006673#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6674 if (opt->jo_set2 & JO2_ANSI_COLORS)
6675 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6676 else
6677 init_vterm_ansi_colors(term->tl_vterm);
6678#endif
6679
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006680 channel_set_job(channel, job, opt);
6681 job_set_options(job, opt);
6682
6683 job->jv_channel = channel;
6684 job->jv_proc_info.hProcess = child_process_handle;
6685 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6686 job->jv_job_object = jo;
6687 job->jv_status = JOB_STARTED;
6688 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006689 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006690 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006691 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006692 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006693 ++job->jv_refcount;
6694 term->tl_job = job;
6695
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006696 // Redirecting stdout and stderr doesn't work at the job level. Instead
6697 // open the file here and handle it in. opt->jo_io was changed in
6698 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006699 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6700 {
6701 char_u *fname = opt->jo_io_name[PART_OUT];
6702
6703 ch_log(channel, "Opening output file %s", fname);
6704 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6705 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006706 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006707 }
6708
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006709 return OK;
6710
6711failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006712 ga_clear(&ga_cmd);
6713 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006714 vim_free(cmd_wchar);
6715 vim_free(cwd_wchar);
6716 if (spawn_config != NULL)
6717 winpty_spawn_config_free(spawn_config);
6718 if (channel != NULL)
6719 channel_clear(channel);
6720 if (job != NULL)
6721 {
6722 job->jv_channel = NULL;
6723 job_cleanup(job);
6724 }
6725 term->tl_job = NULL;
6726 if (jo != NULL)
6727 CloseHandle(jo);
6728 if (term->tl_winpty != NULL)
6729 winpty_free(term->tl_winpty);
6730 term->tl_winpty = NULL;
6731 if (term->tl_winpty_config != NULL)
6732 winpty_config_free(term->tl_winpty_config);
6733 term->tl_winpty_config = NULL;
6734 if (winpty_err != NULL)
6735 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006736 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006737 (short_u *)winpty_error_msg(winpty_err), NULL);
6738
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006739 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006740 winpty_error_free(winpty_err);
6741 }
6742 return FAIL;
6743}
6744
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006745/*
6746 * Create a new terminal of "rows" by "cols" cells.
6747 * Store a reference in "term".
6748 * Return OK or FAIL.
6749 */
6750 static int
6751term_and_job_init(
6752 term_T *term,
6753 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01006754 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006755 jobopt_T *opt,
6756 jobopt_T *orig_opt)
6757{
6758 int use_winpty = FALSE;
6759 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006760 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006761
6762 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6763 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6764
6765 if (!has_winpty && !has_conpty)
6766 // If neither is available give the errors for winpty, since when
6767 // conpty is not available it can't be installed either.
6768 return dyn_winpty_init(TRUE);
6769
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006770 if (opt->jo_tty_type != NUL)
6771 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006772
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006773 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006774 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006775 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006776 use_conpty = TRUE;
6777 else if (has_winpty)
6778 use_winpty = TRUE;
6779 // else: error
6780 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006781 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006782 {
6783 if (has_winpty)
6784 use_winpty = TRUE;
6785 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006786 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006787 {
6788 if (has_conpty)
6789 use_conpty = TRUE;
6790 else
6791 return dyn_conpty_init(TRUE);
6792 }
6793
6794 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006795 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006796
6797 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006798 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006799
6800 // error
6801 return dyn_winpty_init(TRUE);
6802}
6803
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006804 static int
6805create_pty_only(term_T *term, jobopt_T *options)
6806{
6807 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6808 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6809 char in_name[80], out_name[80];
6810 channel_T *channel = NULL;
6811
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006812 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6813 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006814
6815 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6816 GetCurrentProcessId(),
6817 curbuf->b_fnum);
6818 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6819 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6820 PIPE_UNLIMITED_INSTANCES,
6821 0, 0, NMPWAIT_NOWAIT, NULL);
6822 if (hPipeIn == INVALID_HANDLE_VALUE)
6823 goto failed;
6824
6825 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6826 GetCurrentProcessId(),
6827 curbuf->b_fnum);
6828 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6829 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6830 PIPE_UNLIMITED_INSTANCES,
6831 0, 0, 0, NULL);
6832 if (hPipeOut == INVALID_HANDLE_VALUE)
6833 goto failed;
6834
6835 ConnectNamedPipe(hPipeIn, NULL);
6836 ConnectNamedPipe(hPipeOut, NULL);
6837
6838 term->tl_job = job_alloc();
6839 if (term->tl_job == NULL)
6840 goto failed;
6841 ++term->tl_job->jv_refcount;
6842
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006843 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006844 term->tl_job->jv_status = JOB_FINISHED;
6845
6846 channel = add_channel();
6847 if (channel == NULL)
6848 goto failed;
6849 term->tl_job->jv_channel = channel;
6850 channel->ch_keep_open = TRUE;
6851 channel->ch_named_pipe = TRUE;
6852
6853 channel_set_pipes(channel,
6854 (sock_T)hPipeIn,
6855 (sock_T)hPipeOut,
6856 (sock_T)hPipeOut);
6857 channel_set_job(channel, term->tl_job, options);
6858 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6859 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6860
6861 return OK;
6862
6863failed:
6864 if (hPipeIn != NULL)
6865 CloseHandle(hPipeIn);
6866 if (hPipeOut != NULL)
6867 CloseHandle(hPipeOut);
6868 return FAIL;
6869}
6870
6871/*
6872 * Free the terminal emulator part of "term".
6873 */
6874 static void
6875term_free_vterm(term_T *term)
6876{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006877 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006878 if (term->tl_winpty != NULL)
6879 winpty_free(term->tl_winpty);
6880 term->tl_winpty = NULL;
6881 if (term->tl_winpty_config != NULL)
6882 winpty_config_free(term->tl_winpty_config);
6883 term->tl_winpty_config = NULL;
6884 if (term->tl_vterm != NULL)
6885 vterm_free(term->tl_vterm);
6886 term->tl_vterm = NULL;
6887}
6888
6889/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006890 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006891 */
6892 static void
6893term_report_winsize(term_T *term, int rows, int cols)
6894{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006895 if (term->tl_conpty)
6896 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006897 if (term->tl_winpty)
6898 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6899}
6900
6901 int
6902terminal_enabled(void)
6903{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006904 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006905}
6906
6907# else
6908
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006909///////////////////////////////////////
6910// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006911
6912/*
6913 * Create a new terminal of "rows" by "cols" cells.
6914 * Start job for "cmd".
6915 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006916 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006917 * Return OK or FAIL.
6918 */
6919 static int
6920term_and_job_init(
6921 term_T *term,
6922 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006923 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006924 jobopt_T *opt,
6925 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006926{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006927 term->tl_arg0_cmd = NULL;
6928
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006929 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6930 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006931
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006932#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6933 if (opt->jo_set2 & JO2_ANSI_COLORS)
6934 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6935 else
6936 init_vterm_ansi_colors(term->tl_vterm);
6937#endif
6938
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006939 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01006940 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006941 if (term->tl_job != NULL)
6942 ++term->tl_job->jv_refcount;
6943
6944 return term->tl_job != NULL
6945 && term->tl_job->jv_channel != NULL
6946 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6947}
6948
6949 static int
6950create_pty_only(term_T *term, jobopt_T *opt)
6951{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006952 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6953 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006954
6955 term->tl_job = job_alloc();
6956 if (term->tl_job == NULL)
6957 return FAIL;
6958 ++term->tl_job->jv_refcount;
6959
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006960 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006961 term->tl_job->jv_status = JOB_FINISHED;
6962
6963 return mch_create_pty_channel(term->tl_job, opt);
6964}
6965
6966/*
6967 * Free the terminal emulator part of "term".
6968 */
6969 static void
6970term_free_vterm(term_T *term)
6971{
6972 if (term->tl_vterm != NULL)
6973 vterm_free(term->tl_vterm);
6974 term->tl_vterm = NULL;
6975}
6976
6977/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006978 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006979 */
6980 static void
6981term_report_winsize(term_T *term, int rows, int cols)
6982{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006983 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006984 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6985 {
6986 int fd = -1;
6987 int part;
6988
6989 for (part = PART_OUT; part < PART_COUNT; ++part)
6990 {
6991 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006992 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006993 break;
6994 }
6995 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6996 mch_signal_job(term->tl_job, (char_u *)"winch");
6997 }
6998}
6999
7000# endif
7001
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007002#endif // FEAT_TERMINAL