blob: 13e32eb5d10ef2bdb14dc96b736b8064d1a805ac [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;
706 char_u *cmd;
707 char_u *tofree = NULL;
708
709 init_job_options(&opt);
710
711 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100712 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200713 {
714 char_u *p, *ep;
715
716 cmd += 2;
717 p = skiptowhite(cmd);
718 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200719 if (ep != NULL)
720 {
721 if (ep < p)
722 p = ep;
723 else
724 ep = NULL;
725 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200726
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200727# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
728 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
729 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200730 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200731 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100732 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200733 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200734 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200735 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200736 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200737 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200738 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200739 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100740 opt.jo_term_norestore = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200741 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100742 {
743 opt.jo_set2 |= JO2_TERM_KILL;
744 opt.jo_term_kill = ep + 1;
745 p = skiptowhite(cmd);
746 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200747 else if (OPTARG_HAS("api"))
748 {
749 opt.jo_set2 |= JO2_TERM_API;
750 if (ep != NULL)
751 {
752 opt.jo_term_api = ep + 1;
753 p = skiptowhite(cmd);
754 }
755 else
756 opt.jo_term_api = NULL;
757 }
758 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200759 {
760 opt.jo_set2 |= JO2_TERM_ROWS;
761 opt.jo_term_rows = atoi((char *)ep + 1);
762 p = skiptowhite(cmd);
763 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200764 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200765 {
766 opt.jo_set2 |= JO2_TERM_COLS;
767 opt.jo_term_cols = atoi((char *)ep + 1);
768 p = skiptowhite(cmd);
769 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200770 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200771 {
772 char_u *buf = NULL;
773 char_u *keys;
774
775 p = skiptowhite(cmd);
776 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200777 keys = replace_termcodes(ep + 1, &buf,
778 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200779 opt.jo_set2 |= JO2_EOF_CHARS;
780 opt.jo_eof_chars = vim_strsave(keys);
781 vim_free(buf);
782 *p = ' ';
783 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100784#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100785 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
786 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100787 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100788 int tty_type = NUL;
789
790 p = skiptowhite(cmd);
791 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
792 tty_type = 'w';
793 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
794 tty_type = 'c';
795 else
796 {
797 semsg(e_invargval, "type");
798 goto theend;
799 }
800 opt.jo_set2 |= JO2_TTY_TYPE;
801 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100802 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100803#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200804 else
805 {
806 if (*p)
807 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100808 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100809 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200810 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200811# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200812 cmd = skipwhite(p);
813 }
814 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100815 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200816 /* Make a copy of 'shell', an autocommand may change the option. */
817 tofree = cmd = vim_strsave(p_sh);
818
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100819 /* default to close when the shell exits */
820 if (opt.jo_term_finish == NUL)
821 opt.jo_term_finish = 'c';
822 }
823
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200824 if (eap->addr_count > 0)
825 {
826 /* Write lines from current buffer to the job. */
827 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
828 opt.jo_io[PART_IN] = JIO_BUFFER;
829 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
830 opt.jo_in_top = eap->line1;
831 opt.jo_in_bot = eap->line2;
832 }
833
834 argvar[0].v_type = VAR_STRING;
835 argvar[0].vval.v_string = cmd;
836 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100837 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200838 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100839
840theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200841 vim_free(opt.jo_eof_chars);
842}
843
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100844#if defined(FEAT_SESSION) || defined(PROTO)
845/*
846 * Write a :terminal command to the session file to restore the terminal in
847 * window "wp".
848 * Return FAIL if writing fails.
849 */
850 int
851term_write_session(FILE *fd, win_T *wp)
852{
853 term_T *term = wp->w_buffer->b_term;
854
855 /* Create the terminal and run the command. This is not without
856 * risk, but let's assume the user only creates a session when this
857 * will be OK. */
858 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
859 term->tl_cols, term->tl_rows) < 0)
860 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100861#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100862 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
863 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100864#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100865 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
866 return FAIL;
867
868 return put_eol(fd);
869}
870
871/*
872 * Return TRUE if "buf" has a terminal that should be restored.
873 */
874 int
875term_should_restore(buf_T *buf)
876{
877 term_T *term = buf->b_term;
878
879 return term != NULL && (term->tl_command == NULL
880 || STRCMP(term->tl_command, "NONE") != 0);
881}
882#endif
883
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200884/*
885 * Free the scrollback buffer for "term".
886 */
887 static void
888free_scrollback(term_T *term)
889{
890 int i;
891
892 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
893 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
894 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100895 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
896 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
897 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200898}
899
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100900
901// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200902static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100903
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200904/*
905 * Free a terminal and everything it refers to.
906 * Kills the job if there is one.
907 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100908 * The actual terminal structure is freed later in free_unused_terminals(),
909 * because callbacks may wipe out a buffer while the terminal is still
910 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200911 */
912 void
913free_terminal(buf_T *buf)
914{
915 term_T *term = buf->b_term;
916 term_T *tp;
917
918 if (term == NULL)
919 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100920
921 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200922 if (first_term == term)
923 first_term = term->tl_next;
924 else
925 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
926 if (tp->tl_next == term)
927 {
928 tp->tl_next = term->tl_next;
929 break;
930 }
931
932 if (term->tl_job != NULL)
933 {
934 if (term->tl_job->jv_status != JOB_ENDED
935 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100936 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200937 job_stop(term->tl_job, NULL, "kill");
938 job_unref(term->tl_job);
939 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100940 term->tl_next = terminals_to_free;
941 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200942
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200943 buf->b_term = NULL;
944 if (in_terminal_loop == term)
945 in_terminal_loop = NULL;
946}
947
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100948 void
949free_unused_terminals()
950{
951 while (terminals_to_free != NULL)
952 {
953 term_T *term = terminals_to_free;
954
955 terminals_to_free = term->tl_next;
956
957 free_scrollback(term);
958
959 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200960 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100961 vim_free(term->tl_title);
962#ifdef FEAT_SESSION
963 vim_free(term->tl_command);
964#endif
965 vim_free(term->tl_kill);
966 vim_free(term->tl_status_text);
967 vim_free(term->tl_opencmd);
968 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100969 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100970#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100971 if (term->tl_out_fd != NULL)
972 fclose(term->tl_out_fd);
973#endif
974 vim_free(term->tl_cursor_color);
975 vim_free(term);
976 }
977}
978
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200979/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100980 * Get the part that is connected to the tty. Normally this is PART_IN, but
981 * when writing buffer lines to the job it can be another. This makes it
982 * possible to do "1,5term vim -".
983 */
984 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200985get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100986{
987#ifdef UNIX
988 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
989 int i;
990
991 for (i = 0; i < 3; ++i)
992 {
993 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
994
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +0100995 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100996 return parts[i];
997 }
998#endif
999 return PART_IN;
1000}
1001
1002/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001003 * Write job output "msg[len]" to the vterm.
1004 */
1005 static void
1006term_write_job_output(term_T *term, char_u *msg, size_t len)
1007{
1008 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001009 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001010
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001011 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001012
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001013 /* flush vterm buffer when vterm responded to control sequence */
1014 if (prevlen != vterm_output_get_buffer_current(vterm))
1015 {
1016 char buf[KEY_BUF_LEN];
1017 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1018
1019 if (curlen > 0)
1020 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1021 (char_u *)buf, (int)curlen, NULL);
1022 }
1023
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001024 /* this invokes the damage callbacks */
1025 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1026}
1027
1028 static void
1029update_cursor(term_T *term, int redraw)
1030{
1031 if (term->tl_normal_mode)
1032 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001033#ifdef FEAT_GUI
1034 if (term->tl_system)
1035 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1036 term->tl_cursor_pos.col);
1037 else
1038#endif
1039 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001040 if (redraw)
1041 {
1042 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1043 cursor_on();
1044 out_flush();
1045#ifdef FEAT_GUI
1046 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001047 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001048 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001049 gui_mch_flush();
1050 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001051#endif
1052 }
1053}
1054
1055/*
1056 * Invoked when "msg" output from a job was received. Write it to the terminal
1057 * of "buffer".
1058 */
1059 void
1060write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1061{
1062 size_t len = STRLEN(msg);
1063 term_T *term = buffer->b_term;
1064
Bram Moolenaar4f974752019-02-17 17:44:42 +01001065#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001066 /* Win32: Cannot redirect output of the job, intercept it here and write to
1067 * the file. */
1068 if (term->tl_out_fd != NULL)
1069 {
1070 ch_log(channel, "Writing %d bytes to output file", (int)len);
1071 fwrite(msg, len, 1, term->tl_out_fd);
1072 return;
1073 }
1074#endif
1075
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001076 if (term->tl_vterm == NULL)
1077 {
1078 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1079 return;
1080 }
1081 ch_log(channel, "writing %d bytes to terminal", (int)len);
1082 term_write_job_output(term, msg, len);
1083
Bram Moolenaar13568252018-03-16 20:46:58 +01001084#ifdef FEAT_GUI
1085 if (term->tl_system)
1086 {
1087 /* show system output, scrolling up the screen as needed */
1088 update_system_term(term);
1089 update_cursor(term, TRUE);
1090 }
1091 else
1092#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001093 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
1094 * contents, thus no screen update is needed. */
1095 if (!term->tl_normal_mode)
1096 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001097 // Don't use update_screen() when editing the command line, it gets
1098 // cleared.
1099 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001100 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001101 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001102 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001103 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001104 /* update_screen() can be slow, check the terminal wasn't closed
1105 * already */
1106 if (buffer == curbuf && curbuf->b_term != NULL)
1107 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001108 }
1109 else
1110 redraw_after_callback(TRUE);
1111 }
1112}
1113
1114/*
1115 * Send a mouse position and click to the vterm
1116 */
1117 static int
1118term_send_mouse(VTerm *vterm, int button, int pressed)
1119{
1120 VTermModifier mod = VTERM_MOD_NONE;
1121
1122 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001123 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001124 if (button != 0)
1125 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001126 return TRUE;
1127}
1128
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001129static int enter_mouse_col = -1;
1130static int enter_mouse_row = -1;
1131
1132/*
1133 * Handle a mouse click, drag or release.
1134 * Return TRUE when a mouse event is sent to the terminal.
1135 */
1136 static int
1137term_mouse_click(VTerm *vterm, int key)
1138{
1139#if defined(FEAT_CLIPBOARD)
1140 /* For modeless selection mouse drag and release events are ignored, unless
1141 * they are preceded with a mouse down event */
1142 static int ignore_drag_release = TRUE;
1143 VTermMouseState mouse_state;
1144
1145 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1146 if (mouse_state.flags == 0)
1147 {
1148 /* Terminal is not using the mouse, use modeless selection. */
1149 switch (key)
1150 {
1151 case K_LEFTDRAG:
1152 case K_LEFTRELEASE:
1153 case K_RIGHTDRAG:
1154 case K_RIGHTRELEASE:
1155 /* Ignore drag and release events when the button-down wasn't
1156 * seen before. */
1157 if (ignore_drag_release)
1158 {
1159 int save_mouse_col, save_mouse_row;
1160
1161 if (enter_mouse_col < 0)
1162 break;
1163
1164 /* mouse click in the window gave us focus, handle that
1165 * click now */
1166 save_mouse_col = mouse_col;
1167 save_mouse_row = mouse_row;
1168 mouse_col = enter_mouse_col;
1169 mouse_row = enter_mouse_row;
1170 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1171 mouse_col = save_mouse_col;
1172 mouse_row = save_mouse_row;
1173 }
1174 /* FALLTHROUGH */
1175 case K_LEFTMOUSE:
1176 case K_RIGHTMOUSE:
1177 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1178 ignore_drag_release = TRUE;
1179 else
1180 ignore_drag_release = FALSE;
1181 /* Should we call mouse_has() here? */
1182 if (clip_star.available)
1183 {
1184 int button, is_click, is_drag;
1185
1186 button = get_mouse_button(KEY2TERMCAP1(key),
1187 &is_click, &is_drag);
1188 if (mouse_model_popup() && button == MOUSE_LEFT
1189 && (mod_mask & MOD_MASK_SHIFT))
1190 {
1191 /* Translate shift-left to right button. */
1192 button = MOUSE_RIGHT;
1193 mod_mask &= ~MOD_MASK_SHIFT;
1194 }
1195 clip_modeless(button, is_click, is_drag);
1196 }
1197 break;
1198
1199 case K_MIDDLEMOUSE:
1200 if (clip_star.available)
1201 insert_reg('*', TRUE);
1202 break;
1203 }
1204 enter_mouse_col = -1;
1205 return FALSE;
1206 }
1207#endif
1208 enter_mouse_col = -1;
1209
1210 switch (key)
1211 {
1212 case K_LEFTMOUSE:
1213 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1214 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1215 case K_LEFTRELEASE:
1216 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1217 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1218 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1219 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1220 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1221 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1222 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1223 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1224 }
1225 return TRUE;
1226}
1227
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001228/*
1229 * Convert typed key "c" into bytes to send to the job.
1230 * Return the number of bytes in "buf".
1231 */
1232 static int
1233term_convert_key(term_T *term, int c, char *buf)
1234{
1235 VTerm *vterm = term->tl_vterm;
1236 VTermKey key = VTERM_KEY_NONE;
1237 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001238 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001239
1240 switch (c)
1241 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001242 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1243
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001244 /* don't use VTERM_KEY_BACKSPACE, it always
1245 * becomes 0x7f DEL */
1246 case K_BS: c = term_backspace_char; break;
1247
1248 case ESC: key = VTERM_KEY_ESCAPE; break;
1249 case K_DEL: key = VTERM_KEY_DEL; break;
1250 case K_DOWN: key = VTERM_KEY_DOWN; break;
1251 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1252 key = VTERM_KEY_DOWN; break;
1253 case K_END: key = VTERM_KEY_END; break;
1254 case K_S_END: mod = VTERM_MOD_SHIFT;
1255 key = VTERM_KEY_END; break;
1256 case K_C_END: mod = VTERM_MOD_CTRL;
1257 key = VTERM_KEY_END; break;
1258 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1259 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1260 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1261 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1262 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1263 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1264 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1265 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1266 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1267 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1268 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1269 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1270 case K_HOME: key = VTERM_KEY_HOME; break;
1271 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1272 key = VTERM_KEY_HOME; break;
1273 case K_C_HOME: mod = VTERM_MOD_CTRL;
1274 key = VTERM_KEY_HOME; break;
1275 case K_INS: key = VTERM_KEY_INS; break;
1276 case K_K0: key = VTERM_KEY_KP_0; break;
1277 case K_K1: key = VTERM_KEY_KP_1; break;
1278 case K_K2: key = VTERM_KEY_KP_2; break;
1279 case K_K3: key = VTERM_KEY_KP_3; break;
1280 case K_K4: key = VTERM_KEY_KP_4; break;
1281 case K_K5: key = VTERM_KEY_KP_5; break;
1282 case K_K6: key = VTERM_KEY_KP_6; break;
1283 case K_K7: key = VTERM_KEY_KP_7; break;
1284 case K_K8: key = VTERM_KEY_KP_8; break;
1285 case K_K9: key = VTERM_KEY_KP_9; break;
1286 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1287 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1288 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1289 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1290 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1291 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1292 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1293 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1294 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1295 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1296 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1297 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1298 case K_LEFT: key = VTERM_KEY_LEFT; break;
1299 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1300 key = VTERM_KEY_LEFT; break;
1301 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1302 key = VTERM_KEY_LEFT; break;
1303 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1304 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1305 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1306 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1307 key = VTERM_KEY_RIGHT; break;
1308 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1309 key = VTERM_KEY_RIGHT; break;
1310 case K_UP: key = VTERM_KEY_UP; break;
1311 case K_S_UP: mod = VTERM_MOD_SHIFT;
1312 key = VTERM_KEY_UP; break;
1313 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001314 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1315 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001316
Bram Moolenaara42ad572017-11-16 13:08:04 +01001317 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1318 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001319 case K_MOUSELEFT: /* TODO */ return 0;
1320 case K_MOUSERIGHT: /* TODO */ return 0;
1321
1322 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001323 case K_LEFTMOUSE_NM:
1324 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001325 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001326 case K_LEFTRELEASE_NM:
1327 case K_MOUSEMOVE:
1328 case K_MIDDLEMOUSE:
1329 case K_MIDDLEDRAG:
1330 case K_MIDDLERELEASE:
1331 case K_RIGHTMOUSE:
1332 case K_RIGHTDRAG:
1333 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1334 return 0;
1335 other = TRUE;
1336 break;
1337
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001338 case K_X1MOUSE: /* TODO */ return 0;
1339 case K_X1DRAG: /* TODO */ return 0;
1340 case K_X1RELEASE: /* TODO */ return 0;
1341 case K_X2MOUSE: /* TODO */ return 0;
1342 case K_X2DRAG: /* TODO */ return 0;
1343 case K_X2RELEASE: /* TODO */ return 0;
1344
1345 case K_IGNORE: return 0;
1346 case K_NOP: return 0;
1347 case K_UNDO: return 0;
1348 case K_HELP: return 0;
1349 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1350 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1351 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1352 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1353 case K_SELECT: return 0;
1354#ifdef FEAT_GUI
1355 case K_VER_SCROLLBAR: return 0;
1356 case K_HOR_SCROLLBAR: return 0;
1357#endif
1358#ifdef FEAT_GUI_TABLINE
1359 case K_TABLINE: return 0;
1360 case K_TABMENU: return 0;
1361#endif
1362#ifdef FEAT_NETBEANS_INTG
1363 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1364#endif
1365#ifdef FEAT_DND
1366 case K_DROP: return 0;
1367#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001368 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001369 case K_PS: vterm_keyboard_start_paste(vterm);
1370 other = TRUE;
1371 break;
1372 case K_PE: vterm_keyboard_end_paste(vterm);
1373 other = TRUE;
1374 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001375 }
1376
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001377 // add modifiers for the typed key
Bram Moolenaar459fd782019-10-13 16:43:39 +02001378 if (mod_mask & MOD_MASK_SHIFT)
1379 mod |= VTERM_MOD_SHIFT;
1380 if (mod_mask & MOD_MASK_CTRL)
1381 mod |= VTERM_MOD_CTRL;
1382 if (mod_mask & (MOD_MASK_ALT | MOD_MASK_META))
1383 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001384
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001385 /*
1386 * Convert special keys to vterm keys:
1387 * - Write keys to vterm: vterm_keyboard_key()
1388 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001389 */
1390 if (key != VTERM_KEY_NONE)
1391 /* Special key, let vterm convert it. */
1392 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001393 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001394 /* Normal character, let vterm convert it. */
1395 vterm_keyboard_unichar(vterm, c, mod);
1396
1397 /* Read back the converted escape sequence. */
1398 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1399}
1400
1401/*
1402 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001403 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001404 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001405 */
1406 static int
1407term_job_running_check(term_T *term, int check_job_status)
1408{
1409 /* Also consider the job finished when the channel is closed, to avoid a
1410 * race condition when updating the title. */
1411 if (term != NULL
1412 && term->tl_job != NULL
1413 && channel_is_open(term->tl_job->jv_channel))
1414 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001415 job_T *job = term->tl_job;
1416
1417 // Careful: Checking the job status may invoked callbacks, which close
1418 // the buffer and terminate "term". However, "job" will not be freed
1419 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001420 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001421 job_status(job);
1422 return (job->jv_status == JOB_STARTED
1423 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001424 }
1425 return FALSE;
1426}
1427
1428/*
1429 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001430 */
1431 int
1432term_job_running(term_T *term)
1433{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001434 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001435}
1436
1437/*
1438 * Return TRUE if "term" has an active channel and used ":term NONE".
1439 */
1440 int
1441term_none_open(term_T *term)
1442{
1443 /* Also consider the job finished when the channel is closed, to avoid a
1444 * race condition when updating the title. */
1445 return term != NULL
1446 && term->tl_job != NULL
1447 && channel_is_open(term->tl_job->jv_channel)
1448 && term->tl_job->jv_channel->ch_keep_open;
1449}
1450
1451/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001452 * Used when exiting: kill the job in "buf" if so desired.
1453 * Return OK when the job finished.
1454 * Return FAIL when the job is still running.
1455 */
1456 int
1457term_try_stop_job(buf_T *buf)
1458{
1459 int count;
1460 char *how = (char *)buf->b_term->tl_kill;
1461
1462#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1463 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1464 {
1465 char_u buff[DIALOG_MSG_SIZE];
1466 int ret;
1467
1468 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1469 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1470 if (ret == VIM_YES)
1471 how = "kill";
1472 else if (ret == VIM_CANCEL)
1473 return FAIL;
1474 }
1475#endif
1476 if (how == NULL || *how == NUL)
1477 return FAIL;
1478
1479 job_stop(buf->b_term->tl_job, NULL, how);
1480
Bram Moolenaar9172d232019-01-29 23:06:54 +01001481 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001482 for (count = 0; count < 100; ++count)
1483 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001484 job_T *job;
1485
1486 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001487 if (!buf_valid(buf)
1488 || buf->b_term == NULL
1489 || buf->b_term->tl_job == NULL)
1490 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001491 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001492
Bram Moolenaar9172d232019-01-29 23:06:54 +01001493 // Call job_status() to update jv_status. It may cause the job to be
1494 // cleaned up but it won't be freed.
1495 job_status(job);
1496 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001497 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001498
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001499 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001500 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001501 }
1502 return FAIL;
1503}
1504
1505/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001506 * Add the last line of the scrollback buffer to the buffer in the window.
1507 */
1508 static void
1509add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1510{
1511 buf_T *buf = term->tl_buffer;
1512 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1513 linenr_T lnum = buf->b_ml.ml_line_count;
1514
Bram Moolenaar4f974752019-02-17 17:44:42 +01001515#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001516 if (!enc_utf8 && enc_codepage > 0)
1517 {
1518 WCHAR *ret = NULL;
1519 int length = 0;
1520
1521 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1522 &ret, &length);
1523 if (ret != NULL)
1524 {
1525 WideCharToMultiByte_alloc(enc_codepage, 0,
1526 ret, length, (char **)&text, &len, 0, 0);
1527 vim_free(ret);
1528 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1529 vim_free(text);
1530 }
1531 }
1532 else
1533#endif
1534 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1535 if (empty)
1536 {
1537 /* Delete the empty line that was in the empty buffer. */
1538 curbuf = buf;
1539 ml_delete(1, FALSE);
1540 curbuf = curwin->w_buffer;
1541 }
1542}
1543
1544 static void
1545cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1546{
1547 attr->width = cell->width;
1548 attr->attrs = cell->attrs;
1549 attr->fg = cell->fg;
1550 attr->bg = cell->bg;
1551}
1552
1553 static int
1554equal_celattr(cellattr_T *a, cellattr_T *b)
1555{
1556 /* Comparing the colors should be sufficient. */
1557 return a->fg.red == b->fg.red
1558 && a->fg.green == b->fg.green
1559 && a->fg.blue == b->fg.blue
1560 && a->bg.red == b->bg.red
1561 && a->bg.green == b->bg.green
1562 && a->bg.blue == b->bg.blue;
1563}
1564
Bram Moolenaard96ff162018-02-18 22:13:29 +01001565/*
1566 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1567 * line at this position. Otherwise at the end.
1568 */
1569 static int
1570add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1571{
1572 if (ga_grow(&term->tl_scrollback, 1) == OK)
1573 {
1574 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1575 + term->tl_scrollback.ga_len;
1576
1577 if (lnum > 0)
1578 {
1579 int i;
1580
1581 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1582 {
1583 *line = *(line - 1);
1584 --line;
1585 }
1586 }
1587 line->sb_cols = 0;
1588 line->sb_cells = NULL;
1589 line->sb_fill_attr = *fill_attr;
1590 ++term->tl_scrollback.ga_len;
1591 return OK;
1592 }
1593 return FALSE;
1594}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001595
1596/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001597 * Remove the terminal contents from the scrollback and the buffer.
1598 * Used before adding a new scrollback line or updating the buffer for lines
1599 * displayed in the terminal.
1600 */
1601 static void
1602cleanup_scrollback(term_T *term)
1603{
1604 sb_line_T *line;
1605 garray_T *gap;
1606
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001607 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001608 gap = &term->tl_scrollback;
1609 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1610 && gap->ga_len > 0)
1611 {
1612 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1613 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1614 vim_free(line->sb_cells);
1615 --gap->ga_len;
1616 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001617 curbuf = curwin->w_buffer;
1618 if (curbuf == term->tl_buffer)
1619 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001620}
1621
1622/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001623 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001624 */
1625 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001626update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001628 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001629 int len;
1630 int lines_skipped = 0;
1631 VTermPos pos;
1632 VTermScreenCell cell;
1633 cellattr_T fill_attr, new_fill_attr;
1634 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001635
1636 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1637 "Adding terminal window snapshot to buffer");
1638
1639 /* First remove the lines that were appended before, they might be
1640 * outdated. */
1641 cleanup_scrollback(term);
1642
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001643 screen = vterm_obtain_screen(term->tl_vterm);
1644 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001645 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1646 {
1647 len = 0;
1648 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1649 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1650 && cell.chars[0] != NUL)
1651 {
1652 len = pos.col + 1;
1653 new_fill_attr = term->tl_default_color;
1654 }
1655 else
1656 /* Assume the last attr is the filler attr. */
1657 cell2cellattr(&cell, &new_fill_attr);
1658
1659 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1660 ++lines_skipped;
1661 else
1662 {
1663 while (lines_skipped > 0)
1664 {
1665 /* Line was skipped, add an empty line. */
1666 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001667 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001668 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001669 }
1670
1671 if (len == 0)
1672 p = NULL;
1673 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001674 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001675 if ((p != NULL || len == 0)
1676 && ga_grow(&term->tl_scrollback, 1) == OK)
1677 {
1678 garray_T ga;
1679 int width;
1680 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1681 + term->tl_scrollback.ga_len;
1682
1683 ga_init2(&ga, 1, 100);
1684 for (pos.col = 0; pos.col < len; pos.col += width)
1685 {
1686 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1687 {
1688 width = 1;
1689 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1690 if (ga_grow(&ga, 1) == OK)
1691 ga.ga_len += utf_char2bytes(' ',
1692 (char_u *)ga.ga_data + ga.ga_len);
1693 }
1694 else
1695 {
1696 width = cell.width;
1697
1698 cell2cellattr(&cell, &p[pos.col]);
1699
Bram Moolenaara79fd562018-12-20 20:47:32 +01001700 // Each character can be up to 6 bytes.
1701 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001702 {
1703 int i;
1704 int c;
1705
1706 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1707 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1708 (char_u *)ga.ga_data + ga.ga_len);
1709 }
1710 }
1711 }
1712 line->sb_cols = len;
1713 line->sb_cells = p;
1714 line->sb_fill_attr = new_fill_attr;
1715 fill_attr = new_fill_attr;
1716 ++term->tl_scrollback.ga_len;
1717
1718 if (ga_grow(&ga, 1) == FAIL)
1719 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1720 else
1721 {
1722 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1723 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1724 }
1725 ga_clear(&ga);
1726 }
1727 else
1728 vim_free(p);
1729 }
1730 }
1731
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001732 // Add trailing empty lines.
1733 for (pos.row = term->tl_scrollback.ga_len;
1734 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1735 ++pos.row)
1736 {
1737 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1738 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1739 }
1740
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001741 term->tl_dirty_snapshot = FALSE;
1742#ifdef FEAT_TIMERS
1743 term->tl_timer_set = FALSE;
1744#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001745}
1746
1747/*
1748 * If needed, add the current lines of the terminal to scrollback and to the
1749 * buffer. Called after the job has ended and when switching to
1750 * Terminal-Normal mode.
1751 * When "redraw" is TRUE redraw the windows that show the terminal.
1752 */
1753 static void
1754may_move_terminal_to_buffer(term_T *term, int redraw)
1755{
1756 win_T *wp;
1757
1758 if (term->tl_vterm == NULL)
1759 return;
1760
1761 /* Update the snapshot only if something changes or the buffer does not
1762 * have all the lines. */
1763 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1764 <= term->tl_scrollback_scrolled)
1765 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001766
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001767 /* Obtain the current background color. */
1768 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1769 &term->tl_default_color.fg, &term->tl_default_color.bg);
1770
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001771 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001772 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001773 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001774 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001775 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001776 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1777 wp->w_cursor.col = 0;
1778 wp->w_valid = 0;
1779 if (wp->w_cursor.lnum >= wp->w_height)
1780 {
1781 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001782
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001783 if (wp->w_topline < min_topline)
1784 wp->w_topline = min_topline;
1785 }
1786 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001787 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001788 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001789}
1790
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001791#if defined(FEAT_TIMERS) || defined(PROTO)
1792/*
1793 * Check if any terminal timer expired. If so, copy text from the terminal to
1794 * the buffer.
1795 * Return the time until the next timer will expire.
1796 */
1797 int
1798term_check_timers(int next_due_arg, proftime_T *now)
1799{
1800 term_T *term;
1801 int next_due = next_due_arg;
1802
1803 for (term = first_term; term != NULL; term = term->tl_next)
1804 {
1805 if (term->tl_timer_set && !term->tl_normal_mode)
1806 {
1807 long this_due = proftime_time_left(&term->tl_timer_due, now);
1808
1809 if (this_due <= 1)
1810 {
1811 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001812 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001813 }
1814 else if (next_due == -1 || next_due > this_due)
1815 next_due = this_due;
1816 }
1817 }
1818
1819 return next_due;
1820}
1821#endif
1822
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001823/*
1824 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1825 * otherwise end it.
1826 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001827 static void
1828set_terminal_mode(term_T *term, int normal_mode)
1829{
1830 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001831 if (!normal_mode)
1832 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001833 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001834 if (term->tl_buffer == curbuf)
1835 maketitle();
1836}
1837
1838/*
1839 * Called after the job if finished and Terminal mode is not active:
1840 * Move the vterm contents into the scrollback buffer and free the vterm.
1841 */
1842 static void
1843cleanup_vterm(term_T *term)
1844{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001845 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001846 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001847 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001848 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001849}
1850
1851/*
1852 * Switch from Terminal-Job mode to Terminal-Normal mode.
1853 * Suspends updating the terminal window.
1854 */
1855 static void
1856term_enter_normal_mode(void)
1857{
1858 term_T *term = curbuf->b_term;
1859
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001860 set_terminal_mode(term, TRUE);
1861
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001862 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001863 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001864
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001865 /* Move the window cursor to the position of the cursor in the
1866 * terminal. */
1867 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1868 + term->tl_cursor_pos.row + 1;
1869 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001870 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1871 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001872
1873 /* Display the same lines as in the terminal. */
1874 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1875}
1876
1877/*
1878 * Returns TRUE if the current window contains a terminal and we are in
1879 * Terminal-Normal mode.
1880 */
1881 int
1882term_in_normal_mode(void)
1883{
1884 term_T *term = curbuf->b_term;
1885
1886 return term != NULL && term->tl_normal_mode;
1887}
1888
1889/*
1890 * Switch from Terminal-Normal mode to Terminal-Job mode.
1891 * Restores updating the terminal window.
1892 */
1893 void
1894term_enter_job_mode()
1895{
1896 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897
1898 set_terminal_mode(term, FALSE);
1899
1900 if (term->tl_channel_closed)
1901 cleanup_vterm(term);
1902 redraw_buf_and_status_later(curbuf, NOT_VALID);
1903}
1904
1905/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001906 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001907 * Note: while waiting a terminal may be closed and freed if the channel is
1908 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001909 */
1910 static int
1911term_vgetc()
1912{
1913 int c;
1914 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001915 int modify_other_keys =
1916 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001917
1918 State = TERMINAL;
1919 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001920#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001921 ctrl_break_was_pressed = FALSE;
1922#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001923 if (modify_other_keys)
1924 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001925 c = vgetc();
1926 got_int = FALSE;
1927 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001928 if (modify_other_keys)
1929 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001930 return c;
1931}
1932
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001933static int mouse_was_outside = FALSE;
1934
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001935/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001936 * Send keys to terminal.
1937 * Return FAIL when the key needs to be handled in Normal mode.
1938 * Return OK when the key was dropped or sent to the terminal.
1939 */
1940 int
1941send_keys_to_term(term_T *term, int c, int typed)
1942{
1943 char msg[KEY_BUF_LEN];
1944 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001945 int dragging_outside = FALSE;
1946
1947 /* Catch keys that need to be handled as in Normal mode. */
1948 switch (c)
1949 {
1950 case NUL:
1951 case K_ZERO:
1952 if (typed)
1953 stuffcharReadbuff(c);
1954 return FAIL;
1955
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001956 case K_TABLINE:
1957 stuffcharReadbuff(c);
1958 return FAIL;
1959
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001960 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001961 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001962 return FAIL;
1963
1964 case K_LEFTDRAG:
1965 case K_MIDDLEDRAG:
1966 case K_RIGHTDRAG:
1967 case K_X1DRAG:
1968 case K_X2DRAG:
1969 dragging_outside = mouse_was_outside;
1970 /* FALLTHROUGH */
1971 case K_LEFTMOUSE:
1972 case K_LEFTMOUSE_NM:
1973 case K_LEFTRELEASE:
1974 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001975 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001976 case K_MIDDLEMOUSE:
1977 case K_MIDDLERELEASE:
1978 case K_RIGHTMOUSE:
1979 case K_RIGHTRELEASE:
1980 case K_X1MOUSE:
1981 case K_X1RELEASE:
1982 case K_X2MOUSE:
1983 case K_X2RELEASE:
1984
1985 case K_MOUSEUP:
1986 case K_MOUSEDOWN:
1987 case K_MOUSELEFT:
1988 case K_MOUSERIGHT:
1989 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001990 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001991 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001992 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993 || dragging_outside)
1994 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001995 /* click or scroll outside the current window or on status line
1996 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001997 if (typed)
1998 {
1999 stuffcharReadbuff(c);
2000 mouse_was_outside = TRUE;
2001 }
2002 return FAIL;
2003 }
2004 }
2005 if (typed)
2006 mouse_was_outside = FALSE;
2007
2008 /* Convert the typed key to a sequence of bytes for the job. */
2009 len = term_convert_key(term, c, msg);
2010 if (len > 0)
2011 /* TODO: if FAIL is returned, stop? */
2012 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2013 (char_u *)msg, (int)len, NULL);
2014
2015 return OK;
2016}
2017
2018 static void
2019position_cursor(win_T *wp, VTermPos *pos)
2020{
2021 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2022 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
2023 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2024}
2025
2026/*
2027 * Handle CTRL-W "": send register contents to the job.
2028 */
2029 static void
2030term_paste_register(int prev_c UNUSED)
2031{
2032 int c;
2033 list_T *l;
2034 listitem_T *item;
2035 long reglen = 0;
2036 int type;
2037
2038#ifdef FEAT_CMDL_INFO
2039 if (add_to_showcmd(prev_c))
2040 if (add_to_showcmd('"'))
2041 out_flush();
2042#endif
2043 c = term_vgetc();
2044#ifdef FEAT_CMDL_INFO
2045 clear_showcmd();
2046#endif
2047 if (!term_use_loop())
2048 /* job finished while waiting for a character */
2049 return;
2050
2051 /* CTRL-W "= prompt for expression to evaluate. */
2052 if (c == '=' && get_expr_register() != '=')
2053 return;
2054 if (!term_use_loop())
2055 /* job finished while waiting for a character */
2056 return;
2057
2058 l = (list_T *)get_reg_contents(c, GREG_LIST);
2059 if (l != NULL)
2060 {
2061 type = get_reg_type(c, &reglen);
2062 for (item = l->lv_first; item != NULL; item = item->li_next)
2063 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002064 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002065#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002066 char_u *tmp = s;
2067
2068 if (!enc_utf8 && enc_codepage > 0)
2069 {
2070 WCHAR *ret = NULL;
2071 int length = 0;
2072
2073 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2074 (int)STRLEN(s), &ret, &length);
2075 if (ret != NULL)
2076 {
2077 WideCharToMultiByte_alloc(CP_UTF8, 0,
2078 ret, length, (char **)&s, &length, 0, 0);
2079 vim_free(ret);
2080 }
2081 }
2082#endif
2083 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2084 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002085#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002086 if (tmp != s)
2087 vim_free(s);
2088#endif
2089
2090 if (item->li_next != NULL || type == MLINE)
2091 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2092 (char_u *)"\r", 1, NULL);
2093 }
2094 list_free(l);
2095 }
2096}
2097
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002098/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002099 * Return TRUE when waiting for a character in the terminal, the cursor of the
2100 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002101 */
2102 int
2103terminal_is_active()
2104{
2105 return in_terminal_loop != NULL;
2106}
2107
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002108#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002109 cursorentry_T *
2110term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2111{
2112 term_T *term = in_terminal_loop;
2113 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002114 int id;
2115 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002116
2117 vim_memset(&entry, 0, sizeof(entry));
2118 entry.shape = entry.mshape =
2119 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2120 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2121 SHAPE_BLOCK;
2122 entry.percentage = 20;
2123 if (term->tl_cursor_blink)
2124 {
2125 entry.blinkwait = 700;
2126 entry.blinkon = 400;
2127 entry.blinkoff = 250;
2128 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002129
2130 /* The "Terminal" highlight group overrules the defaults. */
2131 id = syn_name2id((char_u *)"Terminal");
2132 if (id != 0)
2133 {
2134 syn_id2colors(id, &term_fg, &term_bg);
2135 *fg = term_bg;
2136 }
2137 else
2138 *fg = gui.back_pixel;
2139
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002140 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002141 {
2142 if (id != 0)
2143 *bg = term_fg;
2144 else
2145 *bg = gui.norm_pixel;
2146 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002147 else
2148 *bg = color_name2handle(term->tl_cursor_color);
2149 entry.name = "n";
2150 entry.used_for = SHAPE_CURSOR;
2151
2152 return &entry;
2153}
2154#endif
2155
Bram Moolenaard317b382018-02-08 22:33:31 +01002156 static void
2157may_output_cursor_props(void)
2158{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002159 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002160 || last_set_cursor_shape != desired_cursor_shape
2161 || last_set_cursor_blink != desired_cursor_blink)
2162 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002163 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002164 last_set_cursor_shape = desired_cursor_shape;
2165 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002166 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002167 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2168 /* this will restore the initial cursor style, if possible */
2169 ui_cursor_shape_forced(TRUE);
2170 else
2171 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2172 }
2173}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002174
Bram Moolenaard317b382018-02-08 22:33:31 +01002175/*
2176 * Set the cursor color and shape, if not last set to these.
2177 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002178 static void
2179may_set_cursor_props(term_T *term)
2180{
2181#ifdef FEAT_GUI
2182 /* For the GUI the cursor properties are obtained with
2183 * term_get_cursor_shape(). */
2184 if (gui.in_use)
2185 return;
2186#endif
2187 if (in_terminal_loop == term)
2188 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002189 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002190 desired_cursor_shape = term->tl_cursor_shape;
2191 desired_cursor_blink = term->tl_cursor_blink;
2192 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002193 }
2194}
2195
Bram Moolenaard317b382018-02-08 22:33:31 +01002196/*
2197 * Reset the desired cursor properties and restore them when needed.
2198 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002199 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002200prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002201{
2202#ifdef FEAT_GUI
2203 if (gui.in_use)
2204 return;
2205#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002206 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002207 desired_cursor_shape = -1;
2208 desired_cursor_blink = -1;
2209 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002210}
2211
2212/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002213 * Returns TRUE if the current window contains a terminal and we are sending
2214 * keys to the job.
2215 * If "check_job_status" is TRUE update the job status.
2216 */
2217 static int
2218term_use_loop_check(int check_job_status)
2219{
2220 term_T *term = curbuf->b_term;
2221
2222 return term != NULL
2223 && !term->tl_normal_mode
2224 && term->tl_vterm != NULL
2225 && term_job_running_check(term, check_job_status);
2226}
2227
2228/*
2229 * Returns TRUE if the current window contains a terminal and we are sending
2230 * keys to the job.
2231 */
2232 int
2233term_use_loop(void)
2234{
2235 return term_use_loop_check(FALSE);
2236}
2237
2238/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002239 * Called when entering a window with the mouse. If this is a terminal window
2240 * we may want to change state.
2241 */
2242 void
2243term_win_entered()
2244{
2245 term_T *term = curbuf->b_term;
2246
2247 if (term != NULL)
2248 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002249 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002250 {
2251 reset_VIsual_and_resel();
2252 if (State & INSERT)
2253 stop_insert_mode = TRUE;
2254 }
2255 mouse_was_outside = FALSE;
2256 enter_mouse_col = mouse_col;
2257 enter_mouse_row = mouse_row;
2258 }
2259}
2260
2261/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262 * Wait for input and send it to the job.
2263 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2264 * when there is no more typahead.
2265 * Return when the start of a CTRL-W command is typed or anything else that
2266 * should be handled as a Normal mode command.
2267 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2268 * the terminal was closed.
2269 */
2270 int
2271terminal_loop(int blocking)
2272{
2273 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002274 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002275 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002276 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002277#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002278 int tty_fd = curbuf->b_term->tl_job->jv_channel
2279 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002280#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002281 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002282
2283 /* Remember the terminal we are sending keys to. However, the terminal
2284 * might be closed while waiting for a character, e.g. typing "exit" in a
2285 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2286 * stored reference. */
2287 in_terminal_loop = curbuf->b_term;
2288
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002289 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002290 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002291 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002292 if (termwinkey == Ctrl_W)
2293 termwinkey = 0;
2294 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002295 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2296 may_set_cursor_props(curbuf->b_term);
2297
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002298 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002299 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002300#ifdef FEAT_GUI
2301 if (!curbuf->b_term->tl_system)
2302#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002303 // TODO: skip screen update when handling a sequence of keys.
2304 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002305 while (must_redraw != 0)
2306 if (update_screen(0) == FAIL)
2307 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002308 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002309 /* job finished while redrawing */
2310 break;
2311
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002312 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002313 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002314
2315 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002316 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002317 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002318 /* Job finished while waiting for a character. Push back the
2319 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002320 if (c != K_IGNORE)
2321 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002322 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002323 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002324 if (c == K_IGNORE)
2325 continue;
2326
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002327 // vgetc may not include CTRL in the key when modify_other_keys is set.
2328 raw_c = c;
2329 if ((mod_mask & MOD_MASK_CTRL)
2330 && ((c >= '`' && c <= 0x7f)
2331 || (c >= '@' && c <= '_')))
2332 c &= 0x1f;
2333
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002334#ifdef UNIX
2335 /*
2336 * The shell or another program may change the tty settings. Getting
2337 * them for every typed character is a bit of overhead, but it's needed
2338 * for the first character typed, e.g. when Vim starts in a shell.
2339 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002340 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002341 {
2342 ttyinfo_T info;
2343
2344 /* Get the current backspace character of the pty. */
2345 if (get_tty_info(tty_fd, &info) == OK)
2346 term_backspace_char = info.backspace;
2347 }
2348#endif
2349
Bram Moolenaar4f974752019-02-17 17:44:42 +01002350#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002351 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2352 * Use CTRL-BREAK to kill the job. */
2353 if (ctrl_break_was_pressed)
2354 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2355#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002356 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002357 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002358 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002359#ifdef FEAT_GUI
2360 && !curbuf->b_term->tl_system
2361#endif
2362 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002363 {
2364 int prev_c = c;
2365
2366#ifdef FEAT_CMDL_INFO
2367 if (add_to_showcmd(c))
2368 out_flush();
2369#endif
2370 c = term_vgetc();
2371#ifdef FEAT_CMDL_INFO
2372 clear_showcmd();
2373#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002374 if (!term_use_loop_check(TRUE)
2375 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002376 /* job finished while waiting for a character */
2377 break;
2378
2379 if (prev_c == Ctrl_BSL)
2380 {
2381 if (c == Ctrl_N)
2382 {
2383 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2384 term_enter_normal_mode();
2385 ret = FAIL;
2386 goto theend;
2387 }
2388 /* Send both keys to the terminal. */
2389 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2390 }
2391 else if (c == Ctrl_C)
2392 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002393 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002394 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2395 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002396 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002397 {
2398 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002399 /* "'termwinkey' .": send 'termwinkey' to the job */
2400 c = termwinkey == 0 ? Ctrl_W : termwinkey;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002401 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002402 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002403 {
2404 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2405 c = Ctrl_BSL;
2406 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002407 else if (c == 'N')
2408 {
2409 /* CTRL-W N : go to Terminal-Normal mode. */
2410 term_enter_normal_mode();
2411 ret = FAIL;
2412 goto theend;
2413 }
2414 else if (c == '"')
2415 {
2416 term_paste_register(prev_c);
2417 continue;
2418 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002419 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002420 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002421 char_u buf[MB_MAXBYTES + 2];
2422
2423 // Put the command into the typeahead buffer, when using the
2424 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2425 buf[0] = Ctrl_W;
2426 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2427 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002428 ret = OK;
2429 goto theend;
2430 }
2431 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002432# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002433 if (!enc_utf8 && has_mbyte && c >= 0x80)
2434 {
2435 WCHAR wc;
2436 char_u mb[3];
2437
2438 mb[0] = (unsigned)c >> 8;
2439 mb[1] = c;
2440 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2441 c = wc;
2442 }
2443# endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002444 if (send_keys_to_term(curbuf->b_term, raw_c, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002445 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002446 if (c == K_MOUSEMOVE)
2447 /* We are sure to come back here, don't reset the cursor color
2448 * and shape to avoid flickering. */
2449 restore_cursor = FALSE;
2450
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002451 ret = OK;
2452 goto theend;
2453 }
2454 }
2455 ret = FAIL;
2456
2457theend:
2458 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002459 if (restore_cursor)
2460 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002461
2462 /* Move a snapshot of the screen contents to the buffer, so that completion
2463 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002464 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2465 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002466
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002467 return ret;
2468}
2469
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002470 static void
2471may_toggle_cursor(term_T *term)
2472{
2473 if (in_terminal_loop == term)
2474 {
2475 if (term->tl_cursor_visible)
2476 cursor_on();
2477 else
2478 cursor_off();
2479 }
2480}
2481
2482/*
2483 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002484 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002485 */
2486 static int
2487color2index(VTermColor *color, int fg, int *boldp)
2488{
2489 int red = color->red;
2490 int blue = color->blue;
2491 int green = color->green;
2492
Bram Moolenaar46359e12017-11-29 22:33:38 +01002493 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002494 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002495 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002496 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002497 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002498 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002499 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002500 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2501 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2502 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002503 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002504 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2505 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2506 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2507 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2508 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2509 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2510 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2511 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2512 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2513 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2514 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002515 }
2516 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002517
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002518 if (t_colors >= 256)
2519 {
2520 if (red == blue && red == green)
2521 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002522 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002523 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002524 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2525 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2526 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002527 int i;
2528
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002529 if (red < 5)
2530 return 17; /* 00/00/00 */
2531 if (red > 245) /* ff/ff/ff */
2532 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002533 for (i = 0; i < 23; ++i)
2534 if (red < cutoff[i])
2535 return i + 233;
2536 return 256;
2537 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002538 {
2539 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2540 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002541
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002542 /* 216-color cube */
2543 for (ri = 0; ri < 5; ++ri)
2544 if (red < cutoff[ri])
2545 break;
2546 for (gi = 0; gi < 5; ++gi)
2547 if (green < cutoff[gi])
2548 break;
2549 for (bi = 0; bi < 5; ++bi)
2550 if (blue < cutoff[bi])
2551 break;
2552 return 17 + ri * 36 + gi * 6 + bi;
2553 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002554 }
2555 return 0;
2556}
2557
2558/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002559 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002560 */
2561 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002562vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002563{
2564 int attr = 0;
2565
2566 if (cellattrs.bold)
2567 attr |= HL_BOLD;
2568 if (cellattrs.underline)
2569 attr |= HL_UNDERLINE;
2570 if (cellattrs.italic)
2571 attr |= HL_ITALIC;
2572 if (cellattrs.strike)
2573 attr |= HL_STRIKETHROUGH;
2574 if (cellattrs.reverse)
2575 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002576 return attr;
2577}
2578
2579/*
2580 * Store Vterm attributes in "cell" from highlight flags.
2581 */
2582 static void
2583hl2vtermAttr(int attr, cellattr_T *cell)
2584{
2585 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2586 if (attr & HL_BOLD)
2587 cell->attrs.bold = 1;
2588 if (attr & HL_UNDERLINE)
2589 cell->attrs.underline = 1;
2590 if (attr & HL_ITALIC)
2591 cell->attrs.italic = 1;
2592 if (attr & HL_STRIKETHROUGH)
2593 cell->attrs.strike = 1;
2594 if (attr & HL_INVERSE)
2595 cell->attrs.reverse = 1;
2596}
2597
2598/*
2599 * Convert the attributes of a vterm cell into an attribute index.
2600 */
2601 static int
2602cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2603{
2604 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002605
2606#ifdef FEAT_GUI
2607 if (gui.in_use)
2608 {
2609 guicolor_T fg, bg;
2610
2611 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2612 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2613 return get_gui_attr_idx(attr, fg, bg);
2614 }
2615 else
2616#endif
2617#ifdef FEAT_TERMGUICOLORS
2618 if (p_tgc)
2619 {
2620 guicolor_T fg, bg;
2621
2622 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2623 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2624
2625 return get_tgc_attr_idx(attr, fg, bg);
2626 }
2627 else
2628#endif
2629 {
2630 int bold = MAYBE;
2631 int fg = color2index(&cellfg, TRUE, &bold);
2632 int bg = color2index(&cellbg, FALSE, &bold);
2633
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002634 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002635 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002636 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002637 if (fg == 0 && term_default_cterm_fg >= 0)
2638 fg = term_default_cterm_fg + 1;
2639 if (bg == 0 && term_default_cterm_bg >= 0)
2640 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002641 }
2642
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002643 /* with 8 colors set the bold attribute to get a bright foreground */
2644 if (bold == TRUE)
2645 attr |= HL_BOLD;
2646 return get_cterm_attr_idx(attr, fg, bg);
2647 }
2648 return 0;
2649}
2650
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002651 static void
2652set_dirty_snapshot(term_T *term)
2653{
2654 term->tl_dirty_snapshot = TRUE;
2655#ifdef FEAT_TIMERS
2656 if (!term->tl_normal_mode)
2657 {
2658 /* Update the snapshot after 100 msec of not getting updates. */
2659 profile_setlimit(100L, &term->tl_timer_due);
2660 term->tl_timer_set = TRUE;
2661 }
2662#endif
2663}
2664
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002665 static int
2666handle_damage(VTermRect rect, void *user)
2667{
2668 term_T *term = (term_T *)user;
2669
2670 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2671 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002672 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002673 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002674 return 1;
2675}
2676
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002677 static void
2678term_scroll_up(term_T *term, int start_row, int count)
2679{
2680 win_T *wp;
2681 VTermColor fg, bg;
2682 VTermScreenCellAttrs attr;
2683 int clear_attr;
2684
2685 /* Set the color to clear lines with. */
2686 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2687 &fg, &bg);
2688 vim_memset(&attr, 0, sizeof(attr));
2689 clear_attr = cell2attr(attr, fg, bg);
2690
2691 FOR_ALL_WINDOWS(wp)
2692 {
2693 if (wp->w_buffer == term->tl_buffer)
2694 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2695 }
2696}
2697
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002698 static int
2699handle_moverect(VTermRect dest, VTermRect src, void *user)
2700{
2701 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002702 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002703
2704 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002705 * redrawing the text. But avoid doing this multiple times, postpone until
2706 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002707 if (dest.start_col == src.start_col
2708 && dest.end_col == src.end_col
2709 && dest.start_row < src.start_row)
2710 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002711 if (dest.start_row == 0)
2712 term->tl_postponed_scroll += count;
2713 else
2714 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002715 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002716
2717 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2718 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002719 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002720
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002721 /* Note sure if the scrolling will work correctly, let's do a complete
2722 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002723 redraw_buf_later(term->tl_buffer, NOT_VALID);
2724 return 1;
2725}
2726
2727 static int
2728handle_movecursor(
2729 VTermPos pos,
2730 VTermPos oldpos UNUSED,
2731 int visible,
2732 void *user)
2733{
2734 term_T *term = (term_T *)user;
2735 win_T *wp;
2736
2737 term->tl_cursor_pos = pos;
2738 term->tl_cursor_visible = visible;
2739
2740 FOR_ALL_WINDOWS(wp)
2741 {
2742 if (wp->w_buffer == term->tl_buffer)
2743 position_cursor(wp, &pos);
2744 }
2745 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2746 {
2747 may_toggle_cursor(term);
2748 update_cursor(term, term->tl_cursor_visible);
2749 }
2750
2751 return 1;
2752}
2753
2754 static int
2755handle_settermprop(
2756 VTermProp prop,
2757 VTermValue *value,
2758 void *user)
2759{
2760 term_T *term = (term_T *)user;
2761
2762 switch (prop)
2763 {
2764 case VTERM_PROP_TITLE:
2765 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002766 // a blank title isn't useful, make it empty, so that "running" is
2767 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002768 if (*skipwhite((char_u *)value->string) == NUL)
2769 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002770 // Same as blank
2771 else if (term->tl_arg0_cmd != NULL
2772 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2773 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2774 term->tl_title = NULL;
2775 // Empty corrupted data of winpty
2776 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2777 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002778#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002779 else if (!enc_utf8 && enc_codepage > 0)
2780 {
2781 WCHAR *ret = NULL;
2782 int length = 0;
2783
2784 MultiByteToWideChar_alloc(CP_UTF8, 0,
2785 (char*)value->string, (int)STRLEN(value->string),
2786 &ret, &length);
2787 if (ret != NULL)
2788 {
2789 WideCharToMultiByte_alloc(enc_codepage, 0,
2790 ret, length, (char**)&term->tl_title,
2791 &length, 0, 0);
2792 vim_free(ret);
2793 }
2794 }
2795#endif
2796 else
2797 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002798 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002799 if (term == curbuf->b_term)
2800 maketitle();
2801 break;
2802
2803 case VTERM_PROP_CURSORVISIBLE:
2804 term->tl_cursor_visible = value->boolean;
2805 may_toggle_cursor(term);
2806 out_flush();
2807 break;
2808
2809 case VTERM_PROP_CURSORBLINK:
2810 term->tl_cursor_blink = value->boolean;
2811 may_set_cursor_props(term);
2812 break;
2813
2814 case VTERM_PROP_CURSORSHAPE:
2815 term->tl_cursor_shape = value->number;
2816 may_set_cursor_props(term);
2817 break;
2818
2819 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002820 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002821 may_set_cursor_props(term);
2822 break;
2823
2824 case VTERM_PROP_ALTSCREEN:
2825 /* TODO: do anything else? */
2826 term->tl_using_altscreen = value->boolean;
2827 break;
2828
2829 default:
2830 break;
2831 }
2832 /* Always return 1, otherwise vterm doesn't store the value internally. */
2833 return 1;
2834}
2835
2836/*
2837 * The job running in the terminal resized the terminal.
2838 */
2839 static int
2840handle_resize(int rows, int cols, void *user)
2841{
2842 term_T *term = (term_T *)user;
2843 win_T *wp;
2844
2845 term->tl_rows = rows;
2846 term->tl_cols = cols;
2847 if (term->tl_vterm_size_changed)
2848 /* Size was set by vterm_set_size(), don't set the window size. */
2849 term->tl_vterm_size_changed = FALSE;
2850 else
2851 {
2852 FOR_ALL_WINDOWS(wp)
2853 {
2854 if (wp->w_buffer == term->tl_buffer)
2855 {
2856 win_setheight_win(rows, wp);
2857 win_setwidth_win(cols, wp);
2858 }
2859 }
2860 redraw_buf_later(term->tl_buffer, NOT_VALID);
2861 }
2862 return 1;
2863}
2864
2865/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002866 * If the number of lines that are stored goes over 'termscrollback' then
2867 * delete the first 10%.
2868 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2869 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002870 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002871 static void
2872limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002873{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002874 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002875 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002876 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002877 int i;
2878
2879 curbuf = term->tl_buffer;
2880 for (i = 0; i < todo; ++i)
2881 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002882 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
2883 if (update_buffer)
2884 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002885 }
2886 curbuf = curwin->w_buffer;
2887
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002888 gap->ga_len -= todo;
2889 mch_memmove(gap->ga_data,
2890 (sb_line_T *)gap->ga_data + todo,
2891 sizeof(sb_line_T) * gap->ga_len);
2892 if (update_buffer)
2893 term->tl_scrollback_scrolled -= todo;
2894 }
2895}
2896
2897/*
2898 * Handle a line that is pushed off the top of the screen.
2899 */
2900 static int
2901handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2902{
2903 term_T *term = (term_T *)user;
2904 garray_T *gap;
2905 int update_buffer;
2906
2907 if (term->tl_normal_mode)
2908 {
2909 // In Terminal-Normal mode the user interacts with the buffer, thus we
2910 // must not change it. Postpone adding the scrollback lines.
2911 gap = &term->tl_scrollback_postponed;
2912 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002913 }
2914 else
2915 {
2916 // First remove the lines that were appended before, the pushed line
2917 // goes above it.
2918 cleanup_scrollback(term);
2919 gap = &term->tl_scrollback;
2920 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002921 }
2922
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002923 limit_scrollback(term, gap, update_buffer);
2924
2925 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002926 {
2927 cellattr_T *p = NULL;
2928 int len = 0;
2929 int i;
2930 int c;
2931 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002932 int text_len;
2933 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002934 sb_line_T *line;
2935 garray_T ga;
2936 cellattr_T fill_attr = term->tl_default_color;
2937
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002938 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002939 for (i = 0; i < cols; ++i)
2940 if (cells[i].chars[0] != 0)
2941 len = i + 1;
2942 else
2943 cell2cellattr(&cells[i], &fill_attr);
2944
2945 ga_init2(&ga, 1, 100);
2946 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002947 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002948 if (p != NULL)
2949 {
2950 for (col = 0; col < len; col += cells[col].width)
2951 {
2952 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2953 {
2954 ga.ga_len = 0;
2955 break;
2956 }
2957 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2958 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2959 (char_u *)ga.ga_data + ga.ga_len);
2960 cell2cellattr(&cells[col], &p[col]);
2961 }
2962 }
2963 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002964 {
2965 if (update_buffer)
2966 text = (char_u *)"";
2967 else
2968 text = vim_strsave((char_u *)"");
2969 text_len = 0;
2970 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002971 else
2972 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002973 text = ga.ga_data;
2974 text_len = ga.ga_len;
2975 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002976 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002977 if (update_buffer)
2978 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002979
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002980 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002981 line->sb_cols = len;
2982 line->sb_cells = p;
2983 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002984 if (update_buffer)
2985 {
2986 line->sb_text = NULL;
2987 ++term->tl_scrollback_scrolled;
2988 ga_clear(&ga); // free the text
2989 }
2990 else
2991 {
2992 line->sb_text = text;
2993 ga_init(&ga); // text is kept in tl_scrollback_postponed
2994 }
2995 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002996 }
2997 return 0; /* ignored */
2998}
2999
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003000/*
3001 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3002 * received and stored in tl_scrollback_postponed.
3003 */
3004 static void
3005handle_postponed_scrollback(term_T *term)
3006{
3007 int i;
3008
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003009 if (term->tl_scrollback_postponed.ga_len == 0)
3010 return;
3011 ch_log(NULL, "Moving postponed scrollback to scrollback");
3012
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003013 // First remove the lines that were appended before, the pushed lines go
3014 // above it.
3015 cleanup_scrollback(term);
3016
3017 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3018 {
3019 char_u *text;
3020 sb_line_T *pp_line;
3021 sb_line_T *line;
3022
3023 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3024 break;
3025 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3026
3027 text = pp_line->sb_text;
3028 if (text == NULL)
3029 text = (char_u *)"";
3030 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3031 vim_free(pp_line->sb_text);
3032
3033 line = (sb_line_T *)term->tl_scrollback.ga_data
3034 + term->tl_scrollback.ga_len;
3035 line->sb_cols = pp_line->sb_cols;
3036 line->sb_cells = pp_line->sb_cells;
3037 line->sb_fill_attr = pp_line->sb_fill_attr;
3038 line->sb_text = NULL;
3039 ++term->tl_scrollback_scrolled;
3040 ++term->tl_scrollback.ga_len;
3041 }
3042
3043 ga_clear(&term->tl_scrollback_postponed);
3044 limit_scrollback(term, &term->tl_scrollback, TRUE);
3045}
3046
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003047static VTermScreenCallbacks screen_callbacks = {
3048 handle_damage, /* damage */
3049 handle_moverect, /* moverect */
3050 handle_movecursor, /* movecursor */
3051 handle_settermprop, /* settermprop */
3052 NULL, /* bell */
3053 handle_resize, /* resize */
3054 handle_pushline, /* sb_pushline */
3055 NULL /* sb_popline */
3056};
3057
3058/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003059 * Do the work after the channel of a terminal was closed.
3060 * Must be called only when updating_screen is FALSE.
3061 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3062 */
3063 static int
3064term_after_channel_closed(term_T *term)
3065{
3066 /* Unless in Terminal-Normal mode: clear the vterm. */
3067 if (!term->tl_normal_mode)
3068 {
3069 int fnum = term->tl_buffer->b_fnum;
3070
3071 cleanup_vterm(term);
3072
3073 if (term->tl_finish == TL_FINISH_CLOSE)
3074 {
3075 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003076 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003077
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003078 // If this is the last normal window: exit Vim.
3079 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3080 {
3081 exarg_T ea;
3082
3083 vim_memset(&ea, 0, sizeof(ea));
3084 ex_quit(&ea);
3085 return TRUE;
3086 }
3087
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003088 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003089 ch_log(NULL, "terminal job finished, closing window");
3090 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003091 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003092 if (curwin == aucmd_win)
3093 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003094 if (do_set_w_closing)
3095 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003096 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003097 if (do_set_w_closing)
3098 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003099 aucmd_restbuf(&aco);
3100 return TRUE;
3101 }
3102 if (term->tl_finish == TL_FINISH_OPEN
3103 && term->tl_buffer->b_nwindows == 0)
3104 {
3105 char buf[50];
3106
3107 /* TODO: use term_opencmd */
3108 ch_log(NULL, "terminal job finished, opening window");
3109 vim_snprintf(buf, sizeof(buf),
3110 term->tl_opencmd == NULL
3111 ? "botright sbuf %d"
3112 : (char *)term->tl_opencmd, fnum);
3113 do_cmdline_cmd((char_u *)buf);
3114 }
3115 else
3116 ch_log(NULL, "terminal job finished");
3117 }
3118
3119 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3120 return FALSE;
3121}
3122
3123/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003124 * Called when a channel has been closed.
3125 * If this was a channel for a terminal window then finish it up.
3126 */
3127 void
3128term_channel_closed(channel_T *ch)
3129{
3130 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003131 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003132 int did_one = FALSE;
3133
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003134 for (term = first_term; term != NULL; term = next_term)
3135 {
3136 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003137 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003138 {
3139 term->tl_channel_closed = TRUE;
3140 did_one = TRUE;
3141
Bram Moolenaard23a8232018-02-10 18:45:26 +01003142 VIM_CLEAR(term->tl_title);
3143 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003144#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003145 if (term->tl_out_fd != NULL)
3146 {
3147 fclose(term->tl_out_fd);
3148 term->tl_out_fd = NULL;
3149 }
3150#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003151
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003152 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003154 /* Cannot open or close windows now. Can happen when
3155 * 'lazyredraw' is set. */
3156 term->tl_channel_recently_closed = TRUE;
3157 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003158 }
3159
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003160 if (term_after_channel_closed(term))
3161 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003162 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003163 }
3164
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003165 if (did_one)
3166 {
3167 redraw_statuslines();
3168
3169 /* Need to break out of vgetc(). */
3170 ins_char_typebuf(K_IGNORE);
3171 typebuf_was_filled = TRUE;
3172
3173 term = curbuf->b_term;
3174 if (term != NULL)
3175 {
3176 if (term->tl_job == ch->ch_job)
3177 maketitle();
3178 update_cursor(term, term->tl_cursor_visible);
3179 }
3180 }
3181}
3182
3183/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003184 * To be called after resetting updating_screen: handle any terminal where the
3185 * channel was closed.
3186 */
3187 void
3188term_check_channel_closed_recently()
3189{
3190 term_T *term;
3191 term_T *next_term;
3192
3193 for (term = first_term; term != NULL; term = next_term)
3194 {
3195 next_term = term->tl_next;
3196 if (term->tl_channel_recently_closed)
3197 {
3198 term->tl_channel_recently_closed = FALSE;
3199 if (term_after_channel_closed(term))
3200 // start over, the list may have changed
3201 next_term = first_term;
3202 }
3203 }
3204}
3205
3206/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003207 * Fill one screen line from a line of the terminal.
3208 * Advances "pos" to past the last column.
3209 */
3210 static void
3211term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3212{
3213 int off = screen_get_current_line_off();
3214
3215 for (pos->col = 0; pos->col < max_col; )
3216 {
3217 VTermScreenCell cell;
3218 int c;
3219
3220 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3221 vim_memset(&cell, 0, sizeof(cell));
3222
3223 c = cell.chars[0];
3224 if (c == NUL)
3225 {
3226 ScreenLines[off] = ' ';
3227 if (enc_utf8)
3228 ScreenLinesUC[off] = NUL;
3229 }
3230 else
3231 {
3232 if (enc_utf8)
3233 {
3234 int i;
3235
3236 /* composing chars */
3237 for (i = 0; i < Screen_mco
3238 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3239 {
3240 ScreenLinesC[i][off] = cell.chars[i + 1];
3241 if (cell.chars[i + 1] == 0)
3242 break;
3243 }
3244 if (c >= 0x80 || (Screen_mco > 0
3245 && ScreenLinesC[0][off] != 0))
3246 {
3247 ScreenLines[off] = ' ';
3248 ScreenLinesUC[off] = c;
3249 }
3250 else
3251 {
3252 ScreenLines[off] = c;
3253 ScreenLinesUC[off] = NUL;
3254 }
3255 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003256#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003257 else if (has_mbyte && c >= 0x80)
3258 {
3259 char_u mb[MB_MAXBYTES+1];
3260 WCHAR wc = c;
3261
3262 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3263 (char*)mb, 2, 0, 0) > 1)
3264 {
3265 ScreenLines[off] = mb[0];
3266 ScreenLines[off + 1] = mb[1];
3267 cell.width = mb_ptr2cells(mb);
3268 }
3269 else
3270 ScreenLines[off] = c;
3271 }
3272#endif
3273 else
3274 ScreenLines[off] = c;
3275 }
3276 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3277
3278 ++pos->col;
3279 ++off;
3280 if (cell.width == 2)
3281 {
3282 if (enc_utf8)
3283 ScreenLinesUC[off] = NUL;
3284
3285 /* don't set the second byte to NUL for a DBCS encoding, it
3286 * has been set above */
3287 if (enc_utf8 || !has_mbyte)
3288 ScreenLines[off] = NUL;
3289
3290 ++pos->col;
3291 ++off;
3292 }
3293 }
3294}
3295
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003296#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003297 static void
3298update_system_term(term_T *term)
3299{
3300 VTermPos pos;
3301 VTermScreen *screen;
3302
3303 if (term->tl_vterm == NULL)
3304 return;
3305 screen = vterm_obtain_screen(term->tl_vterm);
3306
3307 /* Scroll up to make more room for terminal lines if needed. */
3308 while (term->tl_toprow > 0
3309 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3310 {
3311 int save_p_more = p_more;
3312
3313 p_more = FALSE;
3314 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003315 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003316 p_more = save_p_more;
3317 --term->tl_toprow;
3318 }
3319
3320 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3321 && pos.row < Rows; ++pos.row)
3322 {
3323 if (pos.row < term->tl_rows)
3324 {
3325 int max_col = MIN(Columns, term->tl_cols);
3326
3327 term_line2screenline(screen, &pos, max_col);
3328 }
3329 else
3330 pos.col = 0;
3331
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003332 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003333 }
3334
3335 term->tl_dirty_row_start = MAX_ROW;
3336 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003337}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003338#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003339
3340/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003341 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3342 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003343 * Terminal-Normal mode.
3344 */
3345 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003346term_do_update_window(win_T *wp)
3347{
3348 term_T *term = wp->w_buffer->b_term;
3349
3350 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3351}
3352
3353/*
3354 * Called to update a window that contains an active terminal.
3355 */
3356 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357term_update_window(win_T *wp)
3358{
3359 term_T *term = wp->w_buffer->b_term;
3360 VTerm *vterm;
3361 VTermScreen *screen;
3362 VTermState *state;
3363 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003364 int rows, cols;
3365 int newrows, newcols;
3366 int minsize;
3367 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003368
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003369 vterm = term->tl_vterm;
3370 screen = vterm_obtain_screen(vterm);
3371 state = vterm_obtain_state(vterm);
3372
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003373 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3374 * SOME_VALID only redraw what was marked dirty. */
3375 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003376 {
3377 term->tl_dirty_row_start = 0;
3378 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003379
3380 if (term->tl_postponed_scroll > 0
3381 && term->tl_postponed_scroll < term->tl_rows / 3)
3382 /* Scrolling is usually faster than redrawing, when there are only
3383 * a few lines to scroll. */
3384 term_scroll_up(term, 0, term->tl_postponed_scroll);
3385 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003386 }
3387
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003388 /*
3389 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003390 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003391 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003392 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003393
Bram Moolenaar498c2562018-04-15 23:45:15 +02003394 newrows = 99999;
3395 newcols = 99999;
3396 FOR_ALL_WINDOWS(twp)
3397 {
3398 /* When more than one window shows the same terminal, use the
3399 * smallest size. */
3400 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003401 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003402 newrows = MIN(newrows, twp->w_height);
3403 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003404 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003405 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003406 if (newrows == 99999 || newcols == 99999)
3407 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003408 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3409 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3410
3411 if (term->tl_rows != newrows || term->tl_cols != newcols)
3412 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003413 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003414 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003415 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003416 newrows);
3417 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003418
3419 // Updating the terminal size will cause the snapshot to be cleared.
3420 // When not in terminal_loop() we need to restore it.
3421 if (term != in_terminal_loop)
3422 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003423 }
3424
3425 /* The cursor may have been moved when resizing. */
3426 vterm_state_get_cursorpos(state, &pos);
3427 position_cursor(wp, &pos);
3428
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003429 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3430 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003431 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003432 if (pos.row < term->tl_rows)
3433 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003434 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003435
Bram Moolenaar13568252018-03-16 20:46:58 +01003436 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003437 }
3438 else
3439 pos.col = 0;
3440
Bram Moolenaarf118d482018-03-13 13:14:00 +01003441 screen_line(wp->w_winrow + pos.row
3442#ifdef FEAT_MENU
3443 + winbar_height(wp)
3444#endif
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003445 , wp->w_wincol, pos.col, wp->w_width, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003446 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003447 term->tl_dirty_row_start = MAX_ROW;
3448 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003449}
3450
3451/*
3452 * Return TRUE if "wp" is a terminal window where the job has finished.
3453 */
3454 int
3455term_is_finished(buf_T *buf)
3456{
3457 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3458}
3459
3460/*
3461 * Return TRUE if "wp" is a terminal window where the job has finished or we
3462 * are in Terminal-Normal mode, thus we show the buffer contents.
3463 */
3464 int
3465term_show_buffer(buf_T *buf)
3466{
3467 term_T *term = buf->b_term;
3468
3469 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3470}
3471
3472/*
3473 * The current buffer is going to be changed. If there is terminal
3474 * highlighting remove it now.
3475 */
3476 void
3477term_change_in_curbuf(void)
3478{
3479 term_T *term = curbuf->b_term;
3480
3481 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3482 {
3483 free_scrollback(term);
3484 redraw_buf_later(term->tl_buffer, NOT_VALID);
3485
3486 /* The buffer is now like a normal buffer, it cannot be easily
3487 * abandoned when changed. */
3488 set_string_option_direct((char_u *)"buftype", -1,
3489 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3490 }
3491}
3492
3493/*
3494 * Get the screen attribute for a position in the buffer.
3495 * Use a negative "col" to get the filler background color.
3496 */
3497 int
3498term_get_attr(buf_T *buf, linenr_T lnum, int col)
3499{
3500 term_T *term = buf->b_term;
3501 sb_line_T *line;
3502 cellattr_T *cellattr;
3503
3504 if (lnum > term->tl_scrollback.ga_len)
3505 cellattr = &term->tl_default_color;
3506 else
3507 {
3508 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3509 if (col < 0 || col >= line->sb_cols)
3510 cellattr = &line->sb_fill_attr;
3511 else
3512 cellattr = line->sb_cells + col;
3513 }
3514 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3515}
3516
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003517/*
3518 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003519 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003520 */
3521 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003522cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003523{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003524 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003525}
3526
3527/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003528 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003529 */
3530 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003531init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003532{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003533 VTermColor *fg, *bg;
3534 int fgval, bgval;
3535 int id;
3536
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003537 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3538 term->tl_default_color.width = 1;
3539 fg = &term->tl_default_color.fg;
3540 bg = &term->tl_default_color.bg;
3541
3542 /* Vterm uses a default black background. Set it to white when
3543 * 'background' is "light". */
3544 if (*p_bg == 'l')
3545 {
3546 fgval = 0;
3547 bgval = 255;
3548 }
3549 else
3550 {
3551 fgval = 255;
3552 bgval = 0;
3553 }
3554 fg->red = fg->green = fg->blue = fgval;
3555 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003556 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003557
3558 /* The "Terminal" highlight group overrules the defaults. */
3559 id = syn_name2id((char_u *)"Terminal");
3560
Bram Moolenaar46359e12017-11-29 22:33:38 +01003561 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003562#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3563 if (0
3564# ifdef FEAT_GUI
3565 || gui.in_use
3566# endif
3567# ifdef FEAT_TERMGUICOLORS
3568 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003569# ifdef FEAT_VTP
3570 /* Finally get INVALCOLOR on this execution path */
3571 || (!p_tgc && t_colors >= 256)
3572# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003573# endif
3574 )
3575 {
3576 guicolor_T fg_rgb = INVALCOLOR;
3577 guicolor_T bg_rgb = INVALCOLOR;
3578
3579 if (id != 0)
3580 syn_id2colors(id, &fg_rgb, &bg_rgb);
3581
3582# ifdef FEAT_GUI
3583 if (gui.in_use)
3584 {
3585 if (fg_rgb == INVALCOLOR)
3586 fg_rgb = gui.norm_pixel;
3587 if (bg_rgb == INVALCOLOR)
3588 bg_rgb = gui.back_pixel;
3589 }
3590# ifdef FEAT_TERMGUICOLORS
3591 else
3592# endif
3593# endif
3594# ifdef FEAT_TERMGUICOLORS
3595 {
3596 if (fg_rgb == INVALCOLOR)
3597 fg_rgb = cterm_normal_fg_gui_color;
3598 if (bg_rgb == INVALCOLOR)
3599 bg_rgb = cterm_normal_bg_gui_color;
3600 }
3601# endif
3602 if (fg_rgb != INVALCOLOR)
3603 {
3604 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3605
3606 fg->red = (unsigned)(rgb >> 16);
3607 fg->green = (unsigned)(rgb >> 8) & 255;
3608 fg->blue = (unsigned)rgb & 255;
3609 }
3610 if (bg_rgb != INVALCOLOR)
3611 {
3612 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3613
3614 bg->red = (unsigned)(rgb >> 16);
3615 bg->green = (unsigned)(rgb >> 8) & 255;
3616 bg->blue = (unsigned)rgb & 255;
3617 }
3618 }
3619 else
3620#endif
3621 if (id != 0 && t_colors >= 16)
3622 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003623 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003624 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003625 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003626 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003627 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003628 else
3629 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003630#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003631 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003632#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003633
3634 /* In an MS-Windows console we know the normal colors. */
3635 if (cterm_normal_fg_color > 0)
3636 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003637 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003638# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3639# ifdef VIMDLL
3640 if (!gui.in_use)
3641# endif
3642 {
3643 tmp = fg->red;
3644 fg->red = fg->blue;
3645 fg->blue = tmp;
3646 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003647# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003648 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003649# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003650 else
3651 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003652# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003653
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003654 if (cterm_normal_bg_color > 0)
3655 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003656 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003657# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3658# ifdef VIMDLL
3659 if (!gui.in_use)
3660# endif
3661 {
3662 tmp = fg->red;
3663 fg->red = fg->blue;
3664 fg->blue = tmp;
3665 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003666# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003667 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003668# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003669 else
3670 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003671# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003672 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003673}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003674
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003675#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3676/*
3677 * Set the 16 ANSI colors from array of RGB values
3678 */
3679 static void
3680set_vterm_palette(VTerm *vterm, long_u *rgb)
3681{
3682 int index = 0;
3683 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003684
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003685 for (; index < 16; index++)
3686 {
3687 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003688
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003689 color.red = (unsigned)(rgb[index] >> 16);
3690 color.green = (unsigned)(rgb[index] >> 8) & 255;
3691 color.blue = (unsigned)rgb[index] & 255;
3692 vterm_state_set_palette_color(state, index, &color);
3693 }
3694}
3695
3696/*
3697 * Set the ANSI color palette from a list of colors
3698 */
3699 static int
3700set_ansi_colors_list(VTerm *vterm, list_T *list)
3701{
3702 int n = 0;
3703 long_u rgb[16];
3704 listitem_T *li = list->lv_first;
3705
3706 for (; li != NULL && n < 16; li = li->li_next, n++)
3707 {
3708 char_u *color_name;
3709 guicolor_T guicolor;
3710
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003711 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003712 if (color_name == NULL)
3713 return FAIL;
3714
3715 guicolor = GUI_GET_COLOR(color_name);
3716 if (guicolor == INVALCOLOR)
3717 return FAIL;
3718
3719 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3720 }
3721
3722 if (n != 16 || li != NULL)
3723 return FAIL;
3724
3725 set_vterm_palette(vterm, rgb);
3726
3727 return OK;
3728}
3729
3730/*
3731 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3732 */
3733 static void
3734init_vterm_ansi_colors(VTerm *vterm)
3735{
3736 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3737
3738 if (var != NULL
3739 && (var->di_tv.v_type != VAR_LIST
3740 || var->di_tv.vval.v_list == NULL
3741 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003742 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003743}
3744#endif
3745
Bram Moolenaar52acb112018-03-18 19:20:22 +01003746/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003747 * Handles a "drop" command from the job in the terminal.
3748 * "item" is the file name, "item->li_next" may have options.
3749 */
3750 static void
3751handle_drop_command(listitem_T *item)
3752{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003753 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003754 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003755 int bufnr;
3756 win_T *wp;
3757 tabpage_T *tp;
3758 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003759 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003760
3761 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3762 FOR_ALL_TAB_WINDOWS(tp, wp)
3763 {
3764 if (wp->w_buffer->b_fnum == bufnr)
3765 {
3766 /* buffer is in a window already, go there */
3767 goto_tabpage_win(tp, wp);
3768 return;
3769 }
3770 }
3771
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003772 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003773
3774 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3775 && opt_item->li_tv.vval.v_dict != NULL)
3776 {
3777 dict_T *dict = opt_item->li_tv.vval.v_dict;
3778 char_u *p;
3779
Bram Moolenaar8f667172018-12-14 15:38:31 +01003780 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003781 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003782 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003783 if (p != NULL)
3784 {
3785 if (check_ff_value(p) == FAIL)
3786 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3787 else
3788 ea.force_ff = *p;
3789 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003790 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003791 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003792 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003793 if (p != NULL)
3794 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003795 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003796 if (ea.cmd != NULL)
3797 {
3798 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3799 ea.force_enc = 11;
3800 tofree = ea.cmd;
3801 }
3802 }
3803
Bram Moolenaar8f667172018-12-14 15:38:31 +01003804 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003805 if (p != NULL)
3806 get_bad_opt(p, &ea);
3807
3808 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3809 ea.force_bin = FORCE_BIN;
3810 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3811 ea.force_bin = FORCE_BIN;
3812 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3813 ea.force_bin = FORCE_NOBIN;
3814 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3815 ea.force_bin = FORCE_NOBIN;
3816 }
3817
3818 /* open in new window, like ":split fname" */
3819 if (ea.cmd == NULL)
3820 ea.cmd = (char_u *)"split";
3821 ea.arg = fname;
3822 ea.cmdidx = CMD_split;
3823 ex_splitview(&ea);
3824
3825 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003826}
3827
3828/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003829 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
3830 */
3831 static int
3832is_permitted_term_api(char_u *func, char_u *pat)
3833{
3834 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
3835}
3836
3837/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003838 * Handles a function call from the job running in a terminal.
3839 * "item" is the function name, "item->li_next" has the arguments.
3840 */
3841 static void
3842handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3843{
3844 char_u *func;
3845 typval_T argvars[2];
3846 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003847 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003848
3849 if (item->li_next == NULL)
3850 {
3851 ch_log(channel, "Missing function arguments for call");
3852 return;
3853 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003854 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003855
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003856 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003857 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003858 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003859 return;
3860 }
3861
3862 argvars[0].v_type = VAR_NUMBER;
3863 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3864 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003865 vim_memset(&funcexe, 0, sizeof(funcexe));
3866 funcexe.firstline = 1L;
3867 funcexe.lastline = 1L;
3868 funcexe.evaluate = TRUE;
3869 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003870 {
3871 clear_tv(&rettv);
3872 ch_log(channel, "Function %s called", func);
3873 }
3874 else
3875 ch_log(channel, "Calling function %s failed", func);
3876}
3877
3878/*
3879 * Called by libvterm when it cannot recognize an OSC sequence.
3880 * We recognize a terminal API command.
3881 */
3882 static int
3883parse_osc(const char *command, size_t cmdlen, void *user)
3884{
3885 term_T *term = (term_T *)user;
3886 js_read_T reader;
3887 typval_T tv;
3888 channel_T *channel = term->tl_job == NULL ? NULL
3889 : term->tl_job->jv_channel;
3890
3891 /* We recognize only OSC 5 1 ; {command} */
3892 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3893 return 0; /* not handled */
3894
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003895 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003896 if (reader.js_buf == NULL)
3897 return 1;
3898 reader.js_fill = NULL;
3899 reader.js_used = 0;
3900 if (json_decode(&reader, &tv, 0) == OK
3901 && tv.v_type == VAR_LIST
3902 && tv.vval.v_list != NULL)
3903 {
3904 listitem_T *item = tv.vval.v_list->lv_first;
3905
3906 if (item == NULL)
3907 ch_log(channel, "Missing command");
3908 else
3909 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003910 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003911
Bram Moolenaara997b452018-04-17 23:24:06 +02003912 /* Make sure an invoked command doesn't delete the buffer (and the
3913 * terminal) under our fingers. */
3914 ++term->tl_buffer->b_locked;
3915
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003916 item = item->li_next;
3917 if (item == NULL)
3918 ch_log(channel, "Missing argument for %s", cmd);
3919 else if (STRCMP(cmd, "drop") == 0)
3920 handle_drop_command(item);
3921 else if (STRCMP(cmd, "call") == 0)
3922 handle_call_command(term, channel, item);
3923 else
3924 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003925 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003926 }
3927 }
3928 else
3929 ch_log(channel, "Invalid JSON received");
3930
3931 vim_free(reader.js_buf);
3932 clear_tv(&tv);
3933 return 1;
3934}
3935
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003936/*
3937 * Called by libvterm when it cannot recognize a CSI sequence.
3938 * We recognize the window position report.
3939 */
3940 static int
3941parse_csi(
3942 const char *leader UNUSED,
3943 const long args[],
3944 int argcount,
3945 const char *intermed UNUSED,
3946 char command,
3947 void *user)
3948{
3949 term_T *term = (term_T *)user;
3950 char buf[100];
3951 int len;
3952 int x = 0;
3953 int y = 0;
3954 win_T *wp;
3955
3956 // We recognize only CSI 13 t
3957 if (command != 't' || argcount != 1 || args[0] != 13)
3958 return 0; // not handled
3959
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003960 // When getting the window position is not possible or it fails it results
3961 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02003962#if defined(FEAT_GUI) \
3963 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
3964 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003965 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003966#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003967
3968 FOR_ALL_WINDOWS(wp)
3969 if (wp->w_buffer == term->tl_buffer)
3970 break;
3971 if (wp != NULL)
3972 {
3973#ifdef FEAT_GUI
3974 if (gui.in_use)
3975 {
3976 x += wp->w_wincol * gui.char_width;
3977 y += W_WINROW(wp) * gui.char_height;
3978 }
3979 else
3980#endif
3981 {
3982 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003983 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003984 x += wp->w_wincol * 7;
3985 y += W_WINROW(wp) * 10;
3986 }
3987 }
3988
3989 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
3990 channel_send(term->tl_job->jv_channel, get_tty_part(term),
3991 (char_u *)buf, len, NULL);
3992 return 1;
3993}
3994
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003995static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003996 NULL, // text
3997 NULL, // control
3998 NULL, // escape
3999 parse_csi, // csi
4000 parse_osc, // osc
4001 NULL, // dcs
4002 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004003};
4004
4005/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004006 * Use Vim's allocation functions for vterm so profiling works.
4007 */
4008 static void *
4009vterm_malloc(size_t size, void *data UNUSED)
4010{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004011 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004012}
4013
4014 static void
4015vterm_memfree(void *ptr, void *data UNUSED)
4016{
4017 vim_free(ptr);
4018}
4019
4020static VTermAllocatorFunctions vterm_allocator = {
4021 &vterm_malloc,
4022 &vterm_memfree
4023};
4024
4025/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004026 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004027 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004028 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004029 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004030create_vterm(term_T *term, int rows, int cols)
4031{
4032 VTerm *vterm;
4033 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004034 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004035 VTermValue value;
4036
Bram Moolenaar756ef112018-04-10 12:04:27 +02004037 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004038 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004039 if (vterm == NULL)
4040 return FAIL;
4041
4042 // Allocate screen and state here, so we can bail out if that fails.
4043 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004044 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004045 if (state == NULL || screen == NULL)
4046 {
4047 vterm_free(vterm);
4048 return FAIL;
4049 }
4050
Bram Moolenaar52acb112018-03-18 19:20:22 +01004051 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
4052 /* TODO: depends on 'encoding'. */
4053 vterm_set_utf8(vterm, 1);
4054
4055 init_default_colors(term);
4056
4057 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004058 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004059 &term->tl_default_color.fg,
4060 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004061
Bram Moolenaar9e587872019-05-13 20:27:23 +02004062 if (t_colors < 16)
4063 // Less than 16 colors: assume that bold means using a bright color for
4064 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004065 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4066
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004067 /* Required to initialize most things. */
4068 vterm_screen_reset(screen, 1 /* hard */);
4069
4070 /* Allow using alternate screen. */
4071 vterm_screen_enable_altscreen(screen, 1);
4072
4073 /* For unix do not use a blinking cursor. In an xterm this causes the
4074 * cursor to blink if it's blinking in the xterm.
4075 * For Windows we respect the system wide setting. */
Bram Moolenaar4f974752019-02-17 17:44:42 +01004076#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004077 if (GetCaretBlinkTime() == INFINITE)
4078 value.boolean = 0;
4079 else
4080 value.boolean = 1;
4081#else
4082 value.boolean = 0;
4083#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004084 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4085 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004086
4087 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004088}
4089
4090/*
4091 * Return the text to show for the buffer name and status.
4092 */
4093 char_u *
4094term_get_status_text(term_T *term)
4095{
4096 if (term->tl_status_text == NULL)
4097 {
4098 char_u *txt;
4099 size_t len;
4100
4101 if (term->tl_normal_mode)
4102 {
4103 if (term_job_running(term))
4104 txt = (char_u *)_("Terminal");
4105 else
4106 txt = (char_u *)_("Terminal-finished");
4107 }
4108 else if (term->tl_title != NULL)
4109 txt = term->tl_title;
4110 else if (term_none_open(term))
4111 txt = (char_u *)_("active");
4112 else if (term_job_running(term))
4113 txt = (char_u *)_("running");
4114 else
4115 txt = (char_u *)_("finished");
4116 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004117 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004118 if (term->tl_status_text != NULL)
4119 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4120 term->tl_buffer->b_fname, txt);
4121 }
4122 return term->tl_status_text;
4123}
4124
4125/*
4126 * Mark references in jobs of terminals.
4127 */
4128 int
4129set_ref_in_term(int copyID)
4130{
4131 int abort = FALSE;
4132 term_T *term;
4133 typval_T tv;
4134
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004135 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004136 if (term->tl_job != NULL)
4137 {
4138 tv.v_type = VAR_JOB;
4139 tv.vval.v_job = term->tl_job;
4140 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4141 }
4142 return abort;
4143}
4144
4145/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004146 * Cache "Terminal" highlight group colors.
4147 */
4148 void
4149set_terminal_default_colors(int cterm_fg, int cterm_bg)
4150{
4151 term_default_cterm_fg = cterm_fg - 1;
4152 term_default_cterm_bg = cterm_bg - 1;
4153}
4154
4155/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004156 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004157 * Returns NULL when the buffer is not for a terminal window and logs a message
4158 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004159 */
4160 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004161term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004162{
4163 buf_T *buf;
4164
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004165 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004166 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004167 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004168 --emsg_off;
4169 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004170 {
4171 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004172 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004173 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004174 return buf;
4175}
4176
Bram Moolenaard96ff162018-02-18 22:13:29 +01004177 static int
4178same_color(VTermColor *a, VTermColor *b)
4179{
4180 return a->red == b->red
4181 && a->green == b->green
4182 && a->blue == b->blue
4183 && a->ansi_index == b->ansi_index;
4184}
4185
4186 static void
4187dump_term_color(FILE *fd, VTermColor *color)
4188{
4189 fprintf(fd, "%02x%02x%02x%d",
4190 (int)color->red, (int)color->green, (int)color->blue,
4191 (int)color->ansi_index);
4192}
4193
4194/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004195 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004196 *
4197 * Each screen cell in full is:
4198 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4199 * {characters} is a space for an empty cell
4200 * For a double-width character "+" is changed to "*" and the next cell is
4201 * skipped.
4202 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4203 * when "&" use the same as the previous cell.
4204 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4205 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4206 * {color-idx} is a number from 0 to 255
4207 *
4208 * Screen cell with same width, attributes and color as the previous one:
4209 * |{characters}
4210 *
4211 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4212 *
4213 * Repeating the previous screen cell:
4214 * @{count}
4215 */
4216 void
4217f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4218{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004219 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004220 term_T *term;
4221 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004222 int max_height = 0;
4223 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004224 stat_T st;
4225 FILE *fd;
4226 VTermPos pos;
4227 VTermScreen *screen;
4228 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004229 VTermState *state;
4230 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004231
4232 if (check_restricted() || check_secure())
4233 return;
4234 if (buf == NULL)
4235 return;
4236 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004237 if (term->tl_vterm == NULL)
4238 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004239 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004240 return;
4241 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004242
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004243 if (argvars[2].v_type != VAR_UNKNOWN)
4244 {
4245 dict_T *d;
4246
4247 if (argvars[2].v_type != VAR_DICT)
4248 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004249 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004250 return;
4251 }
4252 d = argvars[2].vval.v_dict;
4253 if (d != NULL)
4254 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004255 max_height = dict_get_number(d, (char_u *)"rows");
4256 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004257 }
4258 }
4259
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004260 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004261 if (fname == NULL)
4262 return;
4263 if (mch_stat((char *)fname, &st) >= 0)
4264 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004265 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004266 return;
4267 }
4268
Bram Moolenaard96ff162018-02-18 22:13:29 +01004269 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4270 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004271 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004272 return;
4273 }
4274
4275 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4276
4277 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004278 state = vterm_obtain_state(term->tl_vterm);
4279 vterm_state_get_cursorpos(state, &cursor_pos);
4280
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004281 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4282 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004283 {
4284 int repeat = 0;
4285
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004286 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4287 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004288 {
4289 VTermScreenCell cell;
4290 int same_attr;
4291 int same_chars = TRUE;
4292 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004293 int is_cursor_pos = (pos.col == cursor_pos.col
4294 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004295
4296 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4297 vim_memset(&cell, 0, sizeof(cell));
4298
4299 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4300 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004301 int c = cell.chars[i];
4302 int pc = prev_cell.chars[i];
4303
4304 /* For the first character NUL is the same as space. */
4305 if (i == 0)
4306 {
4307 c = (c == NUL) ? ' ' : c;
4308 pc = (pc == NUL) ? ' ' : pc;
4309 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004310 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004311 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004312 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004313 break;
4314 }
4315 same_attr = vtermAttr2hl(cell.attrs)
4316 == vtermAttr2hl(prev_cell.attrs)
4317 && same_color(&cell.fg, &prev_cell.fg)
4318 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004319 if (same_chars && cell.width == prev_cell.width && same_attr
4320 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004321 {
4322 ++repeat;
4323 }
4324 else
4325 {
4326 if (repeat > 0)
4327 {
4328 fprintf(fd, "@%d", repeat);
4329 repeat = 0;
4330 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004331 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004332
4333 if (cell.chars[0] == NUL)
4334 fputs(" ", fd);
4335 else
4336 {
4337 char_u charbuf[10];
4338 int len;
4339
4340 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4341 && cell.chars[i] != NUL; ++i)
4342 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004343 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004344 fwrite(charbuf, len, 1, fd);
4345 }
4346 }
4347
4348 /* When only the characters differ we don't write anything, the
4349 * following "|", "@" or NL will indicate using the same
4350 * attributes. */
4351 if (cell.width != prev_cell.width || !same_attr)
4352 {
4353 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004354 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004355 else
4356 fputs("+", fd);
4357
4358 if (same_attr)
4359 {
4360 fputs("&", fd);
4361 }
4362 else
4363 {
4364 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4365 if (same_color(&cell.fg, &prev_cell.fg))
4366 fputs("&", fd);
4367 else
4368 {
4369 fputs("#", fd);
4370 dump_term_color(fd, &cell.fg);
4371 }
4372 if (same_color(&cell.bg, &prev_cell.bg))
4373 fputs("&", fd);
4374 else
4375 {
4376 fputs("#", fd);
4377 dump_term_color(fd, &cell.bg);
4378 }
4379 }
4380 }
4381
4382 prev_cell = cell;
4383 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004384
4385 if (cell.width == 2)
4386 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004387 }
4388 if (repeat > 0)
4389 fprintf(fd, "@%d", repeat);
4390 fputs("\n", fd);
4391 }
4392
4393 fclose(fd);
4394}
4395
4396/*
4397 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4398 */
4399 static void
4400dump_is_corrupt(garray_T *gap)
4401{
4402 ga_concat(gap, (char_u *)"CORRUPT");
4403}
4404
4405 static void
4406append_cell(garray_T *gap, cellattr_T *cell)
4407{
4408 if (ga_grow(gap, 1) == OK)
4409 {
4410 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4411 ++gap->ga_len;
4412 }
4413}
4414
4415/*
4416 * Read the dump file from "fd" and append lines to the current buffer.
4417 * Return the cell width of the longest line.
4418 */
4419 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004420read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004421{
4422 int c;
4423 garray_T ga_text;
4424 garray_T ga_cell;
4425 char_u *prev_char = NULL;
4426 int attr = 0;
4427 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004428 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004429 term_T *term = curbuf->b_term;
4430 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004431 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004432
4433 ga_init2(&ga_text, 1, 90);
4434 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4435 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004436 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004437 cursor_pos->row = -1;
4438 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004439
4440 c = fgetc(fd);
4441 for (;;)
4442 {
4443 if (c == EOF)
4444 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004445 if (c == '\r')
4446 {
4447 // DOS line endings? Ignore.
4448 c = fgetc(fd);
4449 }
4450 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004451 {
4452 /* End of a line: append it to the buffer. */
4453 if (ga_text.ga_data == NULL)
4454 dump_is_corrupt(&ga_text);
4455 if (ga_grow(&term->tl_scrollback, 1) == OK)
4456 {
4457 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4458 + term->tl_scrollback.ga_len;
4459
4460 if (max_cells < ga_cell.ga_len)
4461 max_cells = ga_cell.ga_len;
4462 line->sb_cols = ga_cell.ga_len;
4463 line->sb_cells = ga_cell.ga_data;
4464 line->sb_fill_attr = term->tl_default_color;
4465 ++term->tl_scrollback.ga_len;
4466 ga_init(&ga_cell);
4467
4468 ga_append(&ga_text, NUL);
4469 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4470 ga_text.ga_len, FALSE);
4471 }
4472 else
4473 ga_clear(&ga_cell);
4474 ga_text.ga_len = 0;
4475
4476 c = fgetc(fd);
4477 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004478 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004479 {
4480 int prev_len = ga_text.ga_len;
4481
Bram Moolenaar9271d052018-02-25 21:39:46 +01004482 if (c == '>')
4483 {
4484 if (cursor_pos->row != -1)
4485 dump_is_corrupt(&ga_text); /* duplicate cursor */
4486 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4487 cursor_pos->col = ga_cell.ga_len;
4488 }
4489
Bram Moolenaard96ff162018-02-18 22:13:29 +01004490 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4491 c = fgetc(fd);
4492 if (c != EOF)
4493 ga_append(&ga_text, c);
4494 for (;;)
4495 {
4496 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004497 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004498 || c == EOF || c == '\n')
4499 break;
4500 ga_append(&ga_text, c);
4501 }
4502
4503 /* save the character for repeating it */
4504 vim_free(prev_char);
4505 if (ga_text.ga_data != NULL)
4506 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4507 ga_text.ga_len - prev_len);
4508
Bram Moolenaar9271d052018-02-25 21:39:46 +01004509 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004510 {
4511 /* use all attributes from previous cell */
4512 }
4513 else if (c == '+' || c == '*')
4514 {
4515 int is_bg;
4516
4517 cell.width = c == '+' ? 1 : 2;
4518
4519 c = fgetc(fd);
4520 if (c == '&')
4521 {
4522 /* use same attr as previous cell */
4523 c = fgetc(fd);
4524 }
4525 else if (isdigit(c))
4526 {
4527 /* get the decimal attribute */
4528 attr = 0;
4529 while (isdigit(c))
4530 {
4531 attr = attr * 10 + (c - '0');
4532 c = fgetc(fd);
4533 }
4534 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004535
4536 /* is_bg == 0: fg, is_bg == 1: bg */
4537 for (is_bg = 0; is_bg <= 1; ++is_bg)
4538 {
4539 if (c == '&')
4540 {
4541 /* use same color as previous cell */
4542 c = fgetc(fd);
4543 }
4544 else if (c == '#')
4545 {
4546 int red, green, blue, index = 0;
4547
4548 c = fgetc(fd);
4549 red = hex2nr(c);
4550 c = fgetc(fd);
4551 red = (red << 4) + hex2nr(c);
4552 c = fgetc(fd);
4553 green = hex2nr(c);
4554 c = fgetc(fd);
4555 green = (green << 4) + hex2nr(c);
4556 c = fgetc(fd);
4557 blue = hex2nr(c);
4558 c = fgetc(fd);
4559 blue = (blue << 4) + hex2nr(c);
4560 c = fgetc(fd);
4561 if (!isdigit(c))
4562 dump_is_corrupt(&ga_text);
4563 while (isdigit(c))
4564 {
4565 index = index * 10 + (c - '0');
4566 c = fgetc(fd);
4567 }
4568
4569 if (is_bg)
4570 {
4571 cell.bg.red = red;
4572 cell.bg.green = green;
4573 cell.bg.blue = blue;
4574 cell.bg.ansi_index = index;
4575 }
4576 else
4577 {
4578 cell.fg.red = red;
4579 cell.fg.green = green;
4580 cell.fg.blue = blue;
4581 cell.fg.ansi_index = index;
4582 }
4583 }
4584 else
4585 dump_is_corrupt(&ga_text);
4586 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004587 }
4588 else
4589 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004590 }
4591 else
4592 dump_is_corrupt(&ga_text);
4593
4594 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004595 if (cell.width == 2)
4596 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004597 }
4598 else if (c == '@')
4599 {
4600 if (prev_char == NULL)
4601 dump_is_corrupt(&ga_text);
4602 else
4603 {
4604 int count = 0;
4605
4606 /* repeat previous character, get the count */
4607 for (;;)
4608 {
4609 c = fgetc(fd);
4610 if (!isdigit(c))
4611 break;
4612 count = count * 10 + (c - '0');
4613 }
4614
4615 while (count-- > 0)
4616 {
4617 ga_concat(&ga_text, prev_char);
4618 append_cell(&ga_cell, &cell);
4619 }
4620 }
4621 }
4622 else
4623 {
4624 dump_is_corrupt(&ga_text);
4625 c = fgetc(fd);
4626 }
4627 }
4628
4629 if (ga_text.ga_len > 0)
4630 {
4631 /* trailing characters after last NL */
4632 dump_is_corrupt(&ga_text);
4633 ga_append(&ga_text, NUL);
4634 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4635 ga_text.ga_len, FALSE);
4636 }
4637
4638 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004639 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004640 vim_free(prev_char);
4641
4642 return max_cells;
4643}
4644
4645/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004646 * Return an allocated string with at least "text_width" "=" characters and
4647 * "fname" inserted in the middle.
4648 */
4649 static char_u *
4650get_separator(int text_width, char_u *fname)
4651{
4652 int width = MAX(text_width, curwin->w_width);
4653 char_u *textline;
4654 int fname_size;
4655 char_u *p = fname;
4656 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004657 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004658
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004659 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004660 if (textline == NULL)
4661 return NULL;
4662
4663 fname_size = vim_strsize(fname);
4664 if (fname_size < width - 8)
4665 {
4666 /* enough room, don't use the full window width */
4667 width = MAX(text_width, fname_size + 8);
4668 }
4669 else if (fname_size > width - 8)
4670 {
4671 /* full name doesn't fit, use only the tail */
4672 p = gettail(fname);
4673 fname_size = vim_strsize(p);
4674 }
4675 /* skip characters until the name fits */
4676 while (fname_size > width - 8)
4677 {
4678 p += (*mb_ptr2len)(p);
4679 fname_size = vim_strsize(p);
4680 }
4681
4682 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4683 textline[i] = '=';
4684 textline[i++] = ' ';
4685
4686 STRCPY(textline + i, p);
4687 off = STRLEN(textline);
4688 textline[off] = ' ';
4689 for (i = 1; i < (width - fname_size) / 2; ++i)
4690 textline[off + i] = '=';
4691 textline[off + i] = NUL;
4692
4693 return textline;
4694}
4695
4696/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004697 * Common for "term_dumpdiff()" and "term_dumpload()".
4698 */
4699 static void
4700term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4701{
4702 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004703 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004704 char_u buf1[NUMBUFLEN];
4705 char_u buf2[NUMBUFLEN];
4706 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004707 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004708 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004709 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004710 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004711 char_u *textline = NULL;
4712
4713 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004714 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004715 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004716 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004717 if (fname1 == NULL || (do_diff && fname2 == NULL))
4718 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004719 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004720 return;
4721 }
4722 fd1 = mch_fopen((char *)fname1, READBIN);
4723 if (fd1 == NULL)
4724 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004725 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004726 return;
4727 }
4728 if (do_diff)
4729 {
4730 fd2 = mch_fopen((char *)fname2, READBIN);
4731 if (fd2 == NULL)
4732 {
4733 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004734 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004735 return;
4736 }
4737 }
4738
4739 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004740 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4741 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4742 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4743 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4744 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004745
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004746 if (opt.jo_term_name == NULL)
4747 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004748 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004749
Bram Moolenaar51e14382019-05-25 20:21:28 +02004750 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004751 if (fname_tofree != NULL)
4752 {
4753 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4754 opt.jo_term_name = fname_tofree;
4755 }
4756 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004757
Bram Moolenaar87abab92019-06-03 21:14:59 +02004758 if (opt.jo_bufnr_buf != NULL)
4759 {
4760 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4761
4762 // With "bufnr" argument: enter the window with this buffer and make it
4763 // empty.
4764 if (wp == NULL)
4765 semsg(_(e_invarg2), "bufnr");
4766 else
4767 {
4768 buf = curbuf;
4769 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4770 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02004771 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02004772 redraw_later(NOT_VALID);
4773 }
4774 }
4775 else
4776 // Create a new terminal window.
4777 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4778
Bram Moolenaard96ff162018-02-18 22:13:29 +01004779 if (buf != NULL && buf->b_term != NULL)
4780 {
4781 int i;
4782 linenr_T bot_lnum;
4783 linenr_T lnum;
4784 term_T *term = buf->b_term;
4785 int width;
4786 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004787 VTermPos cursor_pos1;
4788 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004789
Bram Moolenaar52acb112018-03-18 19:20:22 +01004790 init_default_colors(term);
4791
Bram Moolenaard96ff162018-02-18 22:13:29 +01004792 rettv->vval.v_number = buf->b_fnum;
4793
4794 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004795 width = read_dump_file(fd1, &cursor_pos1);
4796
4797 /* position the cursor */
4798 if (cursor_pos1.row >= 0)
4799 {
4800 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4801 coladvance(cursor_pos1.col);
4802 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004803
4804 /* Delete the empty line that was in the empty buffer. */
4805 ml_delete(1, FALSE);
4806
4807 /* For term_dumpload() we are done here. */
4808 if (!do_diff)
4809 goto theend;
4810
4811 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4812
Bram Moolenaar4a696342018-04-05 18:45:26 +02004813 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004814 if (textline == NULL)
4815 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004816 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4817 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4818 vim_free(textline);
4819
4820 textline = get_separator(width, fname2);
4821 if (textline == NULL)
4822 goto theend;
4823 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4824 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004825 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004826
4827 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004828 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004829 if (width2 > width)
4830 {
4831 vim_free(textline);
4832 textline = alloc(width2 + 1);
4833 if (textline == NULL)
4834 goto theend;
4835 width = width2;
4836 textline[width] = NUL;
4837 }
4838 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4839
4840 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4841 {
4842 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4843 {
4844 /* bottom part has fewer rows, fill with "-" */
4845 for (i = 0; i < width; ++i)
4846 textline[i] = '-';
4847 }
4848 else
4849 {
4850 char_u *line1;
4851 char_u *line2;
4852 char_u *p1;
4853 char_u *p2;
4854 int col;
4855 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4856 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4857 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4858 ->sb_cells;
4859
4860 /* Make a copy, getting the second line will invalidate it. */
4861 line1 = vim_strsave(ml_get(lnum));
4862 if (line1 == NULL)
4863 break;
4864 p1 = line1;
4865
4866 line2 = ml_get(lnum + bot_lnum);
4867 p2 = line2;
4868 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4869 {
4870 int len1 = utfc_ptr2len(p1);
4871 int len2 = utfc_ptr2len(p2);
4872
4873 textline[col] = ' ';
4874 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004875 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004876 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004877 else if (lnum == cursor_pos1.row + 1
4878 && col == cursor_pos1.col
4879 && (cursor_pos1.row != cursor_pos2.row
4880 || cursor_pos1.col != cursor_pos2.col))
4881 /* cursor in first but not in second */
4882 textline[col] = '>';
4883 else if (lnum == cursor_pos2.row + 1
4884 && col == cursor_pos2.col
4885 && (cursor_pos1.row != cursor_pos2.row
4886 || cursor_pos1.col != cursor_pos2.col))
4887 /* cursor in second but not in first */
4888 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004889 else if (cellattr1 != NULL && cellattr2 != NULL)
4890 {
4891 if ((cellattr1 + col)->width
4892 != (cellattr2 + col)->width)
4893 textline[col] = 'w';
4894 else if (!same_color(&(cellattr1 + col)->fg,
4895 &(cellattr2 + col)->fg))
4896 textline[col] = 'f';
4897 else if (!same_color(&(cellattr1 + col)->bg,
4898 &(cellattr2 + col)->bg))
4899 textline[col] = 'b';
4900 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4901 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4902 textline[col] = 'a';
4903 }
4904 p1 += len1;
4905 p2 += len2;
4906 /* TODO: handle different width */
4907 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004908
4909 while (col < width)
4910 {
4911 if (*p1 == NUL && *p2 == NUL)
4912 textline[col] = '?';
4913 else if (*p1 == NUL)
4914 {
4915 textline[col] = '+';
4916 p2 += utfc_ptr2len(p2);
4917 }
4918 else
4919 {
4920 textline[col] = '-';
4921 p1 += utfc_ptr2len(p1);
4922 }
4923 ++col;
4924 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004925
4926 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004927 }
4928 if (add_empty_scrollback(term, &term->tl_default_color,
4929 term->tl_top_diff_rows) == OK)
4930 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4931 ++bot_lnum;
4932 }
4933
4934 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4935 {
4936 /* bottom part has more rows, fill with "+" */
4937 for (i = 0; i < width; ++i)
4938 textline[i] = '+';
4939 if (add_empty_scrollback(term, &term->tl_default_color,
4940 term->tl_top_diff_rows) == OK)
4941 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4942 ++lnum;
4943 ++bot_lnum;
4944 }
4945
4946 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004947
4948 /* looks better without wrapping */
4949 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004950 }
4951
4952theend:
4953 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004954 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004955 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004956 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004957 fclose(fd2);
4958}
4959
4960/*
4961 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4962 * bottom files.
4963 * Return FAIL when this is not possible.
4964 */
4965 int
4966term_swap_diff()
4967{
4968 term_T *term = curbuf->b_term;
4969 linenr_T line_count;
4970 linenr_T top_rows;
4971 linenr_T bot_rows;
4972 linenr_T bot_start;
4973 linenr_T lnum;
4974 char_u *p;
4975 sb_line_T *sb_line;
4976
4977 if (term == NULL
4978 || !term_is_finished(curbuf)
4979 || term->tl_top_diff_rows == 0
4980 || term->tl_scrollback.ga_len == 0)
4981 return FAIL;
4982
4983 line_count = curbuf->b_ml.ml_line_count;
4984 top_rows = term->tl_top_diff_rows;
4985 bot_rows = term->tl_bot_diff_rows;
4986 bot_start = line_count - bot_rows;
4987 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4988
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004989 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01004990 for (lnum = 1; lnum <= top_rows; ++lnum)
4991 {
4992 p = vim_strsave(ml_get(1));
4993 if (p == NULL)
4994 return OK;
4995 ml_append(bot_start, p, 0, FALSE);
4996 ml_delete(1, FALSE);
4997 vim_free(p);
4998 }
4999
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005000 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005001 for (lnum = 1; lnum <= bot_rows; ++lnum)
5002 {
5003 p = vim_strsave(ml_get(bot_start + lnum));
5004 if (p == NULL)
5005 return OK;
5006 ml_delete(bot_start + lnum, FALSE);
5007 ml_append(lnum - 1, p, 0, FALSE);
5008 vim_free(p);
5009 }
5010
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005011 // move top title to bottom
5012 p = vim_strsave(ml_get(bot_rows + 1));
5013 if (p == NULL)
5014 return OK;
5015 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5016 ml_delete(bot_rows + 1, FALSE);
5017 vim_free(p);
5018
5019 // move bottom title to top
5020 p = vim_strsave(ml_get(line_count - top_rows));
5021 if (p == NULL)
5022 return OK;
5023 ml_delete(line_count - top_rows, FALSE);
5024 ml_append(bot_rows, p, 0, FALSE);
5025 vim_free(p);
5026
Bram Moolenaard96ff162018-02-18 22:13:29 +01005027 if (top_rows == bot_rows)
5028 {
5029 /* rows counts are equal, can swap cell properties */
5030 for (lnum = 0; lnum < top_rows; ++lnum)
5031 {
5032 sb_line_T temp;
5033
5034 temp = *(sb_line + lnum);
5035 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5036 *(sb_line + bot_start + lnum) = temp;
5037 }
5038 }
5039 else
5040 {
5041 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005042 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005043
5044 /* need to copy cell properties into temp memory */
5045 if (temp != NULL)
5046 {
5047 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5048 mch_memmove(term->tl_scrollback.ga_data,
5049 temp + bot_start,
5050 sizeof(sb_line_T) * bot_rows);
5051 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5052 temp + top_rows,
5053 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5054 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5055 + line_count - top_rows,
5056 temp,
5057 sizeof(sb_line_T) * top_rows);
5058 vim_free(temp);
5059 }
5060 }
5061
5062 term->tl_top_diff_rows = bot_rows;
5063 term->tl_bot_diff_rows = top_rows;
5064
5065 update_screen(NOT_VALID);
5066 return OK;
5067}
5068
5069/*
5070 * "term_dumpdiff(filename, filename, options)" function
5071 */
5072 void
5073f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5074{
5075 term_load_dump(argvars, rettv, TRUE);
5076}
5077
5078/*
5079 * "term_dumpload(filename, options)" function
5080 */
5081 void
5082f_term_dumpload(typval_T *argvars, typval_T *rettv)
5083{
5084 term_load_dump(argvars, rettv, FALSE);
5085}
5086
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005087/*
5088 * "term_getaltscreen(buf)" function
5089 */
5090 void
5091f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5092{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005093 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005094
5095 if (buf == NULL)
5096 return;
5097 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5098}
5099
5100/*
5101 * "term_getattr(attr, name)" function
5102 */
5103 void
5104f_term_getattr(typval_T *argvars, typval_T *rettv)
5105{
5106 int attr;
5107 size_t i;
5108 char_u *name;
5109
5110 static struct {
5111 char *name;
5112 int attr;
5113 } attrs[] = {
5114 {"bold", HL_BOLD},
5115 {"italic", HL_ITALIC},
5116 {"underline", HL_UNDERLINE},
5117 {"strike", HL_STRIKETHROUGH},
5118 {"reverse", HL_INVERSE},
5119 };
5120
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005121 attr = tv_get_number(&argvars[0]);
5122 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005123 if (name == NULL)
5124 return;
5125
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005126 if (attr > HL_ALL)
5127 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005128 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5129 if (STRCMP(name, attrs[i].name) == 0)
5130 {
5131 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5132 break;
5133 }
5134}
5135
5136/*
5137 * "term_getcursor(buf)" function
5138 */
5139 void
5140f_term_getcursor(typval_T *argvars, typval_T *rettv)
5141{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005142 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005143 term_T *term;
5144 list_T *l;
5145 dict_T *d;
5146
5147 if (rettv_list_alloc(rettv) == FAIL)
5148 return;
5149 if (buf == NULL)
5150 return;
5151 term = buf->b_term;
5152
5153 l = rettv->vval.v_list;
5154 list_append_number(l, term->tl_cursor_pos.row + 1);
5155 list_append_number(l, term->tl_cursor_pos.col + 1);
5156
5157 d = dict_alloc();
5158 if (d != NULL)
5159 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005160 dict_add_number(d, "visible", term->tl_cursor_visible);
5161 dict_add_number(d, "blink", blink_state_is_inverted()
5162 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5163 dict_add_number(d, "shape", term->tl_cursor_shape);
5164 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005165 list_append_dict(l, d);
5166 }
5167}
5168
5169/*
5170 * "term_getjob(buf)" function
5171 */
5172 void
5173f_term_getjob(typval_T *argvars, typval_T *rettv)
5174{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005175 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005176
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005177 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005178 {
5179 rettv->v_type = VAR_SPECIAL;
5180 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005181 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005182 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005183
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005184 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005185 rettv->vval.v_job = buf->b_term->tl_job;
5186 if (rettv->vval.v_job != NULL)
5187 ++rettv->vval.v_job->jv_refcount;
5188}
5189
5190 static int
5191get_row_number(typval_T *tv, term_T *term)
5192{
5193 if (tv->v_type == VAR_STRING
5194 && tv->vval.v_string != NULL
5195 && STRCMP(tv->vval.v_string, ".") == 0)
5196 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005197 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005198}
5199
5200/*
5201 * "term_getline(buf, row)" function
5202 */
5203 void
5204f_term_getline(typval_T *argvars, typval_T *rettv)
5205{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005206 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005207 term_T *term;
5208 int row;
5209
5210 rettv->v_type = VAR_STRING;
5211 if (buf == NULL)
5212 return;
5213 term = buf->b_term;
5214 row = get_row_number(&argvars[1], term);
5215
5216 if (term->tl_vterm == NULL)
5217 {
5218 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5219
5220 /* vterm is finished, get the text from the buffer */
5221 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5222 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5223 }
5224 else
5225 {
5226 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5227 VTermRect rect;
5228 int len;
5229 char_u *p;
5230
5231 if (row < 0 || row >= term->tl_rows)
5232 return;
5233 len = term->tl_cols * MB_MAXBYTES + 1;
5234 p = alloc(len);
5235 if (p == NULL)
5236 return;
5237 rettv->vval.v_string = p;
5238
5239 rect.start_col = 0;
5240 rect.end_col = term->tl_cols;
5241 rect.start_row = row;
5242 rect.end_row = row + 1;
5243 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5244 }
5245}
5246
5247/*
5248 * "term_getscrolled(buf)" function
5249 */
5250 void
5251f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5252{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005253 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005254
5255 if (buf == NULL)
5256 return;
5257 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5258}
5259
5260/*
5261 * "term_getsize(buf)" function
5262 */
5263 void
5264f_term_getsize(typval_T *argvars, typval_T *rettv)
5265{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005266 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005267 list_T *l;
5268
5269 if (rettv_list_alloc(rettv) == FAIL)
5270 return;
5271 if (buf == NULL)
5272 return;
5273
5274 l = rettv->vval.v_list;
5275 list_append_number(l, buf->b_term->tl_rows);
5276 list_append_number(l, buf->b_term->tl_cols);
5277}
5278
5279/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005280 * "term_setsize(buf, rows, cols)" function
5281 */
5282 void
5283f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5284{
5285 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5286 term_T *term;
5287 varnumber_T rows, cols;
5288
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005289 if (buf == NULL)
5290 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005291 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005292 return;
5293 }
5294 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005295 return;
5296 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005297 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005298 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005299 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005300 cols = cols <= 0 ? term->tl_cols : cols;
5301 vterm_set_size(term->tl_vterm, rows, cols);
5302 /* handle_resize() will resize the windows */
5303
5304 /* Get and remember the size we ended up with. Update the pty. */
5305 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5306 term_report_winsize(term, term->tl_rows, term->tl_cols);
5307}
5308
5309/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005310 * "term_getstatus(buf)" function
5311 */
5312 void
5313f_term_getstatus(typval_T *argvars, typval_T *rettv)
5314{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005315 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005316 term_T *term;
5317 char_u val[100];
5318
5319 rettv->v_type = VAR_STRING;
5320 if (buf == NULL)
5321 return;
5322 term = buf->b_term;
5323
5324 if (term_job_running(term))
5325 STRCPY(val, "running");
5326 else
5327 STRCPY(val, "finished");
5328 if (term->tl_normal_mode)
5329 STRCAT(val, ",normal");
5330 rettv->vval.v_string = vim_strsave(val);
5331}
5332
5333/*
5334 * "term_gettitle(buf)" function
5335 */
5336 void
5337f_term_gettitle(typval_T *argvars, typval_T *rettv)
5338{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005339 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005340
5341 rettv->v_type = VAR_STRING;
5342 if (buf == NULL)
5343 return;
5344
5345 if (buf->b_term->tl_title != NULL)
5346 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5347}
5348
5349/*
5350 * "term_gettty(buf)" function
5351 */
5352 void
5353f_term_gettty(typval_T *argvars, typval_T *rettv)
5354{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005355 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005356 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005357 int num = 0;
5358
5359 rettv->v_type = VAR_STRING;
5360 if (buf == NULL)
5361 return;
5362 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005363 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005364
5365 switch (num)
5366 {
5367 case 0:
5368 if (buf->b_term->tl_job != NULL)
5369 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005370 break;
5371 case 1:
5372 if (buf->b_term->tl_job != NULL)
5373 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005374 break;
5375 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005376 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005377 return;
5378 }
5379 if (p != NULL)
5380 rettv->vval.v_string = vim_strsave(p);
5381}
5382
5383/*
5384 * "term_list()" function
5385 */
5386 void
5387f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5388{
5389 term_T *tp;
5390 list_T *l;
5391
5392 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5393 return;
5394
5395 l = rettv->vval.v_list;
5396 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5397 if (tp != NULL && tp->tl_buffer != NULL)
5398 if (list_append_number(l,
5399 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5400 return;
5401}
5402
5403/*
5404 * "term_scrape(buf, row)" function
5405 */
5406 void
5407f_term_scrape(typval_T *argvars, typval_T *rettv)
5408{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005409 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005410 VTermScreen *screen = NULL;
5411 VTermPos pos;
5412 list_T *l;
5413 term_T *term;
5414 char_u *p;
5415 sb_line_T *line;
5416
5417 if (rettv_list_alloc(rettv) == FAIL)
5418 return;
5419 if (buf == NULL)
5420 return;
5421 term = buf->b_term;
5422
5423 l = rettv->vval.v_list;
5424 pos.row = get_row_number(&argvars[1], term);
5425
5426 if (term->tl_vterm != NULL)
5427 {
5428 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005429 if (screen == NULL) // can't really happen
5430 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005431 p = NULL;
5432 line = NULL;
5433 }
5434 else
5435 {
5436 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5437
5438 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5439 return;
5440 p = ml_get_buf(buf, lnum + 1, FALSE);
5441 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5442 }
5443
5444 for (pos.col = 0; pos.col < term->tl_cols; )
5445 {
5446 dict_T *dcell;
5447 int width;
5448 VTermScreenCellAttrs attrs;
5449 VTermColor fg, bg;
5450 char_u rgb[8];
5451 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5452 int off = 0;
5453 int i;
5454
5455 if (screen == NULL)
5456 {
5457 cellattr_T *cellattr;
5458 int len;
5459
5460 /* vterm has finished, get the cell from scrollback */
5461 if (pos.col >= line->sb_cols)
5462 break;
5463 cellattr = line->sb_cells + pos.col;
5464 width = cellattr->width;
5465 attrs = cellattr->attrs;
5466 fg = cellattr->fg;
5467 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005468 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005469 mch_memmove(mbs, p, len);
5470 mbs[len] = NUL;
5471 p += len;
5472 }
5473 else
5474 {
5475 VTermScreenCell cell;
5476 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5477 break;
5478 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5479 {
5480 if (cell.chars[i] == 0)
5481 break;
5482 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5483 }
5484 mbs[off] = NUL;
5485 width = cell.width;
5486 attrs = cell.attrs;
5487 fg = cell.fg;
5488 bg = cell.bg;
5489 }
5490 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005491 if (dcell == NULL)
5492 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005493 list_append_dict(l, dcell);
5494
Bram Moolenaare0be1672018-07-08 16:50:37 +02005495 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005496
5497 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5498 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005499 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005500 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5501 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005502 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005503
Bram Moolenaare0be1672018-07-08 16:50:37 +02005504 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5505 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005506
5507 ++pos.col;
5508 if (width == 2)
5509 ++pos.col;
5510 }
5511}
5512
5513/*
5514 * "term_sendkeys(buf, keys)" function
5515 */
5516 void
5517f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5518{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005519 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005520 char_u *msg;
5521 term_T *term;
5522
5523 rettv->v_type = VAR_UNKNOWN;
5524 if (buf == NULL)
5525 return;
5526
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005527 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005528 if (msg == NULL)
5529 return;
5530 term = buf->b_term;
5531 if (term->tl_vterm == NULL)
5532 return;
5533
5534 while (*msg != NUL)
5535 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005536 int c;
5537
5538 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5539 {
5540 c = TO_SPECIAL(msg[1], msg[2]);
5541 msg += 3;
5542 }
5543 else
5544 {
5545 c = PTR2CHAR(msg);
5546 msg += MB_CPTR2LEN(msg);
5547 }
5548 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005549 }
5550}
5551
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005552#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5553/*
5554 * "term_getansicolors(buf)" function
5555 */
5556 void
5557f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5558{
5559 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5560 term_T *term;
5561 VTermState *state;
5562 VTermColor color;
5563 char_u hexbuf[10];
5564 int index;
5565 list_T *list;
5566
5567 if (rettv_list_alloc(rettv) == FAIL)
5568 return;
5569
5570 if (buf == NULL)
5571 return;
5572 term = buf->b_term;
5573 if (term->tl_vterm == NULL)
5574 return;
5575
5576 list = rettv->vval.v_list;
5577 state = vterm_obtain_state(term->tl_vterm);
5578 for (index = 0; index < 16; index++)
5579 {
5580 vterm_state_get_palette_color(state, index, &color);
5581 sprintf((char *)hexbuf, "#%02x%02x%02x",
5582 color.red, color.green, color.blue);
5583 if (list_append_string(list, hexbuf, 7) == FAIL)
5584 return;
5585 }
5586}
5587
5588/*
5589 * "term_setansicolors(buf, list)" function
5590 */
5591 void
5592f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5593{
5594 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5595 term_T *term;
5596
5597 if (buf == NULL)
5598 return;
5599 term = buf->b_term;
5600 if (term->tl_vterm == NULL)
5601 return;
5602
5603 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5604 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005605 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005606 return;
5607 }
5608
5609 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005610 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005611}
5612#endif
5613
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005614/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005615 * "term_setapi(buf, api)" function
5616 */
5617 void
5618f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5619{
5620 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5621 term_T *term;
5622 char_u *api;
5623
5624 if (buf == NULL)
5625 return;
5626 term = buf->b_term;
5627 vim_free(term->tl_api);
5628 api = tv_get_string_chk(&argvars[1]);
5629 if (api != NULL)
5630 term->tl_api = vim_strsave(api);
5631 else
5632 term->tl_api = NULL;
5633}
5634
5635/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005636 * "term_setrestore(buf, command)" function
5637 */
5638 void
5639f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5640{
5641#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005642 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005643 term_T *term;
5644 char_u *cmd;
5645
5646 if (buf == NULL)
5647 return;
5648 term = buf->b_term;
5649 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005650 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005651 if (cmd != NULL)
5652 term->tl_command = vim_strsave(cmd);
5653 else
5654 term->tl_command = NULL;
5655#endif
5656}
5657
5658/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005659 * "term_setkill(buf, how)" function
5660 */
5661 void
5662f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5663{
5664 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5665 term_T *term;
5666 char_u *how;
5667
5668 if (buf == NULL)
5669 return;
5670 term = buf->b_term;
5671 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005672 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005673 if (how != NULL)
5674 term->tl_kill = vim_strsave(how);
5675 else
5676 term->tl_kill = NULL;
5677}
5678
5679/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005680 * "term_start(command, options)" function
5681 */
5682 void
5683f_term_start(typval_T *argvars, typval_T *rettv)
5684{
5685 jobopt_T opt;
5686 buf_T *buf;
5687
5688 init_job_options(&opt);
5689 if (argvars[1].v_type != VAR_UNKNOWN
5690 && get_job_options(&argvars[1], &opt,
5691 JO_TIMEOUT_ALL + JO_STOPONEXIT
5692 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5693 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5694 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5695 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005696 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005697 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005698 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005699 return;
5700
Bram Moolenaar13568252018-03-16 20:46:58 +01005701 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005702
5703 if (buf != NULL && buf->b_term != NULL)
5704 rettv->vval.v_number = buf->b_fnum;
5705}
5706
5707/*
5708 * "term_wait" function
5709 */
5710 void
5711f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5712{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005713 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005714
5715 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005716 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005717 if (buf->b_term->tl_job == NULL)
5718 {
5719 ch_log(NULL, "term_wait(): no job to wait for");
5720 return;
5721 }
5722 if (buf->b_term->tl_job->jv_channel == NULL)
5723 /* channel is closed, nothing to do */
5724 return;
5725
5726 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005727 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005728 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5729 {
5730 /* The job is dead, keep reading channel I/O until the channel is
5731 * closed. buf->b_term may become NULL if the terminal was closed while
5732 * waiting. */
5733 ch_log(NULL, "term_wait(): waiting for channel to close");
5734 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5735 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005736 term_flush_messages();
5737
Bram Moolenaard45aa552018-05-21 22:50:29 +02005738 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005739 if (!buf_valid(buf))
5740 /* If the terminal is closed when the channel is closed the
5741 * buffer disappears. */
5742 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005743 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005744
5745 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005746 }
5747 else
5748 {
5749 long wait = 10L;
5750
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005751 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005752
5753 /* Wait for some time for any channel I/O. */
5754 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005755 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005756 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005757
5758 /* Flushing messages on channels is hopefully sufficient.
5759 * TODO: is there a better way? */
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005760 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005761 }
5762}
5763
5764/*
5765 * Called when a channel has sent all the lines to a terminal.
5766 * Send a CTRL-D to mark the end of the text.
5767 */
5768 void
5769term_send_eof(channel_T *ch)
5770{
5771 term_T *term;
5772
5773 for (term = first_term; term != NULL; term = term->tl_next)
5774 if (term->tl_job == ch->ch_job)
5775 {
5776 if (term->tl_eof_chars != NULL)
5777 {
5778 channel_send(ch, PART_IN, term->tl_eof_chars,
5779 (int)STRLEN(term->tl_eof_chars), NULL);
5780 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5781 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005782# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005783 else
5784 /* Default: CTRL-D */
5785 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5786# endif
5787 }
5788}
5789
Bram Moolenaar113e1072019-01-20 15:30:40 +01005790#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005791 job_T *
5792term_getjob(term_T *term)
5793{
5794 return term != NULL ? term->tl_job : NULL;
5795}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005796#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005797
Bram Moolenaar4f974752019-02-17 17:44:42 +01005798# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005799
5800/**************************************
5801 * 2. MS-Windows implementation.
5802 */
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005803#ifdef PROTO
5804typedef int COORD;
5805typedef int DWORD;
5806typedef int HANDLE;
5807typedef int *DWORD_PTR;
5808typedef int HPCON;
5809typedef int HRESULT;
5810typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005811typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005812typedef int PSIZE_T;
5813typedef int PVOID;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005814typedef int WINAPI;
5815#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005816
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005817HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5818HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5819HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005820BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5821BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5822void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005823
5824 static int
5825dyn_conpty_init(int verbose)
5826{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005827 static HMODULE hKerneldll = NULL;
5828 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005829 static struct
5830 {
5831 char *name;
5832 FARPROC *ptr;
5833 } conpty_entry[] =
5834 {
5835 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5836 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5837 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5838 {"InitializeProcThreadAttributeList",
5839 (FARPROC*)&pInitializeProcThreadAttributeList},
5840 {"UpdateProcThreadAttribute",
5841 (FARPROC*)&pUpdateProcThreadAttribute},
5842 {"DeleteProcThreadAttributeList",
5843 (FARPROC*)&pDeleteProcThreadAttributeList},
5844 {NULL, NULL}
5845 };
5846
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005847 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005848 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005849 if (verbose)
5850 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005851 return FAIL;
5852 }
5853
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005854 // No need to initialize twice.
5855 if (hKerneldll)
5856 return OK;
5857
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005858 hKerneldll = vimLoadLib("kernel32.dll");
5859 for (i = 0; conpty_entry[i].name != NULL
5860 && conpty_entry[i].ptr != NULL; ++i)
5861 {
5862 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5863 conpty_entry[i].name)) == NULL)
5864 {
5865 if (verbose)
5866 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005867 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005868 return FAIL;
5869 }
5870 }
5871
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005872 return OK;
5873}
5874
5875 static int
5876conpty_term_and_job_init(
5877 term_T *term,
5878 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005879 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005880 jobopt_T *opt,
5881 jobopt_T *orig_opt)
5882{
5883 WCHAR *cmd_wchar = NULL;
5884 WCHAR *cmd_wchar_copy = NULL;
5885 WCHAR *cwd_wchar = NULL;
5886 WCHAR *env_wchar = NULL;
5887 channel_T *channel = NULL;
5888 job_T *job = NULL;
5889 HANDLE jo = NULL;
5890 garray_T ga_cmd, ga_env;
5891 char_u *cmd = NULL;
5892 HRESULT hr;
5893 COORD consize;
5894 SIZE_T breq;
5895 PROCESS_INFORMATION proc_info;
5896 HANDLE i_theirs = NULL;
5897 HANDLE o_theirs = NULL;
5898 HANDLE i_ours = NULL;
5899 HANDLE o_ours = NULL;
5900
5901 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5902 ga_init2(&ga_env, (int)sizeof(char*), 20);
5903
5904 if (argvar->v_type == VAR_STRING)
5905 {
5906 cmd = argvar->vval.v_string;
5907 }
5908 else if (argvar->v_type == VAR_LIST)
5909 {
5910 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5911 goto failed;
5912 cmd = ga_cmd.ga_data;
5913 }
5914 if (cmd == NULL || *cmd == NUL)
5915 {
5916 emsg(_(e_invarg));
5917 goto failed;
5918 }
5919
5920 term->tl_arg0_cmd = vim_strsave(cmd);
5921
5922 cmd_wchar = enc_to_utf16(cmd, NULL);
5923
5924 if (cmd_wchar != NULL)
5925 {
5926 /* Request by CreateProcessW */
5927 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005928 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005929 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5930 }
5931
5932 ga_clear(&ga_cmd);
5933 if (cmd_wchar == NULL)
5934 goto failed;
5935 if (opt->jo_cwd != NULL)
5936 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5937
5938 win32_build_env(opt->jo_env, &ga_env, TRUE);
5939 env_wchar = ga_env.ga_data;
5940
5941 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5942 goto failed;
5943 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5944 goto failed;
5945
5946 consize.X = term->tl_cols;
5947 consize.Y = term->tl_rows;
5948 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
5949 &term->tl_conpty);
5950 if (FAILED(hr))
5951 goto failed;
5952
5953 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
5954
5955 /* Set up pipe inheritance safely: Vista or later. */
5956 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005957 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005958 if (!term->tl_siex.lpAttributeList)
5959 goto failed;
5960 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
5961 0, &breq))
5962 goto failed;
5963 if (!pUpdateProcThreadAttribute(
5964 term->tl_siex.lpAttributeList, 0,
5965 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
5966 sizeof(HPCON), NULL, NULL))
5967 goto failed;
5968
5969 channel = add_channel();
5970 if (channel == NULL)
5971 goto failed;
5972
5973 job = job_alloc();
5974 if (job == NULL)
5975 goto failed;
5976 if (argvar->v_type == VAR_STRING)
5977 {
5978 int argc;
5979
5980 build_argv_from_string(cmd, &job->jv_argv, &argc);
5981 }
5982 else
5983 {
5984 int argc;
5985
5986 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5987 }
5988
5989 if (opt->jo_set & JO_IN_BUF)
5990 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5991
5992 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
5993 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
5994 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
5995 | CREATE_DEFAULT_ERROR_MODE,
5996 env_wchar, cwd_wchar,
5997 &term->tl_siex.StartupInfo, &proc_info))
5998 goto failed;
5999
6000 CloseHandle(i_theirs);
6001 CloseHandle(o_theirs);
6002
6003 channel_set_pipes(channel,
6004 (sock_T)i_ours,
6005 (sock_T)o_ours,
6006 (sock_T)o_ours);
6007
6008 /* Write lines with CR instead of NL. */
6009 channel->ch_write_text_mode = TRUE;
6010
6011 /* Use to explicitly delete anonymous pipe handle. */
6012 channel->ch_anonymous_pipe = TRUE;
6013
6014 jo = CreateJobObject(NULL, NULL);
6015 if (jo == NULL)
6016 goto failed;
6017
6018 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6019 {
6020 /* Failed, switch the way to terminate process with TerminateProcess. */
6021 CloseHandle(jo);
6022 jo = NULL;
6023 }
6024
6025 ResumeThread(proc_info.hThread);
6026 CloseHandle(proc_info.hThread);
6027
6028 vim_free(cmd_wchar);
6029 vim_free(cmd_wchar_copy);
6030 vim_free(cwd_wchar);
6031 vim_free(env_wchar);
6032
6033 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6034 goto failed;
6035
6036#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6037 if (opt->jo_set2 & JO2_ANSI_COLORS)
6038 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6039 else
6040 init_vterm_ansi_colors(term->tl_vterm);
6041#endif
6042
6043 channel_set_job(channel, job, opt);
6044 job_set_options(job, opt);
6045
6046 job->jv_channel = channel;
6047 job->jv_proc_info = proc_info;
6048 job->jv_job_object = jo;
6049 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006050 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006051 ++job->jv_refcount;
6052 term->tl_job = job;
6053
6054 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6055 * open the file here and handle it in. opt->jo_io was changed in
6056 * setup_job_options(), use the original flags here. */
6057 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6058 {
6059 char_u *fname = opt->jo_io_name[PART_OUT];
6060
6061 ch_log(channel, "Opening output file %s", fname);
6062 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6063 if (term->tl_out_fd == NULL)
6064 semsg(_(e_notopen), fname);
6065 }
6066
6067 return OK;
6068
6069failed:
6070 ga_clear(&ga_cmd);
6071 ga_clear(&ga_env);
6072 vim_free(cmd_wchar);
6073 vim_free(cmd_wchar_copy);
6074 vim_free(cwd_wchar);
6075 if (channel != NULL)
6076 channel_clear(channel);
6077 if (job != NULL)
6078 {
6079 job->jv_channel = NULL;
6080 job_cleanup(job);
6081 }
6082 term->tl_job = NULL;
6083 if (jo != NULL)
6084 CloseHandle(jo);
6085
6086 if (term->tl_siex.lpAttributeList != NULL)
6087 {
6088 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6089 vim_free(term->tl_siex.lpAttributeList);
6090 }
6091 term->tl_siex.lpAttributeList = NULL;
6092 if (o_theirs != NULL)
6093 CloseHandle(o_theirs);
6094 if (o_ours != NULL)
6095 CloseHandle(o_ours);
6096 if (i_ours != NULL)
6097 CloseHandle(i_ours);
6098 if (i_theirs != NULL)
6099 CloseHandle(i_theirs);
6100 if (term->tl_conpty != NULL)
6101 pClosePseudoConsole(term->tl_conpty);
6102 term->tl_conpty = NULL;
6103 return FAIL;
6104}
6105
6106 static void
6107conpty_term_report_winsize(term_T *term, int rows, int cols)
6108{
6109 COORD consize;
6110
6111 consize.X = cols;
6112 consize.Y = rows;
6113 pResizePseudoConsole(term->tl_conpty, consize);
6114}
6115
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006116 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006117term_free_conpty(term_T *term)
6118{
6119 if (term->tl_siex.lpAttributeList != NULL)
6120 {
6121 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6122 vim_free(term->tl_siex.lpAttributeList);
6123 }
6124 term->tl_siex.lpAttributeList = NULL;
6125 if (term->tl_conpty != NULL)
6126 pClosePseudoConsole(term->tl_conpty);
6127 term->tl_conpty = NULL;
6128}
6129
6130 int
6131use_conpty(void)
6132{
6133 return has_conpty;
6134}
6135
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006136# ifndef PROTO
6137
6138#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6139#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006140#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006141
6142void* (*winpty_config_new)(UINT64, void*);
6143void* (*winpty_open)(void*, void*);
6144void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6145BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6146void (*winpty_config_set_mouse_mode)(void*, int);
6147void (*winpty_config_set_initial_size)(void*, int, int);
6148LPCWSTR (*winpty_conin_name)(void*);
6149LPCWSTR (*winpty_conout_name)(void*);
6150LPCWSTR (*winpty_conerr_name)(void*);
6151void (*winpty_free)(void*);
6152void (*winpty_config_free)(void*);
6153void (*winpty_spawn_config_free)(void*);
6154void (*winpty_error_free)(void*);
6155LPCWSTR (*winpty_error_msg)(void*);
6156BOOL (*winpty_set_size)(void*, int, int, void*);
6157HANDLE (*winpty_agent_process)(void*);
6158
6159#define WINPTY_DLL "winpty.dll"
6160
6161static HINSTANCE hWinPtyDLL = NULL;
6162# endif
6163
6164 static int
6165dyn_winpty_init(int verbose)
6166{
6167 int i;
6168 static struct
6169 {
6170 char *name;
6171 FARPROC *ptr;
6172 } winpty_entry[] =
6173 {
6174 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6175 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6176 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6177 {"winpty_config_set_mouse_mode",
6178 (FARPROC*)&winpty_config_set_mouse_mode},
6179 {"winpty_config_set_initial_size",
6180 (FARPROC*)&winpty_config_set_initial_size},
6181 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6182 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6183 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6184 {"winpty_free", (FARPROC*)&winpty_free},
6185 {"winpty_open", (FARPROC*)&winpty_open},
6186 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6187 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6188 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6189 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6190 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6191 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6192 {NULL, NULL}
6193 };
6194
6195 /* No need to initialize twice. */
6196 if (hWinPtyDLL)
6197 return OK;
6198 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6199 * winpty.dll. */
6200 if (*p_winptydll != NUL)
6201 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6202 if (!hWinPtyDLL)
6203 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6204 if (!hWinPtyDLL)
6205 {
6206 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006207 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006208 : (char_u *)WINPTY_DLL);
6209 return FAIL;
6210 }
6211 for (i = 0; winpty_entry[i].name != NULL
6212 && winpty_entry[i].ptr != NULL; ++i)
6213 {
6214 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6215 winpty_entry[i].name)) == NULL)
6216 {
6217 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006218 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006219 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006220 return FAIL;
6221 }
6222 }
6223
6224 return OK;
6225}
6226
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006227 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006228winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006229 term_T *term,
6230 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006231 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006232 jobopt_T *opt,
6233 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006234{
6235 WCHAR *cmd_wchar = NULL;
6236 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006237 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006238 channel_T *channel = NULL;
6239 job_T *job = NULL;
6240 DWORD error;
6241 HANDLE jo = NULL;
6242 HANDLE child_process_handle;
6243 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006244 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006245 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006246 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006247 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006248
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006249 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6250 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006251
6252 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006253 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006254 cmd = argvar->vval.v_string;
6255 }
6256 else if (argvar->v_type == VAR_LIST)
6257 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006258 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006259 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006260 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006261 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006262 if (cmd == NULL || *cmd == NUL)
6263 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006264 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006265 goto failed;
6266 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006267
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006268 term->tl_arg0_cmd = vim_strsave(cmd);
6269
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006270 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006271 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006272 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006273 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006274 if (opt->jo_cwd != NULL)
6275 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006276
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006277 win32_build_env(opt->jo_env, &ga_env, TRUE);
6278 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006279
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006280 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6281 if (term->tl_winpty_config == NULL)
6282 goto failed;
6283
6284 winpty_config_set_mouse_mode(term->tl_winpty_config,
6285 WINPTY_MOUSE_MODE_FORCE);
6286 winpty_config_set_initial_size(term->tl_winpty_config,
6287 term->tl_cols, term->tl_rows);
6288 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6289 if (term->tl_winpty == NULL)
6290 goto failed;
6291
6292 spawn_config = winpty_spawn_config_new(
6293 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6294 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6295 NULL,
6296 cmd_wchar,
6297 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006298 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006299 &winpty_err);
6300 if (spawn_config == NULL)
6301 goto failed;
6302
6303 channel = add_channel();
6304 if (channel == NULL)
6305 goto failed;
6306
6307 job = job_alloc();
6308 if (job == NULL)
6309 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006310 if (argvar->v_type == VAR_STRING)
6311 {
6312 int argc;
6313
6314 build_argv_from_string(cmd, &job->jv_argv, &argc);
6315 }
6316 else
6317 {
6318 int argc;
6319
6320 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6321 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006322
6323 if (opt->jo_set & JO_IN_BUF)
6324 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6325
6326 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6327 &child_thread_handle, &error, &winpty_err))
6328 goto failed;
6329
6330 channel_set_pipes(channel,
6331 (sock_T)CreateFileW(
6332 winpty_conin_name(term->tl_winpty),
6333 GENERIC_WRITE, 0, NULL,
6334 OPEN_EXISTING, 0, NULL),
6335 (sock_T)CreateFileW(
6336 winpty_conout_name(term->tl_winpty),
6337 GENERIC_READ, 0, NULL,
6338 OPEN_EXISTING, 0, NULL),
6339 (sock_T)CreateFileW(
6340 winpty_conerr_name(term->tl_winpty),
6341 GENERIC_READ, 0, NULL,
6342 OPEN_EXISTING, 0, NULL));
6343
6344 /* Write lines with CR instead of NL. */
6345 channel->ch_write_text_mode = TRUE;
6346
6347 jo = CreateJobObject(NULL, NULL);
6348 if (jo == NULL)
6349 goto failed;
6350
6351 if (!AssignProcessToJobObject(jo, child_process_handle))
6352 {
6353 /* Failed, switch the way to terminate process with TerminateProcess. */
6354 CloseHandle(jo);
6355 jo = NULL;
6356 }
6357
6358 winpty_spawn_config_free(spawn_config);
6359 vim_free(cmd_wchar);
6360 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006361 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006362
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006363 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6364 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006365
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006366#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6367 if (opt->jo_set2 & JO2_ANSI_COLORS)
6368 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6369 else
6370 init_vterm_ansi_colors(term->tl_vterm);
6371#endif
6372
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006373 channel_set_job(channel, job, opt);
6374 job_set_options(job, opt);
6375
6376 job->jv_channel = channel;
6377 job->jv_proc_info.hProcess = child_process_handle;
6378 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6379 job->jv_job_object = jo;
6380 job->jv_status = JOB_STARTED;
6381 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006382 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006383 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006384 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006385 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006386 ++job->jv_refcount;
6387 term->tl_job = job;
6388
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006389 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6390 * open the file here and handle it in. opt->jo_io was changed in
6391 * setup_job_options(), use the original flags here. */
6392 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6393 {
6394 char_u *fname = opt->jo_io_name[PART_OUT];
6395
6396 ch_log(channel, "Opening output file %s", fname);
6397 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6398 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006399 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006400 }
6401
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006402 return OK;
6403
6404failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006405 ga_clear(&ga_cmd);
6406 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006407 vim_free(cmd_wchar);
6408 vim_free(cwd_wchar);
6409 if (spawn_config != NULL)
6410 winpty_spawn_config_free(spawn_config);
6411 if (channel != NULL)
6412 channel_clear(channel);
6413 if (job != NULL)
6414 {
6415 job->jv_channel = NULL;
6416 job_cleanup(job);
6417 }
6418 term->tl_job = NULL;
6419 if (jo != NULL)
6420 CloseHandle(jo);
6421 if (term->tl_winpty != NULL)
6422 winpty_free(term->tl_winpty);
6423 term->tl_winpty = NULL;
6424 if (term->tl_winpty_config != NULL)
6425 winpty_config_free(term->tl_winpty_config);
6426 term->tl_winpty_config = NULL;
6427 if (winpty_err != NULL)
6428 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006429 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006430 (short_u *)winpty_error_msg(winpty_err), NULL);
6431
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006432 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006433 winpty_error_free(winpty_err);
6434 }
6435 return FAIL;
6436}
6437
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006438/*
6439 * Create a new terminal of "rows" by "cols" cells.
6440 * Store a reference in "term".
6441 * Return OK or FAIL.
6442 */
6443 static int
6444term_and_job_init(
6445 term_T *term,
6446 typval_T *argvar,
6447 char **argv UNUSED,
6448 jobopt_T *opt,
6449 jobopt_T *orig_opt)
6450{
6451 int use_winpty = FALSE;
6452 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006453 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006454
6455 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6456 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6457
6458 if (!has_winpty && !has_conpty)
6459 // If neither is available give the errors for winpty, since when
6460 // conpty is not available it can't be installed either.
6461 return dyn_winpty_init(TRUE);
6462
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006463 if (opt->jo_tty_type != NUL)
6464 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006465
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006466 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006467 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006468 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006469 use_conpty = TRUE;
6470 else if (has_winpty)
6471 use_winpty = TRUE;
6472 // else: error
6473 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006474 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006475 {
6476 if (has_winpty)
6477 use_winpty = TRUE;
6478 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006479 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006480 {
6481 if (has_conpty)
6482 use_conpty = TRUE;
6483 else
6484 return dyn_conpty_init(TRUE);
6485 }
6486
6487 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006488 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006489
6490 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006491 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006492
6493 // error
6494 return dyn_winpty_init(TRUE);
6495}
6496
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006497 static int
6498create_pty_only(term_T *term, jobopt_T *options)
6499{
6500 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6501 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6502 char in_name[80], out_name[80];
6503 channel_T *channel = NULL;
6504
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006505 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6506 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006507
6508 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6509 GetCurrentProcessId(),
6510 curbuf->b_fnum);
6511 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6512 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6513 PIPE_UNLIMITED_INSTANCES,
6514 0, 0, NMPWAIT_NOWAIT, NULL);
6515 if (hPipeIn == INVALID_HANDLE_VALUE)
6516 goto failed;
6517
6518 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6519 GetCurrentProcessId(),
6520 curbuf->b_fnum);
6521 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6522 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6523 PIPE_UNLIMITED_INSTANCES,
6524 0, 0, 0, NULL);
6525 if (hPipeOut == INVALID_HANDLE_VALUE)
6526 goto failed;
6527
6528 ConnectNamedPipe(hPipeIn, NULL);
6529 ConnectNamedPipe(hPipeOut, NULL);
6530
6531 term->tl_job = job_alloc();
6532 if (term->tl_job == NULL)
6533 goto failed;
6534 ++term->tl_job->jv_refcount;
6535
6536 /* behave like the job is already finished */
6537 term->tl_job->jv_status = JOB_FINISHED;
6538
6539 channel = add_channel();
6540 if (channel == NULL)
6541 goto failed;
6542 term->tl_job->jv_channel = channel;
6543 channel->ch_keep_open = TRUE;
6544 channel->ch_named_pipe = TRUE;
6545
6546 channel_set_pipes(channel,
6547 (sock_T)hPipeIn,
6548 (sock_T)hPipeOut,
6549 (sock_T)hPipeOut);
6550 channel_set_job(channel, term->tl_job, options);
6551 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6552 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6553
6554 return OK;
6555
6556failed:
6557 if (hPipeIn != NULL)
6558 CloseHandle(hPipeIn);
6559 if (hPipeOut != NULL)
6560 CloseHandle(hPipeOut);
6561 return FAIL;
6562}
6563
6564/*
6565 * Free the terminal emulator part of "term".
6566 */
6567 static void
6568term_free_vterm(term_T *term)
6569{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006570 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006571 if (term->tl_winpty != NULL)
6572 winpty_free(term->tl_winpty);
6573 term->tl_winpty = NULL;
6574 if (term->tl_winpty_config != NULL)
6575 winpty_config_free(term->tl_winpty_config);
6576 term->tl_winpty_config = NULL;
6577 if (term->tl_vterm != NULL)
6578 vterm_free(term->tl_vterm);
6579 term->tl_vterm = NULL;
6580}
6581
6582/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006583 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006584 */
6585 static void
6586term_report_winsize(term_T *term, int rows, int cols)
6587{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006588 if (term->tl_conpty)
6589 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006590 if (term->tl_winpty)
6591 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6592}
6593
6594 int
6595terminal_enabled(void)
6596{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006597 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006598}
6599
6600# else
6601
6602/**************************************
6603 * 3. Unix-like implementation.
6604 */
6605
6606/*
6607 * Create a new terminal of "rows" by "cols" cells.
6608 * Start job for "cmd".
6609 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006610 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006611 * Return OK or FAIL.
6612 */
6613 static int
6614term_and_job_init(
6615 term_T *term,
6616 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006617 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006618 jobopt_T *opt,
6619 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006620{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006621 term->tl_arg0_cmd = NULL;
6622
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006623 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6624 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006625
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006626#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6627 if (opt->jo_set2 & JO2_ANSI_COLORS)
6628 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6629 else
6630 init_vterm_ansi_colors(term->tl_vterm);
6631#endif
6632
Bram Moolenaar13568252018-03-16 20:46:58 +01006633 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006634 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006635 if (term->tl_job != NULL)
6636 ++term->tl_job->jv_refcount;
6637
6638 return term->tl_job != NULL
6639 && term->tl_job->jv_channel != NULL
6640 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6641}
6642
6643 static int
6644create_pty_only(term_T *term, jobopt_T *opt)
6645{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006646 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6647 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006648
6649 term->tl_job = job_alloc();
6650 if (term->tl_job == NULL)
6651 return FAIL;
6652 ++term->tl_job->jv_refcount;
6653
6654 /* behave like the job is already finished */
6655 term->tl_job->jv_status = JOB_FINISHED;
6656
6657 return mch_create_pty_channel(term->tl_job, opt);
6658}
6659
6660/*
6661 * Free the terminal emulator part of "term".
6662 */
6663 static void
6664term_free_vterm(term_T *term)
6665{
6666 if (term->tl_vterm != NULL)
6667 vterm_free(term->tl_vterm);
6668 term->tl_vterm = NULL;
6669}
6670
6671/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006672 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006673 */
6674 static void
6675term_report_winsize(term_T *term, int rows, int cols)
6676{
6677 /* Use an ioctl() to report the new window size to the job. */
6678 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6679 {
6680 int fd = -1;
6681 int part;
6682
6683 for (part = PART_OUT; part < PART_COUNT; ++part)
6684 {
6685 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006686 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006687 break;
6688 }
6689 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6690 mch_signal_job(term->tl_job, (char_u *)"winch");
6691 }
6692}
6693
6694# endif
6695
6696#endif /* FEAT_TERMINAL */