blob: 2544f8567abb3704037d823373b16b0abe79e4be [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 {
63 int sb_cols; /* can differ per line */
64 cellattr_T *sb_cells; /* allocated */
65 cellattr_T sb_fill_attr; /* for short line */
66} sb_line_T;
67
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010068#ifdef WIN3264
69# ifndef HPCON
70# define HPCON VOID*
71# endif
72# ifndef EXTENDED_STARTUPINFO_PRESENT
73# define EXTENDED_STARTUPINFO_PRESENT 0x00080000
74# endif
75# ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
76# define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE 0x00020016
77# endif
78typedef struct _DYN_STARTUPINFOEXW
79{
80 STARTUPINFOW StartupInfo;
81 LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
82} DYN_STARTUPINFOEXW, *PDYN_STARTUPINFOEXW;
83#endif
84
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020085/* typedef term_T in structs.h */
86struct terminal_S {
87 term_T *tl_next;
88
89 VTerm *tl_vterm;
90 job_T *tl_job;
91 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010092#if defined(FEAT_GUI)
93 int tl_system; /* when non-zero used for :!cmd output */
94 int tl_toprow; /* row with first line of system terminal */
95#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020096
97 /* Set when setting the size of a vterm, reset after redrawing. */
98 int tl_vterm_size_changed;
99
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200100 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
101 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200102 int tl_channel_recently_closed; // still need to handle tl_finish
103
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100104 int tl_finish;
105#define TL_FINISH_UNSET NUL
106#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
107#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
108#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200109 char_u *tl_opencmd;
110 char_u *tl_eof_chars;
111
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100112 char_u *tl_arg0_cmd; // To format the status bar
113
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200114#ifdef WIN3264
115 void *tl_winpty_config;
116 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200117
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100118 HPCON tl_conpty;
119 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
120
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200121 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200122#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100123#if defined(FEAT_SESSION)
124 char_u *tl_command;
125#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100126 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200127
128 /* last known vterm size */
129 int tl_rows;
130 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200131
132 char_u *tl_title; /* NULL or allocated */
133 char_u *tl_status_text; /* NULL or allocated */
134
135 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200136 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200137 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200138 int tl_dirty_snapshot; /* text updated after making snapshot */
139#ifdef FEAT_TIMERS
140 int tl_timer_set;
141 proftime_T tl_timer_due;
142#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200143 int tl_postponed_scroll; /* to be scrolled up */
144
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200145 garray_T tl_scrollback;
146 int tl_scrollback_scrolled;
147 cellattr_T tl_default_color;
148
Bram Moolenaard96ff162018-02-18 22:13:29 +0100149 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
150 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
151
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200152 VTermPos tl_cursor_pos;
153 int tl_cursor_visible;
154 int tl_cursor_blink;
155 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
156 char_u *tl_cursor_color; /* NULL or allocated */
157
158 int tl_using_altscreen;
159};
160
161#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
162#define TMODE_LOOP 2 /* CTRL-W N used */
163
164/*
165 * List of all active terminals.
166 */
167static term_T *first_term = NULL;
168
169/* Terminal active in terminal_loop(). */
170static term_T *in_terminal_loop = NULL;
171
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100172#ifdef WIN3264
173static BOOL has_winpty = FALSE;
174static BOOL has_conpty = FALSE;
175#endif
176
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200177#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
178#define KEY_BUF_LEN 200
179
180/*
181 * Functions with separate implementation for MS-Windows and Unix-like systems.
182 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200183static 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 +0200184static int create_pty_only(term_T *term, jobopt_T *opt);
185static void term_report_winsize(term_T *term, int rows, int cols);
186static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100187#ifdef FEAT_GUI
188static void update_system_term(term_T *term);
189#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200190
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100191/* The character that we know (or assume) that the terminal expects for the
192 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200194
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100195/* "Terminal" highlight group colors. */
196static int term_default_cterm_fg = -1;
197static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200198
Bram Moolenaard317b382018-02-08 22:33:31 +0100199/* Store the last set and the desired cursor properties, so that we only update
200 * them when needed. Doing it unnecessary may result in flicker. */
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200201static char_u *last_set_cursor_color = NULL;
202static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100203static int last_set_cursor_shape = -1;
204static int desired_cursor_shape = -1;
205static int last_set_cursor_blink = -1;
206static int desired_cursor_blink = -1;
207
208
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200209/**************************************
210 * 1. Generic code for all systems.
211 */
212
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200213 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200214cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
215{
216 if (lhs_color != NULL && rhs_color != NULL)
217 return STRCMP(lhs_color, rhs_color) == 0;
218 return lhs_color == NULL && rhs_color == NULL;
219}
220
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200221 static void
222cursor_color_copy(char_u **to_color, char_u *from_color)
223{
224 // Avoid a free & alloc if the value is already right.
225 if (cursor_color_equal(*to_color, from_color))
226 return;
227 vim_free(*to_color);
228 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
229}
230
231 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200232cursor_color_get(char_u *color)
233{
234 return (color == NULL) ? (char_u *)"" : color;
235}
236
237
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200238/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200239 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200240 * current window.
241 * Sets "rows" and/or "cols" to zero when it should follow the window size.
242 * Return TRUE if the size is the minimum size: "24*80".
243 */
244 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200245parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200246{
247 int minsize = FALSE;
248
249 *rows = 0;
250 *cols = 0;
251
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200252 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200253 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200254 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200255
256 /* Syntax of value was already checked when it's set. */
257 if (p == NULL)
258 {
259 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200260 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200261 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200262 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200263 *cols = atoi((char *)p + 1);
264 }
265 return minsize;
266}
267
268/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200269 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200270 */
271 static void
272set_term_and_win_size(term_T *term)
273{
Bram Moolenaar13568252018-03-16 20:46:58 +0100274#ifdef FEAT_GUI
275 if (term->tl_system)
276 {
277 /* Use the whole screen for the system command. However, it will start
278 * at the command line and scroll up as needed, using tl_toprow. */
279 term->tl_rows = Rows;
280 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200281 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100282 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100283#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200284 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200285 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200286 if (term->tl_rows != 0)
287 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
288 if (term->tl_cols != 0)
289 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200290 }
291 if (term->tl_rows == 0)
292 term->tl_rows = curwin->w_height;
293 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200294 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200295 if (term->tl_cols == 0)
296 term->tl_cols = curwin->w_width;
297 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200298 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200299}
300
301/*
302 * Initialize job options for a terminal job.
303 * Caller may overrule some of them.
304 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100305 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200306init_job_options(jobopt_T *opt)
307{
308 clear_job_options(opt);
309
310 opt->jo_mode = MODE_RAW;
311 opt->jo_out_mode = MODE_RAW;
312 opt->jo_err_mode = MODE_RAW;
313 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
314}
315
316/*
317 * Set job options mandatory for a terminal job.
318 */
319 static void
320setup_job_options(jobopt_T *opt, int rows, int cols)
321{
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200322#ifndef WIN3264
323 /* Win32: Redirecting the job output won't work, thus always connect stdout
324 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200325 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200326#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200327 {
328 /* Connect stdout to the terminal. */
329 opt->jo_io[PART_OUT] = JIO_BUFFER;
330 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
331 opt->jo_modifiable[PART_OUT] = 0;
332 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
333 }
334
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200335#ifndef WIN3264
336 /* Win32: Redirecting the job output won't work, thus always connect stderr
337 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200338 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200339#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200340 {
341 /* Connect stderr to the terminal. */
342 opt->jo_io[PART_ERR] = JIO_BUFFER;
343 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
344 opt->jo_modifiable[PART_ERR] = 0;
345 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
346 }
347
348 opt->jo_pty = TRUE;
349 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
350 opt->jo_term_rows = rows;
351 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
352 opt->jo_term_cols = cols;
353}
354
355/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100356 * Close a terminal buffer (and its window). Used when creating the terminal
357 * fails.
358 */
359 static void
360term_close_buffer(buf_T *buf, buf_T *old_curbuf)
361{
362 free_terminal(buf);
363 if (old_curbuf != NULL)
364 {
365 --curbuf->b_nwindows;
366 curbuf = old_curbuf;
367 curwin->w_buffer = curbuf;
368 ++curbuf->b_nwindows;
369 }
370
371 /* Wiping out the buffer will also close the window and call
372 * free_terminal(). */
373 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
374}
375
376/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200377 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100378 * Use either "argvar" or "argv", the other must be NULL.
379 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
380 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200381 * Returns NULL when failed.
382 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100383 buf_T *
384term_start(
385 typval_T *argvar,
386 char **argv,
387 jobopt_T *opt,
388 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200389{
390 exarg_T split_ea;
391 win_T *old_curwin = curwin;
392 term_T *term;
393 buf_T *old_curbuf = NULL;
394 int res;
395 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100396 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200397 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200398
399 if (check_restricted() || check_secure())
400 return NULL;
401
402 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
403 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
404 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
405 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
406 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100407 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200408 return NULL;
409 }
410
411 term = (term_T *)alloc_clear(sizeof(term_T));
412 if (term == NULL)
413 return NULL;
414 term->tl_dirty_row_end = MAX_ROW;
415 term->tl_cursor_visible = TRUE;
416 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
417 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100418#ifdef FEAT_GUI
419 term->tl_system = (flags & TERM_START_SYSTEM);
420#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200421 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
422
423 vim_memset(&split_ea, 0, sizeof(split_ea));
424 if (opt->jo_curwin)
425 {
426 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100427 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 {
429 no_write_message();
430 vim_free(term);
431 return NULL;
432 }
433 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100434 ECMD_HIDE
435 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
436 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200437 {
438 vim_free(term);
439 return NULL;
440 }
441 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100442 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200443 {
444 buf_T *buf;
445
446 /* Create a new buffer without a window. Make it the current buffer for
447 * a moment to be able to do the initialisations. */
448 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
449 BLN_NEW | BLN_LISTED);
450 if (buf == NULL || ml_open(buf) == FAIL)
451 {
452 vim_free(term);
453 return NULL;
454 }
455 old_curbuf = curbuf;
456 --curbuf->b_nwindows;
457 curbuf = buf;
458 curwin->w_buffer = buf;
459 ++curbuf->b_nwindows;
460 }
461 else
462 {
463 /* Open a new window or tab. */
464 split_ea.cmdidx = CMD_new;
465 split_ea.cmd = (char_u *)"new";
466 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100467 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200468 {
469 split_ea.line2 = opt->jo_term_rows;
470 split_ea.addr_count = 1;
471 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100472 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200473 {
474 split_ea.line2 = opt->jo_term_cols;
475 split_ea.addr_count = 1;
476 }
477
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100478 if (vertical)
479 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200480 ex_splitview(&split_ea);
481 if (curwin == old_curwin)
482 {
483 /* split failed */
484 vim_free(term);
485 return NULL;
486 }
487 }
488 term->tl_buffer = curbuf;
489 curbuf->b_term = term;
490
491 if (!opt->jo_hidden)
492 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100493 /* Only one size was taken care of with :new, do the other one. With
494 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100495 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200496 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100497 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200498 win_setwidth(opt->jo_term_cols);
499 }
500
501 /* Link the new terminal in the list of active terminals. */
502 term->tl_next = first_term;
503 first_term = term;
504
505 if (opt->jo_term_name != NULL)
506 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100507 else if (argv != NULL)
508 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200509 else
510 {
511 int i;
512 size_t len;
513 char_u *cmd, *p;
514
515 if (argvar->v_type == VAR_STRING)
516 {
517 cmd = argvar->vval.v_string;
518 if (cmd == NULL)
519 cmd = (char_u *)"";
520 else if (STRCMP(cmd, "NONE") == 0)
521 cmd = (char_u *)"pty";
522 }
523 else if (argvar->v_type != VAR_LIST
524 || argvar->vval.v_list == NULL
525 || argvar->vval.v_list->lv_len < 1
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100526 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200527 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
528 cmd = (char_u*)"";
529
530 len = STRLEN(cmd) + 10;
531 p = alloc((int)len);
532
533 for (i = 0; p != NULL; ++i)
534 {
535 /* Prepend a ! to the command name to avoid the buffer name equals
536 * the executable, otherwise ":w!" would overwrite it. */
537 if (i == 0)
538 vim_snprintf((char *)p, len, "!%s", cmd);
539 else
540 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
541 if (buflist_findname(p) == NULL)
542 {
543 vim_free(curbuf->b_ffname);
544 curbuf->b_ffname = p;
545 break;
546 }
547 }
548 }
549 curbuf->b_fname = curbuf->b_ffname;
550
551 if (opt->jo_term_opencmd != NULL)
552 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
553
554 if (opt->jo_eof_chars != NULL)
555 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
556
557 set_string_option_direct((char_u *)"buftype", -1,
558 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200559 // Avoid that 'buftype' is reset when this buffer is entered.
560 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200561
562 /* Mark the buffer as not modifiable. It can only be made modifiable after
563 * the job finished. */
564 curbuf->b_p_ma = FALSE;
565
566 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200567#ifdef WIN3264
568 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
569#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200570 setup_job_options(opt, term->tl_rows, term->tl_cols);
571
Bram Moolenaar13568252018-03-16 20:46:58 +0100572 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100573 return curbuf;
574
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100575#if defined(FEAT_SESSION)
576 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100577 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100578 {
579 term->tl_command = vim_strsave((char_u *)"NONE");
580 }
581 else if (argvar->v_type == VAR_STRING)
582 {
583 char_u *cmd = argvar->vval.v_string;
584
585 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
586 term->tl_command = vim_strsave(cmd);
587 }
588 else if (argvar->v_type == VAR_LIST
589 && argvar->vval.v_list != NULL
590 && argvar->vval.v_list->lv_len > 0)
591 {
592 garray_T ga;
593 listitem_T *item;
594
595 ga_init2(&ga, 1, 100);
596 for (item = argvar->vval.v_list->lv_first;
597 item != NULL; item = item->li_next)
598 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100599 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100600 char_u *p;
601
602 if (s == NULL)
603 break;
604 p = vim_strsave_fnameescape(s, FALSE);
605 if (p == NULL)
606 break;
607 ga_concat(&ga, p);
608 vim_free(p);
609 ga_append(&ga, ' ');
610 }
611 if (item == NULL)
612 {
613 ga_append(&ga, NUL);
614 term->tl_command = ga.ga_data;
615 }
616 else
617 ga_clear(&ga);
618 }
619#endif
620
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100621 if (opt->jo_term_kill != NULL)
622 {
623 char_u *p = skiptowhite(opt->jo_term_kill);
624
625 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
626 }
627
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200628 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100629 if (argv == NULL
630 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200631 && argvar->vval.v_string != NULL
632 && STRCMP(argvar->vval.v_string, "NONE") == 0)
633 res = create_pty_only(term, opt);
634 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200635 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200636
637 newbuf = curbuf;
638 if (res == OK)
639 {
640 /* Get and remember the size we ended up with. Update the pty. */
641 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
642 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100643#ifdef FEAT_GUI
644 if (term->tl_system)
645 {
646 /* display first line below typed command */
647 term->tl_toprow = msg_row + 1;
648 term->tl_dirty_row_end = 0;
649 }
650#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200651
652 /* Make sure we don't get stuck on sending keys to the job, it leads to
653 * a deadlock if the job is waiting for Vim to read. */
654 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
655
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200656 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200657 {
658 --curbuf->b_nwindows;
659 curbuf = old_curbuf;
660 curwin->w_buffer = curbuf;
661 ++curbuf->b_nwindows;
662 }
663 }
664 else
665 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100666 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200667 return NULL;
668 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100669
Bram Moolenaar13568252018-03-16 20:46:58 +0100670 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200671 return newbuf;
672}
673
674/*
675 * ":terminal": open a terminal window and execute a job in it.
676 */
677 void
678ex_terminal(exarg_T *eap)
679{
680 typval_T argvar[2];
681 jobopt_T opt;
682 char_u *cmd;
683 char_u *tofree = NULL;
684
685 init_job_options(&opt);
686
687 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100688 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200689 {
690 char_u *p, *ep;
691
692 cmd += 2;
693 p = skiptowhite(cmd);
694 ep = vim_strchr(cmd, '=');
695 if (ep != NULL && ep < p)
696 p = ep;
697
698 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
699 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100700 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
701 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200702 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
703 opt.jo_term_finish = 'o';
704 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
705 opt.jo_curwin = 1;
706 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
707 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100708 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
709 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100710 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
711 && ep != NULL)
712 {
713 opt.jo_set2 |= JO2_TERM_KILL;
714 opt.jo_term_kill = ep + 1;
715 p = skiptowhite(cmd);
716 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200717 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
718 && ep != NULL && isdigit(ep[1]))
719 {
720 opt.jo_set2 |= JO2_TERM_ROWS;
721 opt.jo_term_rows = atoi((char *)ep + 1);
722 p = skiptowhite(cmd);
723 }
724 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
725 && ep != NULL && isdigit(ep[1]))
726 {
727 opt.jo_set2 |= JO2_TERM_COLS;
728 opt.jo_term_cols = atoi((char *)ep + 1);
729 p = skiptowhite(cmd);
730 }
731 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
732 && ep != NULL)
733 {
734 char_u *buf = NULL;
735 char_u *keys;
736
737 p = skiptowhite(cmd);
738 *p = NUL;
739 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
740 opt.jo_set2 |= JO2_EOF_CHARS;
741 opt.jo_eof_chars = vim_strsave(keys);
742 vim_free(buf);
743 *p = ' ';
744 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100745#ifdef WIN3264
746 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
747 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100748 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100749 int tty_type = NUL;
750
751 p = skiptowhite(cmd);
752 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
753 tty_type = 'w';
754 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
755 tty_type = 'c';
756 else
757 {
758 semsg(e_invargval, "type");
759 goto theend;
760 }
761 opt.jo_set2 |= JO2_TTY_TYPE;
762 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100763 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100764#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200765 else
766 {
767 if (*p)
768 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100769 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100770 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200771 }
772 cmd = skipwhite(p);
773 }
774 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100775 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200776 /* Make a copy of 'shell', an autocommand may change the option. */
777 tofree = cmd = vim_strsave(p_sh);
778
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100779 /* default to close when the shell exits */
780 if (opt.jo_term_finish == NUL)
781 opt.jo_term_finish = 'c';
782 }
783
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200784 if (eap->addr_count > 0)
785 {
786 /* Write lines from current buffer to the job. */
787 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
788 opt.jo_io[PART_IN] = JIO_BUFFER;
789 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
790 opt.jo_in_top = eap->line1;
791 opt.jo_in_bot = eap->line2;
792 }
793
794 argvar[0].v_type = VAR_STRING;
795 argvar[0].vval.v_string = cmd;
796 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100797 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200798 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100799
800theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200801 vim_free(opt.jo_eof_chars);
802}
803
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100804#if defined(FEAT_SESSION) || defined(PROTO)
805/*
806 * Write a :terminal command to the session file to restore the terminal in
807 * window "wp".
808 * Return FAIL if writing fails.
809 */
810 int
811term_write_session(FILE *fd, win_T *wp)
812{
813 term_T *term = wp->w_buffer->b_term;
814
815 /* Create the terminal and run the command. This is not without
816 * risk, but let's assume the user only creates a session when this
817 * will be OK. */
818 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
819 term->tl_cols, term->tl_rows) < 0)
820 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100821#ifdef WIN3264
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100822 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
823 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100824#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100825 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
826 return FAIL;
827
828 return put_eol(fd);
829}
830
831/*
832 * Return TRUE if "buf" has a terminal that should be restored.
833 */
834 int
835term_should_restore(buf_T *buf)
836{
837 term_T *term = buf->b_term;
838
839 return term != NULL && (term->tl_command == NULL
840 || STRCMP(term->tl_command, "NONE") != 0);
841}
842#endif
843
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200844/*
845 * Free the scrollback buffer for "term".
846 */
847 static void
848free_scrollback(term_T *term)
849{
850 int i;
851
852 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
853 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
854 ga_clear(&term->tl_scrollback);
855}
856
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100857
858// Terminals that need to be freed soon.
859term_T *terminals_to_free = NULL;
860
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200861/*
862 * Free a terminal and everything it refers to.
863 * Kills the job if there is one.
864 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100865 * The actual terminal structure is freed later in free_unused_terminals(),
866 * because callbacks may wipe out a buffer while the terminal is still
867 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200868 */
869 void
870free_terminal(buf_T *buf)
871{
872 term_T *term = buf->b_term;
873 term_T *tp;
874
875 if (term == NULL)
876 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100877
878 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200879 if (first_term == term)
880 first_term = term->tl_next;
881 else
882 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
883 if (tp->tl_next == term)
884 {
885 tp->tl_next = term->tl_next;
886 break;
887 }
888
889 if (term->tl_job != NULL)
890 {
891 if (term->tl_job->jv_status != JOB_ENDED
892 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100893 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200894 job_stop(term->tl_job, NULL, "kill");
895 job_unref(term->tl_job);
896 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100897 term->tl_next = terminals_to_free;
898 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200899
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200900 buf->b_term = NULL;
901 if (in_terminal_loop == term)
902 in_terminal_loop = NULL;
903}
904
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100905 void
906free_unused_terminals()
907{
908 while (terminals_to_free != NULL)
909 {
910 term_T *term = terminals_to_free;
911
912 terminals_to_free = term->tl_next;
913
914 free_scrollback(term);
915
916 term_free_vterm(term);
917 vim_free(term->tl_title);
918#ifdef FEAT_SESSION
919 vim_free(term->tl_command);
920#endif
921 vim_free(term->tl_kill);
922 vim_free(term->tl_status_text);
923 vim_free(term->tl_opencmd);
924 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100925 vim_free(term->tl_arg0_cmd);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100926#ifdef WIN3264
927 if (term->tl_out_fd != NULL)
928 fclose(term->tl_out_fd);
929#endif
930 vim_free(term->tl_cursor_color);
931 vim_free(term);
932 }
933}
934
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200935/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100936 * Get the part that is connected to the tty. Normally this is PART_IN, but
937 * when writing buffer lines to the job it can be another. This makes it
938 * possible to do "1,5term vim -".
939 */
940 static ch_part_T
941get_tty_part(term_T *term)
942{
943#ifdef UNIX
944 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
945 int i;
946
947 for (i = 0; i < 3; ++i)
948 {
949 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
950
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +0100951 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100952 return parts[i];
953 }
954#endif
955 return PART_IN;
956}
957
958/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200959 * Write job output "msg[len]" to the vterm.
960 */
961 static void
962term_write_job_output(term_T *term, char_u *msg, size_t len)
963{
964 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100965 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200966
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100967 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200968
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100969 /* flush vterm buffer when vterm responded to control sequence */
970 if (prevlen != vterm_output_get_buffer_current(vterm))
971 {
972 char buf[KEY_BUF_LEN];
973 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
974
975 if (curlen > 0)
976 channel_send(term->tl_job->jv_channel, get_tty_part(term),
977 (char_u *)buf, (int)curlen, NULL);
978 }
979
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200980 /* this invokes the damage callbacks */
981 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
982}
983
984 static void
985update_cursor(term_T *term, int redraw)
986{
987 if (term->tl_normal_mode)
988 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100989#ifdef FEAT_GUI
990 if (term->tl_system)
991 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
992 term->tl_cursor_pos.col);
993 else
994#endif
995 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200996 if (redraw)
997 {
998 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
999 cursor_on();
1000 out_flush();
1001#ifdef FEAT_GUI
1002 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001003 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001004 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001005 gui_mch_flush();
1006 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001007#endif
1008 }
1009}
1010
1011/*
1012 * Invoked when "msg" output from a job was received. Write it to the terminal
1013 * of "buffer".
1014 */
1015 void
1016write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1017{
1018 size_t len = STRLEN(msg);
1019 term_T *term = buffer->b_term;
1020
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001021#ifdef WIN3264
1022 /* Win32: Cannot redirect output of the job, intercept it here and write to
1023 * the file. */
1024 if (term->tl_out_fd != NULL)
1025 {
1026 ch_log(channel, "Writing %d bytes to output file", (int)len);
1027 fwrite(msg, len, 1, term->tl_out_fd);
1028 return;
1029 }
1030#endif
1031
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001032 if (term->tl_vterm == NULL)
1033 {
1034 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1035 return;
1036 }
1037 ch_log(channel, "writing %d bytes to terminal", (int)len);
1038 term_write_job_output(term, msg, len);
1039
Bram Moolenaar13568252018-03-16 20:46:58 +01001040#ifdef FEAT_GUI
1041 if (term->tl_system)
1042 {
1043 /* show system output, scrolling up the screen as needed */
1044 update_system_term(term);
1045 update_cursor(term, TRUE);
1046 }
1047 else
1048#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001049 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
1050 * contents, thus no screen update is needed. */
1051 if (!term->tl_normal_mode)
1052 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001053 // Don't use update_screen() when editing the command line, it gets
1054 // cleared.
1055 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001056 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001057 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001058 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001059 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001060 /* update_screen() can be slow, check the terminal wasn't closed
1061 * already */
1062 if (buffer == curbuf && curbuf->b_term != NULL)
1063 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001064 }
1065 else
1066 redraw_after_callback(TRUE);
1067 }
1068}
1069
1070/*
1071 * Send a mouse position and click to the vterm
1072 */
1073 static int
1074term_send_mouse(VTerm *vterm, int button, int pressed)
1075{
1076 VTermModifier mod = VTERM_MOD_NONE;
1077
1078 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001079 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001080 if (button != 0)
1081 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001082 return TRUE;
1083}
1084
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001085static int enter_mouse_col = -1;
1086static int enter_mouse_row = -1;
1087
1088/*
1089 * Handle a mouse click, drag or release.
1090 * Return TRUE when a mouse event is sent to the terminal.
1091 */
1092 static int
1093term_mouse_click(VTerm *vterm, int key)
1094{
1095#if defined(FEAT_CLIPBOARD)
1096 /* For modeless selection mouse drag and release events are ignored, unless
1097 * they are preceded with a mouse down event */
1098 static int ignore_drag_release = TRUE;
1099 VTermMouseState mouse_state;
1100
1101 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1102 if (mouse_state.flags == 0)
1103 {
1104 /* Terminal is not using the mouse, use modeless selection. */
1105 switch (key)
1106 {
1107 case K_LEFTDRAG:
1108 case K_LEFTRELEASE:
1109 case K_RIGHTDRAG:
1110 case K_RIGHTRELEASE:
1111 /* Ignore drag and release events when the button-down wasn't
1112 * seen before. */
1113 if (ignore_drag_release)
1114 {
1115 int save_mouse_col, save_mouse_row;
1116
1117 if (enter_mouse_col < 0)
1118 break;
1119
1120 /* mouse click in the window gave us focus, handle that
1121 * click now */
1122 save_mouse_col = mouse_col;
1123 save_mouse_row = mouse_row;
1124 mouse_col = enter_mouse_col;
1125 mouse_row = enter_mouse_row;
1126 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1127 mouse_col = save_mouse_col;
1128 mouse_row = save_mouse_row;
1129 }
1130 /* FALLTHROUGH */
1131 case K_LEFTMOUSE:
1132 case K_RIGHTMOUSE:
1133 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1134 ignore_drag_release = TRUE;
1135 else
1136 ignore_drag_release = FALSE;
1137 /* Should we call mouse_has() here? */
1138 if (clip_star.available)
1139 {
1140 int button, is_click, is_drag;
1141
1142 button = get_mouse_button(KEY2TERMCAP1(key),
1143 &is_click, &is_drag);
1144 if (mouse_model_popup() && button == MOUSE_LEFT
1145 && (mod_mask & MOD_MASK_SHIFT))
1146 {
1147 /* Translate shift-left to right button. */
1148 button = MOUSE_RIGHT;
1149 mod_mask &= ~MOD_MASK_SHIFT;
1150 }
1151 clip_modeless(button, is_click, is_drag);
1152 }
1153 break;
1154
1155 case K_MIDDLEMOUSE:
1156 if (clip_star.available)
1157 insert_reg('*', TRUE);
1158 break;
1159 }
1160 enter_mouse_col = -1;
1161 return FALSE;
1162 }
1163#endif
1164 enter_mouse_col = -1;
1165
1166 switch (key)
1167 {
1168 case K_LEFTMOUSE:
1169 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1170 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1171 case K_LEFTRELEASE:
1172 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1173 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1174 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1175 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1176 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1177 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1178 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1179 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1180 }
1181 return TRUE;
1182}
1183
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001184/*
1185 * Convert typed key "c" into bytes to send to the job.
1186 * Return the number of bytes in "buf".
1187 */
1188 static int
1189term_convert_key(term_T *term, int c, char *buf)
1190{
1191 VTerm *vterm = term->tl_vterm;
1192 VTermKey key = VTERM_KEY_NONE;
1193 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001194 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001195
1196 switch (c)
1197 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001198 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1199
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001200 /* don't use VTERM_KEY_BACKSPACE, it always
1201 * becomes 0x7f DEL */
1202 case K_BS: c = term_backspace_char; break;
1203
1204 case ESC: key = VTERM_KEY_ESCAPE; break;
1205 case K_DEL: key = VTERM_KEY_DEL; break;
1206 case K_DOWN: key = VTERM_KEY_DOWN; break;
1207 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1208 key = VTERM_KEY_DOWN; break;
1209 case K_END: key = VTERM_KEY_END; break;
1210 case K_S_END: mod = VTERM_MOD_SHIFT;
1211 key = VTERM_KEY_END; break;
1212 case K_C_END: mod = VTERM_MOD_CTRL;
1213 key = VTERM_KEY_END; break;
1214 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1215 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1216 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1217 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1218 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1219 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1220 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1221 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1222 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1223 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1224 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1225 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1226 case K_HOME: key = VTERM_KEY_HOME; break;
1227 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1228 key = VTERM_KEY_HOME; break;
1229 case K_C_HOME: mod = VTERM_MOD_CTRL;
1230 key = VTERM_KEY_HOME; break;
1231 case K_INS: key = VTERM_KEY_INS; break;
1232 case K_K0: key = VTERM_KEY_KP_0; break;
1233 case K_K1: key = VTERM_KEY_KP_1; break;
1234 case K_K2: key = VTERM_KEY_KP_2; break;
1235 case K_K3: key = VTERM_KEY_KP_3; break;
1236 case K_K4: key = VTERM_KEY_KP_4; break;
1237 case K_K5: key = VTERM_KEY_KP_5; break;
1238 case K_K6: key = VTERM_KEY_KP_6; break;
1239 case K_K7: key = VTERM_KEY_KP_7; break;
1240 case K_K8: key = VTERM_KEY_KP_8; break;
1241 case K_K9: key = VTERM_KEY_KP_9; break;
1242 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1243 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1244 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1245 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1246 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1247 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1248 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1249 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1250 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1251 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1252 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1253 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1254 case K_LEFT: key = VTERM_KEY_LEFT; break;
1255 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1256 key = VTERM_KEY_LEFT; break;
1257 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1258 key = VTERM_KEY_LEFT; break;
1259 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1260 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1261 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1262 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1263 key = VTERM_KEY_RIGHT; break;
1264 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1265 key = VTERM_KEY_RIGHT; break;
1266 case K_UP: key = VTERM_KEY_UP; break;
1267 case K_S_UP: mod = VTERM_MOD_SHIFT;
1268 key = VTERM_KEY_UP; break;
1269 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001270 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1271 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001272
Bram Moolenaara42ad572017-11-16 13:08:04 +01001273 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1274 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001275 case K_MOUSELEFT: /* TODO */ return 0;
1276 case K_MOUSERIGHT: /* TODO */ return 0;
1277
1278 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001279 case K_LEFTMOUSE_NM:
1280 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001281 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001282 case K_LEFTRELEASE_NM:
1283 case K_MOUSEMOVE:
1284 case K_MIDDLEMOUSE:
1285 case K_MIDDLEDRAG:
1286 case K_MIDDLERELEASE:
1287 case K_RIGHTMOUSE:
1288 case K_RIGHTDRAG:
1289 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1290 return 0;
1291 other = TRUE;
1292 break;
1293
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001294 case K_X1MOUSE: /* TODO */ return 0;
1295 case K_X1DRAG: /* TODO */ return 0;
1296 case K_X1RELEASE: /* TODO */ return 0;
1297 case K_X2MOUSE: /* TODO */ return 0;
1298 case K_X2DRAG: /* TODO */ return 0;
1299 case K_X2RELEASE: /* TODO */ return 0;
1300
1301 case K_IGNORE: return 0;
1302 case K_NOP: return 0;
1303 case K_UNDO: return 0;
1304 case K_HELP: return 0;
1305 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1306 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1307 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1308 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1309 case K_SELECT: return 0;
1310#ifdef FEAT_GUI
1311 case K_VER_SCROLLBAR: return 0;
1312 case K_HOR_SCROLLBAR: return 0;
1313#endif
1314#ifdef FEAT_GUI_TABLINE
1315 case K_TABLINE: return 0;
1316 case K_TABMENU: return 0;
1317#endif
1318#ifdef FEAT_NETBEANS_INTG
1319 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1320#endif
1321#ifdef FEAT_DND
1322 case K_DROP: return 0;
1323#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001324 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001325 case K_PS: vterm_keyboard_start_paste(vterm);
1326 other = TRUE;
1327 break;
1328 case K_PE: vterm_keyboard_end_paste(vterm);
1329 other = TRUE;
1330 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001331 }
1332
1333 /*
1334 * Convert special keys to vterm keys:
1335 * - Write keys to vterm: vterm_keyboard_key()
1336 * - Write output to channel.
1337 * TODO: use mod_mask
1338 */
1339 if (key != VTERM_KEY_NONE)
1340 /* Special key, let vterm convert it. */
1341 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001342 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001343 /* Normal character, let vterm convert it. */
1344 vterm_keyboard_unichar(vterm, c, mod);
1345
1346 /* Read back the converted escape sequence. */
1347 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1348}
1349
1350/*
1351 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001352 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001353 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001354 */
1355 static int
1356term_job_running_check(term_T *term, int check_job_status)
1357{
1358 /* Also consider the job finished when the channel is closed, to avoid a
1359 * race condition when updating the title. */
1360 if (term != NULL
1361 && term->tl_job != NULL
1362 && channel_is_open(term->tl_job->jv_channel))
1363 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001364 job_T *job = term->tl_job;
1365
1366 // Careful: Checking the job status may invoked callbacks, which close
1367 // the buffer and terminate "term". However, "job" will not be freed
1368 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001369 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001370 job_status(job);
1371 return (job->jv_status == JOB_STARTED
1372 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001373 }
1374 return FALSE;
1375}
1376
1377/*
1378 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001379 */
1380 int
1381term_job_running(term_T *term)
1382{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001383 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001384}
1385
1386/*
1387 * Return TRUE if "term" has an active channel and used ":term NONE".
1388 */
1389 int
1390term_none_open(term_T *term)
1391{
1392 /* Also consider the job finished when the channel is closed, to avoid a
1393 * race condition when updating the title. */
1394 return term != NULL
1395 && term->tl_job != NULL
1396 && channel_is_open(term->tl_job->jv_channel)
1397 && term->tl_job->jv_channel->ch_keep_open;
1398}
1399
1400/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001401 * Used when exiting: kill the job in "buf" if so desired.
1402 * Return OK when the job finished.
1403 * Return FAIL when the job is still running.
1404 */
1405 int
1406term_try_stop_job(buf_T *buf)
1407{
1408 int count;
1409 char *how = (char *)buf->b_term->tl_kill;
1410
1411#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1412 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1413 {
1414 char_u buff[DIALOG_MSG_SIZE];
1415 int ret;
1416
1417 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1418 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1419 if (ret == VIM_YES)
1420 how = "kill";
1421 else if (ret == VIM_CANCEL)
1422 return FAIL;
1423 }
1424#endif
1425 if (how == NULL || *how == NUL)
1426 return FAIL;
1427
1428 job_stop(buf->b_term->tl_job, NULL, how);
1429
Bram Moolenaar9172d232019-01-29 23:06:54 +01001430 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001431 for (count = 0; count < 100; ++count)
1432 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001433 job_T *job;
1434
1435 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001436 if (!buf_valid(buf)
1437 || buf->b_term == NULL
1438 || buf->b_term->tl_job == NULL)
1439 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001440 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001441
Bram Moolenaar9172d232019-01-29 23:06:54 +01001442 // Call job_status() to update jv_status. It may cause the job to be
1443 // cleaned up but it won't be freed.
1444 job_status(job);
1445 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001446 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001447
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001448 ui_delay(10L, FALSE);
1449 mch_check_messages();
1450 parse_queued_messages();
1451 }
1452 return FAIL;
1453}
1454
1455/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001456 * Add the last line of the scrollback buffer to the buffer in the window.
1457 */
1458 static void
1459add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1460{
1461 buf_T *buf = term->tl_buffer;
1462 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1463 linenr_T lnum = buf->b_ml.ml_line_count;
1464
1465#ifdef WIN3264
1466 if (!enc_utf8 && enc_codepage > 0)
1467 {
1468 WCHAR *ret = NULL;
1469 int length = 0;
1470
1471 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1472 &ret, &length);
1473 if (ret != NULL)
1474 {
1475 WideCharToMultiByte_alloc(enc_codepage, 0,
1476 ret, length, (char **)&text, &len, 0, 0);
1477 vim_free(ret);
1478 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1479 vim_free(text);
1480 }
1481 }
1482 else
1483#endif
1484 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1485 if (empty)
1486 {
1487 /* Delete the empty line that was in the empty buffer. */
1488 curbuf = buf;
1489 ml_delete(1, FALSE);
1490 curbuf = curwin->w_buffer;
1491 }
1492}
1493
1494 static void
1495cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1496{
1497 attr->width = cell->width;
1498 attr->attrs = cell->attrs;
1499 attr->fg = cell->fg;
1500 attr->bg = cell->bg;
1501}
1502
1503 static int
1504equal_celattr(cellattr_T *a, cellattr_T *b)
1505{
1506 /* Comparing the colors should be sufficient. */
1507 return a->fg.red == b->fg.red
1508 && a->fg.green == b->fg.green
1509 && a->fg.blue == b->fg.blue
1510 && a->bg.red == b->bg.red
1511 && a->bg.green == b->bg.green
1512 && a->bg.blue == b->bg.blue;
1513}
1514
Bram Moolenaard96ff162018-02-18 22:13:29 +01001515/*
1516 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1517 * line at this position. Otherwise at the end.
1518 */
1519 static int
1520add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1521{
1522 if (ga_grow(&term->tl_scrollback, 1) == OK)
1523 {
1524 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1525 + term->tl_scrollback.ga_len;
1526
1527 if (lnum > 0)
1528 {
1529 int i;
1530
1531 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1532 {
1533 *line = *(line - 1);
1534 --line;
1535 }
1536 }
1537 line->sb_cols = 0;
1538 line->sb_cells = NULL;
1539 line->sb_fill_attr = *fill_attr;
1540 ++term->tl_scrollback.ga_len;
1541 return OK;
1542 }
1543 return FALSE;
1544}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001545
1546/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001547 * Remove the terminal contents from the scrollback and the buffer.
1548 * Used before adding a new scrollback line or updating the buffer for lines
1549 * displayed in the terminal.
1550 */
1551 static void
1552cleanup_scrollback(term_T *term)
1553{
1554 sb_line_T *line;
1555 garray_T *gap;
1556
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001557 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001558 gap = &term->tl_scrollback;
1559 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1560 && gap->ga_len > 0)
1561 {
1562 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1563 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1564 vim_free(line->sb_cells);
1565 --gap->ga_len;
1566 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001567 curbuf = curwin->w_buffer;
1568 if (curbuf == term->tl_buffer)
1569 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001570}
1571
1572/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001573 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001574 */
1575 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001576update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001577{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001578 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001579 int len;
1580 int lines_skipped = 0;
1581 VTermPos pos;
1582 VTermScreenCell cell;
1583 cellattr_T fill_attr, new_fill_attr;
1584 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001585
1586 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1587 "Adding terminal window snapshot to buffer");
1588
1589 /* First remove the lines that were appended before, they might be
1590 * outdated. */
1591 cleanup_scrollback(term);
1592
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001593 screen = vterm_obtain_screen(term->tl_vterm);
1594 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001595 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1596 {
1597 len = 0;
1598 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1599 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1600 && cell.chars[0] != NUL)
1601 {
1602 len = pos.col + 1;
1603 new_fill_attr = term->tl_default_color;
1604 }
1605 else
1606 /* Assume the last attr is the filler attr. */
1607 cell2cellattr(&cell, &new_fill_attr);
1608
1609 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1610 ++lines_skipped;
1611 else
1612 {
1613 while (lines_skipped > 0)
1614 {
1615 /* Line was skipped, add an empty line. */
1616 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001617 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001618 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001619 }
1620
1621 if (len == 0)
1622 p = NULL;
1623 else
1624 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1625 if ((p != NULL || len == 0)
1626 && ga_grow(&term->tl_scrollback, 1) == OK)
1627 {
1628 garray_T ga;
1629 int width;
1630 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1631 + term->tl_scrollback.ga_len;
1632
1633 ga_init2(&ga, 1, 100);
1634 for (pos.col = 0; pos.col < len; pos.col += width)
1635 {
1636 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1637 {
1638 width = 1;
1639 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1640 if (ga_grow(&ga, 1) == OK)
1641 ga.ga_len += utf_char2bytes(' ',
1642 (char_u *)ga.ga_data + ga.ga_len);
1643 }
1644 else
1645 {
1646 width = cell.width;
1647
1648 cell2cellattr(&cell, &p[pos.col]);
1649
Bram Moolenaara79fd562018-12-20 20:47:32 +01001650 // Each character can be up to 6 bytes.
1651 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001652 {
1653 int i;
1654 int c;
1655
1656 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1657 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1658 (char_u *)ga.ga_data + ga.ga_len);
1659 }
1660 }
1661 }
1662 line->sb_cols = len;
1663 line->sb_cells = p;
1664 line->sb_fill_attr = new_fill_attr;
1665 fill_attr = new_fill_attr;
1666 ++term->tl_scrollback.ga_len;
1667
1668 if (ga_grow(&ga, 1) == FAIL)
1669 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1670 else
1671 {
1672 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1673 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1674 }
1675 ga_clear(&ga);
1676 }
1677 else
1678 vim_free(p);
1679 }
1680 }
1681
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001682 // Add trailing empty lines.
1683 for (pos.row = term->tl_scrollback.ga_len;
1684 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1685 ++pos.row)
1686 {
1687 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1688 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1689 }
1690
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001691 term->tl_dirty_snapshot = FALSE;
1692#ifdef FEAT_TIMERS
1693 term->tl_timer_set = FALSE;
1694#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001695}
1696
1697/*
1698 * If needed, add the current lines of the terminal to scrollback and to the
1699 * buffer. Called after the job has ended and when switching to
1700 * Terminal-Normal mode.
1701 * When "redraw" is TRUE redraw the windows that show the terminal.
1702 */
1703 static void
1704may_move_terminal_to_buffer(term_T *term, int redraw)
1705{
1706 win_T *wp;
1707
1708 if (term->tl_vterm == NULL)
1709 return;
1710
1711 /* Update the snapshot only if something changes or the buffer does not
1712 * have all the lines. */
1713 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1714 <= term->tl_scrollback_scrolled)
1715 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001716
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001717 /* Obtain the current background color. */
1718 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1719 &term->tl_default_color.fg, &term->tl_default_color.bg);
1720
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001721 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001722 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001723 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001724 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001725 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001726 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1727 wp->w_cursor.col = 0;
1728 wp->w_valid = 0;
1729 if (wp->w_cursor.lnum >= wp->w_height)
1730 {
1731 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001732
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001733 if (wp->w_topline < min_topline)
1734 wp->w_topline = min_topline;
1735 }
1736 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001737 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001738 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001739}
1740
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001741#if defined(FEAT_TIMERS) || defined(PROTO)
1742/*
1743 * Check if any terminal timer expired. If so, copy text from the terminal to
1744 * the buffer.
1745 * Return the time until the next timer will expire.
1746 */
1747 int
1748term_check_timers(int next_due_arg, proftime_T *now)
1749{
1750 term_T *term;
1751 int next_due = next_due_arg;
1752
1753 for (term = first_term; term != NULL; term = term->tl_next)
1754 {
1755 if (term->tl_timer_set && !term->tl_normal_mode)
1756 {
1757 long this_due = proftime_time_left(&term->tl_timer_due, now);
1758
1759 if (this_due <= 1)
1760 {
1761 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001762 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001763 }
1764 else if (next_due == -1 || next_due > this_due)
1765 next_due = this_due;
1766 }
1767 }
1768
1769 return next_due;
1770}
1771#endif
1772
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001773 static void
1774set_terminal_mode(term_T *term, int normal_mode)
1775{
1776 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001777 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001778 if (term->tl_buffer == curbuf)
1779 maketitle();
1780}
1781
1782/*
1783 * Called after the job if finished and Terminal mode is not active:
1784 * Move the vterm contents into the scrollback buffer and free the vterm.
1785 */
1786 static void
1787cleanup_vterm(term_T *term)
1788{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001789 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001790 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001791 term_free_vterm(term);
1792 set_terminal_mode(term, FALSE);
1793}
1794
1795/*
1796 * Switch from Terminal-Job mode to Terminal-Normal mode.
1797 * Suspends updating the terminal window.
1798 */
1799 static void
1800term_enter_normal_mode(void)
1801{
1802 term_T *term = curbuf->b_term;
1803
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001804 set_terminal_mode(term, TRUE);
1805
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001806 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001807 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001808
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001809 /* Move the window cursor to the position of the cursor in the
1810 * terminal. */
1811 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1812 + term->tl_cursor_pos.row + 1;
1813 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001814 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1815 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001816
1817 /* Display the same lines as in the terminal. */
1818 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1819}
1820
1821/*
1822 * Returns TRUE if the current window contains a terminal and we are in
1823 * Terminal-Normal mode.
1824 */
1825 int
1826term_in_normal_mode(void)
1827{
1828 term_T *term = curbuf->b_term;
1829
1830 return term != NULL && term->tl_normal_mode;
1831}
1832
1833/*
1834 * Switch from Terminal-Normal mode to Terminal-Job mode.
1835 * Restores updating the terminal window.
1836 */
1837 void
1838term_enter_job_mode()
1839{
1840 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001841
1842 set_terminal_mode(term, FALSE);
1843
1844 if (term->tl_channel_closed)
1845 cleanup_vterm(term);
1846 redraw_buf_and_status_later(curbuf, NOT_VALID);
1847}
1848
1849/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001850 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001851 * Note: while waiting a terminal may be closed and freed if the channel is
1852 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001853 */
1854 static int
1855term_vgetc()
1856{
1857 int c;
1858 int save_State = State;
1859
1860 State = TERMINAL;
1861 got_int = FALSE;
1862#ifdef WIN3264
1863 ctrl_break_was_pressed = FALSE;
1864#endif
1865 c = vgetc();
1866 got_int = FALSE;
1867 State = save_State;
1868 return c;
1869}
1870
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001871static int mouse_was_outside = FALSE;
1872
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001873/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001874 * Send keys to terminal.
1875 * Return FAIL when the key needs to be handled in Normal mode.
1876 * Return OK when the key was dropped or sent to the terminal.
1877 */
1878 int
1879send_keys_to_term(term_T *term, int c, int typed)
1880{
1881 char msg[KEY_BUF_LEN];
1882 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001883 int dragging_outside = FALSE;
1884
1885 /* Catch keys that need to be handled as in Normal mode. */
1886 switch (c)
1887 {
1888 case NUL:
1889 case K_ZERO:
1890 if (typed)
1891 stuffcharReadbuff(c);
1892 return FAIL;
1893
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001894 case K_TABLINE:
1895 stuffcharReadbuff(c);
1896 return FAIL;
1897
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001898 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001899 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001900 return FAIL;
1901
1902 case K_LEFTDRAG:
1903 case K_MIDDLEDRAG:
1904 case K_RIGHTDRAG:
1905 case K_X1DRAG:
1906 case K_X2DRAG:
1907 dragging_outside = mouse_was_outside;
1908 /* FALLTHROUGH */
1909 case K_LEFTMOUSE:
1910 case K_LEFTMOUSE_NM:
1911 case K_LEFTRELEASE:
1912 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001913 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001914 case K_MIDDLEMOUSE:
1915 case K_MIDDLERELEASE:
1916 case K_RIGHTMOUSE:
1917 case K_RIGHTRELEASE:
1918 case K_X1MOUSE:
1919 case K_X1RELEASE:
1920 case K_X2MOUSE:
1921 case K_X2RELEASE:
1922
1923 case K_MOUSEUP:
1924 case K_MOUSEDOWN:
1925 case K_MOUSELEFT:
1926 case K_MOUSERIGHT:
1927 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001928 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001929 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001930 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001931 || dragging_outside)
1932 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001933 /* click or scroll outside the current window or on status line
1934 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001935 if (typed)
1936 {
1937 stuffcharReadbuff(c);
1938 mouse_was_outside = TRUE;
1939 }
1940 return FAIL;
1941 }
1942 }
1943 if (typed)
1944 mouse_was_outside = FALSE;
1945
1946 /* Convert the typed key to a sequence of bytes for the job. */
1947 len = term_convert_key(term, c, msg);
1948 if (len > 0)
1949 /* TODO: if FAIL is returned, stop? */
1950 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1951 (char_u *)msg, (int)len, NULL);
1952
1953 return OK;
1954}
1955
1956 static void
1957position_cursor(win_T *wp, VTermPos *pos)
1958{
1959 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1960 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1961 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1962}
1963
1964/*
1965 * Handle CTRL-W "": send register contents to the job.
1966 */
1967 static void
1968term_paste_register(int prev_c UNUSED)
1969{
1970 int c;
1971 list_T *l;
1972 listitem_T *item;
1973 long reglen = 0;
1974 int type;
1975
1976#ifdef FEAT_CMDL_INFO
1977 if (add_to_showcmd(prev_c))
1978 if (add_to_showcmd('"'))
1979 out_flush();
1980#endif
1981 c = term_vgetc();
1982#ifdef FEAT_CMDL_INFO
1983 clear_showcmd();
1984#endif
1985 if (!term_use_loop())
1986 /* job finished while waiting for a character */
1987 return;
1988
1989 /* CTRL-W "= prompt for expression to evaluate. */
1990 if (c == '=' && get_expr_register() != '=')
1991 return;
1992 if (!term_use_loop())
1993 /* job finished while waiting for a character */
1994 return;
1995
1996 l = (list_T *)get_reg_contents(c, GREG_LIST);
1997 if (l != NULL)
1998 {
1999 type = get_reg_type(c, &reglen);
2000 for (item = l->lv_first; item != NULL; item = item->li_next)
2001 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002002 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002003#ifdef WIN3264
2004 char_u *tmp = s;
2005
2006 if (!enc_utf8 && enc_codepage > 0)
2007 {
2008 WCHAR *ret = NULL;
2009 int length = 0;
2010
2011 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2012 (int)STRLEN(s), &ret, &length);
2013 if (ret != NULL)
2014 {
2015 WideCharToMultiByte_alloc(CP_UTF8, 0,
2016 ret, length, (char **)&s, &length, 0, 0);
2017 vim_free(ret);
2018 }
2019 }
2020#endif
2021 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2022 s, (int)STRLEN(s), NULL);
2023#ifdef WIN3264
2024 if (tmp != s)
2025 vim_free(s);
2026#endif
2027
2028 if (item->li_next != NULL || type == MLINE)
2029 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2030 (char_u *)"\r", 1, NULL);
2031 }
2032 list_free(l);
2033 }
2034}
2035
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002036/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002037 * Return TRUE when waiting for a character in the terminal, the cursor of the
2038 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002039 */
2040 int
2041terminal_is_active()
2042{
2043 return in_terminal_loop != NULL;
2044}
2045
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002046#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002047 cursorentry_T *
2048term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2049{
2050 term_T *term = in_terminal_loop;
2051 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002052 int id;
2053 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002054
2055 vim_memset(&entry, 0, sizeof(entry));
2056 entry.shape = entry.mshape =
2057 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2058 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2059 SHAPE_BLOCK;
2060 entry.percentage = 20;
2061 if (term->tl_cursor_blink)
2062 {
2063 entry.blinkwait = 700;
2064 entry.blinkon = 400;
2065 entry.blinkoff = 250;
2066 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002067
2068 /* The "Terminal" highlight group overrules the defaults. */
2069 id = syn_name2id((char_u *)"Terminal");
2070 if (id != 0)
2071 {
2072 syn_id2colors(id, &term_fg, &term_bg);
2073 *fg = term_bg;
2074 }
2075 else
2076 *fg = gui.back_pixel;
2077
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002078 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002079 {
2080 if (id != 0)
2081 *bg = term_fg;
2082 else
2083 *bg = gui.norm_pixel;
2084 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002085 else
2086 *bg = color_name2handle(term->tl_cursor_color);
2087 entry.name = "n";
2088 entry.used_for = SHAPE_CURSOR;
2089
2090 return &entry;
2091}
2092#endif
2093
Bram Moolenaard317b382018-02-08 22:33:31 +01002094 static void
2095may_output_cursor_props(void)
2096{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002097 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002098 || last_set_cursor_shape != desired_cursor_shape
2099 || last_set_cursor_blink != desired_cursor_blink)
2100 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002101 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002102 last_set_cursor_shape = desired_cursor_shape;
2103 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002104 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002105 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2106 /* this will restore the initial cursor style, if possible */
2107 ui_cursor_shape_forced(TRUE);
2108 else
2109 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2110 }
2111}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002112
Bram Moolenaard317b382018-02-08 22:33:31 +01002113/*
2114 * Set the cursor color and shape, if not last set to these.
2115 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002116 static void
2117may_set_cursor_props(term_T *term)
2118{
2119#ifdef FEAT_GUI
2120 /* For the GUI the cursor properties are obtained with
2121 * term_get_cursor_shape(). */
2122 if (gui.in_use)
2123 return;
2124#endif
2125 if (in_terminal_loop == term)
2126 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002127 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002128 desired_cursor_shape = term->tl_cursor_shape;
2129 desired_cursor_blink = term->tl_cursor_blink;
2130 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002131 }
2132}
2133
Bram Moolenaard317b382018-02-08 22:33:31 +01002134/*
2135 * Reset the desired cursor properties and restore them when needed.
2136 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002137 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002138prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002139{
2140#ifdef FEAT_GUI
2141 if (gui.in_use)
2142 return;
2143#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002144 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002145 desired_cursor_shape = -1;
2146 desired_cursor_blink = -1;
2147 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002148}
2149
2150/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002151 * Returns TRUE if the current window contains a terminal and we are sending
2152 * keys to the job.
2153 * If "check_job_status" is TRUE update the job status.
2154 */
2155 static int
2156term_use_loop_check(int check_job_status)
2157{
2158 term_T *term = curbuf->b_term;
2159
2160 return term != NULL
2161 && !term->tl_normal_mode
2162 && term->tl_vterm != NULL
2163 && term_job_running_check(term, check_job_status);
2164}
2165
2166/*
2167 * Returns TRUE if the current window contains a terminal and we are sending
2168 * keys to the job.
2169 */
2170 int
2171term_use_loop(void)
2172{
2173 return term_use_loop_check(FALSE);
2174}
2175
2176/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002177 * Called when entering a window with the mouse. If this is a terminal window
2178 * we may want to change state.
2179 */
2180 void
2181term_win_entered()
2182{
2183 term_T *term = curbuf->b_term;
2184
2185 if (term != NULL)
2186 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002187 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002188 {
2189 reset_VIsual_and_resel();
2190 if (State & INSERT)
2191 stop_insert_mode = TRUE;
2192 }
2193 mouse_was_outside = FALSE;
2194 enter_mouse_col = mouse_col;
2195 enter_mouse_row = mouse_row;
2196 }
2197}
2198
2199/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002200 * Wait for input and send it to the job.
2201 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2202 * when there is no more typahead.
2203 * Return when the start of a CTRL-W command is typed or anything else that
2204 * should be handled as a Normal mode command.
2205 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2206 * the terminal was closed.
2207 */
2208 int
2209terminal_loop(int blocking)
2210{
2211 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002212 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002213 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002214#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002215 int tty_fd = curbuf->b_term->tl_job->jv_channel
2216 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002217#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002218 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002219
2220 /* Remember the terminal we are sending keys to. However, the terminal
2221 * might be closed while waiting for a character, e.g. typing "exit" in a
2222 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2223 * stored reference. */
2224 in_terminal_loop = curbuf->b_term;
2225
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002226 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002227 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002228 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002229 if (termwinkey == Ctrl_W)
2230 termwinkey = 0;
2231 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002232 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2233 may_set_cursor_props(curbuf->b_term);
2234
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002235 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002237#ifdef FEAT_GUI
2238 if (!curbuf->b_term->tl_system)
2239#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002240 // TODO: skip screen update when handling a sequence of keys.
2241 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002242 while (must_redraw != 0)
2243 if (update_screen(0) == FAIL)
2244 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002245 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002246 /* job finished while redrawing */
2247 break;
2248
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002249 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002250 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002251
2252 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002253 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002254 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002255 /* Job finished while waiting for a character. Push back the
2256 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002257 if (c != K_IGNORE)
2258 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002259 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002260 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002261 if (c == K_IGNORE)
2262 continue;
2263
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002264#ifdef UNIX
2265 /*
2266 * The shell or another program may change the tty settings. Getting
2267 * them for every typed character is a bit of overhead, but it's needed
2268 * for the first character typed, e.g. when Vim starts in a shell.
2269 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002270 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002271 {
2272 ttyinfo_T info;
2273
2274 /* Get the current backspace character of the pty. */
2275 if (get_tty_info(tty_fd, &info) == OK)
2276 term_backspace_char = info.backspace;
2277 }
2278#endif
2279
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002280#ifdef WIN3264
2281 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2282 * Use CTRL-BREAK to kill the job. */
2283 if (ctrl_break_was_pressed)
2284 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2285#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002286 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002287 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002288 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002289#ifdef FEAT_GUI
2290 && !curbuf->b_term->tl_system
2291#endif
2292 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002293 {
2294 int prev_c = c;
2295
2296#ifdef FEAT_CMDL_INFO
2297 if (add_to_showcmd(c))
2298 out_flush();
2299#endif
2300 c = term_vgetc();
2301#ifdef FEAT_CMDL_INFO
2302 clear_showcmd();
2303#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002304 if (!term_use_loop_check(TRUE)
2305 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002306 /* job finished while waiting for a character */
2307 break;
2308
2309 if (prev_c == Ctrl_BSL)
2310 {
2311 if (c == Ctrl_N)
2312 {
2313 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2314 term_enter_normal_mode();
2315 ret = FAIL;
2316 goto theend;
2317 }
2318 /* Send both keys to the terminal. */
2319 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2320 }
2321 else if (c == Ctrl_C)
2322 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002323 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002324 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2325 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002326 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002327 {
2328 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002329 /* "'termwinkey' .": send 'termwinkey' to the job */
2330 c = termwinkey == 0 ? Ctrl_W : termwinkey;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002331 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002332 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002333 {
2334 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2335 c = Ctrl_BSL;
2336 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002337 else if (c == 'N')
2338 {
2339 /* CTRL-W N : go to Terminal-Normal mode. */
2340 term_enter_normal_mode();
2341 ret = FAIL;
2342 goto theend;
2343 }
2344 else if (c == '"')
2345 {
2346 term_paste_register(prev_c);
2347 continue;
2348 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002349 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002350 {
2351 stuffcharReadbuff(Ctrl_W);
2352 stuffcharReadbuff(c);
2353 ret = OK;
2354 goto theend;
2355 }
2356 }
2357# ifdef WIN3264
2358 if (!enc_utf8 && has_mbyte && c >= 0x80)
2359 {
2360 WCHAR wc;
2361 char_u mb[3];
2362
2363 mb[0] = (unsigned)c >> 8;
2364 mb[1] = c;
2365 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2366 c = wc;
2367 }
2368# endif
2369 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2370 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002371 if (c == K_MOUSEMOVE)
2372 /* We are sure to come back here, don't reset the cursor color
2373 * and shape to avoid flickering. */
2374 restore_cursor = FALSE;
2375
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002376 ret = OK;
2377 goto theend;
2378 }
2379 }
2380 ret = FAIL;
2381
2382theend:
2383 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002384 if (restore_cursor)
2385 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002386
2387 /* Move a snapshot of the screen contents to the buffer, so that completion
2388 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002389 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2390 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002391
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002392 return ret;
2393}
2394
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002395 static void
2396may_toggle_cursor(term_T *term)
2397{
2398 if (in_terminal_loop == term)
2399 {
2400 if (term->tl_cursor_visible)
2401 cursor_on();
2402 else
2403 cursor_off();
2404 }
2405}
2406
2407/*
2408 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002409 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002410 */
2411 static int
2412color2index(VTermColor *color, int fg, int *boldp)
2413{
2414 int red = color->red;
2415 int blue = color->blue;
2416 int green = color->green;
2417
Bram Moolenaar46359e12017-11-29 22:33:38 +01002418 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002419 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002420 /* First 16 colors and default: use the ANSI index, because these
2421 * colors can be redefined. */
2422 if (t_colors >= 16)
2423 return color->ansi_index;
2424 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002425 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002426 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002427 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002428 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2429 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2430 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002431 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002432 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2433 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2434 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2435 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2436 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2437 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2438 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2439 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2440 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2441 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2442 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002443 }
2444 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002445
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002446 if (t_colors >= 256)
2447 {
2448 if (red == blue && red == green)
2449 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002450 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002451 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002452 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2453 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2454 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002455 int i;
2456
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002457 if (red < 5)
2458 return 17; /* 00/00/00 */
2459 if (red > 245) /* ff/ff/ff */
2460 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002461 for (i = 0; i < 23; ++i)
2462 if (red < cutoff[i])
2463 return i + 233;
2464 return 256;
2465 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002466 {
2467 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2468 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002469
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002470 /* 216-color cube */
2471 for (ri = 0; ri < 5; ++ri)
2472 if (red < cutoff[ri])
2473 break;
2474 for (gi = 0; gi < 5; ++gi)
2475 if (green < cutoff[gi])
2476 break;
2477 for (bi = 0; bi < 5; ++bi)
2478 if (blue < cutoff[bi])
2479 break;
2480 return 17 + ri * 36 + gi * 6 + bi;
2481 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002482 }
2483 return 0;
2484}
2485
2486/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002487 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002488 */
2489 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002490vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002491{
2492 int attr = 0;
2493
2494 if (cellattrs.bold)
2495 attr |= HL_BOLD;
2496 if (cellattrs.underline)
2497 attr |= HL_UNDERLINE;
2498 if (cellattrs.italic)
2499 attr |= HL_ITALIC;
2500 if (cellattrs.strike)
2501 attr |= HL_STRIKETHROUGH;
2502 if (cellattrs.reverse)
2503 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002504 return attr;
2505}
2506
2507/*
2508 * Store Vterm attributes in "cell" from highlight flags.
2509 */
2510 static void
2511hl2vtermAttr(int attr, cellattr_T *cell)
2512{
2513 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2514 if (attr & HL_BOLD)
2515 cell->attrs.bold = 1;
2516 if (attr & HL_UNDERLINE)
2517 cell->attrs.underline = 1;
2518 if (attr & HL_ITALIC)
2519 cell->attrs.italic = 1;
2520 if (attr & HL_STRIKETHROUGH)
2521 cell->attrs.strike = 1;
2522 if (attr & HL_INVERSE)
2523 cell->attrs.reverse = 1;
2524}
2525
2526/*
2527 * Convert the attributes of a vterm cell into an attribute index.
2528 */
2529 static int
2530cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2531{
2532 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002533
2534#ifdef FEAT_GUI
2535 if (gui.in_use)
2536 {
2537 guicolor_T fg, bg;
2538
2539 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2540 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2541 return get_gui_attr_idx(attr, fg, bg);
2542 }
2543 else
2544#endif
2545#ifdef FEAT_TERMGUICOLORS
2546 if (p_tgc)
2547 {
2548 guicolor_T fg, bg;
2549
2550 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2551 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2552
2553 return get_tgc_attr_idx(attr, fg, bg);
2554 }
2555 else
2556#endif
2557 {
2558 int bold = MAYBE;
2559 int fg = color2index(&cellfg, TRUE, &bold);
2560 int bg = color2index(&cellbg, FALSE, &bold);
2561
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002562 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002563 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002564 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002565 if (fg == 0 && term_default_cterm_fg >= 0)
2566 fg = term_default_cterm_fg + 1;
2567 if (bg == 0 && term_default_cterm_bg >= 0)
2568 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002569 }
2570
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002571 /* with 8 colors set the bold attribute to get a bright foreground */
2572 if (bold == TRUE)
2573 attr |= HL_BOLD;
2574 return get_cterm_attr_idx(attr, fg, bg);
2575 }
2576 return 0;
2577}
2578
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002579 static void
2580set_dirty_snapshot(term_T *term)
2581{
2582 term->tl_dirty_snapshot = TRUE;
2583#ifdef FEAT_TIMERS
2584 if (!term->tl_normal_mode)
2585 {
2586 /* Update the snapshot after 100 msec of not getting updates. */
2587 profile_setlimit(100L, &term->tl_timer_due);
2588 term->tl_timer_set = TRUE;
2589 }
2590#endif
2591}
2592
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 static int
2594handle_damage(VTermRect rect, void *user)
2595{
2596 term_T *term = (term_T *)user;
2597
2598 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2599 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002600 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002601 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002602 return 1;
2603}
2604
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002605 static void
2606term_scroll_up(term_T *term, int start_row, int count)
2607{
2608 win_T *wp;
2609 VTermColor fg, bg;
2610 VTermScreenCellAttrs attr;
2611 int clear_attr;
2612
2613 /* Set the color to clear lines with. */
2614 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2615 &fg, &bg);
2616 vim_memset(&attr, 0, sizeof(attr));
2617 clear_attr = cell2attr(attr, fg, bg);
2618
2619 FOR_ALL_WINDOWS(wp)
2620 {
2621 if (wp->w_buffer == term->tl_buffer)
2622 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2623 }
2624}
2625
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002626 static int
2627handle_moverect(VTermRect dest, VTermRect src, void *user)
2628{
2629 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002630 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002631
2632 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002633 * redrawing the text. But avoid doing this multiple times, postpone until
2634 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002635 if (dest.start_col == src.start_col
2636 && dest.end_col == src.end_col
2637 && dest.start_row < src.start_row)
2638 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002639 if (dest.start_row == 0)
2640 term->tl_postponed_scroll += count;
2641 else
2642 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002643 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002644
2645 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2646 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002647 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002648
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002649 /* Note sure if the scrolling will work correctly, let's do a complete
2650 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002651 redraw_buf_later(term->tl_buffer, NOT_VALID);
2652 return 1;
2653}
2654
2655 static int
2656handle_movecursor(
2657 VTermPos pos,
2658 VTermPos oldpos UNUSED,
2659 int visible,
2660 void *user)
2661{
2662 term_T *term = (term_T *)user;
2663 win_T *wp;
2664
2665 term->tl_cursor_pos = pos;
2666 term->tl_cursor_visible = visible;
2667
2668 FOR_ALL_WINDOWS(wp)
2669 {
2670 if (wp->w_buffer == term->tl_buffer)
2671 position_cursor(wp, &pos);
2672 }
2673 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2674 {
2675 may_toggle_cursor(term);
2676 update_cursor(term, term->tl_cursor_visible);
2677 }
2678
2679 return 1;
2680}
2681
2682 static int
2683handle_settermprop(
2684 VTermProp prop,
2685 VTermValue *value,
2686 void *user)
2687{
2688 term_T *term = (term_T *)user;
2689
2690 switch (prop)
2691 {
2692 case VTERM_PROP_TITLE:
2693 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002694 // a blank title isn't useful, make it empty, so that "running" is
2695 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002696 if (*skipwhite((char_u *)value->string) == NUL)
2697 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002698 // Same as blank
2699 else if (term->tl_arg0_cmd != NULL
2700 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2701 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2702 term->tl_title = NULL;
2703 // Empty corrupted data of winpty
2704 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2705 term->tl_title = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002706#ifdef WIN3264
2707 else if (!enc_utf8 && enc_codepage > 0)
2708 {
2709 WCHAR *ret = NULL;
2710 int length = 0;
2711
2712 MultiByteToWideChar_alloc(CP_UTF8, 0,
2713 (char*)value->string, (int)STRLEN(value->string),
2714 &ret, &length);
2715 if (ret != NULL)
2716 {
2717 WideCharToMultiByte_alloc(enc_codepage, 0,
2718 ret, length, (char**)&term->tl_title,
2719 &length, 0, 0);
2720 vim_free(ret);
2721 }
2722 }
2723#endif
2724 else
2725 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002726 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002727 if (term == curbuf->b_term)
2728 maketitle();
2729 break;
2730
2731 case VTERM_PROP_CURSORVISIBLE:
2732 term->tl_cursor_visible = value->boolean;
2733 may_toggle_cursor(term);
2734 out_flush();
2735 break;
2736
2737 case VTERM_PROP_CURSORBLINK:
2738 term->tl_cursor_blink = value->boolean;
2739 may_set_cursor_props(term);
2740 break;
2741
2742 case VTERM_PROP_CURSORSHAPE:
2743 term->tl_cursor_shape = value->number;
2744 may_set_cursor_props(term);
2745 break;
2746
2747 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002748 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002749 may_set_cursor_props(term);
2750 break;
2751
2752 case VTERM_PROP_ALTSCREEN:
2753 /* TODO: do anything else? */
2754 term->tl_using_altscreen = value->boolean;
2755 break;
2756
2757 default:
2758 break;
2759 }
2760 /* Always return 1, otherwise vterm doesn't store the value internally. */
2761 return 1;
2762}
2763
2764/*
2765 * The job running in the terminal resized the terminal.
2766 */
2767 static int
2768handle_resize(int rows, int cols, void *user)
2769{
2770 term_T *term = (term_T *)user;
2771 win_T *wp;
2772
2773 term->tl_rows = rows;
2774 term->tl_cols = cols;
2775 if (term->tl_vterm_size_changed)
2776 /* Size was set by vterm_set_size(), don't set the window size. */
2777 term->tl_vterm_size_changed = FALSE;
2778 else
2779 {
2780 FOR_ALL_WINDOWS(wp)
2781 {
2782 if (wp->w_buffer == term->tl_buffer)
2783 {
2784 win_setheight_win(rows, wp);
2785 win_setwidth_win(cols, wp);
2786 }
2787 }
2788 redraw_buf_later(term->tl_buffer, NOT_VALID);
2789 }
2790 return 1;
2791}
2792
2793/*
2794 * Handle a line that is pushed off the top of the screen.
2795 */
2796 static int
2797handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2798{
2799 term_T *term = (term_T *)user;
2800
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002801 /* First remove the lines that were appended before, the pushed line goes
2802 * above it. */
2803 cleanup_scrollback(term);
2804
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002805 /* If the number of lines that are stored goes over 'termscrollback' then
2806 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002807 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002808 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002809 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002810 int i;
2811
2812 curbuf = term->tl_buffer;
2813 for (i = 0; i < todo; ++i)
2814 {
2815 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2816 ml_delete(1, FALSE);
2817 }
2818 curbuf = curwin->w_buffer;
2819
2820 term->tl_scrollback.ga_len -= todo;
2821 mch_memmove(term->tl_scrollback.ga_data,
2822 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2823 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
Bram Moolenaar4d6cd292018-05-15 23:53:26 +02002824 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002825 }
2826
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002827 if (ga_grow(&term->tl_scrollback, 1) == OK)
2828 {
2829 cellattr_T *p = NULL;
2830 int len = 0;
2831 int i;
2832 int c;
2833 int col;
2834 sb_line_T *line;
2835 garray_T ga;
2836 cellattr_T fill_attr = term->tl_default_color;
2837
2838 /* do not store empty cells at the end */
2839 for (i = 0; i < cols; ++i)
2840 if (cells[i].chars[0] != 0)
2841 len = i + 1;
2842 else
2843 cell2cellattr(&cells[i], &fill_attr);
2844
2845 ga_init2(&ga, 1, 100);
2846 if (len > 0)
2847 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2848 if (p != NULL)
2849 {
2850 for (col = 0; col < len; col += cells[col].width)
2851 {
2852 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2853 {
2854 ga.ga_len = 0;
2855 break;
2856 }
2857 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2858 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2859 (char_u *)ga.ga_data + ga.ga_len);
2860 cell2cellattr(&cells[col], &p[col]);
2861 }
2862 }
2863 if (ga_grow(&ga, 1) == FAIL)
2864 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2865 else
2866 {
2867 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2868 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2869 }
2870 ga_clear(&ga);
2871
2872 line = (sb_line_T *)term->tl_scrollback.ga_data
2873 + term->tl_scrollback.ga_len;
2874 line->sb_cols = len;
2875 line->sb_cells = p;
2876 line->sb_fill_attr = fill_attr;
2877 ++term->tl_scrollback.ga_len;
2878 ++term->tl_scrollback_scrolled;
2879 }
2880 return 0; /* ignored */
2881}
2882
2883static VTermScreenCallbacks screen_callbacks = {
2884 handle_damage, /* damage */
2885 handle_moverect, /* moverect */
2886 handle_movecursor, /* movecursor */
2887 handle_settermprop, /* settermprop */
2888 NULL, /* bell */
2889 handle_resize, /* resize */
2890 handle_pushline, /* sb_pushline */
2891 NULL /* sb_popline */
2892};
2893
2894/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002895 * Do the work after the channel of a terminal was closed.
2896 * Must be called only when updating_screen is FALSE.
2897 * Returns TRUE when a buffer was closed (list of terminals may have changed).
2898 */
2899 static int
2900term_after_channel_closed(term_T *term)
2901{
2902 /* Unless in Terminal-Normal mode: clear the vterm. */
2903 if (!term->tl_normal_mode)
2904 {
2905 int fnum = term->tl_buffer->b_fnum;
2906
2907 cleanup_vterm(term);
2908
2909 if (term->tl_finish == TL_FINISH_CLOSE)
2910 {
2911 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002912 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002913
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002914 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002915 ch_log(NULL, "terminal job finished, closing window");
2916 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002917 // Avoid closing the window if we temporarily use it.
2918 if (do_set_w_closing)
2919 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002920 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02002921 if (do_set_w_closing)
2922 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002923 aucmd_restbuf(&aco);
2924 return TRUE;
2925 }
2926 if (term->tl_finish == TL_FINISH_OPEN
2927 && term->tl_buffer->b_nwindows == 0)
2928 {
2929 char buf[50];
2930
2931 /* TODO: use term_opencmd */
2932 ch_log(NULL, "terminal job finished, opening window");
2933 vim_snprintf(buf, sizeof(buf),
2934 term->tl_opencmd == NULL
2935 ? "botright sbuf %d"
2936 : (char *)term->tl_opencmd, fnum);
2937 do_cmdline_cmd((char_u *)buf);
2938 }
2939 else
2940 ch_log(NULL, "terminal job finished");
2941 }
2942
2943 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2944 return FALSE;
2945}
2946
2947/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002948 * Called when a channel has been closed.
2949 * If this was a channel for a terminal window then finish it up.
2950 */
2951 void
2952term_channel_closed(channel_T *ch)
2953{
2954 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002955 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002956 int did_one = FALSE;
2957
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002958 for (term = first_term; term != NULL; term = next_term)
2959 {
2960 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002961 if (term->tl_job == ch->ch_job)
2962 {
2963 term->tl_channel_closed = TRUE;
2964 did_one = TRUE;
2965
Bram Moolenaard23a8232018-02-10 18:45:26 +01002966 VIM_CLEAR(term->tl_title);
2967 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002968#ifdef WIN3264
2969 if (term->tl_out_fd != NULL)
2970 {
2971 fclose(term->tl_out_fd);
2972 term->tl_out_fd = NULL;
2973 }
2974#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002975
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002976 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002977 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002978 /* Cannot open or close windows now. Can happen when
2979 * 'lazyredraw' is set. */
2980 term->tl_channel_recently_closed = TRUE;
2981 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002982 }
2983
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002984 if (term_after_channel_closed(term))
2985 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002986 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002987 }
2988
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002989 if (did_one)
2990 {
2991 redraw_statuslines();
2992
2993 /* Need to break out of vgetc(). */
2994 ins_char_typebuf(K_IGNORE);
2995 typebuf_was_filled = TRUE;
2996
2997 term = curbuf->b_term;
2998 if (term != NULL)
2999 {
3000 if (term->tl_job == ch->ch_job)
3001 maketitle();
3002 update_cursor(term, term->tl_cursor_visible);
3003 }
3004 }
3005}
3006
3007/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003008 * To be called after resetting updating_screen: handle any terminal where the
3009 * channel was closed.
3010 */
3011 void
3012term_check_channel_closed_recently()
3013{
3014 term_T *term;
3015 term_T *next_term;
3016
3017 for (term = first_term; term != NULL; term = next_term)
3018 {
3019 next_term = term->tl_next;
3020 if (term->tl_channel_recently_closed)
3021 {
3022 term->tl_channel_recently_closed = FALSE;
3023 if (term_after_channel_closed(term))
3024 // start over, the list may have changed
3025 next_term = first_term;
3026 }
3027 }
3028}
3029
3030/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003031 * Fill one screen line from a line of the terminal.
3032 * Advances "pos" to past the last column.
3033 */
3034 static void
3035term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3036{
3037 int off = screen_get_current_line_off();
3038
3039 for (pos->col = 0; pos->col < max_col; )
3040 {
3041 VTermScreenCell cell;
3042 int c;
3043
3044 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3045 vim_memset(&cell, 0, sizeof(cell));
3046
3047 c = cell.chars[0];
3048 if (c == NUL)
3049 {
3050 ScreenLines[off] = ' ';
3051 if (enc_utf8)
3052 ScreenLinesUC[off] = NUL;
3053 }
3054 else
3055 {
3056 if (enc_utf8)
3057 {
3058 int i;
3059
3060 /* composing chars */
3061 for (i = 0; i < Screen_mco
3062 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3063 {
3064 ScreenLinesC[i][off] = cell.chars[i + 1];
3065 if (cell.chars[i + 1] == 0)
3066 break;
3067 }
3068 if (c >= 0x80 || (Screen_mco > 0
3069 && ScreenLinesC[0][off] != 0))
3070 {
3071 ScreenLines[off] = ' ';
3072 ScreenLinesUC[off] = c;
3073 }
3074 else
3075 {
3076 ScreenLines[off] = c;
3077 ScreenLinesUC[off] = NUL;
3078 }
3079 }
3080#ifdef WIN3264
3081 else if (has_mbyte && c >= 0x80)
3082 {
3083 char_u mb[MB_MAXBYTES+1];
3084 WCHAR wc = c;
3085
3086 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3087 (char*)mb, 2, 0, 0) > 1)
3088 {
3089 ScreenLines[off] = mb[0];
3090 ScreenLines[off + 1] = mb[1];
3091 cell.width = mb_ptr2cells(mb);
3092 }
3093 else
3094 ScreenLines[off] = c;
3095 }
3096#endif
3097 else
3098 ScreenLines[off] = c;
3099 }
3100 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3101
3102 ++pos->col;
3103 ++off;
3104 if (cell.width == 2)
3105 {
3106 if (enc_utf8)
3107 ScreenLinesUC[off] = NUL;
3108
3109 /* don't set the second byte to NUL for a DBCS encoding, it
3110 * has been set above */
3111 if (enc_utf8 || !has_mbyte)
3112 ScreenLines[off] = NUL;
3113
3114 ++pos->col;
3115 ++off;
3116 }
3117 }
3118}
3119
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003120#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003121 static void
3122update_system_term(term_T *term)
3123{
3124 VTermPos pos;
3125 VTermScreen *screen;
3126
3127 if (term->tl_vterm == NULL)
3128 return;
3129 screen = vterm_obtain_screen(term->tl_vterm);
3130
3131 /* Scroll up to make more room for terminal lines if needed. */
3132 while (term->tl_toprow > 0
3133 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3134 {
3135 int save_p_more = p_more;
3136
3137 p_more = FALSE;
3138 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003139 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003140 p_more = save_p_more;
3141 --term->tl_toprow;
3142 }
3143
3144 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3145 && pos.row < Rows; ++pos.row)
3146 {
3147 if (pos.row < term->tl_rows)
3148 {
3149 int max_col = MIN(Columns, term->tl_cols);
3150
3151 term_line2screenline(screen, &pos, max_col);
3152 }
3153 else
3154 pos.col = 0;
3155
3156 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
3157 }
3158
3159 term->tl_dirty_row_start = MAX_ROW;
3160 term->tl_dirty_row_end = 0;
3161 update_cursor(term, TRUE);
3162}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003163#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003164
3165/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003166 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3167 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003168 * Terminal-Normal mode.
3169 */
3170 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003171term_do_update_window(win_T *wp)
3172{
3173 term_T *term = wp->w_buffer->b_term;
3174
3175 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3176}
3177
3178/*
3179 * Called to update a window that contains an active terminal.
3180 */
3181 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003182term_update_window(win_T *wp)
3183{
3184 term_T *term = wp->w_buffer->b_term;
3185 VTerm *vterm;
3186 VTermScreen *screen;
3187 VTermState *state;
3188 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003189 int rows, cols;
3190 int newrows, newcols;
3191 int minsize;
3192 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003193
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003194 vterm = term->tl_vterm;
3195 screen = vterm_obtain_screen(vterm);
3196 state = vterm_obtain_state(vterm);
3197
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003198 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3199 * SOME_VALID only redraw what was marked dirty. */
3200 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003201 {
3202 term->tl_dirty_row_start = 0;
3203 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003204
3205 if (term->tl_postponed_scroll > 0
3206 && term->tl_postponed_scroll < term->tl_rows / 3)
3207 /* Scrolling is usually faster than redrawing, when there are only
3208 * a few lines to scroll. */
3209 term_scroll_up(term, 0, term->tl_postponed_scroll);
3210 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003211 }
3212
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003213 /*
3214 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003215 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003216 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003217 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003218
Bram Moolenaar498c2562018-04-15 23:45:15 +02003219 newrows = 99999;
3220 newcols = 99999;
3221 FOR_ALL_WINDOWS(twp)
3222 {
3223 /* When more than one window shows the same terminal, use the
3224 * smallest size. */
3225 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003226 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003227 newrows = MIN(newrows, twp->w_height);
3228 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003229 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003230 }
3231 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3232 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3233
3234 if (term->tl_rows != newrows || term->tl_cols != newcols)
3235 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003236 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003237 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003238 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003239 newrows);
3240 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003241
3242 // Updating the terminal size will cause the snapshot to be cleared.
3243 // When not in terminal_loop() we need to restore it.
3244 if (term != in_terminal_loop)
3245 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003246 }
3247
3248 /* The cursor may have been moved when resizing. */
3249 vterm_state_get_cursorpos(state, &pos);
3250 position_cursor(wp, &pos);
3251
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003252 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3253 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003254 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003255 if (pos.row < term->tl_rows)
3256 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003257 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003258
Bram Moolenaar13568252018-03-16 20:46:58 +01003259 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003260 }
3261 else
3262 pos.col = 0;
3263
Bram Moolenaarf118d482018-03-13 13:14:00 +01003264 screen_line(wp->w_winrow + pos.row
3265#ifdef FEAT_MENU
3266 + winbar_height(wp)
3267#endif
3268 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003269 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003270 term->tl_dirty_row_start = MAX_ROW;
3271 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003272}
3273
3274/*
3275 * Return TRUE if "wp" is a terminal window where the job has finished.
3276 */
3277 int
3278term_is_finished(buf_T *buf)
3279{
3280 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3281}
3282
3283/*
3284 * Return TRUE if "wp" is a terminal window where the job has finished or we
3285 * are in Terminal-Normal mode, thus we show the buffer contents.
3286 */
3287 int
3288term_show_buffer(buf_T *buf)
3289{
3290 term_T *term = buf->b_term;
3291
3292 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3293}
3294
3295/*
3296 * The current buffer is going to be changed. If there is terminal
3297 * highlighting remove it now.
3298 */
3299 void
3300term_change_in_curbuf(void)
3301{
3302 term_T *term = curbuf->b_term;
3303
3304 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3305 {
3306 free_scrollback(term);
3307 redraw_buf_later(term->tl_buffer, NOT_VALID);
3308
3309 /* The buffer is now like a normal buffer, it cannot be easily
3310 * abandoned when changed. */
3311 set_string_option_direct((char_u *)"buftype", -1,
3312 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3313 }
3314}
3315
3316/*
3317 * Get the screen attribute for a position in the buffer.
3318 * Use a negative "col" to get the filler background color.
3319 */
3320 int
3321term_get_attr(buf_T *buf, linenr_T lnum, int col)
3322{
3323 term_T *term = buf->b_term;
3324 sb_line_T *line;
3325 cellattr_T *cellattr;
3326
3327 if (lnum > term->tl_scrollback.ga_len)
3328 cellattr = &term->tl_default_color;
3329 else
3330 {
3331 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3332 if (col < 0 || col >= line->sb_cols)
3333 cellattr = &line->sb_fill_attr;
3334 else
3335 cellattr = line->sb_cells + col;
3336 }
3337 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3338}
3339
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003340/*
3341 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003342 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003343 */
3344 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003345cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003346{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003347 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003348}
3349
3350/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003351 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003352 */
3353 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003354init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003355{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003356 VTermColor *fg, *bg;
3357 int fgval, bgval;
3358 int id;
3359
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003360 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3361 term->tl_default_color.width = 1;
3362 fg = &term->tl_default_color.fg;
3363 bg = &term->tl_default_color.bg;
3364
3365 /* Vterm uses a default black background. Set it to white when
3366 * 'background' is "light". */
3367 if (*p_bg == 'l')
3368 {
3369 fgval = 0;
3370 bgval = 255;
3371 }
3372 else
3373 {
3374 fgval = 255;
3375 bgval = 0;
3376 }
3377 fg->red = fg->green = fg->blue = fgval;
3378 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003379 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003380
3381 /* The "Terminal" highlight group overrules the defaults. */
3382 id = syn_name2id((char_u *)"Terminal");
3383
Bram Moolenaar46359e12017-11-29 22:33:38 +01003384 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003385#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3386 if (0
3387# ifdef FEAT_GUI
3388 || gui.in_use
3389# endif
3390# ifdef FEAT_TERMGUICOLORS
3391 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003392# ifdef FEAT_VTP
3393 /* Finally get INVALCOLOR on this execution path */
3394 || (!p_tgc && t_colors >= 256)
3395# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003396# endif
3397 )
3398 {
3399 guicolor_T fg_rgb = INVALCOLOR;
3400 guicolor_T bg_rgb = INVALCOLOR;
3401
3402 if (id != 0)
3403 syn_id2colors(id, &fg_rgb, &bg_rgb);
3404
3405# ifdef FEAT_GUI
3406 if (gui.in_use)
3407 {
3408 if (fg_rgb == INVALCOLOR)
3409 fg_rgb = gui.norm_pixel;
3410 if (bg_rgb == INVALCOLOR)
3411 bg_rgb = gui.back_pixel;
3412 }
3413# ifdef FEAT_TERMGUICOLORS
3414 else
3415# endif
3416# endif
3417# ifdef FEAT_TERMGUICOLORS
3418 {
3419 if (fg_rgb == INVALCOLOR)
3420 fg_rgb = cterm_normal_fg_gui_color;
3421 if (bg_rgb == INVALCOLOR)
3422 bg_rgb = cterm_normal_bg_gui_color;
3423 }
3424# endif
3425 if (fg_rgb != INVALCOLOR)
3426 {
3427 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3428
3429 fg->red = (unsigned)(rgb >> 16);
3430 fg->green = (unsigned)(rgb >> 8) & 255;
3431 fg->blue = (unsigned)rgb & 255;
3432 }
3433 if (bg_rgb != INVALCOLOR)
3434 {
3435 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3436
3437 bg->red = (unsigned)(rgb >> 16);
3438 bg->green = (unsigned)(rgb >> 8) & 255;
3439 bg->blue = (unsigned)rgb & 255;
3440 }
3441 }
3442 else
3443#endif
3444 if (id != 0 && t_colors >= 16)
3445 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003446 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003447 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003448 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003449 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003450 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003451 else
3452 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003453#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003454 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003455#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003456
3457 /* In an MS-Windows console we know the normal colors. */
3458 if (cterm_normal_fg_color > 0)
3459 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003460 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003461# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003462 tmp = fg->red;
3463 fg->red = fg->blue;
3464 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003465# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003466 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003467# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003468 else
3469 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003470# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003471
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003472 if (cterm_normal_bg_color > 0)
3473 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003474 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003475# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003476 tmp = bg->red;
3477 bg->red = bg->blue;
3478 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003479# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003480 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003481# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003482 else
3483 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003484# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003485 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003486}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003487
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003488#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3489/*
3490 * Set the 16 ANSI colors from array of RGB values
3491 */
3492 static void
3493set_vterm_palette(VTerm *vterm, long_u *rgb)
3494{
3495 int index = 0;
3496 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003497
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003498 for (; index < 16; index++)
3499 {
3500 VTermColor color;
3501 color.red = (unsigned)(rgb[index] >> 16);
3502 color.green = (unsigned)(rgb[index] >> 8) & 255;
3503 color.blue = (unsigned)rgb[index] & 255;
3504 vterm_state_set_palette_color(state, index, &color);
3505 }
3506}
3507
3508/*
3509 * Set the ANSI color palette from a list of colors
3510 */
3511 static int
3512set_ansi_colors_list(VTerm *vterm, list_T *list)
3513{
3514 int n = 0;
3515 long_u rgb[16];
3516 listitem_T *li = list->lv_first;
3517
3518 for (; li != NULL && n < 16; li = li->li_next, n++)
3519 {
3520 char_u *color_name;
3521 guicolor_T guicolor;
3522
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003523 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003524 if (color_name == NULL)
3525 return FAIL;
3526
3527 guicolor = GUI_GET_COLOR(color_name);
3528 if (guicolor == INVALCOLOR)
3529 return FAIL;
3530
3531 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3532 }
3533
3534 if (n != 16 || li != NULL)
3535 return FAIL;
3536
3537 set_vterm_palette(vterm, rgb);
3538
3539 return OK;
3540}
3541
3542/*
3543 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3544 */
3545 static void
3546init_vterm_ansi_colors(VTerm *vterm)
3547{
3548 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3549
3550 if (var != NULL
3551 && (var->di_tv.v_type != VAR_LIST
3552 || var->di_tv.vval.v_list == NULL
3553 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003554 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003555}
3556#endif
3557
Bram Moolenaar52acb112018-03-18 19:20:22 +01003558/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003559 * Handles a "drop" command from the job in the terminal.
3560 * "item" is the file name, "item->li_next" may have options.
3561 */
3562 static void
3563handle_drop_command(listitem_T *item)
3564{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003565 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003566 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003567 int bufnr;
3568 win_T *wp;
3569 tabpage_T *tp;
3570 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003571 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003572
3573 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3574 FOR_ALL_TAB_WINDOWS(tp, wp)
3575 {
3576 if (wp->w_buffer->b_fnum == bufnr)
3577 {
3578 /* buffer is in a window already, go there */
3579 goto_tabpage_win(tp, wp);
3580 return;
3581 }
3582 }
3583
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003584 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003585
3586 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3587 && opt_item->li_tv.vval.v_dict != NULL)
3588 {
3589 dict_T *dict = opt_item->li_tv.vval.v_dict;
3590 char_u *p;
3591
Bram Moolenaar8f667172018-12-14 15:38:31 +01003592 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003593 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003594 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003595 if (p != NULL)
3596 {
3597 if (check_ff_value(p) == FAIL)
3598 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3599 else
3600 ea.force_ff = *p;
3601 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003602 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003603 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003604 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003605 if (p != NULL)
3606 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003607 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003608 if (ea.cmd != NULL)
3609 {
3610 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3611 ea.force_enc = 11;
3612 tofree = ea.cmd;
3613 }
3614 }
3615
Bram Moolenaar8f667172018-12-14 15:38:31 +01003616 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003617 if (p != NULL)
3618 get_bad_opt(p, &ea);
3619
3620 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3621 ea.force_bin = FORCE_BIN;
3622 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3623 ea.force_bin = FORCE_BIN;
3624 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3625 ea.force_bin = FORCE_NOBIN;
3626 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3627 ea.force_bin = FORCE_NOBIN;
3628 }
3629
3630 /* open in new window, like ":split fname" */
3631 if (ea.cmd == NULL)
3632 ea.cmd = (char_u *)"split";
3633 ea.arg = fname;
3634 ea.cmdidx = CMD_split;
3635 ex_splitview(&ea);
3636
3637 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003638}
3639
3640/*
3641 * Handles a function call from the job running in a terminal.
3642 * "item" is the function name, "item->li_next" has the arguments.
3643 */
3644 static void
3645handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3646{
3647 char_u *func;
3648 typval_T argvars[2];
3649 typval_T rettv;
3650 int doesrange;
3651
3652 if (item->li_next == NULL)
3653 {
3654 ch_log(channel, "Missing function arguments for call");
3655 return;
3656 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003657 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003658
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003659 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003660 {
3661 ch_log(channel, "Invalid function name: %s", func);
3662 return;
3663 }
3664
3665 argvars[0].v_type = VAR_NUMBER;
3666 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3667 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003668 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003669 2, argvars, /* argv_func */ NULL,
3670 /* firstline */ 1, /* lastline */ 1,
3671 &doesrange, /* evaluate */ TRUE,
3672 /* partial */ NULL, /* selfdict */ NULL) == OK)
3673 {
3674 clear_tv(&rettv);
3675 ch_log(channel, "Function %s called", func);
3676 }
3677 else
3678 ch_log(channel, "Calling function %s failed", func);
3679}
3680
3681/*
3682 * Called by libvterm when it cannot recognize an OSC sequence.
3683 * We recognize a terminal API command.
3684 */
3685 static int
3686parse_osc(const char *command, size_t cmdlen, void *user)
3687{
3688 term_T *term = (term_T *)user;
3689 js_read_T reader;
3690 typval_T tv;
3691 channel_T *channel = term->tl_job == NULL ? NULL
3692 : term->tl_job->jv_channel;
3693
3694 /* We recognize only OSC 5 1 ; {command} */
3695 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3696 return 0; /* not handled */
3697
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003698 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003699 if (reader.js_buf == NULL)
3700 return 1;
3701 reader.js_fill = NULL;
3702 reader.js_used = 0;
3703 if (json_decode(&reader, &tv, 0) == OK
3704 && tv.v_type == VAR_LIST
3705 && tv.vval.v_list != NULL)
3706 {
3707 listitem_T *item = tv.vval.v_list->lv_first;
3708
3709 if (item == NULL)
3710 ch_log(channel, "Missing command");
3711 else
3712 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003713 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003714
Bram Moolenaara997b452018-04-17 23:24:06 +02003715 /* Make sure an invoked command doesn't delete the buffer (and the
3716 * terminal) under our fingers. */
3717 ++term->tl_buffer->b_locked;
3718
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003719 item = item->li_next;
3720 if (item == NULL)
3721 ch_log(channel, "Missing argument for %s", cmd);
3722 else if (STRCMP(cmd, "drop") == 0)
3723 handle_drop_command(item);
3724 else if (STRCMP(cmd, "call") == 0)
3725 handle_call_command(term, channel, item);
3726 else
3727 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003728 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003729 }
3730 }
3731 else
3732 ch_log(channel, "Invalid JSON received");
3733
3734 vim_free(reader.js_buf);
3735 clear_tv(&tv);
3736 return 1;
3737}
3738
3739static VTermParserCallbacks parser_fallbacks = {
3740 NULL, /* text */
3741 NULL, /* control */
3742 NULL, /* escape */
3743 NULL, /* csi */
3744 parse_osc, /* osc */
3745 NULL, /* dcs */
3746 NULL /* resize */
3747};
3748
3749/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003750 * Use Vim's allocation functions for vterm so profiling works.
3751 */
3752 static void *
3753vterm_malloc(size_t size, void *data UNUSED)
3754{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003755 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003756}
3757
3758 static void
3759vterm_memfree(void *ptr, void *data UNUSED)
3760{
3761 vim_free(ptr);
3762}
3763
3764static VTermAllocatorFunctions vterm_allocator = {
3765 &vterm_malloc,
3766 &vterm_memfree
3767};
3768
3769/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003770 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003771 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01003772 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003773 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01003774create_vterm(term_T *term, int rows, int cols)
3775{
3776 VTerm *vterm;
3777 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003778 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003779 VTermValue value;
3780
Bram Moolenaar756ef112018-04-10 12:04:27 +02003781 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003782 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003783 if (vterm == NULL)
3784 return FAIL;
3785
3786 // Allocate screen and state here, so we can bail out if that fails.
3787 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003788 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003789 if (state == NULL || screen == NULL)
3790 {
3791 vterm_free(vterm);
3792 return FAIL;
3793 }
3794
Bram Moolenaar52acb112018-03-18 19:20:22 +01003795 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3796 /* TODO: depends on 'encoding'. */
3797 vterm_set_utf8(vterm, 1);
3798
3799 init_default_colors(term);
3800
3801 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003802 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01003803 &term->tl_default_color.fg,
3804 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003805
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003806 if (t_colors >= 16)
3807 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3808
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003809 /* Required to initialize most things. */
3810 vterm_screen_reset(screen, 1 /* hard */);
3811
3812 /* Allow using alternate screen. */
3813 vterm_screen_enable_altscreen(screen, 1);
3814
3815 /* For unix do not use a blinking cursor. In an xterm this causes the
3816 * cursor to blink if it's blinking in the xterm.
3817 * For Windows we respect the system wide setting. */
3818#ifdef WIN3264
3819 if (GetCaretBlinkTime() == INFINITE)
3820 value.boolean = 0;
3821 else
3822 value.boolean = 1;
3823#else
3824 value.boolean = 0;
3825#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003826 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3827 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003828
3829 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003830}
3831
3832/*
3833 * Return the text to show for the buffer name and status.
3834 */
3835 char_u *
3836term_get_status_text(term_T *term)
3837{
3838 if (term->tl_status_text == NULL)
3839 {
3840 char_u *txt;
3841 size_t len;
3842
3843 if (term->tl_normal_mode)
3844 {
3845 if (term_job_running(term))
3846 txt = (char_u *)_("Terminal");
3847 else
3848 txt = (char_u *)_("Terminal-finished");
3849 }
3850 else if (term->tl_title != NULL)
3851 txt = term->tl_title;
3852 else if (term_none_open(term))
3853 txt = (char_u *)_("active");
3854 else if (term_job_running(term))
3855 txt = (char_u *)_("running");
3856 else
3857 txt = (char_u *)_("finished");
3858 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3859 term->tl_status_text = alloc((int)len);
3860 if (term->tl_status_text != NULL)
3861 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3862 term->tl_buffer->b_fname, txt);
3863 }
3864 return term->tl_status_text;
3865}
3866
3867/*
3868 * Mark references in jobs of terminals.
3869 */
3870 int
3871set_ref_in_term(int copyID)
3872{
3873 int abort = FALSE;
3874 term_T *term;
3875 typval_T tv;
3876
3877 for (term = first_term; term != NULL; term = term->tl_next)
3878 if (term->tl_job != NULL)
3879 {
3880 tv.v_type = VAR_JOB;
3881 tv.vval.v_job = term->tl_job;
3882 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3883 }
3884 return abort;
3885}
3886
3887/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003888 * Cache "Terminal" highlight group colors.
3889 */
3890 void
3891set_terminal_default_colors(int cterm_fg, int cterm_bg)
3892{
3893 term_default_cterm_fg = cterm_fg - 1;
3894 term_default_cterm_bg = cterm_bg - 1;
3895}
3896
3897/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003898 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003899 * Returns NULL when the buffer is not for a terminal window and logs a message
3900 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003901 */
3902 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003903term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003904{
3905 buf_T *buf;
3906
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003907 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003908 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01003909 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003910 --emsg_off;
3911 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003912 {
3913 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003914 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003915 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003916 return buf;
3917}
3918
Bram Moolenaard96ff162018-02-18 22:13:29 +01003919 static int
3920same_color(VTermColor *a, VTermColor *b)
3921{
3922 return a->red == b->red
3923 && a->green == b->green
3924 && a->blue == b->blue
3925 && a->ansi_index == b->ansi_index;
3926}
3927
3928 static void
3929dump_term_color(FILE *fd, VTermColor *color)
3930{
3931 fprintf(fd, "%02x%02x%02x%d",
3932 (int)color->red, (int)color->green, (int)color->blue,
3933 (int)color->ansi_index);
3934}
3935
3936/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003937 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003938 *
3939 * Each screen cell in full is:
3940 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3941 * {characters} is a space for an empty cell
3942 * For a double-width character "+" is changed to "*" and the next cell is
3943 * skipped.
3944 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3945 * when "&" use the same as the previous cell.
3946 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3947 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3948 * {color-idx} is a number from 0 to 255
3949 *
3950 * Screen cell with same width, attributes and color as the previous one:
3951 * |{characters}
3952 *
3953 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3954 *
3955 * Repeating the previous screen cell:
3956 * @{count}
3957 */
3958 void
3959f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3960{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003961 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003962 term_T *term;
3963 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003964 int max_height = 0;
3965 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003966 stat_T st;
3967 FILE *fd;
3968 VTermPos pos;
3969 VTermScreen *screen;
3970 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003971 VTermState *state;
3972 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003973
3974 if (check_restricted() || check_secure())
3975 return;
3976 if (buf == NULL)
3977 return;
3978 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02003979 if (term->tl_vterm == NULL)
3980 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003981 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02003982 return;
3983 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003984
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003985 if (argvars[2].v_type != VAR_UNKNOWN)
3986 {
3987 dict_T *d;
3988
3989 if (argvars[2].v_type != VAR_DICT)
3990 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003991 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003992 return;
3993 }
3994 d = argvars[2].vval.v_dict;
3995 if (d != NULL)
3996 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01003997 max_height = dict_get_number(d, (char_u *)"rows");
3998 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003999 }
4000 }
4001
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004002 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004003 if (fname == NULL)
4004 return;
4005 if (mch_stat((char *)fname, &st) >= 0)
4006 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004007 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004008 return;
4009 }
4010
Bram Moolenaard96ff162018-02-18 22:13:29 +01004011 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4012 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004013 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004014 return;
4015 }
4016
4017 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4018
4019 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004020 state = vterm_obtain_state(term->tl_vterm);
4021 vterm_state_get_cursorpos(state, &cursor_pos);
4022
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004023 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4024 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004025 {
4026 int repeat = 0;
4027
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004028 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4029 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004030 {
4031 VTermScreenCell cell;
4032 int same_attr;
4033 int same_chars = TRUE;
4034 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004035 int is_cursor_pos = (pos.col == cursor_pos.col
4036 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004037
4038 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4039 vim_memset(&cell, 0, sizeof(cell));
4040
4041 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4042 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004043 int c = cell.chars[i];
4044 int pc = prev_cell.chars[i];
4045
4046 /* For the first character NUL is the same as space. */
4047 if (i == 0)
4048 {
4049 c = (c == NUL) ? ' ' : c;
4050 pc = (pc == NUL) ? ' ' : pc;
4051 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004052 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004053 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004054 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004055 break;
4056 }
4057 same_attr = vtermAttr2hl(cell.attrs)
4058 == vtermAttr2hl(prev_cell.attrs)
4059 && same_color(&cell.fg, &prev_cell.fg)
4060 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004061 if (same_chars && cell.width == prev_cell.width && same_attr
4062 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004063 {
4064 ++repeat;
4065 }
4066 else
4067 {
4068 if (repeat > 0)
4069 {
4070 fprintf(fd, "@%d", repeat);
4071 repeat = 0;
4072 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004073 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004074
4075 if (cell.chars[0] == NUL)
4076 fputs(" ", fd);
4077 else
4078 {
4079 char_u charbuf[10];
4080 int len;
4081
4082 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4083 && cell.chars[i] != NUL; ++i)
4084 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004085 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004086 fwrite(charbuf, len, 1, fd);
4087 }
4088 }
4089
4090 /* When only the characters differ we don't write anything, the
4091 * following "|", "@" or NL will indicate using the same
4092 * attributes. */
4093 if (cell.width != prev_cell.width || !same_attr)
4094 {
4095 if (cell.width == 2)
4096 {
4097 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004098 }
4099 else
4100 fputs("+", fd);
4101
4102 if (same_attr)
4103 {
4104 fputs("&", fd);
4105 }
4106 else
4107 {
4108 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4109 if (same_color(&cell.fg, &prev_cell.fg))
4110 fputs("&", fd);
4111 else
4112 {
4113 fputs("#", fd);
4114 dump_term_color(fd, &cell.fg);
4115 }
4116 if (same_color(&cell.bg, &prev_cell.bg))
4117 fputs("&", fd);
4118 else
4119 {
4120 fputs("#", fd);
4121 dump_term_color(fd, &cell.bg);
4122 }
4123 }
4124 }
4125
4126 prev_cell = cell;
4127 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004128
4129 if (cell.width == 2)
4130 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004131 }
4132 if (repeat > 0)
4133 fprintf(fd, "@%d", repeat);
4134 fputs("\n", fd);
4135 }
4136
4137 fclose(fd);
4138}
4139
4140/*
4141 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4142 */
4143 static void
4144dump_is_corrupt(garray_T *gap)
4145{
4146 ga_concat(gap, (char_u *)"CORRUPT");
4147}
4148
4149 static void
4150append_cell(garray_T *gap, cellattr_T *cell)
4151{
4152 if (ga_grow(gap, 1) == OK)
4153 {
4154 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4155 ++gap->ga_len;
4156 }
4157}
4158
4159/*
4160 * Read the dump file from "fd" and append lines to the current buffer.
4161 * Return the cell width of the longest line.
4162 */
4163 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004164read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004165{
4166 int c;
4167 garray_T ga_text;
4168 garray_T ga_cell;
4169 char_u *prev_char = NULL;
4170 int attr = 0;
4171 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004172 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004173 term_T *term = curbuf->b_term;
4174 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004175 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004176
4177 ga_init2(&ga_text, 1, 90);
4178 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4179 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004180 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004181 cursor_pos->row = -1;
4182 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004183
4184 c = fgetc(fd);
4185 for (;;)
4186 {
4187 if (c == EOF)
4188 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004189 if (c == '\r')
4190 {
4191 // DOS line endings? Ignore.
4192 c = fgetc(fd);
4193 }
4194 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004195 {
4196 /* End of a line: append it to the buffer. */
4197 if (ga_text.ga_data == NULL)
4198 dump_is_corrupt(&ga_text);
4199 if (ga_grow(&term->tl_scrollback, 1) == OK)
4200 {
4201 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4202 + term->tl_scrollback.ga_len;
4203
4204 if (max_cells < ga_cell.ga_len)
4205 max_cells = ga_cell.ga_len;
4206 line->sb_cols = ga_cell.ga_len;
4207 line->sb_cells = ga_cell.ga_data;
4208 line->sb_fill_attr = term->tl_default_color;
4209 ++term->tl_scrollback.ga_len;
4210 ga_init(&ga_cell);
4211
4212 ga_append(&ga_text, NUL);
4213 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4214 ga_text.ga_len, FALSE);
4215 }
4216 else
4217 ga_clear(&ga_cell);
4218 ga_text.ga_len = 0;
4219
4220 c = fgetc(fd);
4221 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004222 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004223 {
4224 int prev_len = ga_text.ga_len;
4225
Bram Moolenaar9271d052018-02-25 21:39:46 +01004226 if (c == '>')
4227 {
4228 if (cursor_pos->row != -1)
4229 dump_is_corrupt(&ga_text); /* duplicate cursor */
4230 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4231 cursor_pos->col = ga_cell.ga_len;
4232 }
4233
Bram Moolenaard96ff162018-02-18 22:13:29 +01004234 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4235 c = fgetc(fd);
4236 if (c != EOF)
4237 ga_append(&ga_text, c);
4238 for (;;)
4239 {
4240 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004241 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004242 || c == EOF || c == '\n')
4243 break;
4244 ga_append(&ga_text, c);
4245 }
4246
4247 /* save the character for repeating it */
4248 vim_free(prev_char);
4249 if (ga_text.ga_data != NULL)
4250 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4251 ga_text.ga_len - prev_len);
4252
Bram Moolenaar9271d052018-02-25 21:39:46 +01004253 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004254 {
4255 /* use all attributes from previous cell */
4256 }
4257 else if (c == '+' || c == '*')
4258 {
4259 int is_bg;
4260
4261 cell.width = c == '+' ? 1 : 2;
4262
4263 c = fgetc(fd);
4264 if (c == '&')
4265 {
4266 /* use same attr as previous cell */
4267 c = fgetc(fd);
4268 }
4269 else if (isdigit(c))
4270 {
4271 /* get the decimal attribute */
4272 attr = 0;
4273 while (isdigit(c))
4274 {
4275 attr = attr * 10 + (c - '0');
4276 c = fgetc(fd);
4277 }
4278 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004279
4280 /* is_bg == 0: fg, is_bg == 1: bg */
4281 for (is_bg = 0; is_bg <= 1; ++is_bg)
4282 {
4283 if (c == '&')
4284 {
4285 /* use same color as previous cell */
4286 c = fgetc(fd);
4287 }
4288 else if (c == '#')
4289 {
4290 int red, green, blue, index = 0;
4291
4292 c = fgetc(fd);
4293 red = hex2nr(c);
4294 c = fgetc(fd);
4295 red = (red << 4) + hex2nr(c);
4296 c = fgetc(fd);
4297 green = hex2nr(c);
4298 c = fgetc(fd);
4299 green = (green << 4) + hex2nr(c);
4300 c = fgetc(fd);
4301 blue = hex2nr(c);
4302 c = fgetc(fd);
4303 blue = (blue << 4) + hex2nr(c);
4304 c = fgetc(fd);
4305 if (!isdigit(c))
4306 dump_is_corrupt(&ga_text);
4307 while (isdigit(c))
4308 {
4309 index = index * 10 + (c - '0');
4310 c = fgetc(fd);
4311 }
4312
4313 if (is_bg)
4314 {
4315 cell.bg.red = red;
4316 cell.bg.green = green;
4317 cell.bg.blue = blue;
4318 cell.bg.ansi_index = index;
4319 }
4320 else
4321 {
4322 cell.fg.red = red;
4323 cell.fg.green = green;
4324 cell.fg.blue = blue;
4325 cell.fg.ansi_index = index;
4326 }
4327 }
4328 else
4329 dump_is_corrupt(&ga_text);
4330 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004331 }
4332 else
4333 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004334 }
4335 else
4336 dump_is_corrupt(&ga_text);
4337
4338 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004339 if (cell.width == 2)
4340 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004341 }
4342 else if (c == '@')
4343 {
4344 if (prev_char == NULL)
4345 dump_is_corrupt(&ga_text);
4346 else
4347 {
4348 int count = 0;
4349
4350 /* repeat previous character, get the count */
4351 for (;;)
4352 {
4353 c = fgetc(fd);
4354 if (!isdigit(c))
4355 break;
4356 count = count * 10 + (c - '0');
4357 }
4358
4359 while (count-- > 0)
4360 {
4361 ga_concat(&ga_text, prev_char);
4362 append_cell(&ga_cell, &cell);
4363 }
4364 }
4365 }
4366 else
4367 {
4368 dump_is_corrupt(&ga_text);
4369 c = fgetc(fd);
4370 }
4371 }
4372
4373 if (ga_text.ga_len > 0)
4374 {
4375 /* trailing characters after last NL */
4376 dump_is_corrupt(&ga_text);
4377 ga_append(&ga_text, NUL);
4378 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4379 ga_text.ga_len, FALSE);
4380 }
4381
4382 ga_clear(&ga_text);
4383 vim_free(prev_char);
4384
4385 return max_cells;
4386}
4387
4388/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004389 * Return an allocated string with at least "text_width" "=" characters and
4390 * "fname" inserted in the middle.
4391 */
4392 static char_u *
4393get_separator(int text_width, char_u *fname)
4394{
4395 int width = MAX(text_width, curwin->w_width);
4396 char_u *textline;
4397 int fname_size;
4398 char_u *p = fname;
4399 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004400 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004401
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004402 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004403 if (textline == NULL)
4404 return NULL;
4405
4406 fname_size = vim_strsize(fname);
4407 if (fname_size < width - 8)
4408 {
4409 /* enough room, don't use the full window width */
4410 width = MAX(text_width, fname_size + 8);
4411 }
4412 else if (fname_size > width - 8)
4413 {
4414 /* full name doesn't fit, use only the tail */
4415 p = gettail(fname);
4416 fname_size = vim_strsize(p);
4417 }
4418 /* skip characters until the name fits */
4419 while (fname_size > width - 8)
4420 {
4421 p += (*mb_ptr2len)(p);
4422 fname_size = vim_strsize(p);
4423 }
4424
4425 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4426 textline[i] = '=';
4427 textline[i++] = ' ';
4428
4429 STRCPY(textline + i, p);
4430 off = STRLEN(textline);
4431 textline[off] = ' ';
4432 for (i = 1; i < (width - fname_size) / 2; ++i)
4433 textline[off + i] = '=';
4434 textline[off + i] = NUL;
4435
4436 return textline;
4437}
4438
4439/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004440 * Common for "term_dumpdiff()" and "term_dumpload()".
4441 */
4442 static void
4443term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4444{
4445 jobopt_T opt;
4446 buf_T *buf;
4447 char_u buf1[NUMBUFLEN];
4448 char_u buf2[NUMBUFLEN];
4449 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004450 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004451 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004452 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004453 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004454 char_u *textline = NULL;
4455
4456 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004457 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004458 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004459 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004460 if (fname1 == NULL || (do_diff && fname2 == NULL))
4461 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004462 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004463 return;
4464 }
4465 fd1 = mch_fopen((char *)fname1, READBIN);
4466 if (fd1 == NULL)
4467 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004468 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004469 return;
4470 }
4471 if (do_diff)
4472 {
4473 fd2 = mch_fopen((char *)fname2, READBIN);
4474 if (fd2 == NULL)
4475 {
4476 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004477 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004478 return;
4479 }
4480 }
4481
4482 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004483 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4484 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4485 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4486 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4487 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004488
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004489 if (opt.jo_term_name == NULL)
4490 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004491 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004492
Bram Moolenaarb571c632018-03-21 22:27:59 +01004493 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004494 if (fname_tofree != NULL)
4495 {
4496 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4497 opt.jo_term_name = fname_tofree;
4498 }
4499 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004500
Bram Moolenaar13568252018-03-16 20:46:58 +01004501 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004502 if (buf != NULL && buf->b_term != NULL)
4503 {
4504 int i;
4505 linenr_T bot_lnum;
4506 linenr_T lnum;
4507 term_T *term = buf->b_term;
4508 int width;
4509 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004510 VTermPos cursor_pos1;
4511 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004512
Bram Moolenaar52acb112018-03-18 19:20:22 +01004513 init_default_colors(term);
4514
Bram Moolenaard96ff162018-02-18 22:13:29 +01004515 rettv->vval.v_number = buf->b_fnum;
4516
4517 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004518 width = read_dump_file(fd1, &cursor_pos1);
4519
4520 /* position the cursor */
4521 if (cursor_pos1.row >= 0)
4522 {
4523 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4524 coladvance(cursor_pos1.col);
4525 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004526
4527 /* Delete the empty line that was in the empty buffer. */
4528 ml_delete(1, FALSE);
4529
4530 /* For term_dumpload() we are done here. */
4531 if (!do_diff)
4532 goto theend;
4533
4534 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4535
Bram Moolenaar4a696342018-04-05 18:45:26 +02004536 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004537 if (textline == NULL)
4538 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004539 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4540 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4541 vim_free(textline);
4542
4543 textline = get_separator(width, fname2);
4544 if (textline == NULL)
4545 goto theend;
4546 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4547 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004548 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004549
4550 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004551 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004552 if (width2 > width)
4553 {
4554 vim_free(textline);
4555 textline = alloc(width2 + 1);
4556 if (textline == NULL)
4557 goto theend;
4558 width = width2;
4559 textline[width] = NUL;
4560 }
4561 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4562
4563 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4564 {
4565 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4566 {
4567 /* bottom part has fewer rows, fill with "-" */
4568 for (i = 0; i < width; ++i)
4569 textline[i] = '-';
4570 }
4571 else
4572 {
4573 char_u *line1;
4574 char_u *line2;
4575 char_u *p1;
4576 char_u *p2;
4577 int col;
4578 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4579 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4580 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4581 ->sb_cells;
4582
4583 /* Make a copy, getting the second line will invalidate it. */
4584 line1 = vim_strsave(ml_get(lnum));
4585 if (line1 == NULL)
4586 break;
4587 p1 = line1;
4588
4589 line2 = ml_get(lnum + bot_lnum);
4590 p2 = line2;
4591 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4592 {
4593 int len1 = utfc_ptr2len(p1);
4594 int len2 = utfc_ptr2len(p2);
4595
4596 textline[col] = ' ';
4597 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004598 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004599 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004600 else if (lnum == cursor_pos1.row + 1
4601 && col == cursor_pos1.col
4602 && (cursor_pos1.row != cursor_pos2.row
4603 || cursor_pos1.col != cursor_pos2.col))
4604 /* cursor in first but not in second */
4605 textline[col] = '>';
4606 else if (lnum == cursor_pos2.row + 1
4607 && col == cursor_pos2.col
4608 && (cursor_pos1.row != cursor_pos2.row
4609 || cursor_pos1.col != cursor_pos2.col))
4610 /* cursor in second but not in first */
4611 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004612 else if (cellattr1 != NULL && cellattr2 != NULL)
4613 {
4614 if ((cellattr1 + col)->width
4615 != (cellattr2 + col)->width)
4616 textline[col] = 'w';
4617 else if (!same_color(&(cellattr1 + col)->fg,
4618 &(cellattr2 + col)->fg))
4619 textline[col] = 'f';
4620 else if (!same_color(&(cellattr1 + col)->bg,
4621 &(cellattr2 + col)->bg))
4622 textline[col] = 'b';
4623 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4624 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4625 textline[col] = 'a';
4626 }
4627 p1 += len1;
4628 p2 += len2;
4629 /* TODO: handle different width */
4630 }
4631 vim_free(line1);
4632
4633 while (col < width)
4634 {
4635 if (*p1 == NUL && *p2 == NUL)
4636 textline[col] = '?';
4637 else if (*p1 == NUL)
4638 {
4639 textline[col] = '+';
4640 p2 += utfc_ptr2len(p2);
4641 }
4642 else
4643 {
4644 textline[col] = '-';
4645 p1 += utfc_ptr2len(p1);
4646 }
4647 ++col;
4648 }
4649 }
4650 if (add_empty_scrollback(term, &term->tl_default_color,
4651 term->tl_top_diff_rows) == OK)
4652 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4653 ++bot_lnum;
4654 }
4655
4656 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4657 {
4658 /* bottom part has more rows, fill with "+" */
4659 for (i = 0; i < width; ++i)
4660 textline[i] = '+';
4661 if (add_empty_scrollback(term, &term->tl_default_color,
4662 term->tl_top_diff_rows) == OK)
4663 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4664 ++lnum;
4665 ++bot_lnum;
4666 }
4667
4668 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004669
4670 /* looks better without wrapping */
4671 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004672 }
4673
4674theend:
4675 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004676 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004677 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004678 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004679 fclose(fd2);
4680}
4681
4682/*
4683 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4684 * bottom files.
4685 * Return FAIL when this is not possible.
4686 */
4687 int
4688term_swap_diff()
4689{
4690 term_T *term = curbuf->b_term;
4691 linenr_T line_count;
4692 linenr_T top_rows;
4693 linenr_T bot_rows;
4694 linenr_T bot_start;
4695 linenr_T lnum;
4696 char_u *p;
4697 sb_line_T *sb_line;
4698
4699 if (term == NULL
4700 || !term_is_finished(curbuf)
4701 || term->tl_top_diff_rows == 0
4702 || term->tl_scrollback.ga_len == 0)
4703 return FAIL;
4704
4705 line_count = curbuf->b_ml.ml_line_count;
4706 top_rows = term->tl_top_diff_rows;
4707 bot_rows = term->tl_bot_diff_rows;
4708 bot_start = line_count - bot_rows;
4709 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4710
4711 /* move lines from top to above the bottom part */
4712 for (lnum = 1; lnum <= top_rows; ++lnum)
4713 {
4714 p = vim_strsave(ml_get(1));
4715 if (p == NULL)
4716 return OK;
4717 ml_append(bot_start, p, 0, FALSE);
4718 ml_delete(1, FALSE);
4719 vim_free(p);
4720 }
4721
4722 /* move lines from bottom to the top */
4723 for (lnum = 1; lnum <= bot_rows; ++lnum)
4724 {
4725 p = vim_strsave(ml_get(bot_start + lnum));
4726 if (p == NULL)
4727 return OK;
4728 ml_delete(bot_start + lnum, FALSE);
4729 ml_append(lnum - 1, p, 0, FALSE);
4730 vim_free(p);
4731 }
4732
4733 if (top_rows == bot_rows)
4734 {
4735 /* rows counts are equal, can swap cell properties */
4736 for (lnum = 0; lnum < top_rows; ++lnum)
4737 {
4738 sb_line_T temp;
4739
4740 temp = *(sb_line + lnum);
4741 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4742 *(sb_line + bot_start + lnum) = temp;
4743 }
4744 }
4745 else
4746 {
4747 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4748 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4749
4750 /* need to copy cell properties into temp memory */
4751 if (temp != NULL)
4752 {
4753 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4754 mch_memmove(term->tl_scrollback.ga_data,
4755 temp + bot_start,
4756 sizeof(sb_line_T) * bot_rows);
4757 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4758 temp + top_rows,
4759 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4760 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4761 + line_count - top_rows,
4762 temp,
4763 sizeof(sb_line_T) * top_rows);
4764 vim_free(temp);
4765 }
4766 }
4767
4768 term->tl_top_diff_rows = bot_rows;
4769 term->tl_bot_diff_rows = top_rows;
4770
4771 update_screen(NOT_VALID);
4772 return OK;
4773}
4774
4775/*
4776 * "term_dumpdiff(filename, filename, options)" function
4777 */
4778 void
4779f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4780{
4781 term_load_dump(argvars, rettv, TRUE);
4782}
4783
4784/*
4785 * "term_dumpload(filename, options)" function
4786 */
4787 void
4788f_term_dumpload(typval_T *argvars, typval_T *rettv)
4789{
4790 term_load_dump(argvars, rettv, FALSE);
4791}
4792
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004793/*
4794 * "term_getaltscreen(buf)" function
4795 */
4796 void
4797f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4798{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004799 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004800
4801 if (buf == NULL)
4802 return;
4803 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4804}
4805
4806/*
4807 * "term_getattr(attr, name)" function
4808 */
4809 void
4810f_term_getattr(typval_T *argvars, typval_T *rettv)
4811{
4812 int attr;
4813 size_t i;
4814 char_u *name;
4815
4816 static struct {
4817 char *name;
4818 int attr;
4819 } attrs[] = {
4820 {"bold", HL_BOLD},
4821 {"italic", HL_ITALIC},
4822 {"underline", HL_UNDERLINE},
4823 {"strike", HL_STRIKETHROUGH},
4824 {"reverse", HL_INVERSE},
4825 };
4826
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004827 attr = tv_get_number(&argvars[0]);
4828 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004829 if (name == NULL)
4830 return;
4831
4832 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4833 if (STRCMP(name, attrs[i].name) == 0)
4834 {
4835 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4836 break;
4837 }
4838}
4839
4840/*
4841 * "term_getcursor(buf)" function
4842 */
4843 void
4844f_term_getcursor(typval_T *argvars, typval_T *rettv)
4845{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004846 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004847 term_T *term;
4848 list_T *l;
4849 dict_T *d;
4850
4851 if (rettv_list_alloc(rettv) == FAIL)
4852 return;
4853 if (buf == NULL)
4854 return;
4855 term = buf->b_term;
4856
4857 l = rettv->vval.v_list;
4858 list_append_number(l, term->tl_cursor_pos.row + 1);
4859 list_append_number(l, term->tl_cursor_pos.col + 1);
4860
4861 d = dict_alloc();
4862 if (d != NULL)
4863 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02004864 dict_add_number(d, "visible", term->tl_cursor_visible);
4865 dict_add_number(d, "blink", blink_state_is_inverted()
4866 ? !term->tl_cursor_blink : term->tl_cursor_blink);
4867 dict_add_number(d, "shape", term->tl_cursor_shape);
4868 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004869 list_append_dict(l, d);
4870 }
4871}
4872
4873/*
4874 * "term_getjob(buf)" function
4875 */
4876 void
4877f_term_getjob(typval_T *argvars, typval_T *rettv)
4878{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004879 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004880
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004881 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01004882 {
4883 rettv->v_type = VAR_SPECIAL;
4884 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004885 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01004886 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004887
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01004888 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004889 rettv->vval.v_job = buf->b_term->tl_job;
4890 if (rettv->vval.v_job != NULL)
4891 ++rettv->vval.v_job->jv_refcount;
4892}
4893
4894 static int
4895get_row_number(typval_T *tv, term_T *term)
4896{
4897 if (tv->v_type == VAR_STRING
4898 && tv->vval.v_string != NULL
4899 && STRCMP(tv->vval.v_string, ".") == 0)
4900 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004901 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004902}
4903
4904/*
4905 * "term_getline(buf, row)" function
4906 */
4907 void
4908f_term_getline(typval_T *argvars, typval_T *rettv)
4909{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004910 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004911 term_T *term;
4912 int row;
4913
4914 rettv->v_type = VAR_STRING;
4915 if (buf == NULL)
4916 return;
4917 term = buf->b_term;
4918 row = get_row_number(&argvars[1], term);
4919
4920 if (term->tl_vterm == NULL)
4921 {
4922 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4923
4924 /* vterm is finished, get the text from the buffer */
4925 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4926 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4927 }
4928 else
4929 {
4930 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4931 VTermRect rect;
4932 int len;
4933 char_u *p;
4934
4935 if (row < 0 || row >= term->tl_rows)
4936 return;
4937 len = term->tl_cols * MB_MAXBYTES + 1;
4938 p = alloc(len);
4939 if (p == NULL)
4940 return;
4941 rettv->vval.v_string = p;
4942
4943 rect.start_col = 0;
4944 rect.end_col = term->tl_cols;
4945 rect.start_row = row;
4946 rect.end_row = row + 1;
4947 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4948 }
4949}
4950
4951/*
4952 * "term_getscrolled(buf)" function
4953 */
4954 void
4955f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4956{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004957 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004958
4959 if (buf == NULL)
4960 return;
4961 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4962}
4963
4964/*
4965 * "term_getsize(buf)" function
4966 */
4967 void
4968f_term_getsize(typval_T *argvars, typval_T *rettv)
4969{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004970 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004971 list_T *l;
4972
4973 if (rettv_list_alloc(rettv) == FAIL)
4974 return;
4975 if (buf == NULL)
4976 return;
4977
4978 l = rettv->vval.v_list;
4979 list_append_number(l, buf->b_term->tl_rows);
4980 list_append_number(l, buf->b_term->tl_cols);
4981}
4982
4983/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004984 * "term_setsize(buf, rows, cols)" function
4985 */
4986 void
4987f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4988{
4989 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4990 term_T *term;
4991 varnumber_T rows, cols;
4992
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004993 if (buf == NULL)
4994 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004995 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004996 return;
4997 }
4998 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004999 return;
5000 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005001 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005002 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005003 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005004 cols = cols <= 0 ? term->tl_cols : cols;
5005 vterm_set_size(term->tl_vterm, rows, cols);
5006 /* handle_resize() will resize the windows */
5007
5008 /* Get and remember the size we ended up with. Update the pty. */
5009 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5010 term_report_winsize(term, term->tl_rows, term->tl_cols);
5011}
5012
5013/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005014 * "term_getstatus(buf)" function
5015 */
5016 void
5017f_term_getstatus(typval_T *argvars, typval_T *rettv)
5018{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005019 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005020 term_T *term;
5021 char_u val[100];
5022
5023 rettv->v_type = VAR_STRING;
5024 if (buf == NULL)
5025 return;
5026 term = buf->b_term;
5027
5028 if (term_job_running(term))
5029 STRCPY(val, "running");
5030 else
5031 STRCPY(val, "finished");
5032 if (term->tl_normal_mode)
5033 STRCAT(val, ",normal");
5034 rettv->vval.v_string = vim_strsave(val);
5035}
5036
5037/*
5038 * "term_gettitle(buf)" function
5039 */
5040 void
5041f_term_gettitle(typval_T *argvars, typval_T *rettv)
5042{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005043 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005044
5045 rettv->v_type = VAR_STRING;
5046 if (buf == NULL)
5047 return;
5048
5049 if (buf->b_term->tl_title != NULL)
5050 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5051}
5052
5053/*
5054 * "term_gettty(buf)" function
5055 */
5056 void
5057f_term_gettty(typval_T *argvars, typval_T *rettv)
5058{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005059 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005060 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005061 int num = 0;
5062
5063 rettv->v_type = VAR_STRING;
5064 if (buf == NULL)
5065 return;
5066 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005067 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005068
5069 switch (num)
5070 {
5071 case 0:
5072 if (buf->b_term->tl_job != NULL)
5073 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005074 break;
5075 case 1:
5076 if (buf->b_term->tl_job != NULL)
5077 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005078 break;
5079 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005080 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005081 return;
5082 }
5083 if (p != NULL)
5084 rettv->vval.v_string = vim_strsave(p);
5085}
5086
5087/*
5088 * "term_list()" function
5089 */
5090 void
5091f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5092{
5093 term_T *tp;
5094 list_T *l;
5095
5096 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5097 return;
5098
5099 l = rettv->vval.v_list;
5100 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5101 if (tp != NULL && tp->tl_buffer != NULL)
5102 if (list_append_number(l,
5103 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5104 return;
5105}
5106
5107/*
5108 * "term_scrape(buf, row)" function
5109 */
5110 void
5111f_term_scrape(typval_T *argvars, typval_T *rettv)
5112{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005113 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005114 VTermScreen *screen = NULL;
5115 VTermPos pos;
5116 list_T *l;
5117 term_T *term;
5118 char_u *p;
5119 sb_line_T *line;
5120
5121 if (rettv_list_alloc(rettv) == FAIL)
5122 return;
5123 if (buf == NULL)
5124 return;
5125 term = buf->b_term;
5126
5127 l = rettv->vval.v_list;
5128 pos.row = get_row_number(&argvars[1], term);
5129
5130 if (term->tl_vterm != NULL)
5131 {
5132 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005133 if (screen == NULL) // can't really happen
5134 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005135 p = NULL;
5136 line = NULL;
5137 }
5138 else
5139 {
5140 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5141
5142 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5143 return;
5144 p = ml_get_buf(buf, lnum + 1, FALSE);
5145 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5146 }
5147
5148 for (pos.col = 0; pos.col < term->tl_cols; )
5149 {
5150 dict_T *dcell;
5151 int width;
5152 VTermScreenCellAttrs attrs;
5153 VTermColor fg, bg;
5154 char_u rgb[8];
5155 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5156 int off = 0;
5157 int i;
5158
5159 if (screen == NULL)
5160 {
5161 cellattr_T *cellattr;
5162 int len;
5163
5164 /* vterm has finished, get the cell from scrollback */
5165 if (pos.col >= line->sb_cols)
5166 break;
5167 cellattr = line->sb_cells + pos.col;
5168 width = cellattr->width;
5169 attrs = cellattr->attrs;
5170 fg = cellattr->fg;
5171 bg = cellattr->bg;
5172 len = MB_PTR2LEN(p);
5173 mch_memmove(mbs, p, len);
5174 mbs[len] = NUL;
5175 p += len;
5176 }
5177 else
5178 {
5179 VTermScreenCell cell;
5180 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5181 break;
5182 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5183 {
5184 if (cell.chars[i] == 0)
5185 break;
5186 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5187 }
5188 mbs[off] = NUL;
5189 width = cell.width;
5190 attrs = cell.attrs;
5191 fg = cell.fg;
5192 bg = cell.bg;
5193 }
5194 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005195 if (dcell == NULL)
5196 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005197 list_append_dict(l, dcell);
5198
Bram Moolenaare0be1672018-07-08 16:50:37 +02005199 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005200
5201 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5202 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005203 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005204 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5205 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005206 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005207
Bram Moolenaare0be1672018-07-08 16:50:37 +02005208 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5209 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005210
5211 ++pos.col;
5212 if (width == 2)
5213 ++pos.col;
5214 }
5215}
5216
5217/*
5218 * "term_sendkeys(buf, keys)" function
5219 */
5220 void
5221f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5222{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005223 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005224 char_u *msg;
5225 term_T *term;
5226
5227 rettv->v_type = VAR_UNKNOWN;
5228 if (buf == NULL)
5229 return;
5230
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005231 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005232 if (msg == NULL)
5233 return;
5234 term = buf->b_term;
5235 if (term->tl_vterm == NULL)
5236 return;
5237
5238 while (*msg != NUL)
5239 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005240 int c;
5241
5242 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5243 {
5244 c = TO_SPECIAL(msg[1], msg[2]);
5245 msg += 3;
5246 }
5247 else
5248 {
5249 c = PTR2CHAR(msg);
5250 msg += MB_CPTR2LEN(msg);
5251 }
5252 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005253 }
5254}
5255
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005256#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5257/*
5258 * "term_getansicolors(buf)" function
5259 */
5260 void
5261f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5262{
5263 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5264 term_T *term;
5265 VTermState *state;
5266 VTermColor color;
5267 char_u hexbuf[10];
5268 int index;
5269 list_T *list;
5270
5271 if (rettv_list_alloc(rettv) == FAIL)
5272 return;
5273
5274 if (buf == NULL)
5275 return;
5276 term = buf->b_term;
5277 if (term->tl_vterm == NULL)
5278 return;
5279
5280 list = rettv->vval.v_list;
5281 state = vterm_obtain_state(term->tl_vterm);
5282 for (index = 0; index < 16; index++)
5283 {
5284 vterm_state_get_palette_color(state, index, &color);
5285 sprintf((char *)hexbuf, "#%02x%02x%02x",
5286 color.red, color.green, color.blue);
5287 if (list_append_string(list, hexbuf, 7) == FAIL)
5288 return;
5289 }
5290}
5291
5292/*
5293 * "term_setansicolors(buf, list)" function
5294 */
5295 void
5296f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5297{
5298 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5299 term_T *term;
5300
5301 if (buf == NULL)
5302 return;
5303 term = buf->b_term;
5304 if (term->tl_vterm == NULL)
5305 return;
5306
5307 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5308 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005309 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005310 return;
5311 }
5312
5313 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005314 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005315}
5316#endif
5317
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005318/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005319 * "term_setrestore(buf, command)" function
5320 */
5321 void
5322f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5323{
5324#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005325 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005326 term_T *term;
5327 char_u *cmd;
5328
5329 if (buf == NULL)
5330 return;
5331 term = buf->b_term;
5332 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005333 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005334 if (cmd != NULL)
5335 term->tl_command = vim_strsave(cmd);
5336 else
5337 term->tl_command = NULL;
5338#endif
5339}
5340
5341/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005342 * "term_setkill(buf, how)" function
5343 */
5344 void
5345f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5346{
5347 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5348 term_T *term;
5349 char_u *how;
5350
5351 if (buf == NULL)
5352 return;
5353 term = buf->b_term;
5354 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005355 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005356 if (how != NULL)
5357 term->tl_kill = vim_strsave(how);
5358 else
5359 term->tl_kill = NULL;
5360}
5361
5362/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005363 * "term_start(command, options)" function
5364 */
5365 void
5366f_term_start(typval_T *argvars, typval_T *rettv)
5367{
5368 jobopt_T opt;
5369 buf_T *buf;
5370
5371 init_job_options(&opt);
5372 if (argvars[1].v_type != VAR_UNKNOWN
5373 && get_job_options(&argvars[1], &opt,
5374 JO_TIMEOUT_ALL + JO_STOPONEXIT
5375 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5376 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5377 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5378 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005379 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005380 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01005381 + JO2_ANSI_COLORS + JO2_TTY_TYPE) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005382 return;
5383
Bram Moolenaar13568252018-03-16 20:46:58 +01005384 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005385
5386 if (buf != NULL && buf->b_term != NULL)
5387 rettv->vval.v_number = buf->b_fnum;
5388}
5389
5390/*
5391 * "term_wait" function
5392 */
5393 void
5394f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5395{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005396 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005397
5398 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005399 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005400 if (buf->b_term->tl_job == NULL)
5401 {
5402 ch_log(NULL, "term_wait(): no job to wait for");
5403 return;
5404 }
5405 if (buf->b_term->tl_job->jv_channel == NULL)
5406 /* channel is closed, nothing to do */
5407 return;
5408
5409 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005410 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005411 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5412 {
5413 /* The job is dead, keep reading channel I/O until the channel is
5414 * closed. buf->b_term may become NULL if the terminal was closed while
5415 * waiting. */
5416 ch_log(NULL, "term_wait(): waiting for channel to close");
5417 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5418 {
5419 mch_check_messages();
5420 parse_queued_messages();
Bram Moolenaard45aa552018-05-21 22:50:29 +02005421 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005422 if (!buf_valid(buf))
5423 /* If the terminal is closed when the channel is closed the
5424 * buffer disappears. */
5425 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005426 }
5427 mch_check_messages();
5428 parse_queued_messages();
5429 }
5430 else
5431 {
5432 long wait = 10L;
5433
5434 mch_check_messages();
5435 parse_queued_messages();
5436
5437 /* Wait for some time for any channel I/O. */
5438 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005439 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005440 ui_delay(wait, TRUE);
5441 mch_check_messages();
5442
5443 /* Flushing messages on channels is hopefully sufficient.
5444 * TODO: is there a better way? */
5445 parse_queued_messages();
5446 }
5447}
5448
5449/*
5450 * Called when a channel has sent all the lines to a terminal.
5451 * Send a CTRL-D to mark the end of the text.
5452 */
5453 void
5454term_send_eof(channel_T *ch)
5455{
5456 term_T *term;
5457
5458 for (term = first_term; term != NULL; term = term->tl_next)
5459 if (term->tl_job == ch->ch_job)
5460 {
5461 if (term->tl_eof_chars != NULL)
5462 {
5463 channel_send(ch, PART_IN, term->tl_eof_chars,
5464 (int)STRLEN(term->tl_eof_chars), NULL);
5465 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5466 }
5467# ifdef WIN3264
5468 else
5469 /* Default: CTRL-D */
5470 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5471# endif
5472 }
5473}
5474
Bram Moolenaar113e1072019-01-20 15:30:40 +01005475#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005476 job_T *
5477term_getjob(term_T *term)
5478{
5479 return term != NULL ? term->tl_job : NULL;
5480}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005481#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005482
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005483# if defined(WIN3264) || defined(PROTO)
5484
5485/**************************************
5486 * 2. MS-Windows implementation.
5487 */
5488
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005489HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5490HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5491HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005492BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5493BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5494void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005495
5496 static int
5497dyn_conpty_init(int verbose)
5498{
5499 static BOOL handled = FALSE;
5500 static int result;
5501 HMODULE hKerneldll;
5502 int i;
5503 static struct
5504 {
5505 char *name;
5506 FARPROC *ptr;
5507 } conpty_entry[] =
5508 {
5509 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5510 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5511 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5512 {"InitializeProcThreadAttributeList",
5513 (FARPROC*)&pInitializeProcThreadAttributeList},
5514 {"UpdateProcThreadAttribute",
5515 (FARPROC*)&pUpdateProcThreadAttribute},
5516 {"DeleteProcThreadAttributeList",
5517 (FARPROC*)&pDeleteProcThreadAttributeList},
5518 {NULL, NULL}
5519 };
5520
5521 if (handled)
5522 return result;
5523
5524 if (!has_vtp_working())
5525 {
5526 handled = TRUE;
5527 result = FAIL;
5528 return FAIL;
5529 }
5530
5531 hKerneldll = vimLoadLib("kernel32.dll");
5532 for (i = 0; conpty_entry[i].name != NULL
5533 && conpty_entry[i].ptr != NULL; ++i)
5534 {
5535 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5536 conpty_entry[i].name)) == NULL)
5537 {
5538 if (verbose)
5539 semsg(_(e_loadfunc), conpty_entry[i].name);
5540 return FAIL;
5541 }
5542 }
5543
5544 handled = TRUE;
5545 result = OK;
5546 return OK;
5547}
5548
5549 static int
5550conpty_term_and_job_init(
5551 term_T *term,
5552 typval_T *argvar,
5553 char **argv,
5554 jobopt_T *opt,
5555 jobopt_T *orig_opt)
5556{
5557 WCHAR *cmd_wchar = NULL;
5558 WCHAR *cmd_wchar_copy = NULL;
5559 WCHAR *cwd_wchar = NULL;
5560 WCHAR *env_wchar = NULL;
5561 channel_T *channel = NULL;
5562 job_T *job = NULL;
5563 HANDLE jo = NULL;
5564 garray_T ga_cmd, ga_env;
5565 char_u *cmd = NULL;
5566 HRESULT hr;
5567 COORD consize;
5568 SIZE_T breq;
5569 PROCESS_INFORMATION proc_info;
5570 HANDLE i_theirs = NULL;
5571 HANDLE o_theirs = NULL;
5572 HANDLE i_ours = NULL;
5573 HANDLE o_ours = NULL;
5574
5575 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5576 ga_init2(&ga_env, (int)sizeof(char*), 20);
5577
5578 if (argvar->v_type == VAR_STRING)
5579 {
5580 cmd = argvar->vval.v_string;
5581 }
5582 else if (argvar->v_type == VAR_LIST)
5583 {
5584 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5585 goto failed;
5586 cmd = ga_cmd.ga_data;
5587 }
5588 if (cmd == NULL || *cmd == NUL)
5589 {
5590 emsg(_(e_invarg));
5591 goto failed;
5592 }
5593
5594 term->tl_arg0_cmd = vim_strsave(cmd);
5595
5596 cmd_wchar = enc_to_utf16(cmd, NULL);
5597
5598 if (cmd_wchar != NULL)
5599 {
5600 /* Request by CreateProcessW */
5601 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
5602 cmd_wchar_copy = (PWSTR)alloc((int)(breq * sizeof(WCHAR)));
5603 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5604 }
5605
5606 ga_clear(&ga_cmd);
5607 if (cmd_wchar == NULL)
5608 goto failed;
5609 if (opt->jo_cwd != NULL)
5610 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5611
5612 win32_build_env(opt->jo_env, &ga_env, TRUE);
5613 env_wchar = ga_env.ga_data;
5614
5615 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5616 goto failed;
5617 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5618 goto failed;
5619
5620 consize.X = term->tl_cols;
5621 consize.Y = term->tl_rows;
5622 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
5623 &term->tl_conpty);
5624 if (FAILED(hr))
5625 goto failed;
5626
5627 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
5628
5629 /* Set up pipe inheritance safely: Vista or later. */
5630 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
5631 term->tl_siex.lpAttributeList =
5632 (PPROC_THREAD_ATTRIBUTE_LIST)alloc((int)breq);
5633 if (!term->tl_siex.lpAttributeList)
5634 goto failed;
5635 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
5636 0, &breq))
5637 goto failed;
5638 if (!pUpdateProcThreadAttribute(
5639 term->tl_siex.lpAttributeList, 0,
5640 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
5641 sizeof(HPCON), NULL, NULL))
5642 goto failed;
5643
5644 channel = add_channel();
5645 if (channel == NULL)
5646 goto failed;
5647
5648 job = job_alloc();
5649 if (job == NULL)
5650 goto failed;
5651 if (argvar->v_type == VAR_STRING)
5652 {
5653 int argc;
5654
5655 build_argv_from_string(cmd, &job->jv_argv, &argc);
5656 }
5657 else
5658 {
5659 int argc;
5660
5661 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5662 }
5663
5664 if (opt->jo_set & JO_IN_BUF)
5665 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5666
5667 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
5668 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
5669 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
5670 | CREATE_DEFAULT_ERROR_MODE,
5671 env_wchar, cwd_wchar,
5672 &term->tl_siex.StartupInfo, &proc_info))
5673 goto failed;
5674
5675 CloseHandle(i_theirs);
5676 CloseHandle(o_theirs);
5677
5678 channel_set_pipes(channel,
5679 (sock_T)i_ours,
5680 (sock_T)o_ours,
5681 (sock_T)o_ours);
5682
5683 /* Write lines with CR instead of NL. */
5684 channel->ch_write_text_mode = TRUE;
5685
5686 /* Use to explicitly delete anonymous pipe handle. */
5687 channel->ch_anonymous_pipe = TRUE;
5688
5689 jo = CreateJobObject(NULL, NULL);
5690 if (jo == NULL)
5691 goto failed;
5692
5693 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
5694 {
5695 /* Failed, switch the way to terminate process with TerminateProcess. */
5696 CloseHandle(jo);
5697 jo = NULL;
5698 }
5699
5700 ResumeThread(proc_info.hThread);
5701 CloseHandle(proc_info.hThread);
5702
5703 vim_free(cmd_wchar);
5704 vim_free(cmd_wchar_copy);
5705 vim_free(cwd_wchar);
5706 vim_free(env_wchar);
5707
5708 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
5709 goto failed;
5710
5711#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5712 if (opt->jo_set2 & JO2_ANSI_COLORS)
5713 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5714 else
5715 init_vterm_ansi_colors(term->tl_vterm);
5716#endif
5717
5718 channel_set_job(channel, job, opt);
5719 job_set_options(job, opt);
5720
5721 job->jv_channel = channel;
5722 job->jv_proc_info = proc_info;
5723 job->jv_job_object = jo;
5724 job->jv_status = JOB_STARTED;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01005725 job->jv_tty_type = vim_strsave("conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005726 ++job->jv_refcount;
5727 term->tl_job = job;
5728
5729 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5730 * open the file here and handle it in. opt->jo_io was changed in
5731 * setup_job_options(), use the original flags here. */
5732 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5733 {
5734 char_u *fname = opt->jo_io_name[PART_OUT];
5735
5736 ch_log(channel, "Opening output file %s", fname);
5737 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5738 if (term->tl_out_fd == NULL)
5739 semsg(_(e_notopen), fname);
5740 }
5741
5742 return OK;
5743
5744failed:
5745 ga_clear(&ga_cmd);
5746 ga_clear(&ga_env);
5747 vim_free(cmd_wchar);
5748 vim_free(cmd_wchar_copy);
5749 vim_free(cwd_wchar);
5750 if (channel != NULL)
5751 channel_clear(channel);
5752 if (job != NULL)
5753 {
5754 job->jv_channel = NULL;
5755 job_cleanup(job);
5756 }
5757 term->tl_job = NULL;
5758 if (jo != NULL)
5759 CloseHandle(jo);
5760
5761 if (term->tl_siex.lpAttributeList != NULL)
5762 {
5763 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
5764 vim_free(term->tl_siex.lpAttributeList);
5765 }
5766 term->tl_siex.lpAttributeList = NULL;
5767 if (o_theirs != NULL)
5768 CloseHandle(o_theirs);
5769 if (o_ours != NULL)
5770 CloseHandle(o_ours);
5771 if (i_ours != NULL)
5772 CloseHandle(i_ours);
5773 if (i_theirs != NULL)
5774 CloseHandle(i_theirs);
5775 if (term->tl_conpty != NULL)
5776 pClosePseudoConsole(term->tl_conpty);
5777 term->tl_conpty = NULL;
5778 return FAIL;
5779}
5780
5781 static void
5782conpty_term_report_winsize(term_T *term, int rows, int cols)
5783{
5784 COORD consize;
5785
5786 consize.X = cols;
5787 consize.Y = rows;
5788 pResizePseudoConsole(term->tl_conpty, consize);
5789}
5790
5791 void
5792term_free_conpty(term_T *term)
5793{
5794 if (term->tl_siex.lpAttributeList != NULL)
5795 {
5796 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
5797 vim_free(term->tl_siex.lpAttributeList);
5798 }
5799 term->tl_siex.lpAttributeList = NULL;
5800 if (term->tl_conpty != NULL)
5801 pClosePseudoConsole(term->tl_conpty);
5802 term->tl_conpty = NULL;
5803}
5804
5805 int
5806use_conpty(void)
5807{
5808 return has_conpty;
5809}
5810
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005811# ifndef PROTO
5812
5813#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5814#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005815#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005816
5817void* (*winpty_config_new)(UINT64, void*);
5818void* (*winpty_open)(void*, void*);
5819void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5820BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5821void (*winpty_config_set_mouse_mode)(void*, int);
5822void (*winpty_config_set_initial_size)(void*, int, int);
5823LPCWSTR (*winpty_conin_name)(void*);
5824LPCWSTR (*winpty_conout_name)(void*);
5825LPCWSTR (*winpty_conerr_name)(void*);
5826void (*winpty_free)(void*);
5827void (*winpty_config_free)(void*);
5828void (*winpty_spawn_config_free)(void*);
5829void (*winpty_error_free)(void*);
5830LPCWSTR (*winpty_error_msg)(void*);
5831BOOL (*winpty_set_size)(void*, int, int, void*);
5832HANDLE (*winpty_agent_process)(void*);
5833
5834#define WINPTY_DLL "winpty.dll"
5835
5836static HINSTANCE hWinPtyDLL = NULL;
5837# endif
5838
5839 static int
5840dyn_winpty_init(int verbose)
5841{
5842 int i;
5843 static struct
5844 {
5845 char *name;
5846 FARPROC *ptr;
5847 } winpty_entry[] =
5848 {
5849 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5850 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5851 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5852 {"winpty_config_set_mouse_mode",
5853 (FARPROC*)&winpty_config_set_mouse_mode},
5854 {"winpty_config_set_initial_size",
5855 (FARPROC*)&winpty_config_set_initial_size},
5856 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5857 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5858 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5859 {"winpty_free", (FARPROC*)&winpty_free},
5860 {"winpty_open", (FARPROC*)&winpty_open},
5861 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5862 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5863 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5864 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5865 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5866 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5867 {NULL, NULL}
5868 };
5869
5870 /* No need to initialize twice. */
5871 if (hWinPtyDLL)
5872 return OK;
5873 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5874 * winpty.dll. */
5875 if (*p_winptydll != NUL)
5876 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5877 if (!hWinPtyDLL)
5878 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5879 if (!hWinPtyDLL)
5880 {
5881 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005882 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005883 : (char_u *)WINPTY_DLL);
5884 return FAIL;
5885 }
5886 for (i = 0; winpty_entry[i].name != NULL
5887 && winpty_entry[i].ptr != NULL; ++i)
5888 {
5889 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5890 winpty_entry[i].name)) == NULL)
5891 {
5892 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005893 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005894 return FAIL;
5895 }
5896 }
5897
5898 return OK;
5899}
5900
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005901 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005902winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005903 term_T *term,
5904 typval_T *argvar,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005905 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005906 jobopt_T *opt,
5907 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005908{
5909 WCHAR *cmd_wchar = NULL;
5910 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005911 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005912 channel_T *channel = NULL;
5913 job_T *job = NULL;
5914 DWORD error;
5915 HANDLE jo = NULL;
5916 HANDLE child_process_handle;
5917 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005918 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005919 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005920 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005921 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005922
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005923 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5924 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005925
5926 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005927 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005928 cmd = argvar->vval.v_string;
5929 }
5930 else if (argvar->v_type == VAR_LIST)
5931 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005932 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005933 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005934 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005935 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005936 if (cmd == NULL || *cmd == NUL)
5937 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005938 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005939 goto failed;
5940 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005941
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005942 term->tl_arg0_cmd = vim_strsave(cmd);
5943
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005944 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005945 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005946 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005947 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005948 if (opt->jo_cwd != NULL)
5949 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005950
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005951 win32_build_env(opt->jo_env, &ga_env, TRUE);
5952 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005953
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005954 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5955 if (term->tl_winpty_config == NULL)
5956 goto failed;
5957
5958 winpty_config_set_mouse_mode(term->tl_winpty_config,
5959 WINPTY_MOUSE_MODE_FORCE);
5960 winpty_config_set_initial_size(term->tl_winpty_config,
5961 term->tl_cols, term->tl_rows);
5962 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5963 if (term->tl_winpty == NULL)
5964 goto failed;
5965
5966 spawn_config = winpty_spawn_config_new(
5967 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5968 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5969 NULL,
5970 cmd_wchar,
5971 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005972 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005973 &winpty_err);
5974 if (spawn_config == NULL)
5975 goto failed;
5976
5977 channel = add_channel();
5978 if (channel == NULL)
5979 goto failed;
5980
5981 job = job_alloc();
5982 if (job == NULL)
5983 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005984 if (argvar->v_type == VAR_STRING)
5985 {
5986 int argc;
5987
5988 build_argv_from_string(cmd, &job->jv_argv, &argc);
5989 }
5990 else
5991 {
5992 int argc;
5993
5994 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5995 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005996
5997 if (opt->jo_set & JO_IN_BUF)
5998 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5999
6000 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6001 &child_thread_handle, &error, &winpty_err))
6002 goto failed;
6003
6004 channel_set_pipes(channel,
6005 (sock_T)CreateFileW(
6006 winpty_conin_name(term->tl_winpty),
6007 GENERIC_WRITE, 0, NULL,
6008 OPEN_EXISTING, 0, NULL),
6009 (sock_T)CreateFileW(
6010 winpty_conout_name(term->tl_winpty),
6011 GENERIC_READ, 0, NULL,
6012 OPEN_EXISTING, 0, NULL),
6013 (sock_T)CreateFileW(
6014 winpty_conerr_name(term->tl_winpty),
6015 GENERIC_READ, 0, NULL,
6016 OPEN_EXISTING, 0, NULL));
6017
6018 /* Write lines with CR instead of NL. */
6019 channel->ch_write_text_mode = TRUE;
6020
6021 jo = CreateJobObject(NULL, NULL);
6022 if (jo == NULL)
6023 goto failed;
6024
6025 if (!AssignProcessToJobObject(jo, child_process_handle))
6026 {
6027 /* Failed, switch the way to terminate process with TerminateProcess. */
6028 CloseHandle(jo);
6029 jo = NULL;
6030 }
6031
6032 winpty_spawn_config_free(spawn_config);
6033 vim_free(cmd_wchar);
6034 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006035 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006036
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006037 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6038 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006039
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006040#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6041 if (opt->jo_set2 & JO2_ANSI_COLORS)
6042 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6043 else
6044 init_vterm_ansi_colors(term->tl_vterm);
6045#endif
6046
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006047 channel_set_job(channel, job, opt);
6048 job_set_options(job, opt);
6049
6050 job->jv_channel = channel;
6051 job->jv_proc_info.hProcess = child_process_handle;
6052 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6053 job->jv_job_object = jo;
6054 job->jv_status = JOB_STARTED;
6055 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006056 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006057 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006058 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006059 job->jv_tty_type = vim_strsave("winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006060 ++job->jv_refcount;
6061 term->tl_job = job;
6062
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006063 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6064 * open the file here and handle it in. opt->jo_io was changed in
6065 * setup_job_options(), use the original flags here. */
6066 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6067 {
6068 char_u *fname = opt->jo_io_name[PART_OUT];
6069
6070 ch_log(channel, "Opening output file %s", fname);
6071 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6072 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006073 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006074 }
6075
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006076 return OK;
6077
6078failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006079 ga_clear(&ga_cmd);
6080 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006081 vim_free(cmd_wchar);
6082 vim_free(cwd_wchar);
6083 if (spawn_config != NULL)
6084 winpty_spawn_config_free(spawn_config);
6085 if (channel != NULL)
6086 channel_clear(channel);
6087 if (job != NULL)
6088 {
6089 job->jv_channel = NULL;
6090 job_cleanup(job);
6091 }
6092 term->tl_job = NULL;
6093 if (jo != NULL)
6094 CloseHandle(jo);
6095 if (term->tl_winpty != NULL)
6096 winpty_free(term->tl_winpty);
6097 term->tl_winpty = NULL;
6098 if (term->tl_winpty_config != NULL)
6099 winpty_config_free(term->tl_winpty_config);
6100 term->tl_winpty_config = NULL;
6101 if (winpty_err != NULL)
6102 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006103 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006104 (short_u *)winpty_error_msg(winpty_err), NULL);
6105
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006106 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006107 winpty_error_free(winpty_err);
6108 }
6109 return FAIL;
6110}
6111
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006112/*
6113 * Create a new terminal of "rows" by "cols" cells.
6114 * Store a reference in "term".
6115 * Return OK or FAIL.
6116 */
6117 static int
6118term_and_job_init(
6119 term_T *term,
6120 typval_T *argvar,
6121 char **argv UNUSED,
6122 jobopt_T *opt,
6123 jobopt_T *orig_opt)
6124{
6125 int use_winpty = FALSE;
6126 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006127 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006128
6129 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6130 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6131
6132 if (!has_winpty && !has_conpty)
6133 // If neither is available give the errors for winpty, since when
6134 // conpty is not available it can't be installed either.
6135 return dyn_winpty_init(TRUE);
6136
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006137 if (opt->jo_tty_type != NUL)
6138 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006139
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006140 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006141 {
6142 if (has_conpty)
6143 use_conpty = TRUE;
6144 else if (has_winpty)
6145 use_winpty = TRUE;
6146 // else: error
6147 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006148 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006149 {
6150 if (has_winpty)
6151 use_winpty = TRUE;
6152 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006153 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006154 {
6155 if (has_conpty)
6156 use_conpty = TRUE;
6157 else
6158 return dyn_conpty_init(TRUE);
6159 }
6160
6161 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006162 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006163
6164 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006165 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006166
6167 // error
6168 return dyn_winpty_init(TRUE);
6169}
6170
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006171 static int
6172create_pty_only(term_T *term, jobopt_T *options)
6173{
6174 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6175 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6176 char in_name[80], out_name[80];
6177 channel_T *channel = NULL;
6178
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006179 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6180 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006181
6182 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6183 GetCurrentProcessId(),
6184 curbuf->b_fnum);
6185 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6186 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6187 PIPE_UNLIMITED_INSTANCES,
6188 0, 0, NMPWAIT_NOWAIT, NULL);
6189 if (hPipeIn == INVALID_HANDLE_VALUE)
6190 goto failed;
6191
6192 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6193 GetCurrentProcessId(),
6194 curbuf->b_fnum);
6195 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6196 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6197 PIPE_UNLIMITED_INSTANCES,
6198 0, 0, 0, NULL);
6199 if (hPipeOut == INVALID_HANDLE_VALUE)
6200 goto failed;
6201
6202 ConnectNamedPipe(hPipeIn, NULL);
6203 ConnectNamedPipe(hPipeOut, NULL);
6204
6205 term->tl_job = job_alloc();
6206 if (term->tl_job == NULL)
6207 goto failed;
6208 ++term->tl_job->jv_refcount;
6209
6210 /* behave like the job is already finished */
6211 term->tl_job->jv_status = JOB_FINISHED;
6212
6213 channel = add_channel();
6214 if (channel == NULL)
6215 goto failed;
6216 term->tl_job->jv_channel = channel;
6217 channel->ch_keep_open = TRUE;
6218 channel->ch_named_pipe = TRUE;
6219
6220 channel_set_pipes(channel,
6221 (sock_T)hPipeIn,
6222 (sock_T)hPipeOut,
6223 (sock_T)hPipeOut);
6224 channel_set_job(channel, term->tl_job, options);
6225 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6226 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6227
6228 return OK;
6229
6230failed:
6231 if (hPipeIn != NULL)
6232 CloseHandle(hPipeIn);
6233 if (hPipeOut != NULL)
6234 CloseHandle(hPipeOut);
6235 return FAIL;
6236}
6237
6238/*
6239 * Free the terminal emulator part of "term".
6240 */
6241 static void
6242term_free_vterm(term_T *term)
6243{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006244 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006245 if (term->tl_winpty != NULL)
6246 winpty_free(term->tl_winpty);
6247 term->tl_winpty = NULL;
6248 if (term->tl_winpty_config != NULL)
6249 winpty_config_free(term->tl_winpty_config);
6250 term->tl_winpty_config = NULL;
6251 if (term->tl_vterm != NULL)
6252 vterm_free(term->tl_vterm);
6253 term->tl_vterm = NULL;
6254}
6255
6256/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006257 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006258 */
6259 static void
6260term_report_winsize(term_T *term, int rows, int cols)
6261{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006262 if (term->tl_conpty)
6263 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006264 if (term->tl_winpty)
6265 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6266}
6267
6268 int
6269terminal_enabled(void)
6270{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006271 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006272}
6273
6274# else
6275
6276/**************************************
6277 * 3. Unix-like implementation.
6278 */
6279
6280/*
6281 * Create a new terminal of "rows" by "cols" cells.
6282 * Start job for "cmd".
6283 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006284 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006285 * Return OK or FAIL.
6286 */
6287 static int
6288term_and_job_init(
6289 term_T *term,
6290 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006291 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006292 jobopt_T *opt,
6293 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006294{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006295 term->tl_arg0_cmd = NULL;
6296
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006297 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6298 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006299
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006300#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6301 if (opt->jo_set2 & JO2_ANSI_COLORS)
6302 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6303 else
6304 init_vterm_ansi_colors(term->tl_vterm);
6305#endif
6306
Bram Moolenaar13568252018-03-16 20:46:58 +01006307 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006308 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006309 if (term->tl_job != NULL)
6310 ++term->tl_job->jv_refcount;
6311
6312 return term->tl_job != NULL
6313 && term->tl_job->jv_channel != NULL
6314 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6315}
6316
6317 static int
6318create_pty_only(term_T *term, jobopt_T *opt)
6319{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006320 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6321 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006322
6323 term->tl_job = job_alloc();
6324 if (term->tl_job == NULL)
6325 return FAIL;
6326 ++term->tl_job->jv_refcount;
6327
6328 /* behave like the job is already finished */
6329 term->tl_job->jv_status = JOB_FINISHED;
6330
6331 return mch_create_pty_channel(term->tl_job, opt);
6332}
6333
6334/*
6335 * Free the terminal emulator part of "term".
6336 */
6337 static void
6338term_free_vterm(term_T *term)
6339{
6340 if (term->tl_vterm != NULL)
6341 vterm_free(term->tl_vterm);
6342 term->tl_vterm = NULL;
6343}
6344
6345/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006346 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006347 */
6348 static void
6349term_report_winsize(term_T *term, int rows, int cols)
6350{
6351 /* Use an ioctl() to report the new window size to the job. */
6352 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6353 {
6354 int fd = -1;
6355 int part;
6356
6357 for (part = PART_OUT; part < PART_COUNT; ++part)
6358 {
6359 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006360 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006361 break;
6362 }
6363 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6364 mch_signal_job(term->tl_job, (char_u *)"winch");
6365 }
6366}
6367
6368# endif
6369
6370#endif /* FEAT_TERMINAL */