blob: dcb4c398d42f7093cf1a4bf2a2dc88e14c20bec1 [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
54/* This is VTermScreenCell without the characters, thus much smaller. */
55typedef 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 Moolenaar2e6ab182017-09-20 10:03:07 +020086/* typedef term_T in structs.h */
87struct 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)
94 int tl_system; /* when non-zero used for :!cmd output */
95 int tl_toprow; /* row with first line of system terminal */
96#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
98 /* Set when setting the size of a vterm, reset after redrawing. */
99 int tl_vterm_size_changed;
100
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200101 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
102 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
107#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
130 /* last known vterm size */
131 int tl_rows;
132 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200133
134 char_u *tl_title; /* NULL or allocated */
135 char_u *tl_status_text; /* NULL or allocated */
136
137 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200138 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200139 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200140 int tl_dirty_snapshot; /* text updated after making snapshot */
141#ifdef FEAT_TIMERS
142 int tl_timer_set;
143 proftime_T tl_timer_due;
144#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200145 int tl_postponed_scroll; /* to be scrolled up */
146
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200147 garray_T tl_scrollback;
148 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100149 garray_T tl_scrollback_postponed;
150
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200151 cellattr_T tl_default_color;
152
Bram Moolenaard96ff162018-02-18 22:13:29 +0100153 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
154 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
155
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200156 VTermPos tl_cursor_pos;
157 int tl_cursor_visible;
158 int tl_cursor_blink;
159 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
160 char_u *tl_cursor_color; /* NULL or allocated */
161
162 int tl_using_altscreen;
163};
164
165#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
166#define TMODE_LOOP 2 /* CTRL-W N used */
167
168/*
169 * List of all active terminals.
170 */
171static term_T *first_term = NULL;
172
173/* Terminal active in terminal_loop(). */
174static term_T *in_terminal_loop = NULL;
175
Bram Moolenaar4f974752019-02-17 17:44:42 +0100176#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100177static BOOL has_winpty = FALSE;
178static BOOL has_conpty = FALSE;
179#endif
180
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200181#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
182#define KEY_BUF_LEN 200
183
184/*
185 * Functions with separate implementation for MS-Windows and Unix-like systems.
186 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200187static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188static int create_pty_only(term_T *term, jobopt_T *opt);
189static void term_report_winsize(term_T *term, int rows, int cols);
190static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100191#ifdef FEAT_GUI
192static void update_system_term(term_T *term);
193#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200194
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100195static void handle_postponed_scrollback(term_T *term);
196
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100197/* The character that we know (or assume) that the terminal expects for the
198 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200199static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200200
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100201/* "Terminal" highlight group colors. */
202static int term_default_cterm_fg = -1;
203static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200204
Bram Moolenaard317b382018-02-08 22:33:31 +0100205/* Store the last set and the desired cursor properties, so that we only update
206 * them when needed. Doing it unnecessary may result in flicker. */
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200207static char_u *last_set_cursor_color = NULL;
208static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100209static int last_set_cursor_shape = -1;
210static int desired_cursor_shape = -1;
211static int last_set_cursor_blink = -1;
212static int desired_cursor_blink = -1;
213
214
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200215/**************************************
216 * 1. Generic code for all systems.
217 */
218
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200219 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200220cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
221{
222 if (lhs_color != NULL && rhs_color != NULL)
223 return STRCMP(lhs_color, rhs_color) == 0;
224 return lhs_color == NULL && rhs_color == NULL;
225}
226
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200227 static void
228cursor_color_copy(char_u **to_color, char_u *from_color)
229{
230 // Avoid a free & alloc if the value is already right.
231 if (cursor_color_equal(*to_color, from_color))
232 return;
233 vim_free(*to_color);
234 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
235}
236
237 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200238cursor_color_get(char_u *color)
239{
240 return (color == NULL) ? (char_u *)"" : color;
241}
242
243
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200244/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200245 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200246 * current window.
247 * Sets "rows" and/or "cols" to zero when it should follow the window size.
248 * Return TRUE if the size is the minimum size: "24*80".
249 */
250 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200251parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200252{
253 int minsize = FALSE;
254
255 *rows = 0;
256 *cols = 0;
257
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200258 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200259 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200260 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200261
262 /* Syntax of value was already checked when it's set. */
263 if (p == NULL)
264 {
265 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200266 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200267 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200268 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200269 *cols = atoi((char *)p + 1);
270 }
271 return minsize;
272}
273
274/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200275 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200276 */
277 static void
278set_term_and_win_size(term_T *term)
279{
Bram Moolenaar13568252018-03-16 20:46:58 +0100280#ifdef FEAT_GUI
281 if (term->tl_system)
282 {
283 /* Use the whole screen for the system command. However, it will start
284 * at the command line and scroll up as needed, using tl_toprow. */
285 term->tl_rows = Rows;
286 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200287 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100288 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100289#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200290 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200291 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200292 if (term->tl_rows != 0)
293 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
294 if (term->tl_cols != 0)
295 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200296 }
297 if (term->tl_rows == 0)
298 term->tl_rows = curwin->w_height;
299 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200301 if (term->tl_cols == 0)
302 term->tl_cols = curwin->w_width;
303 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200304 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200305}
306
307/*
308 * Initialize job options for a terminal job.
309 * Caller may overrule some of them.
310 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100311 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200312init_job_options(jobopt_T *opt)
313{
314 clear_job_options(opt);
315
316 opt->jo_mode = MODE_RAW;
317 opt->jo_out_mode = MODE_RAW;
318 opt->jo_err_mode = MODE_RAW;
319 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
320}
321
322/*
323 * Set job options mandatory for a terminal job.
324 */
325 static void
326setup_job_options(jobopt_T *opt, int rows, int cols)
327{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100328#ifndef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200329 /* Win32: Redirecting the job output won't work, thus always connect stdout
330 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200331 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200332#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200333 {
334 /* Connect stdout to the terminal. */
335 opt->jo_io[PART_OUT] = JIO_BUFFER;
336 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
337 opt->jo_modifiable[PART_OUT] = 0;
338 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
339 }
340
Bram Moolenaar4f974752019-02-17 17:44:42 +0100341#ifndef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200342 /* Win32: Redirecting the job output won't work, thus always connect stderr
343 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200344 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200345#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346 {
347 /* Connect stderr to the terminal. */
348 opt->jo_io[PART_ERR] = JIO_BUFFER;
349 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
350 opt->jo_modifiable[PART_ERR] = 0;
351 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
352 }
353
354 opt->jo_pty = TRUE;
355 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
356 opt->jo_term_rows = rows;
357 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
358 opt->jo_term_cols = cols;
359}
360
361/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200362 * Flush messages on channels.
363 */
364 static void
365term_flush_messages()
366{
367 mch_check_messages();
368 parse_queued_messages();
369}
370
371/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100372 * Close a terminal buffer (and its window). Used when creating the terminal
373 * fails.
374 */
375 static void
376term_close_buffer(buf_T *buf, buf_T *old_curbuf)
377{
378 free_terminal(buf);
379 if (old_curbuf != NULL)
380 {
381 --curbuf->b_nwindows;
382 curbuf = old_curbuf;
383 curwin->w_buffer = curbuf;
384 ++curbuf->b_nwindows;
385 }
386
387 /* Wiping out the buffer will also close the window and call
388 * free_terminal(). */
389 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
390}
391
392/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200393 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100394 * Use either "argvar" or "argv", the other must be NULL.
395 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
396 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200397 * Returns NULL when failed.
398 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100399 buf_T *
400term_start(
401 typval_T *argvar,
402 char **argv,
403 jobopt_T *opt,
404 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200405{
406 exarg_T split_ea;
407 win_T *old_curwin = curwin;
408 term_T *term;
409 buf_T *old_curbuf = NULL;
410 int res;
411 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100412 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200413 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200414
415 if (check_restricted() || check_secure())
416 return NULL;
417
418 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
419 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
420 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
421 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
422 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100423 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200424 return NULL;
425 }
426
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200427 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 if (term == NULL)
429 return NULL;
430 term->tl_dirty_row_end = MAX_ROW;
431 term->tl_cursor_visible = TRUE;
432 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
433 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100434#ifdef FEAT_GUI
435 term->tl_system = (flags & TERM_START_SYSTEM);
436#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200437 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100438 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200439
440 vim_memset(&split_ea, 0, sizeof(split_ea));
441 if (opt->jo_curwin)
442 {
443 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100444 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200445 {
446 no_write_message();
447 vim_free(term);
448 return NULL;
449 }
450 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100451 ECMD_HIDE
452 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
453 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200454 {
455 vim_free(term);
456 return NULL;
457 }
458 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100459 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200460 {
461 buf_T *buf;
462
463 /* Create a new buffer without a window. Make it the current buffer for
464 * a moment to be able to do the initialisations. */
465 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
466 BLN_NEW | BLN_LISTED);
467 if (buf == NULL || ml_open(buf) == FAIL)
468 {
469 vim_free(term);
470 return NULL;
471 }
472 old_curbuf = curbuf;
473 --curbuf->b_nwindows;
474 curbuf = buf;
475 curwin->w_buffer = buf;
476 ++curbuf->b_nwindows;
477 }
478 else
479 {
480 /* Open a new window or tab. */
481 split_ea.cmdidx = CMD_new;
482 split_ea.cmd = (char_u *)"new";
483 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100484 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200485 {
486 split_ea.line2 = opt->jo_term_rows;
487 split_ea.addr_count = 1;
488 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100489 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200490 {
491 split_ea.line2 = opt->jo_term_cols;
492 split_ea.addr_count = 1;
493 }
494
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100495 if (vertical)
496 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200497 ex_splitview(&split_ea);
498 if (curwin == old_curwin)
499 {
500 /* split failed */
501 vim_free(term);
502 return NULL;
503 }
504 }
505 term->tl_buffer = curbuf;
506 curbuf->b_term = term;
507
508 if (!opt->jo_hidden)
509 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100510 /* Only one size was taken care of with :new, do the other one. With
511 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100512 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200513 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100514 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200515 win_setwidth(opt->jo_term_cols);
516 }
517
518 /* Link the new terminal in the list of active terminals. */
519 term->tl_next = first_term;
520 first_term = term;
521
522 if (opt->jo_term_name != NULL)
523 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100524 else if (argv != NULL)
525 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200526 else
527 {
528 int i;
529 size_t len;
530 char_u *cmd, *p;
531
532 if (argvar->v_type == VAR_STRING)
533 {
534 cmd = argvar->vval.v_string;
535 if (cmd == NULL)
536 cmd = (char_u *)"";
537 else if (STRCMP(cmd, "NONE") == 0)
538 cmd = (char_u *)"pty";
539 }
540 else if (argvar->v_type != VAR_LIST
541 || argvar->vval.v_list == NULL
542 || argvar->vval.v_list->lv_len < 1
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100543 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200544 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
545 cmd = (char_u*)"";
546
547 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200548 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200549
550 for (i = 0; p != NULL; ++i)
551 {
552 /* Prepend a ! to the command name to avoid the buffer name equals
553 * the executable, otherwise ":w!" would overwrite it. */
554 if (i == 0)
555 vim_snprintf((char *)p, len, "!%s", cmd);
556 else
557 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
558 if (buflist_findname(p) == NULL)
559 {
560 vim_free(curbuf->b_ffname);
561 curbuf->b_ffname = p;
562 break;
563 }
564 }
565 }
566 curbuf->b_fname = curbuf->b_ffname;
567
568 if (opt->jo_term_opencmd != NULL)
569 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
570
571 if (opt->jo_eof_chars != NULL)
572 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
573
574 set_string_option_direct((char_u *)"buftype", -1,
575 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200576 // Avoid that 'buftype' is reset when this buffer is entered.
577 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200578
579 /* Mark the buffer as not modifiable. It can only be made modifiable after
580 * the job finished. */
581 curbuf->b_p_ma = FALSE;
582
583 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100584#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200585 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
586#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200587 setup_job_options(opt, term->tl_rows, term->tl_cols);
588
Bram Moolenaar13568252018-03-16 20:46:58 +0100589 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100590 return curbuf;
591
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100592#if defined(FEAT_SESSION)
593 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100594 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100595 {
596 term->tl_command = vim_strsave((char_u *)"NONE");
597 }
598 else if (argvar->v_type == VAR_STRING)
599 {
600 char_u *cmd = argvar->vval.v_string;
601
602 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
603 term->tl_command = vim_strsave(cmd);
604 }
605 else if (argvar->v_type == VAR_LIST
606 && argvar->vval.v_list != NULL
607 && argvar->vval.v_list->lv_len > 0)
608 {
609 garray_T ga;
610 listitem_T *item;
611
612 ga_init2(&ga, 1, 100);
613 for (item = argvar->vval.v_list->lv_first;
614 item != NULL; item = item->li_next)
615 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100616 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100617 char_u *p;
618
619 if (s == NULL)
620 break;
621 p = vim_strsave_fnameescape(s, FALSE);
622 if (p == NULL)
623 break;
624 ga_concat(&ga, p);
625 vim_free(p);
626 ga_append(&ga, ' ');
627 }
628 if (item == NULL)
629 {
630 ga_append(&ga, NUL);
631 term->tl_command = ga.ga_data;
632 }
633 else
634 ga_clear(&ga);
635 }
636#endif
637
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100638 if (opt->jo_term_kill != NULL)
639 {
640 char_u *p = skiptowhite(opt->jo_term_kill);
641
642 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
643 }
644
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200645 if (opt->jo_term_api != NULL)
646 term->tl_api = vim_strsave(opt->jo_term_api);
647 else
648 term->tl_api = vim_strsave((char_u *)"Tapi_");
649
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200650 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100651 if (argv == NULL
652 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200653 && argvar->vval.v_string != NULL
654 && STRCMP(argvar->vval.v_string, "NONE") == 0)
655 res = create_pty_only(term, opt);
656 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200657 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200658
659 newbuf = curbuf;
660 if (res == OK)
661 {
662 /* Get and remember the size we ended up with. Update the pty. */
663 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
664 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100665#ifdef FEAT_GUI
666 if (term->tl_system)
667 {
668 /* display first line below typed command */
669 term->tl_toprow = msg_row + 1;
670 term->tl_dirty_row_end = 0;
671 }
672#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200673
674 /* Make sure we don't get stuck on sending keys to the job, it leads to
675 * a deadlock if the job is waiting for Vim to read. */
676 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
677
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200678 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200679 {
680 --curbuf->b_nwindows;
681 curbuf = old_curbuf;
682 curwin->w_buffer = curbuf;
683 ++curbuf->b_nwindows;
684 }
685 }
686 else
687 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100688 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200689 return NULL;
690 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100691
Bram Moolenaar13568252018-03-16 20:46:58 +0100692 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200693 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
694 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200695 return newbuf;
696}
697
698/*
699 * ":terminal": open a terminal window and execute a job in it.
700 */
701 void
702ex_terminal(exarg_T *eap)
703{
704 typval_T argvar[2];
705 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100706 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200707 char_u *cmd;
708 char_u *tofree = NULL;
709
710 init_job_options(&opt);
711
712 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100713 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200714 {
715 char_u *p, *ep;
716
717 cmd += 2;
718 p = skiptowhite(cmd);
719 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200720 if (ep != NULL)
721 {
722 if (ep < p)
723 p = ep;
724 else
725 ep = NULL;
726 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200727
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200728# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
729 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
730 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200731 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200732 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100733 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200734 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200735 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200736 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200737 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200738 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200739 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200740 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100741 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100742 else if (OPTARG_HAS("shell"))
743 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200744 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100745 {
746 opt.jo_set2 |= JO2_TERM_KILL;
747 opt.jo_term_kill = ep + 1;
748 p = skiptowhite(cmd);
749 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200750 else if (OPTARG_HAS("api"))
751 {
752 opt.jo_set2 |= JO2_TERM_API;
753 if (ep != NULL)
754 {
755 opt.jo_term_api = ep + 1;
756 p = skiptowhite(cmd);
757 }
758 else
759 opt.jo_term_api = NULL;
760 }
761 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200762 {
763 opt.jo_set2 |= JO2_TERM_ROWS;
764 opt.jo_term_rows = atoi((char *)ep + 1);
765 p = skiptowhite(cmd);
766 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200767 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200768 {
769 opt.jo_set2 |= JO2_TERM_COLS;
770 opt.jo_term_cols = atoi((char *)ep + 1);
771 p = skiptowhite(cmd);
772 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200773 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200774 {
775 char_u *buf = NULL;
776 char_u *keys;
777
778 p = skiptowhite(cmd);
779 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200780 keys = replace_termcodes(ep + 1, &buf,
781 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200782 opt.jo_set2 |= JO2_EOF_CHARS;
783 opt.jo_eof_chars = vim_strsave(keys);
784 vim_free(buf);
785 *p = ' ';
786 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100787#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100788 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
789 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100790 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100791 int tty_type = NUL;
792
793 p = skiptowhite(cmd);
794 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
795 tty_type = 'w';
796 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
797 tty_type = 'c';
798 else
799 {
800 semsg(e_invargval, "type");
801 goto theend;
802 }
803 opt.jo_set2 |= JO2_TTY_TYPE;
804 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100805 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100806#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200807 else
808 {
809 if (*p)
810 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100811 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100812 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200813 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200814# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200815 cmd = skipwhite(p);
816 }
817 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100818 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200819 /* Make a copy of 'shell', an autocommand may change the option. */
820 tofree = cmd = vim_strsave(p_sh);
821
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100822 /* default to close when the shell exits */
823 if (opt.jo_term_finish == NUL)
824 opt.jo_term_finish = 'c';
825 }
826
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200827 if (eap->addr_count > 0)
828 {
829 /* Write lines from current buffer to the job. */
830 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
831 opt.jo_io[PART_IN] = JIO_BUFFER;
832 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
833 opt.jo_in_top = eap->line1;
834 opt.jo_in_bot = eap->line2;
835 }
836
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100837 if (opt_shell && tofree == NULL)
838 {
839#ifdef UNIX
840 char **argv = NULL;
841 char_u *tofree1 = NULL;
842 char_u *tofree2 = NULL;
843
844 // :term ++shell command
845 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
846 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100847 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100848 vim_free(tofree1);
849 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100850 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100851#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100852# ifdef MSWIN
853 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
854 char_u *newcmd;
855
856 newcmd = alloc(cmdlen);
857 if (newcmd == NULL)
858 goto theend;
859 tofree = newcmd;
860 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
861 cmd = newcmd;
862# else
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100863 emsg(_("E279: Sorry, ++shell is not supported on this system"));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100864 goto theend;
865# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100866#endif
867 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100868 argvar[0].v_type = VAR_STRING;
869 argvar[0].vval.v_string = cmd;
870 argvar[1].v_type = VAR_UNKNOWN;
871 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100872
873theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100874 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200875 vim_free(opt.jo_eof_chars);
876}
877
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100878#if defined(FEAT_SESSION) || defined(PROTO)
879/*
880 * Write a :terminal command to the session file to restore the terminal in
881 * window "wp".
882 * Return FAIL if writing fails.
883 */
884 int
885term_write_session(FILE *fd, win_T *wp)
886{
887 term_T *term = wp->w_buffer->b_term;
888
889 /* Create the terminal and run the command. This is not without
890 * risk, but let's assume the user only creates a session when this
891 * will be OK. */
892 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
893 term->tl_cols, term->tl_rows) < 0)
894 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100895#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100896 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
897 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100898#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100899 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
900 return FAIL;
901
902 return put_eol(fd);
903}
904
905/*
906 * Return TRUE if "buf" has a terminal that should be restored.
907 */
908 int
909term_should_restore(buf_T *buf)
910{
911 term_T *term = buf->b_term;
912
913 return term != NULL && (term->tl_command == NULL
914 || STRCMP(term->tl_command, "NONE") != 0);
915}
916#endif
917
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200918/*
919 * Free the scrollback buffer for "term".
920 */
921 static void
922free_scrollback(term_T *term)
923{
924 int i;
925
926 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
927 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
928 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100929 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
930 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
931 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200932}
933
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100934
935// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200936static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100937
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200938/*
939 * Free a terminal and everything it refers to.
940 * Kills the job if there is one.
941 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100942 * The actual terminal structure is freed later in free_unused_terminals(),
943 * because callbacks may wipe out a buffer while the terminal is still
944 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200945 */
946 void
947free_terminal(buf_T *buf)
948{
949 term_T *term = buf->b_term;
950 term_T *tp;
951
952 if (term == NULL)
953 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100954
955 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200956 if (first_term == term)
957 first_term = term->tl_next;
958 else
959 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
960 if (tp->tl_next == term)
961 {
962 tp->tl_next = term->tl_next;
963 break;
964 }
965
966 if (term->tl_job != NULL)
967 {
968 if (term->tl_job->jv_status != JOB_ENDED
969 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100970 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200971 job_stop(term->tl_job, NULL, "kill");
972 job_unref(term->tl_job);
973 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100974 term->tl_next = terminals_to_free;
975 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200976
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200977 buf->b_term = NULL;
978 if (in_terminal_loop == term)
979 in_terminal_loop = NULL;
980}
981
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100982 void
983free_unused_terminals()
984{
985 while (terminals_to_free != NULL)
986 {
987 term_T *term = terminals_to_free;
988
989 terminals_to_free = term->tl_next;
990
991 free_scrollback(term);
992
993 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200994 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100995 vim_free(term->tl_title);
996#ifdef FEAT_SESSION
997 vim_free(term->tl_command);
998#endif
999 vim_free(term->tl_kill);
1000 vim_free(term->tl_status_text);
1001 vim_free(term->tl_opencmd);
1002 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001003 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001004#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001005 if (term->tl_out_fd != NULL)
1006 fclose(term->tl_out_fd);
1007#endif
1008 vim_free(term->tl_cursor_color);
1009 vim_free(term);
1010 }
1011}
1012
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001013/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001014 * Get the part that is connected to the tty. Normally this is PART_IN, but
1015 * when writing buffer lines to the job it can be another. This makes it
1016 * possible to do "1,5term vim -".
1017 */
1018 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001019get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001020{
1021#ifdef UNIX
1022 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1023 int i;
1024
1025 for (i = 0; i < 3; ++i)
1026 {
1027 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1028
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001029 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001030 return parts[i];
1031 }
1032#endif
1033 return PART_IN;
1034}
1035
1036/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001037 * Write job output "msg[len]" to the vterm.
1038 */
1039 static void
1040term_write_job_output(term_T *term, char_u *msg, size_t len)
1041{
1042 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001043 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001044
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001045 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001046
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001047 /* flush vterm buffer when vterm responded to control sequence */
1048 if (prevlen != vterm_output_get_buffer_current(vterm))
1049 {
1050 char buf[KEY_BUF_LEN];
1051 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1052
1053 if (curlen > 0)
1054 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1055 (char_u *)buf, (int)curlen, NULL);
1056 }
1057
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001058 /* this invokes the damage callbacks */
1059 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1060}
1061
1062 static void
1063update_cursor(term_T *term, int redraw)
1064{
1065 if (term->tl_normal_mode)
1066 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001067#ifdef FEAT_GUI
1068 if (term->tl_system)
1069 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1070 term->tl_cursor_pos.col);
1071 else
1072#endif
1073 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001074 if (redraw)
1075 {
1076 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1077 cursor_on();
1078 out_flush();
1079#ifdef FEAT_GUI
1080 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001081 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001082 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001083 gui_mch_flush();
1084 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001085#endif
1086 }
1087}
1088
1089/*
1090 * Invoked when "msg" output from a job was received. Write it to the terminal
1091 * of "buffer".
1092 */
1093 void
1094write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1095{
1096 size_t len = STRLEN(msg);
1097 term_T *term = buffer->b_term;
1098
Bram Moolenaar4f974752019-02-17 17:44:42 +01001099#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001100 /* Win32: Cannot redirect output of the job, intercept it here and write to
1101 * the file. */
1102 if (term->tl_out_fd != NULL)
1103 {
1104 ch_log(channel, "Writing %d bytes to output file", (int)len);
1105 fwrite(msg, len, 1, term->tl_out_fd);
1106 return;
1107 }
1108#endif
1109
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001110 if (term->tl_vterm == NULL)
1111 {
1112 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1113 return;
1114 }
1115 ch_log(channel, "writing %d bytes to terminal", (int)len);
1116 term_write_job_output(term, msg, len);
1117
Bram Moolenaar13568252018-03-16 20:46:58 +01001118#ifdef FEAT_GUI
1119 if (term->tl_system)
1120 {
1121 /* show system output, scrolling up the screen as needed */
1122 update_system_term(term);
1123 update_cursor(term, TRUE);
1124 }
1125 else
1126#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001127 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
1128 * contents, thus no screen update is needed. */
1129 if (!term->tl_normal_mode)
1130 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001131 // Don't use update_screen() when editing the command line, it gets
1132 // cleared.
1133 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001134 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001135 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001136 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001137 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001138 /* update_screen() can be slow, check the terminal wasn't closed
1139 * already */
1140 if (buffer == curbuf && curbuf->b_term != NULL)
1141 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001142 }
1143 else
1144 redraw_after_callback(TRUE);
1145 }
1146}
1147
1148/*
1149 * Send a mouse position and click to the vterm
1150 */
1151 static int
1152term_send_mouse(VTerm *vterm, int button, int pressed)
1153{
1154 VTermModifier mod = VTERM_MOD_NONE;
1155
1156 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001157 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001158 if (button != 0)
1159 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001160 return TRUE;
1161}
1162
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001163static int enter_mouse_col = -1;
1164static int enter_mouse_row = -1;
1165
1166/*
1167 * Handle a mouse click, drag or release.
1168 * Return TRUE when a mouse event is sent to the terminal.
1169 */
1170 static int
1171term_mouse_click(VTerm *vterm, int key)
1172{
1173#if defined(FEAT_CLIPBOARD)
1174 /* For modeless selection mouse drag and release events are ignored, unless
1175 * they are preceded with a mouse down event */
1176 static int ignore_drag_release = TRUE;
1177 VTermMouseState mouse_state;
1178
1179 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1180 if (mouse_state.flags == 0)
1181 {
1182 /* Terminal is not using the mouse, use modeless selection. */
1183 switch (key)
1184 {
1185 case K_LEFTDRAG:
1186 case K_LEFTRELEASE:
1187 case K_RIGHTDRAG:
1188 case K_RIGHTRELEASE:
1189 /* Ignore drag and release events when the button-down wasn't
1190 * seen before. */
1191 if (ignore_drag_release)
1192 {
1193 int save_mouse_col, save_mouse_row;
1194
1195 if (enter_mouse_col < 0)
1196 break;
1197
1198 /* mouse click in the window gave us focus, handle that
1199 * click now */
1200 save_mouse_col = mouse_col;
1201 save_mouse_row = mouse_row;
1202 mouse_col = enter_mouse_col;
1203 mouse_row = enter_mouse_row;
1204 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1205 mouse_col = save_mouse_col;
1206 mouse_row = save_mouse_row;
1207 }
1208 /* FALLTHROUGH */
1209 case K_LEFTMOUSE:
1210 case K_RIGHTMOUSE:
1211 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1212 ignore_drag_release = TRUE;
1213 else
1214 ignore_drag_release = FALSE;
1215 /* Should we call mouse_has() here? */
1216 if (clip_star.available)
1217 {
1218 int button, is_click, is_drag;
1219
1220 button = get_mouse_button(KEY2TERMCAP1(key),
1221 &is_click, &is_drag);
1222 if (mouse_model_popup() && button == MOUSE_LEFT
1223 && (mod_mask & MOD_MASK_SHIFT))
1224 {
1225 /* Translate shift-left to right button. */
1226 button = MOUSE_RIGHT;
1227 mod_mask &= ~MOD_MASK_SHIFT;
1228 }
1229 clip_modeless(button, is_click, is_drag);
1230 }
1231 break;
1232
1233 case K_MIDDLEMOUSE:
1234 if (clip_star.available)
1235 insert_reg('*', TRUE);
1236 break;
1237 }
1238 enter_mouse_col = -1;
1239 return FALSE;
1240 }
1241#endif
1242 enter_mouse_col = -1;
1243
1244 switch (key)
1245 {
1246 case K_LEFTMOUSE:
1247 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1248 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1249 case K_LEFTRELEASE:
1250 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1251 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1252 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1253 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1254 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1255 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1256 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1257 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1258 }
1259 return TRUE;
1260}
1261
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001262/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001263 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1264 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001265 * Return the number of bytes in "buf".
1266 */
1267 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001268term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001269{
1270 VTerm *vterm = term->tl_vterm;
1271 VTermKey key = VTERM_KEY_NONE;
1272 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001273 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001274
1275 switch (c)
1276 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001277 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1278
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001279 /* don't use VTERM_KEY_BACKSPACE, it always
1280 * becomes 0x7f DEL */
1281 case K_BS: c = term_backspace_char; break;
1282
1283 case ESC: key = VTERM_KEY_ESCAPE; break;
1284 case K_DEL: key = VTERM_KEY_DEL; break;
1285 case K_DOWN: key = VTERM_KEY_DOWN; break;
1286 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1287 key = VTERM_KEY_DOWN; break;
1288 case K_END: key = VTERM_KEY_END; break;
1289 case K_S_END: mod = VTERM_MOD_SHIFT;
1290 key = VTERM_KEY_END; break;
1291 case K_C_END: mod = VTERM_MOD_CTRL;
1292 key = VTERM_KEY_END; break;
1293 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1294 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1295 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1296 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1297 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1298 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1299 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1300 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1301 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1302 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1303 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1304 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1305 case K_HOME: key = VTERM_KEY_HOME; break;
1306 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1307 key = VTERM_KEY_HOME; break;
1308 case K_C_HOME: mod = VTERM_MOD_CTRL;
1309 key = VTERM_KEY_HOME; break;
1310 case K_INS: key = VTERM_KEY_INS; break;
1311 case K_K0: key = VTERM_KEY_KP_0; break;
1312 case K_K1: key = VTERM_KEY_KP_1; break;
1313 case K_K2: key = VTERM_KEY_KP_2; break;
1314 case K_K3: key = VTERM_KEY_KP_3; break;
1315 case K_K4: key = VTERM_KEY_KP_4; break;
1316 case K_K5: key = VTERM_KEY_KP_5; break;
1317 case K_K6: key = VTERM_KEY_KP_6; break;
1318 case K_K7: key = VTERM_KEY_KP_7; break;
1319 case K_K8: key = VTERM_KEY_KP_8; break;
1320 case K_K9: key = VTERM_KEY_KP_9; break;
1321 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1322 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1323 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1324 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1325 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1326 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1327 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1328 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1329 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1330 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1331 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1332 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1333 case K_LEFT: key = VTERM_KEY_LEFT; break;
1334 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1335 key = VTERM_KEY_LEFT; break;
1336 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1337 key = VTERM_KEY_LEFT; break;
1338 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1339 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1340 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1341 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1342 key = VTERM_KEY_RIGHT; break;
1343 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1344 key = VTERM_KEY_RIGHT; break;
1345 case K_UP: key = VTERM_KEY_UP; break;
1346 case K_S_UP: mod = VTERM_MOD_SHIFT;
1347 key = VTERM_KEY_UP; break;
1348 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001349 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1350 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001351
Bram Moolenaara42ad572017-11-16 13:08:04 +01001352 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1353 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001354 case K_MOUSELEFT: /* TODO */ return 0;
1355 case K_MOUSERIGHT: /* TODO */ return 0;
1356
1357 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001358 case K_LEFTMOUSE_NM:
1359 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001360 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001361 case K_LEFTRELEASE_NM:
1362 case K_MOUSEMOVE:
1363 case K_MIDDLEMOUSE:
1364 case K_MIDDLEDRAG:
1365 case K_MIDDLERELEASE:
1366 case K_RIGHTMOUSE:
1367 case K_RIGHTDRAG:
1368 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1369 return 0;
1370 other = TRUE;
1371 break;
1372
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001373 case K_X1MOUSE: /* TODO */ return 0;
1374 case K_X1DRAG: /* TODO */ return 0;
1375 case K_X1RELEASE: /* TODO */ return 0;
1376 case K_X2MOUSE: /* TODO */ return 0;
1377 case K_X2DRAG: /* TODO */ return 0;
1378 case K_X2RELEASE: /* TODO */ return 0;
1379
1380 case K_IGNORE: return 0;
1381 case K_NOP: return 0;
1382 case K_UNDO: return 0;
1383 case K_HELP: return 0;
1384 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1385 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1386 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1387 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1388 case K_SELECT: return 0;
1389#ifdef FEAT_GUI
1390 case K_VER_SCROLLBAR: return 0;
1391 case K_HOR_SCROLLBAR: return 0;
1392#endif
1393#ifdef FEAT_GUI_TABLINE
1394 case K_TABLINE: return 0;
1395 case K_TABMENU: return 0;
1396#endif
1397#ifdef FEAT_NETBEANS_INTG
1398 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1399#endif
1400#ifdef FEAT_DND
1401 case K_DROP: return 0;
1402#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001403 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001404 case K_PS: vterm_keyboard_start_paste(vterm);
1405 other = TRUE;
1406 break;
1407 case K_PE: vterm_keyboard_end_paste(vterm);
1408 other = TRUE;
1409 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001410 }
1411
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001412 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001413 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001414 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001415 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001416 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001417 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001418 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001419
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001420 /*
1421 * Convert special keys to vterm keys:
1422 * - Write keys to vterm: vterm_keyboard_key()
1423 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001424 */
1425 if (key != VTERM_KEY_NONE)
1426 /* Special key, let vterm convert it. */
1427 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001428 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001429 /* Normal character, let vterm convert it. */
1430 vterm_keyboard_unichar(vterm, c, mod);
1431
1432 /* Read back the converted escape sequence. */
1433 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1434}
1435
1436/*
1437 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001438 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001439 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001440 */
1441 static int
1442term_job_running_check(term_T *term, int check_job_status)
1443{
1444 /* Also consider the job finished when the channel is closed, to avoid a
1445 * race condition when updating the title. */
1446 if (term != NULL
1447 && term->tl_job != NULL
1448 && channel_is_open(term->tl_job->jv_channel))
1449 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001450 job_T *job = term->tl_job;
1451
1452 // Careful: Checking the job status may invoked callbacks, which close
1453 // the buffer and terminate "term". However, "job" will not be freed
1454 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001455 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001456 job_status(job);
1457 return (job->jv_status == JOB_STARTED
1458 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001459 }
1460 return FALSE;
1461}
1462
1463/*
1464 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001465 */
1466 int
1467term_job_running(term_T *term)
1468{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001469 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001470}
1471
1472/*
1473 * Return TRUE if "term" has an active channel and used ":term NONE".
1474 */
1475 int
1476term_none_open(term_T *term)
1477{
1478 /* Also consider the job finished when the channel is closed, to avoid a
1479 * race condition when updating the title. */
1480 return term != NULL
1481 && term->tl_job != NULL
1482 && channel_is_open(term->tl_job->jv_channel)
1483 && term->tl_job->jv_channel->ch_keep_open;
1484}
1485
1486/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001487 * Used when exiting: kill the job in "buf" if so desired.
1488 * Return OK when the job finished.
1489 * Return FAIL when the job is still running.
1490 */
1491 int
1492term_try_stop_job(buf_T *buf)
1493{
1494 int count;
1495 char *how = (char *)buf->b_term->tl_kill;
1496
1497#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1498 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1499 {
1500 char_u buff[DIALOG_MSG_SIZE];
1501 int ret;
1502
1503 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1504 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1505 if (ret == VIM_YES)
1506 how = "kill";
1507 else if (ret == VIM_CANCEL)
1508 return FAIL;
1509 }
1510#endif
1511 if (how == NULL || *how == NUL)
1512 return FAIL;
1513
1514 job_stop(buf->b_term->tl_job, NULL, how);
1515
Bram Moolenaar9172d232019-01-29 23:06:54 +01001516 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001517 for (count = 0; count < 100; ++count)
1518 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001519 job_T *job;
1520
1521 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001522 if (!buf_valid(buf)
1523 || buf->b_term == NULL
1524 || buf->b_term->tl_job == NULL)
1525 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001526 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001527
Bram Moolenaar9172d232019-01-29 23:06:54 +01001528 // Call job_status() to update jv_status. It may cause the job to be
1529 // cleaned up but it won't be freed.
1530 job_status(job);
1531 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001532 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001533
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001534 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001535 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001536 }
1537 return FAIL;
1538}
1539
1540/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001541 * Add the last line of the scrollback buffer to the buffer in the window.
1542 */
1543 static void
1544add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1545{
1546 buf_T *buf = term->tl_buffer;
1547 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1548 linenr_T lnum = buf->b_ml.ml_line_count;
1549
Bram Moolenaar4f974752019-02-17 17:44:42 +01001550#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001551 if (!enc_utf8 && enc_codepage > 0)
1552 {
1553 WCHAR *ret = NULL;
1554 int length = 0;
1555
1556 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1557 &ret, &length);
1558 if (ret != NULL)
1559 {
1560 WideCharToMultiByte_alloc(enc_codepage, 0,
1561 ret, length, (char **)&text, &len, 0, 0);
1562 vim_free(ret);
1563 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1564 vim_free(text);
1565 }
1566 }
1567 else
1568#endif
1569 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1570 if (empty)
1571 {
1572 /* Delete the empty line that was in the empty buffer. */
1573 curbuf = buf;
1574 ml_delete(1, FALSE);
1575 curbuf = curwin->w_buffer;
1576 }
1577}
1578
1579 static void
1580cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1581{
1582 attr->width = cell->width;
1583 attr->attrs = cell->attrs;
1584 attr->fg = cell->fg;
1585 attr->bg = cell->bg;
1586}
1587
1588 static int
1589equal_celattr(cellattr_T *a, cellattr_T *b)
1590{
1591 /* Comparing the colors should be sufficient. */
1592 return a->fg.red == b->fg.red
1593 && a->fg.green == b->fg.green
1594 && a->fg.blue == b->fg.blue
1595 && a->bg.red == b->bg.red
1596 && a->bg.green == b->bg.green
1597 && a->bg.blue == b->bg.blue;
1598}
1599
Bram Moolenaard96ff162018-02-18 22:13:29 +01001600/*
1601 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1602 * line at this position. Otherwise at the end.
1603 */
1604 static int
1605add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1606{
1607 if (ga_grow(&term->tl_scrollback, 1) == OK)
1608 {
1609 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1610 + term->tl_scrollback.ga_len;
1611
1612 if (lnum > 0)
1613 {
1614 int i;
1615
1616 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1617 {
1618 *line = *(line - 1);
1619 --line;
1620 }
1621 }
1622 line->sb_cols = 0;
1623 line->sb_cells = NULL;
1624 line->sb_fill_attr = *fill_attr;
1625 ++term->tl_scrollback.ga_len;
1626 return OK;
1627 }
1628 return FALSE;
1629}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001630
1631/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001632 * Remove the terminal contents from the scrollback and the buffer.
1633 * Used before adding a new scrollback line or updating the buffer for lines
1634 * displayed in the terminal.
1635 */
1636 static void
1637cleanup_scrollback(term_T *term)
1638{
1639 sb_line_T *line;
1640 garray_T *gap;
1641
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001642 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001643 gap = &term->tl_scrollback;
1644 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1645 && gap->ga_len > 0)
1646 {
1647 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1648 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1649 vim_free(line->sb_cells);
1650 --gap->ga_len;
1651 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001652 curbuf = curwin->w_buffer;
1653 if (curbuf == term->tl_buffer)
1654 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001655}
1656
1657/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001658 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001659 */
1660 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001661update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001662{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001663 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001664 int len;
1665 int lines_skipped = 0;
1666 VTermPos pos;
1667 VTermScreenCell cell;
1668 cellattr_T fill_attr, new_fill_attr;
1669 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001670
1671 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1672 "Adding terminal window snapshot to buffer");
1673
1674 /* First remove the lines that were appended before, they might be
1675 * outdated. */
1676 cleanup_scrollback(term);
1677
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001678 screen = vterm_obtain_screen(term->tl_vterm);
1679 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001680 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1681 {
1682 len = 0;
1683 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1684 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1685 && cell.chars[0] != NUL)
1686 {
1687 len = pos.col + 1;
1688 new_fill_attr = term->tl_default_color;
1689 }
1690 else
1691 /* Assume the last attr is the filler attr. */
1692 cell2cellattr(&cell, &new_fill_attr);
1693
1694 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1695 ++lines_skipped;
1696 else
1697 {
1698 while (lines_skipped > 0)
1699 {
1700 /* Line was skipped, add an empty line. */
1701 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001702 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001703 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001704 }
1705
1706 if (len == 0)
1707 p = NULL;
1708 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001709 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001710 if ((p != NULL || len == 0)
1711 && ga_grow(&term->tl_scrollback, 1) == OK)
1712 {
1713 garray_T ga;
1714 int width;
1715 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1716 + term->tl_scrollback.ga_len;
1717
1718 ga_init2(&ga, 1, 100);
1719 for (pos.col = 0; pos.col < len; pos.col += width)
1720 {
1721 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1722 {
1723 width = 1;
1724 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1725 if (ga_grow(&ga, 1) == OK)
1726 ga.ga_len += utf_char2bytes(' ',
1727 (char_u *)ga.ga_data + ga.ga_len);
1728 }
1729 else
1730 {
1731 width = cell.width;
1732
1733 cell2cellattr(&cell, &p[pos.col]);
1734
Bram Moolenaara79fd562018-12-20 20:47:32 +01001735 // Each character can be up to 6 bytes.
1736 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001737 {
1738 int i;
1739 int c;
1740
1741 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1742 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1743 (char_u *)ga.ga_data + ga.ga_len);
1744 }
1745 }
1746 }
1747 line->sb_cols = len;
1748 line->sb_cells = p;
1749 line->sb_fill_attr = new_fill_attr;
1750 fill_attr = new_fill_attr;
1751 ++term->tl_scrollback.ga_len;
1752
1753 if (ga_grow(&ga, 1) == FAIL)
1754 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1755 else
1756 {
1757 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1758 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1759 }
1760 ga_clear(&ga);
1761 }
1762 else
1763 vim_free(p);
1764 }
1765 }
1766
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001767 // Add trailing empty lines.
1768 for (pos.row = term->tl_scrollback.ga_len;
1769 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1770 ++pos.row)
1771 {
1772 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1773 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1774 }
1775
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001776 term->tl_dirty_snapshot = FALSE;
1777#ifdef FEAT_TIMERS
1778 term->tl_timer_set = FALSE;
1779#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001780}
1781
1782/*
1783 * If needed, add the current lines of the terminal to scrollback and to the
1784 * buffer. Called after the job has ended and when switching to
1785 * Terminal-Normal mode.
1786 * When "redraw" is TRUE redraw the windows that show the terminal.
1787 */
1788 static void
1789may_move_terminal_to_buffer(term_T *term, int redraw)
1790{
1791 win_T *wp;
1792
1793 if (term->tl_vterm == NULL)
1794 return;
1795
1796 /* Update the snapshot only if something changes or the buffer does not
1797 * have all the lines. */
1798 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1799 <= term->tl_scrollback_scrolled)
1800 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001801
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001802 /* Obtain the current background color. */
1803 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1804 &term->tl_default_color.fg, &term->tl_default_color.bg);
1805
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001806 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001807 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001808 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001809 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001810 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001811 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1812 wp->w_cursor.col = 0;
1813 wp->w_valid = 0;
1814 if (wp->w_cursor.lnum >= wp->w_height)
1815 {
1816 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001817
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001818 if (wp->w_topline < min_topline)
1819 wp->w_topline = min_topline;
1820 }
1821 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001822 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001823 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824}
1825
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001826#if defined(FEAT_TIMERS) || defined(PROTO)
1827/*
1828 * Check if any terminal timer expired. If so, copy text from the terminal to
1829 * the buffer.
1830 * Return the time until the next timer will expire.
1831 */
1832 int
1833term_check_timers(int next_due_arg, proftime_T *now)
1834{
1835 term_T *term;
1836 int next_due = next_due_arg;
1837
1838 for (term = first_term; term != NULL; term = term->tl_next)
1839 {
1840 if (term->tl_timer_set && !term->tl_normal_mode)
1841 {
1842 long this_due = proftime_time_left(&term->tl_timer_due, now);
1843
1844 if (this_due <= 1)
1845 {
1846 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001847 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001848 }
1849 else if (next_due == -1 || next_due > this_due)
1850 next_due = this_due;
1851 }
1852 }
1853
1854 return next_due;
1855}
1856#endif
1857
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001858/*
1859 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1860 * otherwise end it.
1861 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001862 static void
1863set_terminal_mode(term_T *term, int normal_mode)
1864{
1865 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001866 if (!normal_mode)
1867 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001868 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001869 if (term->tl_buffer == curbuf)
1870 maketitle();
1871}
1872
1873/*
1874 * Called after the job if finished and Terminal mode is not active:
1875 * Move the vterm contents into the scrollback buffer and free the vterm.
1876 */
1877 static void
1878cleanup_vterm(term_T *term)
1879{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001880 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001881 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001882 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001883 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001884}
1885
1886/*
1887 * Switch from Terminal-Job mode to Terminal-Normal mode.
1888 * Suspends updating the terminal window.
1889 */
1890 static void
1891term_enter_normal_mode(void)
1892{
1893 term_T *term = curbuf->b_term;
1894
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001895 set_terminal_mode(term, TRUE);
1896
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001898 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001899
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001900 /* Move the window cursor to the position of the cursor in the
1901 * terminal. */
1902 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1903 + term->tl_cursor_pos.row + 1;
1904 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001905 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1906 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001907
1908 /* Display the same lines as in the terminal. */
1909 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1910}
1911
1912/*
1913 * Returns TRUE if the current window contains a terminal and we are in
1914 * Terminal-Normal mode.
1915 */
1916 int
1917term_in_normal_mode(void)
1918{
1919 term_T *term = curbuf->b_term;
1920
1921 return term != NULL && term->tl_normal_mode;
1922}
1923
1924/*
1925 * Switch from Terminal-Normal mode to Terminal-Job mode.
1926 * Restores updating the terminal window.
1927 */
1928 void
1929term_enter_job_mode()
1930{
1931 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001932
1933 set_terminal_mode(term, FALSE);
1934
1935 if (term->tl_channel_closed)
1936 cleanup_vterm(term);
1937 redraw_buf_and_status_later(curbuf, NOT_VALID);
1938}
1939
1940/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001941 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001942 * Note: while waiting a terminal may be closed and freed if the channel is
1943 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001944 */
1945 static int
1946term_vgetc()
1947{
1948 int c;
1949 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001950 int modify_other_keys =
1951 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001952
1953 State = TERMINAL;
1954 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001955#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001956 ctrl_break_was_pressed = FALSE;
1957#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001958 if (modify_other_keys)
1959 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001960 c = vgetc();
1961 got_int = FALSE;
1962 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001963 if (modify_other_keys)
1964 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001965 return c;
1966}
1967
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001968static int mouse_was_outside = FALSE;
1969
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001970/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001971 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001972 * Return FAIL when the key needs to be handled in Normal mode.
1973 * Return OK when the key was dropped or sent to the terminal.
1974 */
1975 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001976send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001977{
1978 char msg[KEY_BUF_LEN];
1979 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001980 int dragging_outside = FALSE;
1981
1982 /* Catch keys that need to be handled as in Normal mode. */
1983 switch (c)
1984 {
1985 case NUL:
1986 case K_ZERO:
1987 if (typed)
1988 stuffcharReadbuff(c);
1989 return FAIL;
1990
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001991 case K_TABLINE:
1992 stuffcharReadbuff(c);
1993 return FAIL;
1994
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001995 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001996 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001997 return FAIL;
1998
1999 case K_LEFTDRAG:
2000 case K_MIDDLEDRAG:
2001 case K_RIGHTDRAG:
2002 case K_X1DRAG:
2003 case K_X2DRAG:
2004 dragging_outside = mouse_was_outside;
2005 /* FALLTHROUGH */
2006 case K_LEFTMOUSE:
2007 case K_LEFTMOUSE_NM:
2008 case K_LEFTRELEASE:
2009 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002010 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 case K_MIDDLEMOUSE:
2012 case K_MIDDLERELEASE:
2013 case K_RIGHTMOUSE:
2014 case K_RIGHTRELEASE:
2015 case K_X1MOUSE:
2016 case K_X1RELEASE:
2017 case K_X2MOUSE:
2018 case K_X2RELEASE:
2019
2020 case K_MOUSEUP:
2021 case K_MOUSEDOWN:
2022 case K_MOUSELEFT:
2023 case K_MOUSERIGHT:
2024 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01002025 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02002026 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01002027 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 || dragging_outside)
2029 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01002030 /* click or scroll outside the current window or on status line
2031 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002032 if (typed)
2033 {
2034 stuffcharReadbuff(c);
2035 mouse_was_outside = TRUE;
2036 }
2037 return FAIL;
2038 }
2039 }
2040 if (typed)
2041 mouse_was_outside = FALSE;
2042
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002043 // Convert the typed key to a sequence of bytes for the job.
2044 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002045 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002046 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002047 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2048 (char_u *)msg, (int)len, NULL);
2049
2050 return OK;
2051}
2052
2053 static void
2054position_cursor(win_T *wp, VTermPos *pos)
2055{
2056 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2057 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
2058 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2059}
2060
2061/*
2062 * Handle CTRL-W "": send register contents to the job.
2063 */
2064 static void
2065term_paste_register(int prev_c UNUSED)
2066{
2067 int c;
2068 list_T *l;
2069 listitem_T *item;
2070 long reglen = 0;
2071 int type;
2072
2073#ifdef FEAT_CMDL_INFO
2074 if (add_to_showcmd(prev_c))
2075 if (add_to_showcmd('"'))
2076 out_flush();
2077#endif
2078 c = term_vgetc();
2079#ifdef FEAT_CMDL_INFO
2080 clear_showcmd();
2081#endif
2082 if (!term_use_loop())
2083 /* job finished while waiting for a character */
2084 return;
2085
2086 /* CTRL-W "= prompt for expression to evaluate. */
2087 if (c == '=' && get_expr_register() != '=')
2088 return;
2089 if (!term_use_loop())
2090 /* job finished while waiting for a character */
2091 return;
2092
2093 l = (list_T *)get_reg_contents(c, GREG_LIST);
2094 if (l != NULL)
2095 {
2096 type = get_reg_type(c, &reglen);
2097 for (item = l->lv_first; item != NULL; item = item->li_next)
2098 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002099 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002100#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002101 char_u *tmp = s;
2102
2103 if (!enc_utf8 && enc_codepage > 0)
2104 {
2105 WCHAR *ret = NULL;
2106 int length = 0;
2107
2108 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2109 (int)STRLEN(s), &ret, &length);
2110 if (ret != NULL)
2111 {
2112 WideCharToMultiByte_alloc(CP_UTF8, 0,
2113 ret, length, (char **)&s, &length, 0, 0);
2114 vim_free(ret);
2115 }
2116 }
2117#endif
2118 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2119 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002120#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002121 if (tmp != s)
2122 vim_free(s);
2123#endif
2124
2125 if (item->li_next != NULL || type == MLINE)
2126 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2127 (char_u *)"\r", 1, NULL);
2128 }
2129 list_free(l);
2130 }
2131}
2132
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002133/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002134 * Return TRUE when waiting for a character in the terminal, the cursor of the
2135 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002136 */
2137 int
2138terminal_is_active()
2139{
2140 return in_terminal_loop != NULL;
2141}
2142
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002143#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002144 cursorentry_T *
2145term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2146{
2147 term_T *term = in_terminal_loop;
2148 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002149 int id;
2150 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002151
2152 vim_memset(&entry, 0, sizeof(entry));
2153 entry.shape = entry.mshape =
2154 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2155 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2156 SHAPE_BLOCK;
2157 entry.percentage = 20;
2158 if (term->tl_cursor_blink)
2159 {
2160 entry.blinkwait = 700;
2161 entry.blinkon = 400;
2162 entry.blinkoff = 250;
2163 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002164
2165 /* The "Terminal" highlight group overrules the defaults. */
2166 id = syn_name2id((char_u *)"Terminal");
2167 if (id != 0)
2168 {
2169 syn_id2colors(id, &term_fg, &term_bg);
2170 *fg = term_bg;
2171 }
2172 else
2173 *fg = gui.back_pixel;
2174
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002176 {
2177 if (id != 0)
2178 *bg = term_fg;
2179 else
2180 *bg = gui.norm_pixel;
2181 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002182 else
2183 *bg = color_name2handle(term->tl_cursor_color);
2184 entry.name = "n";
2185 entry.used_for = SHAPE_CURSOR;
2186
2187 return &entry;
2188}
2189#endif
2190
Bram Moolenaard317b382018-02-08 22:33:31 +01002191 static void
2192may_output_cursor_props(void)
2193{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002194 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002195 || last_set_cursor_shape != desired_cursor_shape
2196 || last_set_cursor_blink != desired_cursor_blink)
2197 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002198 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002199 last_set_cursor_shape = desired_cursor_shape;
2200 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002201 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002202 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2203 /* this will restore the initial cursor style, if possible */
2204 ui_cursor_shape_forced(TRUE);
2205 else
2206 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2207 }
2208}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002209
Bram Moolenaard317b382018-02-08 22:33:31 +01002210/*
2211 * Set the cursor color and shape, if not last set to these.
2212 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002213 static void
2214may_set_cursor_props(term_T *term)
2215{
2216#ifdef FEAT_GUI
2217 /* For the GUI the cursor properties are obtained with
2218 * term_get_cursor_shape(). */
2219 if (gui.in_use)
2220 return;
2221#endif
2222 if (in_terminal_loop == term)
2223 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002224 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002225 desired_cursor_shape = term->tl_cursor_shape;
2226 desired_cursor_blink = term->tl_cursor_blink;
2227 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002228 }
2229}
2230
Bram Moolenaard317b382018-02-08 22:33:31 +01002231/*
2232 * Reset the desired cursor properties and restore them when needed.
2233 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002234 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002235prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236{
2237#ifdef FEAT_GUI
2238 if (gui.in_use)
2239 return;
2240#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002241 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002242 desired_cursor_shape = -1;
2243 desired_cursor_blink = -1;
2244 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002245}
2246
2247/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002248 * Returns TRUE if the current window contains a terminal and we are sending
2249 * keys to the job.
2250 * If "check_job_status" is TRUE update the job status.
2251 */
2252 static int
2253term_use_loop_check(int check_job_status)
2254{
2255 term_T *term = curbuf->b_term;
2256
2257 return term != NULL
2258 && !term->tl_normal_mode
2259 && term->tl_vterm != NULL
2260 && term_job_running_check(term, check_job_status);
2261}
2262
2263/*
2264 * Returns TRUE if the current window contains a terminal and we are sending
2265 * keys to the job.
2266 */
2267 int
2268term_use_loop(void)
2269{
2270 return term_use_loop_check(FALSE);
2271}
2272
2273/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002274 * Called when entering a window with the mouse. If this is a terminal window
2275 * we may want to change state.
2276 */
2277 void
2278term_win_entered()
2279{
2280 term_T *term = curbuf->b_term;
2281
2282 if (term != NULL)
2283 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002284 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002285 {
2286 reset_VIsual_and_resel();
2287 if (State & INSERT)
2288 stop_insert_mode = TRUE;
2289 }
2290 mouse_was_outside = FALSE;
2291 enter_mouse_col = mouse_col;
2292 enter_mouse_row = mouse_row;
2293 }
2294}
2295
2296/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002297 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2298 * Return the Ctrl-key value in that case.
2299 */
2300 static int
2301raw_c_to_ctrl(int c)
2302{
2303 if ((mod_mask & MOD_MASK_CTRL)
2304 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2305 return c & 0x1f;
2306 return c;
2307}
2308
2309/*
2310 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2311 * May set "mod_mask".
2312 */
2313 static int
2314ctrl_to_raw_c(int c)
2315{
2316 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2317 {
2318 mod_mask |= MOD_MASK_CTRL;
2319 return c + '@';
2320 }
2321 return c;
2322}
2323
2324/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002325 * Wait for input and send it to the job.
2326 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2327 * when there is no more typahead.
2328 * Return when the start of a CTRL-W command is typed or anything else that
2329 * should be handled as a Normal mode command.
2330 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2331 * the terminal was closed.
2332 */
2333 int
2334terminal_loop(int blocking)
2335{
2336 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002337 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002338 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002339 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002340#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002341 int tty_fd = curbuf->b_term->tl_job->jv_channel
2342 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002343#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002344 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002345
2346 /* Remember the terminal we are sending keys to. However, the terminal
2347 * might be closed while waiting for a character, e.g. typing "exit" in a
2348 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2349 * stored reference. */
2350 in_terminal_loop = curbuf->b_term;
2351
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002352 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002353 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002354 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002355 if (termwinkey == Ctrl_W)
2356 termwinkey = 0;
2357 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002358 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2359 may_set_cursor_props(curbuf->b_term);
2360
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002361 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002362 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002363#ifdef FEAT_GUI
2364 if (!curbuf->b_term->tl_system)
2365#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002366 // TODO: skip screen update when handling a sequence of keys.
2367 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002368 while (must_redraw != 0)
2369 if (update_screen(0) == FAIL)
2370 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002371 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002372 /* job finished while redrawing */
2373 break;
2374
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002375 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002376 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002377
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002378 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002379 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002380 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002381 /* Job finished while waiting for a character. Push back the
2382 * received character. */
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002383 if (raw_c != K_IGNORE)
2384 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002385 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002386 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002387 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002388 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002389 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002390
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002391#ifdef UNIX
2392 /*
2393 * The shell or another program may change the tty settings. Getting
2394 * them for every typed character is a bit of overhead, but it's needed
2395 * for the first character typed, e.g. when Vim starts in a shell.
2396 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002397 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002398 {
2399 ttyinfo_T info;
2400
2401 /* Get the current backspace character of the pty. */
2402 if (get_tty_info(tty_fd, &info) == OK)
2403 term_backspace_char = info.backspace;
2404 }
2405#endif
2406
Bram Moolenaar4f974752019-02-17 17:44:42 +01002407#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002408 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2409 * Use CTRL-BREAK to kill the job. */
2410 if (ctrl_break_was_pressed)
2411 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2412#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002413 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002414 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002415 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002416#ifdef FEAT_GUI
2417 && !curbuf->b_term->tl_system
2418#endif
2419 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002420 {
2421 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002422 int prev_raw_c = raw_c;
2423 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002424
2425#ifdef FEAT_CMDL_INFO
2426 if (add_to_showcmd(c))
2427 out_flush();
2428#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002429 raw_c = term_vgetc();
2430 c = raw_c_to_ctrl(raw_c);
2431
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002432#ifdef FEAT_CMDL_INFO
2433 clear_showcmd();
2434#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002435 if (!term_use_loop_check(TRUE)
2436 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002437 /* job finished while waiting for a character */
2438 break;
2439
2440 if (prev_c == Ctrl_BSL)
2441 {
2442 if (c == Ctrl_N)
2443 {
2444 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2445 term_enter_normal_mode();
2446 ret = FAIL;
2447 goto theend;
2448 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002449 // Send both keys to the terminal, first one here, second one
2450 // below.
2451 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2452 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002453 }
2454 else if (c == Ctrl_C)
2455 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002456 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002457 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2458 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002459 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002460 {
2461 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002462 /* "'termwinkey' .": send 'termwinkey' to the job */
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002463 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002464 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002465 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002466 {
2467 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002468 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002469 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002470 else if (c == 'N')
2471 {
2472 /* CTRL-W N : go to Terminal-Normal mode. */
2473 term_enter_normal_mode();
2474 ret = FAIL;
2475 goto theend;
2476 }
2477 else if (c == '"')
2478 {
2479 term_paste_register(prev_c);
2480 continue;
2481 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002482 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002483 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002484 char_u buf[MB_MAXBYTES + 2];
2485
2486 // Put the command into the typeahead buffer, when using the
2487 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2488 buf[0] = Ctrl_W;
2489 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2490 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002491 ret = OK;
2492 goto theend;
2493 }
2494 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002495# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002496 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002497 {
2498 WCHAR wc;
2499 char_u mb[3];
2500
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002501 mb[0] = (unsigned)raw_c >> 8;
2502 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002504 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002505 }
2506# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002507 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002508 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002509 if (raw_c == K_MOUSEMOVE)
Bram Moolenaard317b382018-02-08 22:33:31 +01002510 /* We are sure to come back here, don't reset the cursor color
2511 * and shape to avoid flickering. */
2512 restore_cursor = FALSE;
2513
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002514 ret = OK;
2515 goto theend;
2516 }
2517 }
2518 ret = FAIL;
2519
2520theend:
2521 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002522 if (restore_cursor)
2523 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002524
2525 /* Move a snapshot of the screen contents to the buffer, so that completion
2526 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002527 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2528 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002529
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002530 return ret;
2531}
2532
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002533 static void
2534may_toggle_cursor(term_T *term)
2535{
2536 if (in_terminal_loop == term)
2537 {
2538 if (term->tl_cursor_visible)
2539 cursor_on();
2540 else
2541 cursor_off();
2542 }
2543}
2544
2545/*
2546 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002547 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002548 */
2549 static int
2550color2index(VTermColor *color, int fg, int *boldp)
2551{
2552 int red = color->red;
2553 int blue = color->blue;
2554 int green = color->green;
2555
Bram Moolenaar46359e12017-11-29 22:33:38 +01002556 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002557 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002558 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002559 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002560 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002561 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002562 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002563 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2564 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2565 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002566 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002567 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2568 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2569 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2570 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2571 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2572 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2573 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2574 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2575 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2576 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2577 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002578 }
2579 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002580
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002581 if (t_colors >= 256)
2582 {
2583 if (red == blue && red == green)
2584 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002585 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002586 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002587 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2588 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2589 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002590 int i;
2591
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002592 if (red < 5)
2593 return 17; /* 00/00/00 */
2594 if (red > 245) /* ff/ff/ff */
2595 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002596 for (i = 0; i < 23; ++i)
2597 if (red < cutoff[i])
2598 return i + 233;
2599 return 256;
2600 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002601 {
2602 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2603 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002604
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002605 /* 216-color cube */
2606 for (ri = 0; ri < 5; ++ri)
2607 if (red < cutoff[ri])
2608 break;
2609 for (gi = 0; gi < 5; ++gi)
2610 if (green < cutoff[gi])
2611 break;
2612 for (bi = 0; bi < 5; ++bi)
2613 if (blue < cutoff[bi])
2614 break;
2615 return 17 + ri * 36 + gi * 6 + bi;
2616 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002617 }
2618 return 0;
2619}
2620
2621/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002622 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002623 */
2624 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002625vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002626{
2627 int attr = 0;
2628
2629 if (cellattrs.bold)
2630 attr |= HL_BOLD;
2631 if (cellattrs.underline)
2632 attr |= HL_UNDERLINE;
2633 if (cellattrs.italic)
2634 attr |= HL_ITALIC;
2635 if (cellattrs.strike)
2636 attr |= HL_STRIKETHROUGH;
2637 if (cellattrs.reverse)
2638 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002639 return attr;
2640}
2641
2642/*
2643 * Store Vterm attributes in "cell" from highlight flags.
2644 */
2645 static void
2646hl2vtermAttr(int attr, cellattr_T *cell)
2647{
2648 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2649 if (attr & HL_BOLD)
2650 cell->attrs.bold = 1;
2651 if (attr & HL_UNDERLINE)
2652 cell->attrs.underline = 1;
2653 if (attr & HL_ITALIC)
2654 cell->attrs.italic = 1;
2655 if (attr & HL_STRIKETHROUGH)
2656 cell->attrs.strike = 1;
2657 if (attr & HL_INVERSE)
2658 cell->attrs.reverse = 1;
2659}
2660
2661/*
2662 * Convert the attributes of a vterm cell into an attribute index.
2663 */
2664 static int
2665cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2666{
2667 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002668
2669#ifdef FEAT_GUI
2670 if (gui.in_use)
2671 {
2672 guicolor_T fg, bg;
2673
2674 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2675 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2676 return get_gui_attr_idx(attr, fg, bg);
2677 }
2678 else
2679#endif
2680#ifdef FEAT_TERMGUICOLORS
2681 if (p_tgc)
2682 {
2683 guicolor_T fg, bg;
2684
2685 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2686 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2687
2688 return get_tgc_attr_idx(attr, fg, bg);
2689 }
2690 else
2691#endif
2692 {
2693 int bold = MAYBE;
2694 int fg = color2index(&cellfg, TRUE, &bold);
2695 int bg = color2index(&cellbg, FALSE, &bold);
2696
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002697 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002698 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002699 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002700 if (fg == 0 && term_default_cterm_fg >= 0)
2701 fg = term_default_cterm_fg + 1;
2702 if (bg == 0 && term_default_cterm_bg >= 0)
2703 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002704 }
2705
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002706 /* with 8 colors set the bold attribute to get a bright foreground */
2707 if (bold == TRUE)
2708 attr |= HL_BOLD;
2709 return get_cterm_attr_idx(attr, fg, bg);
2710 }
2711 return 0;
2712}
2713
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002714 static void
2715set_dirty_snapshot(term_T *term)
2716{
2717 term->tl_dirty_snapshot = TRUE;
2718#ifdef FEAT_TIMERS
2719 if (!term->tl_normal_mode)
2720 {
2721 /* Update the snapshot after 100 msec of not getting updates. */
2722 profile_setlimit(100L, &term->tl_timer_due);
2723 term->tl_timer_set = TRUE;
2724 }
2725#endif
2726}
2727
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002728 static int
2729handle_damage(VTermRect rect, void *user)
2730{
2731 term_T *term = (term_T *)user;
2732
2733 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2734 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002735 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002736 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002737 return 1;
2738}
2739
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002740 static void
2741term_scroll_up(term_T *term, int start_row, int count)
2742{
2743 win_T *wp;
2744 VTermColor fg, bg;
2745 VTermScreenCellAttrs attr;
2746 int clear_attr;
2747
2748 /* Set the color to clear lines with. */
2749 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2750 &fg, &bg);
2751 vim_memset(&attr, 0, sizeof(attr));
2752 clear_attr = cell2attr(attr, fg, bg);
2753
2754 FOR_ALL_WINDOWS(wp)
2755 {
2756 if (wp->w_buffer == term->tl_buffer)
2757 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2758 }
2759}
2760
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002761 static int
2762handle_moverect(VTermRect dest, VTermRect src, void *user)
2763{
2764 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002765 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002766
2767 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002768 * redrawing the text. But avoid doing this multiple times, postpone until
2769 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002770 if (dest.start_col == src.start_col
2771 && dest.end_col == src.end_col
2772 && dest.start_row < src.start_row)
2773 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002774 if (dest.start_row == 0)
2775 term->tl_postponed_scroll += count;
2776 else
2777 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002778 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002779
2780 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2781 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002782 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002783
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002784 /* Note sure if the scrolling will work correctly, let's do a complete
2785 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002786 redraw_buf_later(term->tl_buffer, NOT_VALID);
2787 return 1;
2788}
2789
2790 static int
2791handle_movecursor(
2792 VTermPos pos,
2793 VTermPos oldpos UNUSED,
2794 int visible,
2795 void *user)
2796{
2797 term_T *term = (term_T *)user;
2798 win_T *wp;
2799
2800 term->tl_cursor_pos = pos;
2801 term->tl_cursor_visible = visible;
2802
2803 FOR_ALL_WINDOWS(wp)
2804 {
2805 if (wp->w_buffer == term->tl_buffer)
2806 position_cursor(wp, &pos);
2807 }
2808 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2809 {
2810 may_toggle_cursor(term);
2811 update_cursor(term, term->tl_cursor_visible);
2812 }
2813
2814 return 1;
2815}
2816
2817 static int
2818handle_settermprop(
2819 VTermProp prop,
2820 VTermValue *value,
2821 void *user)
2822{
2823 term_T *term = (term_T *)user;
2824
2825 switch (prop)
2826 {
2827 case VTERM_PROP_TITLE:
2828 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002829 // a blank title isn't useful, make it empty, so that "running" is
2830 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002831 if (*skipwhite((char_u *)value->string) == NUL)
2832 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002833 // Same as blank
2834 else if (term->tl_arg0_cmd != NULL
2835 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2836 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2837 term->tl_title = NULL;
2838 // Empty corrupted data of winpty
2839 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2840 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002841#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002842 else if (!enc_utf8 && enc_codepage > 0)
2843 {
2844 WCHAR *ret = NULL;
2845 int length = 0;
2846
2847 MultiByteToWideChar_alloc(CP_UTF8, 0,
2848 (char*)value->string, (int)STRLEN(value->string),
2849 &ret, &length);
2850 if (ret != NULL)
2851 {
2852 WideCharToMultiByte_alloc(enc_codepage, 0,
2853 ret, length, (char**)&term->tl_title,
2854 &length, 0, 0);
2855 vim_free(ret);
2856 }
2857 }
2858#endif
2859 else
2860 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002861 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002862 if (term == curbuf->b_term)
2863 maketitle();
2864 break;
2865
2866 case VTERM_PROP_CURSORVISIBLE:
2867 term->tl_cursor_visible = value->boolean;
2868 may_toggle_cursor(term);
2869 out_flush();
2870 break;
2871
2872 case VTERM_PROP_CURSORBLINK:
2873 term->tl_cursor_blink = value->boolean;
2874 may_set_cursor_props(term);
2875 break;
2876
2877 case VTERM_PROP_CURSORSHAPE:
2878 term->tl_cursor_shape = value->number;
2879 may_set_cursor_props(term);
2880 break;
2881
2882 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002883 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002884 may_set_cursor_props(term);
2885 break;
2886
2887 case VTERM_PROP_ALTSCREEN:
2888 /* TODO: do anything else? */
2889 term->tl_using_altscreen = value->boolean;
2890 break;
2891
2892 default:
2893 break;
2894 }
2895 /* Always return 1, otherwise vterm doesn't store the value internally. */
2896 return 1;
2897}
2898
2899/*
2900 * The job running in the terminal resized the terminal.
2901 */
2902 static int
2903handle_resize(int rows, int cols, void *user)
2904{
2905 term_T *term = (term_T *)user;
2906 win_T *wp;
2907
2908 term->tl_rows = rows;
2909 term->tl_cols = cols;
2910 if (term->tl_vterm_size_changed)
2911 /* Size was set by vterm_set_size(), don't set the window size. */
2912 term->tl_vterm_size_changed = FALSE;
2913 else
2914 {
2915 FOR_ALL_WINDOWS(wp)
2916 {
2917 if (wp->w_buffer == term->tl_buffer)
2918 {
2919 win_setheight_win(rows, wp);
2920 win_setwidth_win(cols, wp);
2921 }
2922 }
2923 redraw_buf_later(term->tl_buffer, NOT_VALID);
2924 }
2925 return 1;
2926}
2927
2928/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002929 * If the number of lines that are stored goes over 'termscrollback' then
2930 * delete the first 10%.
2931 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2932 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002933 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002934 static void
2935limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002936{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002937 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002938 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002939 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002940 int i;
2941
2942 curbuf = term->tl_buffer;
2943 for (i = 0; i < todo; ++i)
2944 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002945 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
2946 if (update_buffer)
2947 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002948 }
2949 curbuf = curwin->w_buffer;
2950
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002951 gap->ga_len -= todo;
2952 mch_memmove(gap->ga_data,
2953 (sb_line_T *)gap->ga_data + todo,
2954 sizeof(sb_line_T) * gap->ga_len);
2955 if (update_buffer)
2956 term->tl_scrollback_scrolled -= todo;
2957 }
2958}
2959
2960/*
2961 * Handle a line that is pushed off the top of the screen.
2962 */
2963 static int
2964handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2965{
2966 term_T *term = (term_T *)user;
2967 garray_T *gap;
2968 int update_buffer;
2969
2970 if (term->tl_normal_mode)
2971 {
2972 // In Terminal-Normal mode the user interacts with the buffer, thus we
2973 // must not change it. Postpone adding the scrollback lines.
2974 gap = &term->tl_scrollback_postponed;
2975 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002976 }
2977 else
2978 {
2979 // First remove the lines that were appended before, the pushed line
2980 // goes above it.
2981 cleanup_scrollback(term);
2982 gap = &term->tl_scrollback;
2983 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002984 }
2985
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002986 limit_scrollback(term, gap, update_buffer);
2987
2988 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002989 {
2990 cellattr_T *p = NULL;
2991 int len = 0;
2992 int i;
2993 int c;
2994 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002995 int text_len;
2996 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002997 sb_line_T *line;
2998 garray_T ga;
2999 cellattr_T fill_attr = term->tl_default_color;
3000
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003001 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003002 for (i = 0; i < cols; ++i)
3003 if (cells[i].chars[0] != 0)
3004 len = i + 1;
3005 else
3006 cell2cellattr(&cells[i], &fill_attr);
3007
3008 ga_init2(&ga, 1, 100);
3009 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003010 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003011 if (p != NULL)
3012 {
3013 for (col = 0; col < len; col += cells[col].width)
3014 {
3015 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3016 {
3017 ga.ga_len = 0;
3018 break;
3019 }
3020 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3021 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3022 (char_u *)ga.ga_data + ga.ga_len);
3023 cell2cellattr(&cells[col], &p[col]);
3024 }
3025 }
3026 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003027 {
3028 if (update_buffer)
3029 text = (char_u *)"";
3030 else
3031 text = vim_strsave((char_u *)"");
3032 text_len = 0;
3033 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003034 else
3035 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003036 text = ga.ga_data;
3037 text_len = ga.ga_len;
3038 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003039 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003040 if (update_buffer)
3041 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003042
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003043 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003044 line->sb_cols = len;
3045 line->sb_cells = p;
3046 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003047 if (update_buffer)
3048 {
3049 line->sb_text = NULL;
3050 ++term->tl_scrollback_scrolled;
3051 ga_clear(&ga); // free the text
3052 }
3053 else
3054 {
3055 line->sb_text = text;
3056 ga_init(&ga); // text is kept in tl_scrollback_postponed
3057 }
3058 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003059 }
3060 return 0; /* ignored */
3061}
3062
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003063/*
3064 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3065 * received and stored in tl_scrollback_postponed.
3066 */
3067 static void
3068handle_postponed_scrollback(term_T *term)
3069{
3070 int i;
3071
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003072 if (term->tl_scrollback_postponed.ga_len == 0)
3073 return;
3074 ch_log(NULL, "Moving postponed scrollback to scrollback");
3075
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003076 // First remove the lines that were appended before, the pushed lines go
3077 // above it.
3078 cleanup_scrollback(term);
3079
3080 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3081 {
3082 char_u *text;
3083 sb_line_T *pp_line;
3084 sb_line_T *line;
3085
3086 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3087 break;
3088 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3089
3090 text = pp_line->sb_text;
3091 if (text == NULL)
3092 text = (char_u *)"";
3093 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3094 vim_free(pp_line->sb_text);
3095
3096 line = (sb_line_T *)term->tl_scrollback.ga_data
3097 + term->tl_scrollback.ga_len;
3098 line->sb_cols = pp_line->sb_cols;
3099 line->sb_cells = pp_line->sb_cells;
3100 line->sb_fill_attr = pp_line->sb_fill_attr;
3101 line->sb_text = NULL;
3102 ++term->tl_scrollback_scrolled;
3103 ++term->tl_scrollback.ga_len;
3104 }
3105
3106 ga_clear(&term->tl_scrollback_postponed);
3107 limit_scrollback(term, &term->tl_scrollback, TRUE);
3108}
3109
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003110static VTermScreenCallbacks screen_callbacks = {
3111 handle_damage, /* damage */
3112 handle_moverect, /* moverect */
3113 handle_movecursor, /* movecursor */
3114 handle_settermprop, /* settermprop */
3115 NULL, /* bell */
3116 handle_resize, /* resize */
3117 handle_pushline, /* sb_pushline */
3118 NULL /* sb_popline */
3119};
3120
3121/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003122 * Do the work after the channel of a terminal was closed.
3123 * Must be called only when updating_screen is FALSE.
3124 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3125 */
3126 static int
3127term_after_channel_closed(term_T *term)
3128{
3129 /* Unless in Terminal-Normal mode: clear the vterm. */
3130 if (!term->tl_normal_mode)
3131 {
3132 int fnum = term->tl_buffer->b_fnum;
3133
3134 cleanup_vterm(term);
3135
3136 if (term->tl_finish == TL_FINISH_CLOSE)
3137 {
3138 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003139 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003140
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003141 // If this is the last normal window: exit Vim.
3142 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3143 {
3144 exarg_T ea;
3145
3146 vim_memset(&ea, 0, sizeof(ea));
3147 ex_quit(&ea);
3148 return TRUE;
3149 }
3150
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003151 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003152 ch_log(NULL, "terminal job finished, closing window");
3153 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003154 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003155 if (curwin == aucmd_win)
3156 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003157 if (do_set_w_closing)
3158 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003159 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003160 if (do_set_w_closing)
3161 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003162 aucmd_restbuf(&aco);
3163 return TRUE;
3164 }
3165 if (term->tl_finish == TL_FINISH_OPEN
3166 && term->tl_buffer->b_nwindows == 0)
3167 {
3168 char buf[50];
3169
3170 /* TODO: use term_opencmd */
3171 ch_log(NULL, "terminal job finished, opening window");
3172 vim_snprintf(buf, sizeof(buf),
3173 term->tl_opencmd == NULL
3174 ? "botright sbuf %d"
3175 : (char *)term->tl_opencmd, fnum);
3176 do_cmdline_cmd((char_u *)buf);
3177 }
3178 else
3179 ch_log(NULL, "terminal job finished");
3180 }
3181
3182 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3183 return FALSE;
3184}
3185
3186/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003187 * Called when a channel has been closed.
3188 * If this was a channel for a terminal window then finish it up.
3189 */
3190 void
3191term_channel_closed(channel_T *ch)
3192{
3193 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003194 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003195 int did_one = FALSE;
3196
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003197 for (term = first_term; term != NULL; term = next_term)
3198 {
3199 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003200 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003201 {
3202 term->tl_channel_closed = TRUE;
3203 did_one = TRUE;
3204
Bram Moolenaard23a8232018-02-10 18:45:26 +01003205 VIM_CLEAR(term->tl_title);
3206 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003207#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003208 if (term->tl_out_fd != NULL)
3209 {
3210 fclose(term->tl_out_fd);
3211 term->tl_out_fd = NULL;
3212 }
3213#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003214
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003215 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003216 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003217 /* Cannot open or close windows now. Can happen when
3218 * 'lazyredraw' is set. */
3219 term->tl_channel_recently_closed = TRUE;
3220 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003221 }
3222
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003223 if (term_after_channel_closed(term))
3224 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003225 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003226 }
3227
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003228 if (did_one)
3229 {
3230 redraw_statuslines();
3231
3232 /* Need to break out of vgetc(). */
3233 ins_char_typebuf(K_IGNORE);
3234 typebuf_was_filled = TRUE;
3235
3236 term = curbuf->b_term;
3237 if (term != NULL)
3238 {
3239 if (term->tl_job == ch->ch_job)
3240 maketitle();
3241 update_cursor(term, term->tl_cursor_visible);
3242 }
3243 }
3244}
3245
3246/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003247 * To be called after resetting updating_screen: handle any terminal where the
3248 * channel was closed.
3249 */
3250 void
3251term_check_channel_closed_recently()
3252{
3253 term_T *term;
3254 term_T *next_term;
3255
3256 for (term = first_term; term != NULL; term = next_term)
3257 {
3258 next_term = term->tl_next;
3259 if (term->tl_channel_recently_closed)
3260 {
3261 term->tl_channel_recently_closed = FALSE;
3262 if (term_after_channel_closed(term))
3263 // start over, the list may have changed
3264 next_term = first_term;
3265 }
3266 }
3267}
3268
3269/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003270 * Fill one screen line from a line of the terminal.
3271 * Advances "pos" to past the last column.
3272 */
3273 static void
3274term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3275{
3276 int off = screen_get_current_line_off();
3277
3278 for (pos->col = 0; pos->col < max_col; )
3279 {
3280 VTermScreenCell cell;
3281 int c;
3282
3283 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3284 vim_memset(&cell, 0, sizeof(cell));
3285
3286 c = cell.chars[0];
3287 if (c == NUL)
3288 {
3289 ScreenLines[off] = ' ';
3290 if (enc_utf8)
3291 ScreenLinesUC[off] = NUL;
3292 }
3293 else
3294 {
3295 if (enc_utf8)
3296 {
3297 int i;
3298
3299 /* composing chars */
3300 for (i = 0; i < Screen_mco
3301 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3302 {
3303 ScreenLinesC[i][off] = cell.chars[i + 1];
3304 if (cell.chars[i + 1] == 0)
3305 break;
3306 }
3307 if (c >= 0x80 || (Screen_mco > 0
3308 && ScreenLinesC[0][off] != 0))
3309 {
3310 ScreenLines[off] = ' ';
3311 ScreenLinesUC[off] = c;
3312 }
3313 else
3314 {
3315 ScreenLines[off] = c;
3316 ScreenLinesUC[off] = NUL;
3317 }
3318 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003319#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003320 else if (has_mbyte && c >= 0x80)
3321 {
3322 char_u mb[MB_MAXBYTES+1];
3323 WCHAR wc = c;
3324
3325 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3326 (char*)mb, 2, 0, 0) > 1)
3327 {
3328 ScreenLines[off] = mb[0];
3329 ScreenLines[off + 1] = mb[1];
3330 cell.width = mb_ptr2cells(mb);
3331 }
3332 else
3333 ScreenLines[off] = c;
3334 }
3335#endif
3336 else
3337 ScreenLines[off] = c;
3338 }
3339 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3340
3341 ++pos->col;
3342 ++off;
3343 if (cell.width == 2)
3344 {
3345 if (enc_utf8)
3346 ScreenLinesUC[off] = NUL;
3347
3348 /* don't set the second byte to NUL for a DBCS encoding, it
3349 * has been set above */
3350 if (enc_utf8 || !has_mbyte)
3351 ScreenLines[off] = NUL;
3352
3353 ++pos->col;
3354 ++off;
3355 }
3356 }
3357}
3358
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003359#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003360 static void
3361update_system_term(term_T *term)
3362{
3363 VTermPos pos;
3364 VTermScreen *screen;
3365
3366 if (term->tl_vterm == NULL)
3367 return;
3368 screen = vterm_obtain_screen(term->tl_vterm);
3369
3370 /* Scroll up to make more room for terminal lines if needed. */
3371 while (term->tl_toprow > 0
3372 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3373 {
3374 int save_p_more = p_more;
3375
3376 p_more = FALSE;
3377 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003378 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003379 p_more = save_p_more;
3380 --term->tl_toprow;
3381 }
3382
3383 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3384 && pos.row < Rows; ++pos.row)
3385 {
3386 if (pos.row < term->tl_rows)
3387 {
3388 int max_col = MIN(Columns, term->tl_cols);
3389
3390 term_line2screenline(screen, &pos, max_col);
3391 }
3392 else
3393 pos.col = 0;
3394
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003395 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003396 }
3397
3398 term->tl_dirty_row_start = MAX_ROW;
3399 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003400}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003401#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003402
3403/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003404 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3405 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003406 * Terminal-Normal mode.
3407 */
3408 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003409term_do_update_window(win_T *wp)
3410{
3411 term_T *term = wp->w_buffer->b_term;
3412
3413 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3414}
3415
3416/*
3417 * Called to update a window that contains an active terminal.
3418 */
3419 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003420term_update_window(win_T *wp)
3421{
3422 term_T *term = wp->w_buffer->b_term;
3423 VTerm *vterm;
3424 VTermScreen *screen;
3425 VTermState *state;
3426 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003427 int rows, cols;
3428 int newrows, newcols;
3429 int minsize;
3430 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003431
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003432 vterm = term->tl_vterm;
3433 screen = vterm_obtain_screen(vterm);
3434 state = vterm_obtain_state(vterm);
3435
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003436 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3437 * SOME_VALID only redraw what was marked dirty. */
3438 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003439 {
3440 term->tl_dirty_row_start = 0;
3441 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003442
3443 if (term->tl_postponed_scroll > 0
3444 && term->tl_postponed_scroll < term->tl_rows / 3)
3445 /* Scrolling is usually faster than redrawing, when there are only
3446 * a few lines to scroll. */
3447 term_scroll_up(term, 0, term->tl_postponed_scroll);
3448 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003449 }
3450
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003451 /*
3452 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003453 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003454 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003455 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003456
Bram Moolenaar498c2562018-04-15 23:45:15 +02003457 newrows = 99999;
3458 newcols = 99999;
3459 FOR_ALL_WINDOWS(twp)
3460 {
3461 /* When more than one window shows the same terminal, use the
3462 * smallest size. */
3463 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003464 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003465 newrows = MIN(newrows, twp->w_height);
3466 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003467 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003468 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003469 if (newrows == 99999 || newcols == 99999)
3470 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003471 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3472 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3473
3474 if (term->tl_rows != newrows || term->tl_cols != newcols)
3475 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003476 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003477 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003478 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003479 newrows);
3480 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003481
3482 // Updating the terminal size will cause the snapshot to be cleared.
3483 // When not in terminal_loop() we need to restore it.
3484 if (term != in_terminal_loop)
3485 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003486 }
3487
3488 /* The cursor may have been moved when resizing. */
3489 vterm_state_get_cursorpos(state, &pos);
3490 position_cursor(wp, &pos);
3491
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003492 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3493 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003494 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003495 if (pos.row < term->tl_rows)
3496 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003497 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003498
Bram Moolenaar13568252018-03-16 20:46:58 +01003499 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003500 }
3501 else
3502 pos.col = 0;
3503
Bram Moolenaarf118d482018-03-13 13:14:00 +01003504 screen_line(wp->w_winrow + pos.row
3505#ifdef FEAT_MENU
3506 + winbar_height(wp)
3507#endif
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003508 , wp->w_wincol, pos.col, wp->w_width, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003509 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003510 term->tl_dirty_row_start = MAX_ROW;
3511 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003512}
3513
3514/*
3515 * Return TRUE if "wp" is a terminal window where the job has finished.
3516 */
3517 int
3518term_is_finished(buf_T *buf)
3519{
3520 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3521}
3522
3523/*
3524 * Return TRUE if "wp" is a terminal window where the job has finished or we
3525 * are in Terminal-Normal mode, thus we show the buffer contents.
3526 */
3527 int
3528term_show_buffer(buf_T *buf)
3529{
3530 term_T *term = buf->b_term;
3531
3532 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3533}
3534
3535/*
3536 * The current buffer is going to be changed. If there is terminal
3537 * highlighting remove it now.
3538 */
3539 void
3540term_change_in_curbuf(void)
3541{
3542 term_T *term = curbuf->b_term;
3543
3544 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3545 {
3546 free_scrollback(term);
3547 redraw_buf_later(term->tl_buffer, NOT_VALID);
3548
3549 /* The buffer is now like a normal buffer, it cannot be easily
3550 * abandoned when changed. */
3551 set_string_option_direct((char_u *)"buftype", -1,
3552 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3553 }
3554}
3555
3556/*
3557 * Get the screen attribute for a position in the buffer.
3558 * Use a negative "col" to get the filler background color.
3559 */
3560 int
3561term_get_attr(buf_T *buf, linenr_T lnum, int col)
3562{
3563 term_T *term = buf->b_term;
3564 sb_line_T *line;
3565 cellattr_T *cellattr;
3566
3567 if (lnum > term->tl_scrollback.ga_len)
3568 cellattr = &term->tl_default_color;
3569 else
3570 {
3571 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3572 if (col < 0 || col >= line->sb_cols)
3573 cellattr = &line->sb_fill_attr;
3574 else
3575 cellattr = line->sb_cells + col;
3576 }
3577 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3578}
3579
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003580/*
3581 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003582 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003583 */
3584 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003585cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003586{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003587 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003588}
3589
3590/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003591 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003592 */
3593 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003594init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003595{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003596 VTermColor *fg, *bg;
3597 int fgval, bgval;
3598 int id;
3599
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003600 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3601 term->tl_default_color.width = 1;
3602 fg = &term->tl_default_color.fg;
3603 bg = &term->tl_default_color.bg;
3604
3605 /* Vterm uses a default black background. Set it to white when
3606 * 'background' is "light". */
3607 if (*p_bg == 'l')
3608 {
3609 fgval = 0;
3610 bgval = 255;
3611 }
3612 else
3613 {
3614 fgval = 255;
3615 bgval = 0;
3616 }
3617 fg->red = fg->green = fg->blue = fgval;
3618 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003619 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003620
3621 /* The "Terminal" highlight group overrules the defaults. */
3622 id = syn_name2id((char_u *)"Terminal");
3623
Bram Moolenaar46359e12017-11-29 22:33:38 +01003624 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003625#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3626 if (0
3627# ifdef FEAT_GUI
3628 || gui.in_use
3629# endif
3630# ifdef FEAT_TERMGUICOLORS
3631 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003632# ifdef FEAT_VTP
3633 /* Finally get INVALCOLOR on this execution path */
3634 || (!p_tgc && t_colors >= 256)
3635# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003636# endif
3637 )
3638 {
3639 guicolor_T fg_rgb = INVALCOLOR;
3640 guicolor_T bg_rgb = INVALCOLOR;
3641
3642 if (id != 0)
3643 syn_id2colors(id, &fg_rgb, &bg_rgb);
3644
3645# ifdef FEAT_GUI
3646 if (gui.in_use)
3647 {
3648 if (fg_rgb == INVALCOLOR)
3649 fg_rgb = gui.norm_pixel;
3650 if (bg_rgb == INVALCOLOR)
3651 bg_rgb = gui.back_pixel;
3652 }
3653# ifdef FEAT_TERMGUICOLORS
3654 else
3655# endif
3656# endif
3657# ifdef FEAT_TERMGUICOLORS
3658 {
3659 if (fg_rgb == INVALCOLOR)
3660 fg_rgb = cterm_normal_fg_gui_color;
3661 if (bg_rgb == INVALCOLOR)
3662 bg_rgb = cterm_normal_bg_gui_color;
3663 }
3664# endif
3665 if (fg_rgb != INVALCOLOR)
3666 {
3667 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3668
3669 fg->red = (unsigned)(rgb >> 16);
3670 fg->green = (unsigned)(rgb >> 8) & 255;
3671 fg->blue = (unsigned)rgb & 255;
3672 }
3673 if (bg_rgb != INVALCOLOR)
3674 {
3675 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3676
3677 bg->red = (unsigned)(rgb >> 16);
3678 bg->green = (unsigned)(rgb >> 8) & 255;
3679 bg->blue = (unsigned)rgb & 255;
3680 }
3681 }
3682 else
3683#endif
3684 if (id != 0 && t_colors >= 16)
3685 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003686 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003687 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003688 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003689 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003690 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003691 else
3692 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003693#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003694 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003695#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003696
3697 /* In an MS-Windows console we know the normal colors. */
3698 if (cterm_normal_fg_color > 0)
3699 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003700 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003701# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3702# ifdef VIMDLL
3703 if (!gui.in_use)
3704# endif
3705 {
3706 tmp = fg->red;
3707 fg->red = fg->blue;
3708 fg->blue = tmp;
3709 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003710# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003711 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003712# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003713 else
3714 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003715# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003716
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003717 if (cterm_normal_bg_color > 0)
3718 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003719 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003720# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3721# ifdef VIMDLL
3722 if (!gui.in_use)
3723# endif
3724 {
3725 tmp = fg->red;
3726 fg->red = fg->blue;
3727 fg->blue = tmp;
3728 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003729# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003730 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003731# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003732 else
3733 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003734# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003735 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003736}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003737
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003738#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3739/*
3740 * Set the 16 ANSI colors from array of RGB values
3741 */
3742 static void
3743set_vterm_palette(VTerm *vterm, long_u *rgb)
3744{
3745 int index = 0;
3746 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003747
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003748 for (; index < 16; index++)
3749 {
3750 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003751
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003752 color.red = (unsigned)(rgb[index] >> 16);
3753 color.green = (unsigned)(rgb[index] >> 8) & 255;
3754 color.blue = (unsigned)rgb[index] & 255;
3755 vterm_state_set_palette_color(state, index, &color);
3756 }
3757}
3758
3759/*
3760 * Set the ANSI color palette from a list of colors
3761 */
3762 static int
3763set_ansi_colors_list(VTerm *vterm, list_T *list)
3764{
3765 int n = 0;
3766 long_u rgb[16];
3767 listitem_T *li = list->lv_first;
3768
3769 for (; li != NULL && n < 16; li = li->li_next, n++)
3770 {
3771 char_u *color_name;
3772 guicolor_T guicolor;
3773
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003774 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003775 if (color_name == NULL)
3776 return FAIL;
3777
3778 guicolor = GUI_GET_COLOR(color_name);
3779 if (guicolor == INVALCOLOR)
3780 return FAIL;
3781
3782 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3783 }
3784
3785 if (n != 16 || li != NULL)
3786 return FAIL;
3787
3788 set_vterm_palette(vterm, rgb);
3789
3790 return OK;
3791}
3792
3793/*
3794 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3795 */
3796 static void
3797init_vterm_ansi_colors(VTerm *vterm)
3798{
3799 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3800
3801 if (var != NULL
3802 && (var->di_tv.v_type != VAR_LIST
3803 || var->di_tv.vval.v_list == NULL
3804 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003805 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003806}
3807#endif
3808
Bram Moolenaar52acb112018-03-18 19:20:22 +01003809/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003810 * Handles a "drop" command from the job in the terminal.
3811 * "item" is the file name, "item->li_next" may have options.
3812 */
3813 static void
3814handle_drop_command(listitem_T *item)
3815{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003816 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003817 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003818 int bufnr;
3819 win_T *wp;
3820 tabpage_T *tp;
3821 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003822 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003823
3824 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3825 FOR_ALL_TAB_WINDOWS(tp, wp)
3826 {
3827 if (wp->w_buffer->b_fnum == bufnr)
3828 {
3829 /* buffer is in a window already, go there */
3830 goto_tabpage_win(tp, wp);
3831 return;
3832 }
3833 }
3834
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003835 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003836
3837 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3838 && opt_item->li_tv.vval.v_dict != NULL)
3839 {
3840 dict_T *dict = opt_item->li_tv.vval.v_dict;
3841 char_u *p;
3842
Bram Moolenaar8f667172018-12-14 15:38:31 +01003843 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003844 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003845 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003846 if (p != NULL)
3847 {
3848 if (check_ff_value(p) == FAIL)
3849 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3850 else
3851 ea.force_ff = *p;
3852 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003853 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003854 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003855 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003856 if (p != NULL)
3857 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003858 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003859 if (ea.cmd != NULL)
3860 {
3861 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3862 ea.force_enc = 11;
3863 tofree = ea.cmd;
3864 }
3865 }
3866
Bram Moolenaar8f667172018-12-14 15:38:31 +01003867 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003868 if (p != NULL)
3869 get_bad_opt(p, &ea);
3870
3871 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3872 ea.force_bin = FORCE_BIN;
3873 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3874 ea.force_bin = FORCE_BIN;
3875 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3876 ea.force_bin = FORCE_NOBIN;
3877 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3878 ea.force_bin = FORCE_NOBIN;
3879 }
3880
3881 /* open in new window, like ":split fname" */
3882 if (ea.cmd == NULL)
3883 ea.cmd = (char_u *)"split";
3884 ea.arg = fname;
3885 ea.cmdidx = CMD_split;
3886 ex_splitview(&ea);
3887
3888 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003889}
3890
3891/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003892 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
3893 */
3894 static int
3895is_permitted_term_api(char_u *func, char_u *pat)
3896{
3897 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
3898}
3899
3900/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003901 * Handles a function call from the job running in a terminal.
3902 * "item" is the function name, "item->li_next" has the arguments.
3903 */
3904 static void
3905handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3906{
3907 char_u *func;
3908 typval_T argvars[2];
3909 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003910 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003911
3912 if (item->li_next == NULL)
3913 {
3914 ch_log(channel, "Missing function arguments for call");
3915 return;
3916 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003917 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003918
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003919 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003920 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003921 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003922 return;
3923 }
3924
3925 argvars[0].v_type = VAR_NUMBER;
3926 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3927 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003928 vim_memset(&funcexe, 0, sizeof(funcexe));
3929 funcexe.firstline = 1L;
3930 funcexe.lastline = 1L;
3931 funcexe.evaluate = TRUE;
3932 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003933 {
3934 clear_tv(&rettv);
3935 ch_log(channel, "Function %s called", func);
3936 }
3937 else
3938 ch_log(channel, "Calling function %s failed", func);
3939}
3940
3941/*
3942 * Called by libvterm when it cannot recognize an OSC sequence.
3943 * We recognize a terminal API command.
3944 */
3945 static int
3946parse_osc(const char *command, size_t cmdlen, void *user)
3947{
3948 term_T *term = (term_T *)user;
3949 js_read_T reader;
3950 typval_T tv;
3951 channel_T *channel = term->tl_job == NULL ? NULL
3952 : term->tl_job->jv_channel;
3953
3954 /* We recognize only OSC 5 1 ; {command} */
3955 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3956 return 0; /* not handled */
3957
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003958 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003959 if (reader.js_buf == NULL)
3960 return 1;
3961 reader.js_fill = NULL;
3962 reader.js_used = 0;
3963 if (json_decode(&reader, &tv, 0) == OK
3964 && tv.v_type == VAR_LIST
3965 && tv.vval.v_list != NULL)
3966 {
3967 listitem_T *item = tv.vval.v_list->lv_first;
3968
3969 if (item == NULL)
3970 ch_log(channel, "Missing command");
3971 else
3972 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003973 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003974
Bram Moolenaara997b452018-04-17 23:24:06 +02003975 /* Make sure an invoked command doesn't delete the buffer (and the
3976 * terminal) under our fingers. */
3977 ++term->tl_buffer->b_locked;
3978
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003979 item = item->li_next;
3980 if (item == NULL)
3981 ch_log(channel, "Missing argument for %s", cmd);
3982 else if (STRCMP(cmd, "drop") == 0)
3983 handle_drop_command(item);
3984 else if (STRCMP(cmd, "call") == 0)
3985 handle_call_command(term, channel, item);
3986 else
3987 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003988 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003989 }
3990 }
3991 else
3992 ch_log(channel, "Invalid JSON received");
3993
3994 vim_free(reader.js_buf);
3995 clear_tv(&tv);
3996 return 1;
3997}
3998
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003999/*
4000 * Called by libvterm when it cannot recognize a CSI sequence.
4001 * We recognize the window position report.
4002 */
4003 static int
4004parse_csi(
4005 const char *leader UNUSED,
4006 const long args[],
4007 int argcount,
4008 const char *intermed UNUSED,
4009 char command,
4010 void *user)
4011{
4012 term_T *term = (term_T *)user;
4013 char buf[100];
4014 int len;
4015 int x = 0;
4016 int y = 0;
4017 win_T *wp;
4018
4019 // We recognize only CSI 13 t
4020 if (command != 't' || argcount != 1 || args[0] != 13)
4021 return 0; // not handled
4022
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004023 // When getting the window position is not possible or it fails it results
4024 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004025#if defined(FEAT_GUI) \
4026 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4027 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004028 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004029#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004030
4031 FOR_ALL_WINDOWS(wp)
4032 if (wp->w_buffer == term->tl_buffer)
4033 break;
4034 if (wp != NULL)
4035 {
4036#ifdef FEAT_GUI
4037 if (gui.in_use)
4038 {
4039 x += wp->w_wincol * gui.char_width;
4040 y += W_WINROW(wp) * gui.char_height;
4041 }
4042 else
4043#endif
4044 {
4045 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004046 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004047 x += wp->w_wincol * 7;
4048 y += W_WINROW(wp) * 10;
4049 }
4050 }
4051
4052 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4053 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4054 (char_u *)buf, len, NULL);
4055 return 1;
4056}
4057
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004058static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004059 NULL, // text
4060 NULL, // control
4061 NULL, // escape
4062 parse_csi, // csi
4063 parse_osc, // osc
4064 NULL, // dcs
4065 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004066};
4067
4068/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004069 * Use Vim's allocation functions for vterm so profiling works.
4070 */
4071 static void *
4072vterm_malloc(size_t size, void *data UNUSED)
4073{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004074 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004075}
4076
4077 static void
4078vterm_memfree(void *ptr, void *data UNUSED)
4079{
4080 vim_free(ptr);
4081}
4082
4083static VTermAllocatorFunctions vterm_allocator = {
4084 &vterm_malloc,
4085 &vterm_memfree
4086};
4087
4088/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004089 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004090 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004091 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004092 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004093create_vterm(term_T *term, int rows, int cols)
4094{
4095 VTerm *vterm;
4096 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004097 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004098 VTermValue value;
4099
Bram Moolenaar756ef112018-04-10 12:04:27 +02004100 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004101 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004102 if (vterm == NULL)
4103 return FAIL;
4104
4105 // Allocate screen and state here, so we can bail out if that fails.
4106 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004107 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004108 if (state == NULL || screen == NULL)
4109 {
4110 vterm_free(vterm);
4111 return FAIL;
4112 }
4113
Bram Moolenaar52acb112018-03-18 19:20:22 +01004114 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
4115 /* TODO: depends on 'encoding'. */
4116 vterm_set_utf8(vterm, 1);
4117
4118 init_default_colors(term);
4119
4120 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004121 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004122 &term->tl_default_color.fg,
4123 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004124
Bram Moolenaar9e587872019-05-13 20:27:23 +02004125 if (t_colors < 16)
4126 // Less than 16 colors: assume that bold means using a bright color for
4127 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004128 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4129
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004130 /* Required to initialize most things. */
4131 vterm_screen_reset(screen, 1 /* hard */);
4132
4133 /* Allow using alternate screen. */
4134 vterm_screen_enable_altscreen(screen, 1);
4135
4136 /* For unix do not use a blinking cursor. In an xterm this causes the
4137 * cursor to blink if it's blinking in the xterm.
4138 * For Windows we respect the system wide setting. */
Bram Moolenaar4f974752019-02-17 17:44:42 +01004139#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004140 if (GetCaretBlinkTime() == INFINITE)
4141 value.boolean = 0;
4142 else
4143 value.boolean = 1;
4144#else
4145 value.boolean = 0;
4146#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004147 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4148 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004149
4150 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004151}
4152
4153/*
4154 * Return the text to show for the buffer name and status.
4155 */
4156 char_u *
4157term_get_status_text(term_T *term)
4158{
4159 if (term->tl_status_text == NULL)
4160 {
4161 char_u *txt;
4162 size_t len;
4163
4164 if (term->tl_normal_mode)
4165 {
4166 if (term_job_running(term))
4167 txt = (char_u *)_("Terminal");
4168 else
4169 txt = (char_u *)_("Terminal-finished");
4170 }
4171 else if (term->tl_title != NULL)
4172 txt = term->tl_title;
4173 else if (term_none_open(term))
4174 txt = (char_u *)_("active");
4175 else if (term_job_running(term))
4176 txt = (char_u *)_("running");
4177 else
4178 txt = (char_u *)_("finished");
4179 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004180 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004181 if (term->tl_status_text != NULL)
4182 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4183 term->tl_buffer->b_fname, txt);
4184 }
4185 return term->tl_status_text;
4186}
4187
4188/*
4189 * Mark references in jobs of terminals.
4190 */
4191 int
4192set_ref_in_term(int copyID)
4193{
4194 int abort = FALSE;
4195 term_T *term;
4196 typval_T tv;
4197
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004198 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004199 if (term->tl_job != NULL)
4200 {
4201 tv.v_type = VAR_JOB;
4202 tv.vval.v_job = term->tl_job;
4203 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4204 }
4205 return abort;
4206}
4207
4208/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004209 * Cache "Terminal" highlight group colors.
4210 */
4211 void
4212set_terminal_default_colors(int cterm_fg, int cterm_bg)
4213{
4214 term_default_cterm_fg = cterm_fg - 1;
4215 term_default_cterm_bg = cterm_bg - 1;
4216}
4217
4218/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004219 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004220 * Returns NULL when the buffer is not for a terminal window and logs a message
4221 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004222 */
4223 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004224term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004225{
4226 buf_T *buf;
4227
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004228 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004229 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004230 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004231 --emsg_off;
4232 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004233 {
4234 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004235 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004236 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004237 return buf;
4238}
4239
Bram Moolenaard96ff162018-02-18 22:13:29 +01004240 static int
4241same_color(VTermColor *a, VTermColor *b)
4242{
4243 return a->red == b->red
4244 && a->green == b->green
4245 && a->blue == b->blue
4246 && a->ansi_index == b->ansi_index;
4247}
4248
4249 static void
4250dump_term_color(FILE *fd, VTermColor *color)
4251{
4252 fprintf(fd, "%02x%02x%02x%d",
4253 (int)color->red, (int)color->green, (int)color->blue,
4254 (int)color->ansi_index);
4255}
4256
4257/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004258 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004259 *
4260 * Each screen cell in full is:
4261 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4262 * {characters} is a space for an empty cell
4263 * For a double-width character "+" is changed to "*" and the next cell is
4264 * skipped.
4265 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4266 * when "&" use the same as the previous cell.
4267 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4268 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4269 * {color-idx} is a number from 0 to 255
4270 *
4271 * Screen cell with same width, attributes and color as the previous one:
4272 * |{characters}
4273 *
4274 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4275 *
4276 * Repeating the previous screen cell:
4277 * @{count}
4278 */
4279 void
4280f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4281{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004282 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004283 term_T *term;
4284 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004285 int max_height = 0;
4286 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004287 stat_T st;
4288 FILE *fd;
4289 VTermPos pos;
4290 VTermScreen *screen;
4291 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004292 VTermState *state;
4293 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004294
4295 if (check_restricted() || check_secure())
4296 return;
4297 if (buf == NULL)
4298 return;
4299 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004300 if (term->tl_vterm == NULL)
4301 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004302 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004303 return;
4304 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004305
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004306 if (argvars[2].v_type != VAR_UNKNOWN)
4307 {
4308 dict_T *d;
4309
4310 if (argvars[2].v_type != VAR_DICT)
4311 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004312 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004313 return;
4314 }
4315 d = argvars[2].vval.v_dict;
4316 if (d != NULL)
4317 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004318 max_height = dict_get_number(d, (char_u *)"rows");
4319 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004320 }
4321 }
4322
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004323 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004324 if (fname == NULL)
4325 return;
4326 if (mch_stat((char *)fname, &st) >= 0)
4327 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004328 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004329 return;
4330 }
4331
Bram Moolenaard96ff162018-02-18 22:13:29 +01004332 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4333 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004334 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004335 return;
4336 }
4337
4338 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4339
4340 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004341 state = vterm_obtain_state(term->tl_vterm);
4342 vterm_state_get_cursorpos(state, &cursor_pos);
4343
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004344 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4345 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004346 {
4347 int repeat = 0;
4348
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004349 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4350 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004351 {
4352 VTermScreenCell cell;
4353 int same_attr;
4354 int same_chars = TRUE;
4355 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004356 int is_cursor_pos = (pos.col == cursor_pos.col
4357 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004358
4359 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4360 vim_memset(&cell, 0, sizeof(cell));
4361
4362 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4363 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004364 int c = cell.chars[i];
4365 int pc = prev_cell.chars[i];
4366
4367 /* For the first character NUL is the same as space. */
4368 if (i == 0)
4369 {
4370 c = (c == NUL) ? ' ' : c;
4371 pc = (pc == NUL) ? ' ' : pc;
4372 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004373 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004374 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004375 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004376 break;
4377 }
4378 same_attr = vtermAttr2hl(cell.attrs)
4379 == vtermAttr2hl(prev_cell.attrs)
4380 && same_color(&cell.fg, &prev_cell.fg)
4381 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004382 if (same_chars && cell.width == prev_cell.width && same_attr
4383 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004384 {
4385 ++repeat;
4386 }
4387 else
4388 {
4389 if (repeat > 0)
4390 {
4391 fprintf(fd, "@%d", repeat);
4392 repeat = 0;
4393 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004394 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004395
4396 if (cell.chars[0] == NUL)
4397 fputs(" ", fd);
4398 else
4399 {
4400 char_u charbuf[10];
4401 int len;
4402
4403 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4404 && cell.chars[i] != NUL; ++i)
4405 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004406 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004407 fwrite(charbuf, len, 1, fd);
4408 }
4409 }
4410
4411 /* When only the characters differ we don't write anything, the
4412 * following "|", "@" or NL will indicate using the same
4413 * attributes. */
4414 if (cell.width != prev_cell.width || !same_attr)
4415 {
4416 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004417 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004418 else
4419 fputs("+", fd);
4420
4421 if (same_attr)
4422 {
4423 fputs("&", fd);
4424 }
4425 else
4426 {
4427 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4428 if (same_color(&cell.fg, &prev_cell.fg))
4429 fputs("&", fd);
4430 else
4431 {
4432 fputs("#", fd);
4433 dump_term_color(fd, &cell.fg);
4434 }
4435 if (same_color(&cell.bg, &prev_cell.bg))
4436 fputs("&", fd);
4437 else
4438 {
4439 fputs("#", fd);
4440 dump_term_color(fd, &cell.bg);
4441 }
4442 }
4443 }
4444
4445 prev_cell = cell;
4446 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004447
4448 if (cell.width == 2)
4449 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004450 }
4451 if (repeat > 0)
4452 fprintf(fd, "@%d", repeat);
4453 fputs("\n", fd);
4454 }
4455
4456 fclose(fd);
4457}
4458
4459/*
4460 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4461 */
4462 static void
4463dump_is_corrupt(garray_T *gap)
4464{
4465 ga_concat(gap, (char_u *)"CORRUPT");
4466}
4467
4468 static void
4469append_cell(garray_T *gap, cellattr_T *cell)
4470{
4471 if (ga_grow(gap, 1) == OK)
4472 {
4473 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4474 ++gap->ga_len;
4475 }
4476}
4477
4478/*
4479 * Read the dump file from "fd" and append lines to the current buffer.
4480 * Return the cell width of the longest line.
4481 */
4482 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004483read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004484{
4485 int c;
4486 garray_T ga_text;
4487 garray_T ga_cell;
4488 char_u *prev_char = NULL;
4489 int attr = 0;
4490 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004491 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004492 term_T *term = curbuf->b_term;
4493 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004494 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004495
4496 ga_init2(&ga_text, 1, 90);
4497 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4498 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004499 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004500 cursor_pos->row = -1;
4501 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004502
4503 c = fgetc(fd);
4504 for (;;)
4505 {
4506 if (c == EOF)
4507 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004508 if (c == '\r')
4509 {
4510 // DOS line endings? Ignore.
4511 c = fgetc(fd);
4512 }
4513 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004514 {
4515 /* End of a line: append it to the buffer. */
4516 if (ga_text.ga_data == NULL)
4517 dump_is_corrupt(&ga_text);
4518 if (ga_grow(&term->tl_scrollback, 1) == OK)
4519 {
4520 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4521 + term->tl_scrollback.ga_len;
4522
4523 if (max_cells < ga_cell.ga_len)
4524 max_cells = ga_cell.ga_len;
4525 line->sb_cols = ga_cell.ga_len;
4526 line->sb_cells = ga_cell.ga_data;
4527 line->sb_fill_attr = term->tl_default_color;
4528 ++term->tl_scrollback.ga_len;
4529 ga_init(&ga_cell);
4530
4531 ga_append(&ga_text, NUL);
4532 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4533 ga_text.ga_len, FALSE);
4534 }
4535 else
4536 ga_clear(&ga_cell);
4537 ga_text.ga_len = 0;
4538
4539 c = fgetc(fd);
4540 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004541 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004542 {
4543 int prev_len = ga_text.ga_len;
4544
Bram Moolenaar9271d052018-02-25 21:39:46 +01004545 if (c == '>')
4546 {
4547 if (cursor_pos->row != -1)
4548 dump_is_corrupt(&ga_text); /* duplicate cursor */
4549 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4550 cursor_pos->col = ga_cell.ga_len;
4551 }
4552
Bram Moolenaard96ff162018-02-18 22:13:29 +01004553 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4554 c = fgetc(fd);
4555 if (c != EOF)
4556 ga_append(&ga_text, c);
4557 for (;;)
4558 {
4559 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004560 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004561 || c == EOF || c == '\n')
4562 break;
4563 ga_append(&ga_text, c);
4564 }
4565
4566 /* save the character for repeating it */
4567 vim_free(prev_char);
4568 if (ga_text.ga_data != NULL)
4569 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4570 ga_text.ga_len - prev_len);
4571
Bram Moolenaar9271d052018-02-25 21:39:46 +01004572 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004573 {
4574 /* use all attributes from previous cell */
4575 }
4576 else if (c == '+' || c == '*')
4577 {
4578 int is_bg;
4579
4580 cell.width = c == '+' ? 1 : 2;
4581
4582 c = fgetc(fd);
4583 if (c == '&')
4584 {
4585 /* use same attr as previous cell */
4586 c = fgetc(fd);
4587 }
4588 else if (isdigit(c))
4589 {
4590 /* get the decimal attribute */
4591 attr = 0;
4592 while (isdigit(c))
4593 {
4594 attr = attr * 10 + (c - '0');
4595 c = fgetc(fd);
4596 }
4597 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004598
4599 /* is_bg == 0: fg, is_bg == 1: bg */
4600 for (is_bg = 0; is_bg <= 1; ++is_bg)
4601 {
4602 if (c == '&')
4603 {
4604 /* use same color as previous cell */
4605 c = fgetc(fd);
4606 }
4607 else if (c == '#')
4608 {
4609 int red, green, blue, index = 0;
4610
4611 c = fgetc(fd);
4612 red = hex2nr(c);
4613 c = fgetc(fd);
4614 red = (red << 4) + hex2nr(c);
4615 c = fgetc(fd);
4616 green = hex2nr(c);
4617 c = fgetc(fd);
4618 green = (green << 4) + hex2nr(c);
4619 c = fgetc(fd);
4620 blue = hex2nr(c);
4621 c = fgetc(fd);
4622 blue = (blue << 4) + hex2nr(c);
4623 c = fgetc(fd);
4624 if (!isdigit(c))
4625 dump_is_corrupt(&ga_text);
4626 while (isdigit(c))
4627 {
4628 index = index * 10 + (c - '0');
4629 c = fgetc(fd);
4630 }
4631
4632 if (is_bg)
4633 {
4634 cell.bg.red = red;
4635 cell.bg.green = green;
4636 cell.bg.blue = blue;
4637 cell.bg.ansi_index = index;
4638 }
4639 else
4640 {
4641 cell.fg.red = red;
4642 cell.fg.green = green;
4643 cell.fg.blue = blue;
4644 cell.fg.ansi_index = index;
4645 }
4646 }
4647 else
4648 dump_is_corrupt(&ga_text);
4649 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004650 }
4651 else
4652 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004653 }
4654 else
4655 dump_is_corrupt(&ga_text);
4656
4657 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004658 if (cell.width == 2)
4659 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004660 }
4661 else if (c == '@')
4662 {
4663 if (prev_char == NULL)
4664 dump_is_corrupt(&ga_text);
4665 else
4666 {
4667 int count = 0;
4668
4669 /* repeat previous character, get the count */
4670 for (;;)
4671 {
4672 c = fgetc(fd);
4673 if (!isdigit(c))
4674 break;
4675 count = count * 10 + (c - '0');
4676 }
4677
4678 while (count-- > 0)
4679 {
4680 ga_concat(&ga_text, prev_char);
4681 append_cell(&ga_cell, &cell);
4682 }
4683 }
4684 }
4685 else
4686 {
4687 dump_is_corrupt(&ga_text);
4688 c = fgetc(fd);
4689 }
4690 }
4691
4692 if (ga_text.ga_len > 0)
4693 {
4694 /* trailing characters after last NL */
4695 dump_is_corrupt(&ga_text);
4696 ga_append(&ga_text, NUL);
4697 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4698 ga_text.ga_len, FALSE);
4699 }
4700
4701 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004702 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004703 vim_free(prev_char);
4704
4705 return max_cells;
4706}
4707
4708/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004709 * Return an allocated string with at least "text_width" "=" characters and
4710 * "fname" inserted in the middle.
4711 */
4712 static char_u *
4713get_separator(int text_width, char_u *fname)
4714{
4715 int width = MAX(text_width, curwin->w_width);
4716 char_u *textline;
4717 int fname_size;
4718 char_u *p = fname;
4719 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004720 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004721
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004722 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004723 if (textline == NULL)
4724 return NULL;
4725
4726 fname_size = vim_strsize(fname);
4727 if (fname_size < width - 8)
4728 {
4729 /* enough room, don't use the full window width */
4730 width = MAX(text_width, fname_size + 8);
4731 }
4732 else if (fname_size > width - 8)
4733 {
4734 /* full name doesn't fit, use only the tail */
4735 p = gettail(fname);
4736 fname_size = vim_strsize(p);
4737 }
4738 /* skip characters until the name fits */
4739 while (fname_size > width - 8)
4740 {
4741 p += (*mb_ptr2len)(p);
4742 fname_size = vim_strsize(p);
4743 }
4744
4745 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4746 textline[i] = '=';
4747 textline[i++] = ' ';
4748
4749 STRCPY(textline + i, p);
4750 off = STRLEN(textline);
4751 textline[off] = ' ';
4752 for (i = 1; i < (width - fname_size) / 2; ++i)
4753 textline[off + i] = '=';
4754 textline[off + i] = NUL;
4755
4756 return textline;
4757}
4758
4759/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004760 * Common for "term_dumpdiff()" and "term_dumpload()".
4761 */
4762 static void
4763term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4764{
4765 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004766 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004767 char_u buf1[NUMBUFLEN];
4768 char_u buf2[NUMBUFLEN];
4769 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004770 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004771 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004772 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004773 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004774 char_u *textline = NULL;
4775
4776 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004777 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004778 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004779 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004780 if (fname1 == NULL || (do_diff && fname2 == NULL))
4781 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004782 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004783 return;
4784 }
4785 fd1 = mch_fopen((char *)fname1, READBIN);
4786 if (fd1 == NULL)
4787 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004788 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004789 return;
4790 }
4791 if (do_diff)
4792 {
4793 fd2 = mch_fopen((char *)fname2, READBIN);
4794 if (fd2 == NULL)
4795 {
4796 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004797 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004798 return;
4799 }
4800 }
4801
4802 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004803 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4804 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4805 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4806 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4807 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004808
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004809 if (opt.jo_term_name == NULL)
4810 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004811 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004812
Bram Moolenaar51e14382019-05-25 20:21:28 +02004813 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004814 if (fname_tofree != NULL)
4815 {
4816 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4817 opt.jo_term_name = fname_tofree;
4818 }
4819 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004820
Bram Moolenaar87abab92019-06-03 21:14:59 +02004821 if (opt.jo_bufnr_buf != NULL)
4822 {
4823 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4824
4825 // With "bufnr" argument: enter the window with this buffer and make it
4826 // empty.
4827 if (wp == NULL)
4828 semsg(_(e_invarg2), "bufnr");
4829 else
4830 {
4831 buf = curbuf;
4832 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4833 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02004834 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02004835 redraw_later(NOT_VALID);
4836 }
4837 }
4838 else
4839 // Create a new terminal window.
4840 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4841
Bram Moolenaard96ff162018-02-18 22:13:29 +01004842 if (buf != NULL && buf->b_term != NULL)
4843 {
4844 int i;
4845 linenr_T bot_lnum;
4846 linenr_T lnum;
4847 term_T *term = buf->b_term;
4848 int width;
4849 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004850 VTermPos cursor_pos1;
4851 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004852
Bram Moolenaar52acb112018-03-18 19:20:22 +01004853 init_default_colors(term);
4854
Bram Moolenaard96ff162018-02-18 22:13:29 +01004855 rettv->vval.v_number = buf->b_fnum;
4856
4857 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004858 width = read_dump_file(fd1, &cursor_pos1);
4859
4860 /* position the cursor */
4861 if (cursor_pos1.row >= 0)
4862 {
4863 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4864 coladvance(cursor_pos1.col);
4865 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004866
4867 /* Delete the empty line that was in the empty buffer. */
4868 ml_delete(1, FALSE);
4869
4870 /* For term_dumpload() we are done here. */
4871 if (!do_diff)
4872 goto theend;
4873
4874 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4875
Bram Moolenaar4a696342018-04-05 18:45:26 +02004876 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004877 if (textline == NULL)
4878 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004879 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4880 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4881 vim_free(textline);
4882
4883 textline = get_separator(width, fname2);
4884 if (textline == NULL)
4885 goto theend;
4886 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4887 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004888 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004889
4890 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004891 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004892 if (width2 > width)
4893 {
4894 vim_free(textline);
4895 textline = alloc(width2 + 1);
4896 if (textline == NULL)
4897 goto theend;
4898 width = width2;
4899 textline[width] = NUL;
4900 }
4901 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4902
4903 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4904 {
4905 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4906 {
4907 /* bottom part has fewer rows, fill with "-" */
4908 for (i = 0; i < width; ++i)
4909 textline[i] = '-';
4910 }
4911 else
4912 {
4913 char_u *line1;
4914 char_u *line2;
4915 char_u *p1;
4916 char_u *p2;
4917 int col;
4918 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4919 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4920 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4921 ->sb_cells;
4922
4923 /* Make a copy, getting the second line will invalidate it. */
4924 line1 = vim_strsave(ml_get(lnum));
4925 if (line1 == NULL)
4926 break;
4927 p1 = line1;
4928
4929 line2 = ml_get(lnum + bot_lnum);
4930 p2 = line2;
4931 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4932 {
4933 int len1 = utfc_ptr2len(p1);
4934 int len2 = utfc_ptr2len(p2);
4935
4936 textline[col] = ' ';
4937 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004938 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004939 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004940 else if (lnum == cursor_pos1.row + 1
4941 && col == cursor_pos1.col
4942 && (cursor_pos1.row != cursor_pos2.row
4943 || cursor_pos1.col != cursor_pos2.col))
4944 /* cursor in first but not in second */
4945 textline[col] = '>';
4946 else if (lnum == cursor_pos2.row + 1
4947 && col == cursor_pos2.col
4948 && (cursor_pos1.row != cursor_pos2.row
4949 || cursor_pos1.col != cursor_pos2.col))
4950 /* cursor in second but not in first */
4951 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004952 else if (cellattr1 != NULL && cellattr2 != NULL)
4953 {
4954 if ((cellattr1 + col)->width
4955 != (cellattr2 + col)->width)
4956 textline[col] = 'w';
4957 else if (!same_color(&(cellattr1 + col)->fg,
4958 &(cellattr2 + col)->fg))
4959 textline[col] = 'f';
4960 else if (!same_color(&(cellattr1 + col)->bg,
4961 &(cellattr2 + col)->bg))
4962 textline[col] = 'b';
4963 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4964 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4965 textline[col] = 'a';
4966 }
4967 p1 += len1;
4968 p2 += len2;
4969 /* TODO: handle different width */
4970 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004971
4972 while (col < width)
4973 {
4974 if (*p1 == NUL && *p2 == NUL)
4975 textline[col] = '?';
4976 else if (*p1 == NUL)
4977 {
4978 textline[col] = '+';
4979 p2 += utfc_ptr2len(p2);
4980 }
4981 else
4982 {
4983 textline[col] = '-';
4984 p1 += utfc_ptr2len(p1);
4985 }
4986 ++col;
4987 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004988
4989 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004990 }
4991 if (add_empty_scrollback(term, &term->tl_default_color,
4992 term->tl_top_diff_rows) == OK)
4993 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4994 ++bot_lnum;
4995 }
4996
4997 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4998 {
4999 /* bottom part has more rows, fill with "+" */
5000 for (i = 0; i < width; ++i)
5001 textline[i] = '+';
5002 if (add_empty_scrollback(term, &term->tl_default_color,
5003 term->tl_top_diff_rows) == OK)
5004 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5005 ++lnum;
5006 ++bot_lnum;
5007 }
5008
5009 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005010
5011 /* looks better without wrapping */
5012 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005013 }
5014
5015theend:
5016 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005017 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005018 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005019 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005020 fclose(fd2);
5021}
5022
5023/*
5024 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5025 * bottom files.
5026 * Return FAIL when this is not possible.
5027 */
5028 int
5029term_swap_diff()
5030{
5031 term_T *term = curbuf->b_term;
5032 linenr_T line_count;
5033 linenr_T top_rows;
5034 linenr_T bot_rows;
5035 linenr_T bot_start;
5036 linenr_T lnum;
5037 char_u *p;
5038 sb_line_T *sb_line;
5039
5040 if (term == NULL
5041 || !term_is_finished(curbuf)
5042 || term->tl_top_diff_rows == 0
5043 || term->tl_scrollback.ga_len == 0)
5044 return FAIL;
5045
5046 line_count = curbuf->b_ml.ml_line_count;
5047 top_rows = term->tl_top_diff_rows;
5048 bot_rows = term->tl_bot_diff_rows;
5049 bot_start = line_count - bot_rows;
5050 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5051
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005052 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005053 for (lnum = 1; lnum <= top_rows; ++lnum)
5054 {
5055 p = vim_strsave(ml_get(1));
5056 if (p == NULL)
5057 return OK;
5058 ml_append(bot_start, p, 0, FALSE);
5059 ml_delete(1, FALSE);
5060 vim_free(p);
5061 }
5062
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005063 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005064 for (lnum = 1; lnum <= bot_rows; ++lnum)
5065 {
5066 p = vim_strsave(ml_get(bot_start + lnum));
5067 if (p == NULL)
5068 return OK;
5069 ml_delete(bot_start + lnum, FALSE);
5070 ml_append(lnum - 1, p, 0, FALSE);
5071 vim_free(p);
5072 }
5073
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005074 // move top title to bottom
5075 p = vim_strsave(ml_get(bot_rows + 1));
5076 if (p == NULL)
5077 return OK;
5078 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5079 ml_delete(bot_rows + 1, FALSE);
5080 vim_free(p);
5081
5082 // move bottom title to top
5083 p = vim_strsave(ml_get(line_count - top_rows));
5084 if (p == NULL)
5085 return OK;
5086 ml_delete(line_count - top_rows, FALSE);
5087 ml_append(bot_rows, p, 0, FALSE);
5088 vim_free(p);
5089
Bram Moolenaard96ff162018-02-18 22:13:29 +01005090 if (top_rows == bot_rows)
5091 {
5092 /* rows counts are equal, can swap cell properties */
5093 for (lnum = 0; lnum < top_rows; ++lnum)
5094 {
5095 sb_line_T temp;
5096
5097 temp = *(sb_line + lnum);
5098 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5099 *(sb_line + bot_start + lnum) = temp;
5100 }
5101 }
5102 else
5103 {
5104 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005105 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005106
5107 /* need to copy cell properties into temp memory */
5108 if (temp != NULL)
5109 {
5110 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5111 mch_memmove(term->tl_scrollback.ga_data,
5112 temp + bot_start,
5113 sizeof(sb_line_T) * bot_rows);
5114 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5115 temp + top_rows,
5116 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5117 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5118 + line_count - top_rows,
5119 temp,
5120 sizeof(sb_line_T) * top_rows);
5121 vim_free(temp);
5122 }
5123 }
5124
5125 term->tl_top_diff_rows = bot_rows;
5126 term->tl_bot_diff_rows = top_rows;
5127
5128 update_screen(NOT_VALID);
5129 return OK;
5130}
5131
5132/*
5133 * "term_dumpdiff(filename, filename, options)" function
5134 */
5135 void
5136f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5137{
5138 term_load_dump(argvars, rettv, TRUE);
5139}
5140
5141/*
5142 * "term_dumpload(filename, options)" function
5143 */
5144 void
5145f_term_dumpload(typval_T *argvars, typval_T *rettv)
5146{
5147 term_load_dump(argvars, rettv, FALSE);
5148}
5149
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005150/*
5151 * "term_getaltscreen(buf)" function
5152 */
5153 void
5154f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5155{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005156 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005157
5158 if (buf == NULL)
5159 return;
5160 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5161}
5162
5163/*
5164 * "term_getattr(attr, name)" function
5165 */
5166 void
5167f_term_getattr(typval_T *argvars, typval_T *rettv)
5168{
5169 int attr;
5170 size_t i;
5171 char_u *name;
5172
5173 static struct {
5174 char *name;
5175 int attr;
5176 } attrs[] = {
5177 {"bold", HL_BOLD},
5178 {"italic", HL_ITALIC},
5179 {"underline", HL_UNDERLINE},
5180 {"strike", HL_STRIKETHROUGH},
5181 {"reverse", HL_INVERSE},
5182 };
5183
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005184 attr = tv_get_number(&argvars[0]);
5185 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005186 if (name == NULL)
5187 return;
5188
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005189 if (attr > HL_ALL)
5190 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005191 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5192 if (STRCMP(name, attrs[i].name) == 0)
5193 {
5194 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5195 break;
5196 }
5197}
5198
5199/*
5200 * "term_getcursor(buf)" function
5201 */
5202 void
5203f_term_getcursor(typval_T *argvars, typval_T *rettv)
5204{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005205 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005206 term_T *term;
5207 list_T *l;
5208 dict_T *d;
5209
5210 if (rettv_list_alloc(rettv) == FAIL)
5211 return;
5212 if (buf == NULL)
5213 return;
5214 term = buf->b_term;
5215
5216 l = rettv->vval.v_list;
5217 list_append_number(l, term->tl_cursor_pos.row + 1);
5218 list_append_number(l, term->tl_cursor_pos.col + 1);
5219
5220 d = dict_alloc();
5221 if (d != NULL)
5222 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005223 dict_add_number(d, "visible", term->tl_cursor_visible);
5224 dict_add_number(d, "blink", blink_state_is_inverted()
5225 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5226 dict_add_number(d, "shape", term->tl_cursor_shape);
5227 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005228 list_append_dict(l, d);
5229 }
5230}
5231
5232/*
5233 * "term_getjob(buf)" function
5234 */
5235 void
5236f_term_getjob(typval_T *argvars, typval_T *rettv)
5237{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005238 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005239
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005240 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005241 {
5242 rettv->v_type = VAR_SPECIAL;
5243 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005244 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005245 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005246
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005247 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005248 rettv->vval.v_job = buf->b_term->tl_job;
5249 if (rettv->vval.v_job != NULL)
5250 ++rettv->vval.v_job->jv_refcount;
5251}
5252
5253 static int
5254get_row_number(typval_T *tv, term_T *term)
5255{
5256 if (tv->v_type == VAR_STRING
5257 && tv->vval.v_string != NULL
5258 && STRCMP(tv->vval.v_string, ".") == 0)
5259 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005260 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005261}
5262
5263/*
5264 * "term_getline(buf, row)" function
5265 */
5266 void
5267f_term_getline(typval_T *argvars, typval_T *rettv)
5268{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005269 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005270 term_T *term;
5271 int row;
5272
5273 rettv->v_type = VAR_STRING;
5274 if (buf == NULL)
5275 return;
5276 term = buf->b_term;
5277 row = get_row_number(&argvars[1], term);
5278
5279 if (term->tl_vterm == NULL)
5280 {
5281 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5282
5283 /* vterm is finished, get the text from the buffer */
5284 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5285 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5286 }
5287 else
5288 {
5289 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5290 VTermRect rect;
5291 int len;
5292 char_u *p;
5293
5294 if (row < 0 || row >= term->tl_rows)
5295 return;
5296 len = term->tl_cols * MB_MAXBYTES + 1;
5297 p = alloc(len);
5298 if (p == NULL)
5299 return;
5300 rettv->vval.v_string = p;
5301
5302 rect.start_col = 0;
5303 rect.end_col = term->tl_cols;
5304 rect.start_row = row;
5305 rect.end_row = row + 1;
5306 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5307 }
5308}
5309
5310/*
5311 * "term_getscrolled(buf)" function
5312 */
5313 void
5314f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5315{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005316 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005317
5318 if (buf == NULL)
5319 return;
5320 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5321}
5322
5323/*
5324 * "term_getsize(buf)" function
5325 */
5326 void
5327f_term_getsize(typval_T *argvars, typval_T *rettv)
5328{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005329 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005330 list_T *l;
5331
5332 if (rettv_list_alloc(rettv) == FAIL)
5333 return;
5334 if (buf == NULL)
5335 return;
5336
5337 l = rettv->vval.v_list;
5338 list_append_number(l, buf->b_term->tl_rows);
5339 list_append_number(l, buf->b_term->tl_cols);
5340}
5341
5342/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005343 * "term_setsize(buf, rows, cols)" function
5344 */
5345 void
5346f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5347{
5348 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5349 term_T *term;
5350 varnumber_T rows, cols;
5351
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005352 if (buf == NULL)
5353 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005354 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005355 return;
5356 }
5357 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005358 return;
5359 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005360 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005361 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005362 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005363 cols = cols <= 0 ? term->tl_cols : cols;
5364 vterm_set_size(term->tl_vterm, rows, cols);
5365 /* handle_resize() will resize the windows */
5366
5367 /* Get and remember the size we ended up with. Update the pty. */
5368 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5369 term_report_winsize(term, term->tl_rows, term->tl_cols);
5370}
5371
5372/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005373 * "term_getstatus(buf)" function
5374 */
5375 void
5376f_term_getstatus(typval_T *argvars, typval_T *rettv)
5377{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005378 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005379 term_T *term;
5380 char_u val[100];
5381
5382 rettv->v_type = VAR_STRING;
5383 if (buf == NULL)
5384 return;
5385 term = buf->b_term;
5386
5387 if (term_job_running(term))
5388 STRCPY(val, "running");
5389 else
5390 STRCPY(val, "finished");
5391 if (term->tl_normal_mode)
5392 STRCAT(val, ",normal");
5393 rettv->vval.v_string = vim_strsave(val);
5394}
5395
5396/*
5397 * "term_gettitle(buf)" function
5398 */
5399 void
5400f_term_gettitle(typval_T *argvars, typval_T *rettv)
5401{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005402 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005403
5404 rettv->v_type = VAR_STRING;
5405 if (buf == NULL)
5406 return;
5407
5408 if (buf->b_term->tl_title != NULL)
5409 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5410}
5411
5412/*
5413 * "term_gettty(buf)" function
5414 */
5415 void
5416f_term_gettty(typval_T *argvars, typval_T *rettv)
5417{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005418 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005419 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005420 int num = 0;
5421
5422 rettv->v_type = VAR_STRING;
5423 if (buf == NULL)
5424 return;
5425 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005426 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005427
5428 switch (num)
5429 {
5430 case 0:
5431 if (buf->b_term->tl_job != NULL)
5432 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005433 break;
5434 case 1:
5435 if (buf->b_term->tl_job != NULL)
5436 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005437 break;
5438 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005439 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005440 return;
5441 }
5442 if (p != NULL)
5443 rettv->vval.v_string = vim_strsave(p);
5444}
5445
5446/*
5447 * "term_list()" function
5448 */
5449 void
5450f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5451{
5452 term_T *tp;
5453 list_T *l;
5454
5455 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5456 return;
5457
5458 l = rettv->vval.v_list;
5459 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5460 if (tp != NULL && tp->tl_buffer != NULL)
5461 if (list_append_number(l,
5462 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5463 return;
5464}
5465
5466/*
5467 * "term_scrape(buf, row)" function
5468 */
5469 void
5470f_term_scrape(typval_T *argvars, typval_T *rettv)
5471{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005472 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005473 VTermScreen *screen = NULL;
5474 VTermPos pos;
5475 list_T *l;
5476 term_T *term;
5477 char_u *p;
5478 sb_line_T *line;
5479
5480 if (rettv_list_alloc(rettv) == FAIL)
5481 return;
5482 if (buf == NULL)
5483 return;
5484 term = buf->b_term;
5485
5486 l = rettv->vval.v_list;
5487 pos.row = get_row_number(&argvars[1], term);
5488
5489 if (term->tl_vterm != NULL)
5490 {
5491 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005492 if (screen == NULL) // can't really happen
5493 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005494 p = NULL;
5495 line = NULL;
5496 }
5497 else
5498 {
5499 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5500
5501 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5502 return;
5503 p = ml_get_buf(buf, lnum + 1, FALSE);
5504 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5505 }
5506
5507 for (pos.col = 0; pos.col < term->tl_cols; )
5508 {
5509 dict_T *dcell;
5510 int width;
5511 VTermScreenCellAttrs attrs;
5512 VTermColor fg, bg;
5513 char_u rgb[8];
5514 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5515 int off = 0;
5516 int i;
5517
5518 if (screen == NULL)
5519 {
5520 cellattr_T *cellattr;
5521 int len;
5522
5523 /* vterm has finished, get the cell from scrollback */
5524 if (pos.col >= line->sb_cols)
5525 break;
5526 cellattr = line->sb_cells + pos.col;
5527 width = cellattr->width;
5528 attrs = cellattr->attrs;
5529 fg = cellattr->fg;
5530 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005531 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005532 mch_memmove(mbs, p, len);
5533 mbs[len] = NUL;
5534 p += len;
5535 }
5536 else
5537 {
5538 VTermScreenCell cell;
5539 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5540 break;
5541 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5542 {
5543 if (cell.chars[i] == 0)
5544 break;
5545 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5546 }
5547 mbs[off] = NUL;
5548 width = cell.width;
5549 attrs = cell.attrs;
5550 fg = cell.fg;
5551 bg = cell.bg;
5552 }
5553 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005554 if (dcell == NULL)
5555 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005556 list_append_dict(l, dcell);
5557
Bram Moolenaare0be1672018-07-08 16:50:37 +02005558 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005559
5560 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5561 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005562 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005563 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5564 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005565 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005566
Bram Moolenaare0be1672018-07-08 16:50:37 +02005567 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5568 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005569
5570 ++pos.col;
5571 if (width == 2)
5572 ++pos.col;
5573 }
5574}
5575
5576/*
5577 * "term_sendkeys(buf, keys)" function
5578 */
5579 void
5580f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5581{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005582 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005583 char_u *msg;
5584 term_T *term;
5585
5586 rettv->v_type = VAR_UNKNOWN;
5587 if (buf == NULL)
5588 return;
5589
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005590 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005591 if (msg == NULL)
5592 return;
5593 term = buf->b_term;
5594 if (term->tl_vterm == NULL)
5595 return;
5596
5597 while (*msg != NUL)
5598 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005599 int c;
5600
5601 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5602 {
5603 c = TO_SPECIAL(msg[1], msg[2]);
5604 msg += 3;
5605 }
5606 else
5607 {
5608 c = PTR2CHAR(msg);
5609 msg += MB_CPTR2LEN(msg);
5610 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005611 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005612 }
5613}
5614
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005615#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5616/*
5617 * "term_getansicolors(buf)" function
5618 */
5619 void
5620f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5621{
5622 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5623 term_T *term;
5624 VTermState *state;
5625 VTermColor color;
5626 char_u hexbuf[10];
5627 int index;
5628 list_T *list;
5629
5630 if (rettv_list_alloc(rettv) == FAIL)
5631 return;
5632
5633 if (buf == NULL)
5634 return;
5635 term = buf->b_term;
5636 if (term->tl_vterm == NULL)
5637 return;
5638
5639 list = rettv->vval.v_list;
5640 state = vterm_obtain_state(term->tl_vterm);
5641 for (index = 0; index < 16; index++)
5642 {
5643 vterm_state_get_palette_color(state, index, &color);
5644 sprintf((char *)hexbuf, "#%02x%02x%02x",
5645 color.red, color.green, color.blue);
5646 if (list_append_string(list, hexbuf, 7) == FAIL)
5647 return;
5648 }
5649}
5650
5651/*
5652 * "term_setansicolors(buf, list)" function
5653 */
5654 void
5655f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5656{
5657 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5658 term_T *term;
5659
5660 if (buf == NULL)
5661 return;
5662 term = buf->b_term;
5663 if (term->tl_vterm == NULL)
5664 return;
5665
5666 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5667 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005668 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005669 return;
5670 }
5671
5672 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005673 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005674}
5675#endif
5676
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005677/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005678 * "term_setapi(buf, api)" function
5679 */
5680 void
5681f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5682{
5683 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5684 term_T *term;
5685 char_u *api;
5686
5687 if (buf == NULL)
5688 return;
5689 term = buf->b_term;
5690 vim_free(term->tl_api);
5691 api = tv_get_string_chk(&argvars[1]);
5692 if (api != NULL)
5693 term->tl_api = vim_strsave(api);
5694 else
5695 term->tl_api = NULL;
5696}
5697
5698/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005699 * "term_setrestore(buf, command)" function
5700 */
5701 void
5702f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5703{
5704#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005705 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005706 term_T *term;
5707 char_u *cmd;
5708
5709 if (buf == NULL)
5710 return;
5711 term = buf->b_term;
5712 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005713 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005714 if (cmd != NULL)
5715 term->tl_command = vim_strsave(cmd);
5716 else
5717 term->tl_command = NULL;
5718#endif
5719}
5720
5721/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005722 * "term_setkill(buf, how)" function
5723 */
5724 void
5725f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5726{
5727 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5728 term_T *term;
5729 char_u *how;
5730
5731 if (buf == NULL)
5732 return;
5733 term = buf->b_term;
5734 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005735 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005736 if (how != NULL)
5737 term->tl_kill = vim_strsave(how);
5738 else
5739 term->tl_kill = NULL;
5740}
5741
5742/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005743 * "term_start(command, options)" function
5744 */
5745 void
5746f_term_start(typval_T *argvars, typval_T *rettv)
5747{
5748 jobopt_T opt;
5749 buf_T *buf;
5750
5751 init_job_options(&opt);
5752 if (argvars[1].v_type != VAR_UNKNOWN
5753 && get_job_options(&argvars[1], &opt,
5754 JO_TIMEOUT_ALL + JO_STOPONEXIT
5755 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5756 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5757 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5758 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005759 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005760 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005761 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005762 return;
5763
Bram Moolenaar13568252018-03-16 20:46:58 +01005764 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005765
5766 if (buf != NULL && buf->b_term != NULL)
5767 rettv->vval.v_number = buf->b_fnum;
5768}
5769
5770/*
5771 * "term_wait" function
5772 */
5773 void
5774f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5775{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005776 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005777
5778 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005779 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005780 if (buf->b_term->tl_job == NULL)
5781 {
5782 ch_log(NULL, "term_wait(): no job to wait for");
5783 return;
5784 }
5785 if (buf->b_term->tl_job->jv_channel == NULL)
5786 /* channel is closed, nothing to do */
5787 return;
5788
5789 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005790 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005791 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5792 {
5793 /* The job is dead, keep reading channel I/O until the channel is
5794 * closed. buf->b_term may become NULL if the terminal was closed while
5795 * waiting. */
5796 ch_log(NULL, "term_wait(): waiting for channel to close");
5797 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5798 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005799 term_flush_messages();
5800
Bram Moolenaard45aa552018-05-21 22:50:29 +02005801 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005802 if (!buf_valid(buf))
5803 /* If the terminal is closed when the channel is closed the
5804 * buffer disappears. */
5805 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005806 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005807
5808 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005809 }
5810 else
5811 {
5812 long wait = 10L;
5813
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005814 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005815
5816 /* Wait for some time for any channel I/O. */
5817 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005818 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005819 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005820
5821 /* Flushing messages on channels is hopefully sufficient.
5822 * TODO: is there a better way? */
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005823 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005824 }
5825}
5826
5827/*
5828 * Called when a channel has sent all the lines to a terminal.
5829 * Send a CTRL-D to mark the end of the text.
5830 */
5831 void
5832term_send_eof(channel_T *ch)
5833{
5834 term_T *term;
5835
5836 for (term = first_term; term != NULL; term = term->tl_next)
5837 if (term->tl_job == ch->ch_job)
5838 {
5839 if (term->tl_eof_chars != NULL)
5840 {
5841 channel_send(ch, PART_IN, term->tl_eof_chars,
5842 (int)STRLEN(term->tl_eof_chars), NULL);
5843 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5844 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005845# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005846 else
5847 /* Default: CTRL-D */
5848 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5849# endif
5850 }
5851}
5852
Bram Moolenaar113e1072019-01-20 15:30:40 +01005853#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005854 job_T *
5855term_getjob(term_T *term)
5856{
5857 return term != NULL ? term->tl_job : NULL;
5858}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005859#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005860
Bram Moolenaar4f974752019-02-17 17:44:42 +01005861# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005862
5863/**************************************
5864 * 2. MS-Windows implementation.
5865 */
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005866#ifdef PROTO
5867typedef int COORD;
5868typedef int DWORD;
5869typedef int HANDLE;
5870typedef int *DWORD_PTR;
5871typedef int HPCON;
5872typedef int HRESULT;
5873typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005874typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005875typedef int PSIZE_T;
5876typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005877typedef int BOOL;
5878# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005879#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005880
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005881HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5882HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5883HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005884BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5885BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5886void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005887
5888 static int
5889dyn_conpty_init(int verbose)
5890{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005891 static HMODULE hKerneldll = NULL;
5892 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005893 static struct
5894 {
5895 char *name;
5896 FARPROC *ptr;
5897 } conpty_entry[] =
5898 {
5899 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5900 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5901 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5902 {"InitializeProcThreadAttributeList",
5903 (FARPROC*)&pInitializeProcThreadAttributeList},
5904 {"UpdateProcThreadAttribute",
5905 (FARPROC*)&pUpdateProcThreadAttribute},
5906 {"DeleteProcThreadAttributeList",
5907 (FARPROC*)&pDeleteProcThreadAttributeList},
5908 {NULL, NULL}
5909 };
5910
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005911 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005912 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005913 if (verbose)
5914 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005915 return FAIL;
5916 }
5917
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005918 // No need to initialize twice.
5919 if (hKerneldll)
5920 return OK;
5921
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005922 hKerneldll = vimLoadLib("kernel32.dll");
5923 for (i = 0; conpty_entry[i].name != NULL
5924 && conpty_entry[i].ptr != NULL; ++i)
5925 {
5926 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5927 conpty_entry[i].name)) == NULL)
5928 {
5929 if (verbose)
5930 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005931 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005932 return FAIL;
5933 }
5934 }
5935
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005936 return OK;
5937}
5938
5939 static int
5940conpty_term_and_job_init(
5941 term_T *term,
5942 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005943 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005944 jobopt_T *opt,
5945 jobopt_T *orig_opt)
5946{
5947 WCHAR *cmd_wchar = NULL;
5948 WCHAR *cmd_wchar_copy = NULL;
5949 WCHAR *cwd_wchar = NULL;
5950 WCHAR *env_wchar = NULL;
5951 channel_T *channel = NULL;
5952 job_T *job = NULL;
5953 HANDLE jo = NULL;
5954 garray_T ga_cmd, ga_env;
5955 char_u *cmd = NULL;
5956 HRESULT hr;
5957 COORD consize;
5958 SIZE_T breq;
5959 PROCESS_INFORMATION proc_info;
5960 HANDLE i_theirs = NULL;
5961 HANDLE o_theirs = NULL;
5962 HANDLE i_ours = NULL;
5963 HANDLE o_ours = NULL;
5964
5965 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5966 ga_init2(&ga_env, (int)sizeof(char*), 20);
5967
5968 if (argvar->v_type == VAR_STRING)
5969 {
5970 cmd = argvar->vval.v_string;
5971 }
5972 else if (argvar->v_type == VAR_LIST)
5973 {
5974 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5975 goto failed;
5976 cmd = ga_cmd.ga_data;
5977 }
5978 if (cmd == NULL || *cmd == NUL)
5979 {
5980 emsg(_(e_invarg));
5981 goto failed;
5982 }
5983
5984 term->tl_arg0_cmd = vim_strsave(cmd);
5985
5986 cmd_wchar = enc_to_utf16(cmd, NULL);
5987
5988 if (cmd_wchar != NULL)
5989 {
5990 /* Request by CreateProcessW */
5991 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005992 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005993 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5994 }
5995
5996 ga_clear(&ga_cmd);
5997 if (cmd_wchar == NULL)
5998 goto failed;
5999 if (opt->jo_cwd != NULL)
6000 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6001
6002 win32_build_env(opt->jo_env, &ga_env, TRUE);
6003 env_wchar = ga_env.ga_data;
6004
6005 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6006 goto failed;
6007 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6008 goto failed;
6009
6010 consize.X = term->tl_cols;
6011 consize.Y = term->tl_rows;
6012 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6013 &term->tl_conpty);
6014 if (FAILED(hr))
6015 goto failed;
6016
6017 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6018
6019 /* Set up pipe inheritance safely: Vista or later. */
6020 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006021 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006022 if (!term->tl_siex.lpAttributeList)
6023 goto failed;
6024 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6025 0, &breq))
6026 goto failed;
6027 if (!pUpdateProcThreadAttribute(
6028 term->tl_siex.lpAttributeList, 0,
6029 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6030 sizeof(HPCON), NULL, NULL))
6031 goto failed;
6032
6033 channel = add_channel();
6034 if (channel == NULL)
6035 goto failed;
6036
6037 job = job_alloc();
6038 if (job == NULL)
6039 goto failed;
6040 if (argvar->v_type == VAR_STRING)
6041 {
6042 int argc;
6043
6044 build_argv_from_string(cmd, &job->jv_argv, &argc);
6045 }
6046 else
6047 {
6048 int argc;
6049
6050 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6051 }
6052
6053 if (opt->jo_set & JO_IN_BUF)
6054 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6055
6056 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6057 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
6058 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
6059 | CREATE_DEFAULT_ERROR_MODE,
6060 env_wchar, cwd_wchar,
6061 &term->tl_siex.StartupInfo, &proc_info))
6062 goto failed;
6063
6064 CloseHandle(i_theirs);
6065 CloseHandle(o_theirs);
6066
6067 channel_set_pipes(channel,
6068 (sock_T)i_ours,
6069 (sock_T)o_ours,
6070 (sock_T)o_ours);
6071
6072 /* Write lines with CR instead of NL. */
6073 channel->ch_write_text_mode = TRUE;
6074
6075 /* Use to explicitly delete anonymous pipe handle. */
6076 channel->ch_anonymous_pipe = TRUE;
6077
6078 jo = CreateJobObject(NULL, NULL);
6079 if (jo == NULL)
6080 goto failed;
6081
6082 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6083 {
6084 /* Failed, switch the way to terminate process with TerminateProcess. */
6085 CloseHandle(jo);
6086 jo = NULL;
6087 }
6088
6089 ResumeThread(proc_info.hThread);
6090 CloseHandle(proc_info.hThread);
6091
6092 vim_free(cmd_wchar);
6093 vim_free(cmd_wchar_copy);
6094 vim_free(cwd_wchar);
6095 vim_free(env_wchar);
6096
6097 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6098 goto failed;
6099
6100#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6101 if (opt->jo_set2 & JO2_ANSI_COLORS)
6102 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6103 else
6104 init_vterm_ansi_colors(term->tl_vterm);
6105#endif
6106
6107 channel_set_job(channel, job, opt);
6108 job_set_options(job, opt);
6109
6110 job->jv_channel = channel;
6111 job->jv_proc_info = proc_info;
6112 job->jv_job_object = jo;
6113 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006114 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006115 ++job->jv_refcount;
6116 term->tl_job = job;
6117
6118 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6119 * open the file here and handle it in. opt->jo_io was changed in
6120 * setup_job_options(), use the original flags here. */
6121 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6122 {
6123 char_u *fname = opt->jo_io_name[PART_OUT];
6124
6125 ch_log(channel, "Opening output file %s", fname);
6126 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6127 if (term->tl_out_fd == NULL)
6128 semsg(_(e_notopen), fname);
6129 }
6130
6131 return OK;
6132
6133failed:
6134 ga_clear(&ga_cmd);
6135 ga_clear(&ga_env);
6136 vim_free(cmd_wchar);
6137 vim_free(cmd_wchar_copy);
6138 vim_free(cwd_wchar);
6139 if (channel != NULL)
6140 channel_clear(channel);
6141 if (job != NULL)
6142 {
6143 job->jv_channel = NULL;
6144 job_cleanup(job);
6145 }
6146 term->tl_job = NULL;
6147 if (jo != NULL)
6148 CloseHandle(jo);
6149
6150 if (term->tl_siex.lpAttributeList != NULL)
6151 {
6152 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6153 vim_free(term->tl_siex.lpAttributeList);
6154 }
6155 term->tl_siex.lpAttributeList = NULL;
6156 if (o_theirs != NULL)
6157 CloseHandle(o_theirs);
6158 if (o_ours != NULL)
6159 CloseHandle(o_ours);
6160 if (i_ours != NULL)
6161 CloseHandle(i_ours);
6162 if (i_theirs != NULL)
6163 CloseHandle(i_theirs);
6164 if (term->tl_conpty != NULL)
6165 pClosePseudoConsole(term->tl_conpty);
6166 term->tl_conpty = NULL;
6167 return FAIL;
6168}
6169
6170 static void
6171conpty_term_report_winsize(term_T *term, int rows, int cols)
6172{
6173 COORD consize;
6174
6175 consize.X = cols;
6176 consize.Y = rows;
6177 pResizePseudoConsole(term->tl_conpty, consize);
6178}
6179
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006180 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006181term_free_conpty(term_T *term)
6182{
6183 if (term->tl_siex.lpAttributeList != NULL)
6184 {
6185 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6186 vim_free(term->tl_siex.lpAttributeList);
6187 }
6188 term->tl_siex.lpAttributeList = NULL;
6189 if (term->tl_conpty != NULL)
6190 pClosePseudoConsole(term->tl_conpty);
6191 term->tl_conpty = NULL;
6192}
6193
6194 int
6195use_conpty(void)
6196{
6197 return has_conpty;
6198}
6199
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006200# ifndef PROTO
6201
6202#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6203#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006204#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006205
6206void* (*winpty_config_new)(UINT64, void*);
6207void* (*winpty_open)(void*, void*);
6208void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6209BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6210void (*winpty_config_set_mouse_mode)(void*, int);
6211void (*winpty_config_set_initial_size)(void*, int, int);
6212LPCWSTR (*winpty_conin_name)(void*);
6213LPCWSTR (*winpty_conout_name)(void*);
6214LPCWSTR (*winpty_conerr_name)(void*);
6215void (*winpty_free)(void*);
6216void (*winpty_config_free)(void*);
6217void (*winpty_spawn_config_free)(void*);
6218void (*winpty_error_free)(void*);
6219LPCWSTR (*winpty_error_msg)(void*);
6220BOOL (*winpty_set_size)(void*, int, int, void*);
6221HANDLE (*winpty_agent_process)(void*);
6222
6223#define WINPTY_DLL "winpty.dll"
6224
6225static HINSTANCE hWinPtyDLL = NULL;
6226# endif
6227
6228 static int
6229dyn_winpty_init(int verbose)
6230{
6231 int i;
6232 static struct
6233 {
6234 char *name;
6235 FARPROC *ptr;
6236 } winpty_entry[] =
6237 {
6238 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6239 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6240 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6241 {"winpty_config_set_mouse_mode",
6242 (FARPROC*)&winpty_config_set_mouse_mode},
6243 {"winpty_config_set_initial_size",
6244 (FARPROC*)&winpty_config_set_initial_size},
6245 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6246 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6247 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6248 {"winpty_free", (FARPROC*)&winpty_free},
6249 {"winpty_open", (FARPROC*)&winpty_open},
6250 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6251 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6252 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6253 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6254 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6255 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6256 {NULL, NULL}
6257 };
6258
6259 /* No need to initialize twice. */
6260 if (hWinPtyDLL)
6261 return OK;
6262 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6263 * winpty.dll. */
6264 if (*p_winptydll != NUL)
6265 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6266 if (!hWinPtyDLL)
6267 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6268 if (!hWinPtyDLL)
6269 {
6270 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006271 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006272 : (char_u *)WINPTY_DLL);
6273 return FAIL;
6274 }
6275 for (i = 0; winpty_entry[i].name != NULL
6276 && winpty_entry[i].ptr != NULL; ++i)
6277 {
6278 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6279 winpty_entry[i].name)) == NULL)
6280 {
6281 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006282 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006283 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006284 return FAIL;
6285 }
6286 }
6287
6288 return OK;
6289}
6290
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006291 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006292winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006293 term_T *term,
6294 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006295 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006296 jobopt_T *opt,
6297 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006298{
6299 WCHAR *cmd_wchar = NULL;
6300 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006301 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006302 channel_T *channel = NULL;
6303 job_T *job = NULL;
6304 DWORD error;
6305 HANDLE jo = NULL;
6306 HANDLE child_process_handle;
6307 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006308 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006309 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006310 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006311 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006312
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006313 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6314 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006315
6316 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006317 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006318 cmd = argvar->vval.v_string;
6319 }
6320 else if (argvar->v_type == VAR_LIST)
6321 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006322 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006323 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006324 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006325 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006326 if (cmd == NULL || *cmd == NUL)
6327 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006328 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006329 goto failed;
6330 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006331
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006332 term->tl_arg0_cmd = vim_strsave(cmd);
6333
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006334 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006335 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006336 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006337 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006338 if (opt->jo_cwd != NULL)
6339 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006340
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006341 win32_build_env(opt->jo_env, &ga_env, TRUE);
6342 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006343
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006344 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6345 if (term->tl_winpty_config == NULL)
6346 goto failed;
6347
6348 winpty_config_set_mouse_mode(term->tl_winpty_config,
6349 WINPTY_MOUSE_MODE_FORCE);
6350 winpty_config_set_initial_size(term->tl_winpty_config,
6351 term->tl_cols, term->tl_rows);
6352 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6353 if (term->tl_winpty == NULL)
6354 goto failed;
6355
6356 spawn_config = winpty_spawn_config_new(
6357 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6358 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6359 NULL,
6360 cmd_wchar,
6361 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006362 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006363 &winpty_err);
6364 if (spawn_config == NULL)
6365 goto failed;
6366
6367 channel = add_channel();
6368 if (channel == NULL)
6369 goto failed;
6370
6371 job = job_alloc();
6372 if (job == NULL)
6373 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006374 if (argvar->v_type == VAR_STRING)
6375 {
6376 int argc;
6377
6378 build_argv_from_string(cmd, &job->jv_argv, &argc);
6379 }
6380 else
6381 {
6382 int argc;
6383
6384 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6385 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006386
6387 if (opt->jo_set & JO_IN_BUF)
6388 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6389
6390 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6391 &child_thread_handle, &error, &winpty_err))
6392 goto failed;
6393
6394 channel_set_pipes(channel,
6395 (sock_T)CreateFileW(
6396 winpty_conin_name(term->tl_winpty),
6397 GENERIC_WRITE, 0, NULL,
6398 OPEN_EXISTING, 0, NULL),
6399 (sock_T)CreateFileW(
6400 winpty_conout_name(term->tl_winpty),
6401 GENERIC_READ, 0, NULL,
6402 OPEN_EXISTING, 0, NULL),
6403 (sock_T)CreateFileW(
6404 winpty_conerr_name(term->tl_winpty),
6405 GENERIC_READ, 0, NULL,
6406 OPEN_EXISTING, 0, NULL));
6407
6408 /* Write lines with CR instead of NL. */
6409 channel->ch_write_text_mode = TRUE;
6410
6411 jo = CreateJobObject(NULL, NULL);
6412 if (jo == NULL)
6413 goto failed;
6414
6415 if (!AssignProcessToJobObject(jo, child_process_handle))
6416 {
6417 /* Failed, switch the way to terminate process with TerminateProcess. */
6418 CloseHandle(jo);
6419 jo = NULL;
6420 }
6421
6422 winpty_spawn_config_free(spawn_config);
6423 vim_free(cmd_wchar);
6424 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006425 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006426
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006427 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6428 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006429
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006430#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6431 if (opt->jo_set2 & JO2_ANSI_COLORS)
6432 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6433 else
6434 init_vterm_ansi_colors(term->tl_vterm);
6435#endif
6436
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006437 channel_set_job(channel, job, opt);
6438 job_set_options(job, opt);
6439
6440 job->jv_channel = channel;
6441 job->jv_proc_info.hProcess = child_process_handle;
6442 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6443 job->jv_job_object = jo;
6444 job->jv_status = JOB_STARTED;
6445 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006446 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006447 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006448 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006449 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006450 ++job->jv_refcount;
6451 term->tl_job = job;
6452
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006453 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6454 * open the file here and handle it in. opt->jo_io was changed in
6455 * setup_job_options(), use the original flags here. */
6456 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6457 {
6458 char_u *fname = opt->jo_io_name[PART_OUT];
6459
6460 ch_log(channel, "Opening output file %s", fname);
6461 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6462 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006463 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006464 }
6465
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006466 return OK;
6467
6468failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006469 ga_clear(&ga_cmd);
6470 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006471 vim_free(cmd_wchar);
6472 vim_free(cwd_wchar);
6473 if (spawn_config != NULL)
6474 winpty_spawn_config_free(spawn_config);
6475 if (channel != NULL)
6476 channel_clear(channel);
6477 if (job != NULL)
6478 {
6479 job->jv_channel = NULL;
6480 job_cleanup(job);
6481 }
6482 term->tl_job = NULL;
6483 if (jo != NULL)
6484 CloseHandle(jo);
6485 if (term->tl_winpty != NULL)
6486 winpty_free(term->tl_winpty);
6487 term->tl_winpty = NULL;
6488 if (term->tl_winpty_config != NULL)
6489 winpty_config_free(term->tl_winpty_config);
6490 term->tl_winpty_config = NULL;
6491 if (winpty_err != NULL)
6492 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006493 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006494 (short_u *)winpty_error_msg(winpty_err), NULL);
6495
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006496 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006497 winpty_error_free(winpty_err);
6498 }
6499 return FAIL;
6500}
6501
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006502/*
6503 * Create a new terminal of "rows" by "cols" cells.
6504 * Store a reference in "term".
6505 * Return OK or FAIL.
6506 */
6507 static int
6508term_and_job_init(
6509 term_T *term,
6510 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01006511 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006512 jobopt_T *opt,
6513 jobopt_T *orig_opt)
6514{
6515 int use_winpty = FALSE;
6516 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006517 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006518
6519 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6520 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6521
6522 if (!has_winpty && !has_conpty)
6523 // If neither is available give the errors for winpty, since when
6524 // conpty is not available it can't be installed either.
6525 return dyn_winpty_init(TRUE);
6526
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006527 if (opt->jo_tty_type != NUL)
6528 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006529
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006530 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006531 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006532 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006533 use_conpty = TRUE;
6534 else if (has_winpty)
6535 use_winpty = TRUE;
6536 // else: error
6537 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006538 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006539 {
6540 if (has_winpty)
6541 use_winpty = TRUE;
6542 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006543 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006544 {
6545 if (has_conpty)
6546 use_conpty = TRUE;
6547 else
6548 return dyn_conpty_init(TRUE);
6549 }
6550
6551 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006552 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006553
6554 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006555 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006556
6557 // error
6558 return dyn_winpty_init(TRUE);
6559}
6560
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006561 static int
6562create_pty_only(term_T *term, jobopt_T *options)
6563{
6564 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6565 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6566 char in_name[80], out_name[80];
6567 channel_T *channel = NULL;
6568
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006569 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6570 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006571
6572 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6573 GetCurrentProcessId(),
6574 curbuf->b_fnum);
6575 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6576 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6577 PIPE_UNLIMITED_INSTANCES,
6578 0, 0, NMPWAIT_NOWAIT, NULL);
6579 if (hPipeIn == INVALID_HANDLE_VALUE)
6580 goto failed;
6581
6582 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6583 GetCurrentProcessId(),
6584 curbuf->b_fnum);
6585 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6586 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6587 PIPE_UNLIMITED_INSTANCES,
6588 0, 0, 0, NULL);
6589 if (hPipeOut == INVALID_HANDLE_VALUE)
6590 goto failed;
6591
6592 ConnectNamedPipe(hPipeIn, NULL);
6593 ConnectNamedPipe(hPipeOut, NULL);
6594
6595 term->tl_job = job_alloc();
6596 if (term->tl_job == NULL)
6597 goto failed;
6598 ++term->tl_job->jv_refcount;
6599
6600 /* behave like the job is already finished */
6601 term->tl_job->jv_status = JOB_FINISHED;
6602
6603 channel = add_channel();
6604 if (channel == NULL)
6605 goto failed;
6606 term->tl_job->jv_channel = channel;
6607 channel->ch_keep_open = TRUE;
6608 channel->ch_named_pipe = TRUE;
6609
6610 channel_set_pipes(channel,
6611 (sock_T)hPipeIn,
6612 (sock_T)hPipeOut,
6613 (sock_T)hPipeOut);
6614 channel_set_job(channel, term->tl_job, options);
6615 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6616 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6617
6618 return OK;
6619
6620failed:
6621 if (hPipeIn != NULL)
6622 CloseHandle(hPipeIn);
6623 if (hPipeOut != NULL)
6624 CloseHandle(hPipeOut);
6625 return FAIL;
6626}
6627
6628/*
6629 * Free the terminal emulator part of "term".
6630 */
6631 static void
6632term_free_vterm(term_T *term)
6633{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006634 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006635 if (term->tl_winpty != NULL)
6636 winpty_free(term->tl_winpty);
6637 term->tl_winpty = NULL;
6638 if (term->tl_winpty_config != NULL)
6639 winpty_config_free(term->tl_winpty_config);
6640 term->tl_winpty_config = NULL;
6641 if (term->tl_vterm != NULL)
6642 vterm_free(term->tl_vterm);
6643 term->tl_vterm = NULL;
6644}
6645
6646/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006647 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006648 */
6649 static void
6650term_report_winsize(term_T *term, int rows, int cols)
6651{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006652 if (term->tl_conpty)
6653 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006654 if (term->tl_winpty)
6655 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6656}
6657
6658 int
6659terminal_enabled(void)
6660{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006661 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006662}
6663
6664# else
6665
6666/**************************************
6667 * 3. Unix-like implementation.
6668 */
6669
6670/*
6671 * Create a new terminal of "rows" by "cols" cells.
6672 * Start job for "cmd".
6673 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006674 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006675 * Return OK or FAIL.
6676 */
6677 static int
6678term_and_job_init(
6679 term_T *term,
6680 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006681 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006682 jobopt_T *opt,
6683 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006684{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006685 term->tl_arg0_cmd = NULL;
6686
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006687 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6688 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006689
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006690#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6691 if (opt->jo_set2 & JO2_ANSI_COLORS)
6692 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6693 else
6694 init_vterm_ansi_colors(term->tl_vterm);
6695#endif
6696
Bram Moolenaar13568252018-03-16 20:46:58 +01006697 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006698 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006699 if (term->tl_job != NULL)
6700 ++term->tl_job->jv_refcount;
6701
6702 return term->tl_job != NULL
6703 && term->tl_job->jv_channel != NULL
6704 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6705}
6706
6707 static int
6708create_pty_only(term_T *term, jobopt_T *opt)
6709{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006710 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6711 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006712
6713 term->tl_job = job_alloc();
6714 if (term->tl_job == NULL)
6715 return FAIL;
6716 ++term->tl_job->jv_refcount;
6717
6718 /* behave like the job is already finished */
6719 term->tl_job->jv_status = JOB_FINISHED;
6720
6721 return mch_create_pty_channel(term->tl_job, opt);
6722}
6723
6724/*
6725 * Free the terminal emulator part of "term".
6726 */
6727 static void
6728term_free_vterm(term_T *term)
6729{
6730 if (term->tl_vterm != NULL)
6731 vterm_free(term->tl_vterm);
6732 term->tl_vterm = NULL;
6733}
6734
6735/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006736 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006737 */
6738 static void
6739term_report_winsize(term_T *term, int rows, int cols)
6740{
6741 /* Use an ioctl() to report the new window size to the job. */
6742 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6743 {
6744 int fd = -1;
6745 int part;
6746
6747 for (part = PART_OUT; part < PART_COUNT; ++part)
6748 {
6749 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006750 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006751 break;
6752 }
6753 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6754 mch_signal_job(term->tl_job, (char_u *)"winch");
6755 }
6756}
6757
6758# endif
6759
6760#endif /* FEAT_TERMINAL */