blob: 4dd666523932e66ecfeb4cec46feff4e37b319b1 [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.
39 *
40 * TODO:
Bram Moolenaarf25329c2018-05-06 21:49:32 +020041 * - Win32: Redirecting input does not work, half of Test_terminal_redir_file()
Bram Moolenaar802bfb12018-04-15 17:28:13 +020042 * is disabled.
Bram Moolenaarf25329c2018-05-06 21:49:32 +020043 * - Win32: Redirecting output works but includes escape sequences.
44 * - Win32: Make terminal used for :!cmd in the GUI work better. Allow for
45 * redirection.
Bram Moolenaar498c2562018-04-15 23:45:15 +020046 * - Copy text in the vterm to the Vim buffer once in a while, so that
47 * completion works.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +020048 * - When the job only outputs lines, we could handle resizing the terminal
49 * better: store lines separated by line breaks, instead of screen lines,
50 * then when the window is resized redraw those lines.
Bram Moolenaarf25329c2018-05-06 21:49:32 +020051 * - Redrawing is slow with Athena and Motif. (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020052 * - For the GUI fill termios with default values, perhaps like pangoterm:
53 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar802bfb12018-04-15 17:28:13 +020054 * - When 'encoding' is not utf-8, or the job is using another encoding, setup
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055 * conversions.
Bram Moolenaar498c2562018-04-15 23:45:15 +020056 * - Termdebug does not work when Vim build with mzscheme: gdb hangs just after
57 * "run". Everything else works, including communication channel. Not
58 * initializing mzscheme avoid the problem, thus it's not some #ifdef.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020059 */
60
61#include "vim.h"
62
63#if defined(FEAT_TERMINAL) || defined(PROTO)
64
65#ifndef MIN
66# define MIN(x,y) ((x) < (y) ? (x) : (y))
67#endif
68#ifndef MAX
69# define MAX(x,y) ((x) > (y) ? (x) : (y))
70#endif
71
72#include "libvterm/include/vterm.h"
73
74/* This is VTermScreenCell without the characters, thus much smaller. */
75typedef struct {
76 VTermScreenCellAttrs attrs;
77 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010078 VTermColor fg;
79 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020080} cellattr_T;
81
82typedef struct sb_line_S {
83 int sb_cols; /* can differ per line */
84 cellattr_T *sb_cells; /* allocated */
85 cellattr_T sb_fill_attr; /* for short line */
86} sb_line_T;
87
88/* typedef term_T in structs.h */
89struct terminal_S {
90 term_T *tl_next;
91
92 VTerm *tl_vterm;
93 job_T *tl_job;
94 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010095#if defined(FEAT_GUI)
96 int tl_system; /* when non-zero used for :!cmd output */
97 int tl_toprow; /* row with first line of system terminal */
98#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020099
100 /* Set when setting the size of a vterm, reset after redrawing. */
101 int tl_vterm_size_changed;
102
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200103 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
104 int tl_channel_closed;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100105 int tl_finish;
106#define TL_FINISH_UNSET NUL
107#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
108#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
109#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200110 char_u *tl_opencmd;
111 char_u *tl_eof_chars;
112
113#ifdef WIN3264
114 void *tl_winpty_config;
115 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200116
117 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200118#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100119#if defined(FEAT_SESSION)
120 char_u *tl_command;
121#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100122 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200123
124 /* last known vterm size */
125 int tl_rows;
126 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200127
128 char_u *tl_title; /* NULL or allocated */
129 char_u *tl_status_text; /* NULL or allocated */
130
131 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200132 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200133 int tl_dirty_row_end; /* row below last one to update */
134
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200135 int tl_postponed_scroll; /* to be scrolled up */
136
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200137 garray_T tl_scrollback;
138 int tl_scrollback_scrolled;
139 cellattr_T tl_default_color;
140
Bram Moolenaard96ff162018-02-18 22:13:29 +0100141 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
142 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
143
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200144 VTermPos tl_cursor_pos;
145 int tl_cursor_visible;
146 int tl_cursor_blink;
147 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
148 char_u *tl_cursor_color; /* NULL or allocated */
149
150 int tl_using_altscreen;
151};
152
153#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
154#define TMODE_LOOP 2 /* CTRL-W N used */
155
156/*
157 * List of all active terminals.
158 */
159static term_T *first_term = NULL;
160
161/* Terminal active in terminal_loop(). */
162static term_T *in_terminal_loop = NULL;
163
164#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
165#define KEY_BUF_LEN 200
166
167/*
168 * Functions with separate implementation for MS-Windows and Unix-like systems.
169 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200170static 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 +0200171static int create_pty_only(term_T *term, jobopt_T *opt);
172static void term_report_winsize(term_T *term, int rows, int cols);
173static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100174#ifdef FEAT_GUI
175static void update_system_term(term_T *term);
176#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200177
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100178/* The character that we know (or assume) that the terminal expects for the
179 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200180static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200181
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100182/* "Terminal" highlight group colors. */
183static int term_default_cterm_fg = -1;
184static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200185
Bram Moolenaard317b382018-02-08 22:33:31 +0100186/* Store the last set and the desired cursor properties, so that we only update
187 * them when needed. Doing it unnecessary may result in flicker. */
188static char_u *last_set_cursor_color = (char_u *)"";
189static char_u *desired_cursor_color = (char_u *)"";
190static int last_set_cursor_shape = -1;
191static int desired_cursor_shape = -1;
192static int last_set_cursor_blink = -1;
193static int desired_cursor_blink = -1;
194
195
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200196/**************************************
197 * 1. Generic code for all systems.
198 */
199
200/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200201 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200202 * current window.
203 * Sets "rows" and/or "cols" to zero when it should follow the window size.
204 * Return TRUE if the size is the minimum size: "24*80".
205 */
206 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200207parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200208{
209 int minsize = FALSE;
210
211 *rows = 0;
212 *cols = 0;
213
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200214 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200215 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200216 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200217
218 /* Syntax of value was already checked when it's set. */
219 if (p == NULL)
220 {
221 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200222 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200223 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200224 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200225 *cols = atoi((char *)p + 1);
226 }
227 return minsize;
228}
229
230/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200231 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200232 */
233 static void
234set_term_and_win_size(term_T *term)
235{
Bram Moolenaar13568252018-03-16 20:46:58 +0100236#ifdef FEAT_GUI
237 if (term->tl_system)
238 {
239 /* Use the whole screen for the system command. However, it will start
240 * at the command line and scroll up as needed, using tl_toprow. */
241 term->tl_rows = Rows;
242 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200243 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100244 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100245#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200246 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200247 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200248 if (term->tl_rows != 0)
249 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
250 if (term->tl_cols != 0)
251 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200252 }
253 if (term->tl_rows == 0)
254 term->tl_rows = curwin->w_height;
255 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200256 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200257 if (term->tl_cols == 0)
258 term->tl_cols = curwin->w_width;
259 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200260 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200261}
262
263/*
264 * Initialize job options for a terminal job.
265 * Caller may overrule some of them.
266 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100267 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200268init_job_options(jobopt_T *opt)
269{
270 clear_job_options(opt);
271
272 opt->jo_mode = MODE_RAW;
273 opt->jo_out_mode = MODE_RAW;
274 opt->jo_err_mode = MODE_RAW;
275 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
276}
277
278/*
279 * Set job options mandatory for a terminal job.
280 */
281 static void
282setup_job_options(jobopt_T *opt, int rows, int cols)
283{
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200284#ifndef WIN3264
285 /* Win32: Redirecting the job output won't work, thus always connect stdout
286 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200287 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200288#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200289 {
290 /* Connect stdout to the terminal. */
291 opt->jo_io[PART_OUT] = JIO_BUFFER;
292 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
293 opt->jo_modifiable[PART_OUT] = 0;
294 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
295 }
296
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200297#ifndef WIN3264
298 /* Win32: Redirecting the job output won't work, thus always connect stderr
299 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200301#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200302 {
303 /* Connect stderr to the terminal. */
304 opt->jo_io[PART_ERR] = JIO_BUFFER;
305 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
306 opt->jo_modifiable[PART_ERR] = 0;
307 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
308 }
309
310 opt->jo_pty = TRUE;
311 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
312 opt->jo_term_rows = rows;
313 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
314 opt->jo_term_cols = cols;
315}
316
317/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100318 * Close a terminal buffer (and its window). Used when creating the terminal
319 * fails.
320 */
321 static void
322term_close_buffer(buf_T *buf, buf_T *old_curbuf)
323{
324 free_terminal(buf);
325 if (old_curbuf != NULL)
326 {
327 --curbuf->b_nwindows;
328 curbuf = old_curbuf;
329 curwin->w_buffer = curbuf;
330 ++curbuf->b_nwindows;
331 }
332
333 /* Wiping out the buffer will also close the window and call
334 * free_terminal(). */
335 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
336}
337
338/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200339 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100340 * Use either "argvar" or "argv", the other must be NULL.
341 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
342 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200343 * Returns NULL when failed.
344 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100345 buf_T *
346term_start(
347 typval_T *argvar,
348 char **argv,
349 jobopt_T *opt,
350 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200351{
352 exarg_T split_ea;
353 win_T *old_curwin = curwin;
354 term_T *term;
355 buf_T *old_curbuf = NULL;
356 int res;
357 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100358 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200359 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200360
361 if (check_restricted() || check_secure())
362 return NULL;
363
364 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
365 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
366 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
367 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
368 {
369 EMSG(_(e_invarg));
370 return NULL;
371 }
372
373 term = (term_T *)alloc_clear(sizeof(term_T));
374 if (term == NULL)
375 return NULL;
376 term->tl_dirty_row_end = MAX_ROW;
377 term->tl_cursor_visible = TRUE;
378 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
379 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100380#ifdef FEAT_GUI
381 term->tl_system = (flags & TERM_START_SYSTEM);
382#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200383 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
384
385 vim_memset(&split_ea, 0, sizeof(split_ea));
386 if (opt->jo_curwin)
387 {
388 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100389 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200390 {
391 no_write_message();
392 vim_free(term);
393 return NULL;
394 }
395 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100396 ECMD_HIDE
397 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
398 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200399 {
400 vim_free(term);
401 return NULL;
402 }
403 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100404 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200405 {
406 buf_T *buf;
407
408 /* Create a new buffer without a window. Make it the current buffer for
409 * a moment to be able to do the initialisations. */
410 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
411 BLN_NEW | BLN_LISTED);
412 if (buf == NULL || ml_open(buf) == FAIL)
413 {
414 vim_free(term);
415 return NULL;
416 }
417 old_curbuf = curbuf;
418 --curbuf->b_nwindows;
419 curbuf = buf;
420 curwin->w_buffer = buf;
421 ++curbuf->b_nwindows;
422 }
423 else
424 {
425 /* Open a new window or tab. */
426 split_ea.cmdidx = CMD_new;
427 split_ea.cmd = (char_u *)"new";
428 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100429 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200430 {
431 split_ea.line2 = opt->jo_term_rows;
432 split_ea.addr_count = 1;
433 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100434 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200435 {
436 split_ea.line2 = opt->jo_term_cols;
437 split_ea.addr_count = 1;
438 }
439
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100440 if (vertical)
441 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200442 ex_splitview(&split_ea);
443 if (curwin == old_curwin)
444 {
445 /* split failed */
446 vim_free(term);
447 return NULL;
448 }
449 }
450 term->tl_buffer = curbuf;
451 curbuf->b_term = term;
452
453 if (!opt->jo_hidden)
454 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100455 /* Only one size was taken care of with :new, do the other one. With
456 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100457 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200458 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100459 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200460 win_setwidth(opt->jo_term_cols);
461 }
462
463 /* Link the new terminal in the list of active terminals. */
464 term->tl_next = first_term;
465 first_term = term;
466
467 if (opt->jo_term_name != NULL)
468 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100469 else if (argv != NULL)
470 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200471 else
472 {
473 int i;
474 size_t len;
475 char_u *cmd, *p;
476
477 if (argvar->v_type == VAR_STRING)
478 {
479 cmd = argvar->vval.v_string;
480 if (cmd == NULL)
481 cmd = (char_u *)"";
482 else if (STRCMP(cmd, "NONE") == 0)
483 cmd = (char_u *)"pty";
484 }
485 else if (argvar->v_type != VAR_LIST
486 || argvar->vval.v_list == NULL
487 || argvar->vval.v_list->lv_len < 1
488 || (cmd = get_tv_string_chk(
489 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
490 cmd = (char_u*)"";
491
492 len = STRLEN(cmd) + 10;
493 p = alloc((int)len);
494
495 for (i = 0; p != NULL; ++i)
496 {
497 /* Prepend a ! to the command name to avoid the buffer name equals
498 * the executable, otherwise ":w!" would overwrite it. */
499 if (i == 0)
500 vim_snprintf((char *)p, len, "!%s", cmd);
501 else
502 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
503 if (buflist_findname(p) == NULL)
504 {
505 vim_free(curbuf->b_ffname);
506 curbuf->b_ffname = p;
507 break;
508 }
509 }
510 }
511 curbuf->b_fname = curbuf->b_ffname;
512
513 if (opt->jo_term_opencmd != NULL)
514 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
515
516 if (opt->jo_eof_chars != NULL)
517 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
518
519 set_string_option_direct((char_u *)"buftype", -1,
520 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
521
522 /* Mark the buffer as not modifiable. It can only be made modifiable after
523 * the job finished. */
524 curbuf->b_p_ma = FALSE;
525
526 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200527#ifdef WIN3264
528 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
529#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200530 setup_job_options(opt, term->tl_rows, term->tl_cols);
531
Bram Moolenaar13568252018-03-16 20:46:58 +0100532 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100533 return curbuf;
534
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100535#if defined(FEAT_SESSION)
536 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100537 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100538 {
539 term->tl_command = vim_strsave((char_u *)"NONE");
540 }
541 else if (argvar->v_type == VAR_STRING)
542 {
543 char_u *cmd = argvar->vval.v_string;
544
545 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
546 term->tl_command = vim_strsave(cmd);
547 }
548 else if (argvar->v_type == VAR_LIST
549 && argvar->vval.v_list != NULL
550 && argvar->vval.v_list->lv_len > 0)
551 {
552 garray_T ga;
553 listitem_T *item;
554
555 ga_init2(&ga, 1, 100);
556 for (item = argvar->vval.v_list->lv_first;
557 item != NULL; item = item->li_next)
558 {
559 char_u *s = get_tv_string_chk(&item->li_tv);
560 char_u *p;
561
562 if (s == NULL)
563 break;
564 p = vim_strsave_fnameescape(s, FALSE);
565 if (p == NULL)
566 break;
567 ga_concat(&ga, p);
568 vim_free(p);
569 ga_append(&ga, ' ');
570 }
571 if (item == NULL)
572 {
573 ga_append(&ga, NUL);
574 term->tl_command = ga.ga_data;
575 }
576 else
577 ga_clear(&ga);
578 }
579#endif
580
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100581 if (opt->jo_term_kill != NULL)
582 {
583 char_u *p = skiptowhite(opt->jo_term_kill);
584
585 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
586 }
587
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200588 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100589 if (argv == NULL
590 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200591 && argvar->vval.v_string != NULL
592 && STRCMP(argvar->vval.v_string, "NONE") == 0)
593 res = create_pty_only(term, opt);
594 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200595 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200596
597 newbuf = curbuf;
598 if (res == OK)
599 {
600 /* Get and remember the size we ended up with. Update the pty. */
601 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
602 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100603#ifdef FEAT_GUI
604 if (term->tl_system)
605 {
606 /* display first line below typed command */
607 term->tl_toprow = msg_row + 1;
608 term->tl_dirty_row_end = 0;
609 }
610#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200611
612 /* Make sure we don't get stuck on sending keys to the job, it leads to
613 * a deadlock if the job is waiting for Vim to read. */
614 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
615
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200616 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200617 {
618 --curbuf->b_nwindows;
619 curbuf = old_curbuf;
620 curwin->w_buffer = curbuf;
621 ++curbuf->b_nwindows;
622 }
623 }
624 else
625 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100626 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200627 return NULL;
628 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100629
Bram Moolenaar13568252018-03-16 20:46:58 +0100630 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200631 return newbuf;
632}
633
634/*
635 * ":terminal": open a terminal window and execute a job in it.
636 */
637 void
638ex_terminal(exarg_T *eap)
639{
640 typval_T argvar[2];
641 jobopt_T opt;
642 char_u *cmd;
643 char_u *tofree = NULL;
644
645 init_job_options(&opt);
646
647 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100648 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200649 {
650 char_u *p, *ep;
651
652 cmd += 2;
653 p = skiptowhite(cmd);
654 ep = vim_strchr(cmd, '=');
655 if (ep != NULL && ep < p)
656 p = ep;
657
658 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
659 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100660 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
661 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200662 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
663 opt.jo_term_finish = 'o';
664 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
665 opt.jo_curwin = 1;
666 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
667 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100668 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
669 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100670 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
671 && ep != NULL)
672 {
673 opt.jo_set2 |= JO2_TERM_KILL;
674 opt.jo_term_kill = ep + 1;
675 p = skiptowhite(cmd);
676 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200677 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
678 && ep != NULL && isdigit(ep[1]))
679 {
680 opt.jo_set2 |= JO2_TERM_ROWS;
681 opt.jo_term_rows = atoi((char *)ep + 1);
682 p = skiptowhite(cmd);
683 }
684 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
685 && ep != NULL && isdigit(ep[1]))
686 {
687 opt.jo_set2 |= JO2_TERM_COLS;
688 opt.jo_term_cols = atoi((char *)ep + 1);
689 p = skiptowhite(cmd);
690 }
691 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
692 && ep != NULL)
693 {
694 char_u *buf = NULL;
695 char_u *keys;
696
697 p = skiptowhite(cmd);
698 *p = NUL;
699 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
700 opt.jo_set2 |= JO2_EOF_CHARS;
701 opt.jo_eof_chars = vim_strsave(keys);
702 vim_free(buf);
703 *p = ' ';
704 }
705 else
706 {
707 if (*p)
708 *p = NUL;
709 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100710 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200711 }
712 cmd = skipwhite(p);
713 }
714 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100715 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200716 /* Make a copy of 'shell', an autocommand may change the option. */
717 tofree = cmd = vim_strsave(p_sh);
718
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100719 /* default to close when the shell exits */
720 if (opt.jo_term_finish == NUL)
721 opt.jo_term_finish = 'c';
722 }
723
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200724 if (eap->addr_count > 0)
725 {
726 /* Write lines from current buffer to the job. */
727 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
728 opt.jo_io[PART_IN] = JIO_BUFFER;
729 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
730 opt.jo_in_top = eap->line1;
731 opt.jo_in_bot = eap->line2;
732 }
733
734 argvar[0].v_type = VAR_STRING;
735 argvar[0].vval.v_string = cmd;
736 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100737 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200738 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100739
740theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200741 vim_free(opt.jo_eof_chars);
742}
743
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100744#if defined(FEAT_SESSION) || defined(PROTO)
745/*
746 * Write a :terminal command to the session file to restore the terminal in
747 * window "wp".
748 * Return FAIL if writing fails.
749 */
750 int
751term_write_session(FILE *fd, win_T *wp)
752{
753 term_T *term = wp->w_buffer->b_term;
754
755 /* Create the terminal and run the command. This is not without
756 * risk, but let's assume the user only creates a session when this
757 * will be OK. */
758 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
759 term->tl_cols, term->tl_rows) < 0)
760 return FAIL;
761 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
762 return FAIL;
763
764 return put_eol(fd);
765}
766
767/*
768 * Return TRUE if "buf" has a terminal that should be restored.
769 */
770 int
771term_should_restore(buf_T *buf)
772{
773 term_T *term = buf->b_term;
774
775 return term != NULL && (term->tl_command == NULL
776 || STRCMP(term->tl_command, "NONE") != 0);
777}
778#endif
779
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200780/*
781 * Free the scrollback buffer for "term".
782 */
783 static void
784free_scrollback(term_T *term)
785{
786 int i;
787
788 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
789 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
790 ga_clear(&term->tl_scrollback);
791}
792
793/*
794 * Free a terminal and everything it refers to.
795 * Kills the job if there is one.
796 * Called when wiping out a buffer.
797 */
798 void
799free_terminal(buf_T *buf)
800{
801 term_T *term = buf->b_term;
802 term_T *tp;
803
804 if (term == NULL)
805 return;
806 if (first_term == term)
807 first_term = term->tl_next;
808 else
809 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
810 if (tp->tl_next == term)
811 {
812 tp->tl_next = term->tl_next;
813 break;
814 }
815
816 if (term->tl_job != NULL)
817 {
818 if (term->tl_job->jv_status != JOB_ENDED
819 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100820 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200821 job_stop(term->tl_job, NULL, "kill");
822 job_unref(term->tl_job);
823 }
824
825 free_scrollback(term);
826
827 term_free_vterm(term);
828 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100829#ifdef FEAT_SESSION
830 vim_free(term->tl_command);
831#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100832 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200833 vim_free(term->tl_status_text);
834 vim_free(term->tl_opencmd);
835 vim_free(term->tl_eof_chars);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200836#ifdef WIN3264
837 if (term->tl_out_fd != NULL)
838 fclose(term->tl_out_fd);
839#endif
Bram Moolenaard317b382018-02-08 22:33:31 +0100840 if (desired_cursor_color == term->tl_cursor_color)
841 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200842 vim_free(term->tl_cursor_color);
843 vim_free(term);
844 buf->b_term = NULL;
845 if (in_terminal_loop == term)
846 in_terminal_loop = NULL;
847}
848
849/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100850 * Get the part that is connected to the tty. Normally this is PART_IN, but
851 * when writing buffer lines to the job it can be another. This makes it
852 * possible to do "1,5term vim -".
853 */
854 static ch_part_T
855get_tty_part(term_T *term)
856{
857#ifdef UNIX
858 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
859 int i;
860
861 for (i = 0; i < 3; ++i)
862 {
863 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
864
865 if (isatty(fd))
866 return parts[i];
867 }
868#endif
869 return PART_IN;
870}
871
872/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200873 * Write job output "msg[len]" to the vterm.
874 */
875 static void
876term_write_job_output(term_T *term, char_u *msg, size_t len)
877{
878 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100879 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200880
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100881 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200882
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100883 /* flush vterm buffer when vterm responded to control sequence */
884 if (prevlen != vterm_output_get_buffer_current(vterm))
885 {
886 char buf[KEY_BUF_LEN];
887 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
888
889 if (curlen > 0)
890 channel_send(term->tl_job->jv_channel, get_tty_part(term),
891 (char_u *)buf, (int)curlen, NULL);
892 }
893
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200894 /* this invokes the damage callbacks */
895 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
896}
897
898 static void
899update_cursor(term_T *term, int redraw)
900{
901 if (term->tl_normal_mode)
902 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100903#ifdef FEAT_GUI
904 if (term->tl_system)
905 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
906 term->tl_cursor_pos.col);
907 else
908#endif
909 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200910 if (redraw)
911 {
912 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
913 cursor_on();
914 out_flush();
915#ifdef FEAT_GUI
916 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100917 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200918 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100919 gui_mch_flush();
920 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200921#endif
922 }
923}
924
925/*
926 * Invoked when "msg" output from a job was received. Write it to the terminal
927 * of "buffer".
928 */
929 void
930write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
931{
932 size_t len = STRLEN(msg);
933 term_T *term = buffer->b_term;
934
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200935#ifdef WIN3264
936 /* Win32: Cannot redirect output of the job, intercept it here and write to
937 * the file. */
938 if (term->tl_out_fd != NULL)
939 {
940 ch_log(channel, "Writing %d bytes to output file", (int)len);
941 fwrite(msg, len, 1, term->tl_out_fd);
942 return;
943 }
944#endif
945
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200946 if (term->tl_vterm == NULL)
947 {
948 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
949 return;
950 }
951 ch_log(channel, "writing %d bytes to terminal", (int)len);
952 term_write_job_output(term, msg, len);
953
Bram Moolenaar13568252018-03-16 20:46:58 +0100954#ifdef FEAT_GUI
955 if (term->tl_system)
956 {
957 /* show system output, scrolling up the screen as needed */
958 update_system_term(term);
959 update_cursor(term, TRUE);
960 }
961 else
962#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200963 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
964 * contents, thus no screen update is needed. */
965 if (!term->tl_normal_mode)
966 {
967 /* TODO: only update once in a while. */
968 ch_log(term->tl_job->jv_channel, "updating screen");
969 if (buffer == curbuf)
970 {
971 update_screen(0);
972 update_cursor(term, TRUE);
973 }
974 else
975 redraw_after_callback(TRUE);
976 }
977}
978
979/*
980 * Send a mouse position and click to the vterm
981 */
982 static int
983term_send_mouse(VTerm *vterm, int button, int pressed)
984{
985 VTermModifier mod = VTERM_MOD_NONE;
986
987 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200988 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100989 if (button != 0)
990 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200991 return TRUE;
992}
993
Bram Moolenaarc48369c2018-03-11 19:30:45 +0100994static int enter_mouse_col = -1;
995static int enter_mouse_row = -1;
996
997/*
998 * Handle a mouse click, drag or release.
999 * Return TRUE when a mouse event is sent to the terminal.
1000 */
1001 static int
1002term_mouse_click(VTerm *vterm, int key)
1003{
1004#if defined(FEAT_CLIPBOARD)
1005 /* For modeless selection mouse drag and release events are ignored, unless
1006 * they are preceded with a mouse down event */
1007 static int ignore_drag_release = TRUE;
1008 VTermMouseState mouse_state;
1009
1010 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1011 if (mouse_state.flags == 0)
1012 {
1013 /* Terminal is not using the mouse, use modeless selection. */
1014 switch (key)
1015 {
1016 case K_LEFTDRAG:
1017 case K_LEFTRELEASE:
1018 case K_RIGHTDRAG:
1019 case K_RIGHTRELEASE:
1020 /* Ignore drag and release events when the button-down wasn't
1021 * seen before. */
1022 if (ignore_drag_release)
1023 {
1024 int save_mouse_col, save_mouse_row;
1025
1026 if (enter_mouse_col < 0)
1027 break;
1028
1029 /* mouse click in the window gave us focus, handle that
1030 * click now */
1031 save_mouse_col = mouse_col;
1032 save_mouse_row = mouse_row;
1033 mouse_col = enter_mouse_col;
1034 mouse_row = enter_mouse_row;
1035 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1036 mouse_col = save_mouse_col;
1037 mouse_row = save_mouse_row;
1038 }
1039 /* FALLTHROUGH */
1040 case K_LEFTMOUSE:
1041 case K_RIGHTMOUSE:
1042 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1043 ignore_drag_release = TRUE;
1044 else
1045 ignore_drag_release = FALSE;
1046 /* Should we call mouse_has() here? */
1047 if (clip_star.available)
1048 {
1049 int button, is_click, is_drag;
1050
1051 button = get_mouse_button(KEY2TERMCAP1(key),
1052 &is_click, &is_drag);
1053 if (mouse_model_popup() && button == MOUSE_LEFT
1054 && (mod_mask & MOD_MASK_SHIFT))
1055 {
1056 /* Translate shift-left to right button. */
1057 button = MOUSE_RIGHT;
1058 mod_mask &= ~MOD_MASK_SHIFT;
1059 }
1060 clip_modeless(button, is_click, is_drag);
1061 }
1062 break;
1063
1064 case K_MIDDLEMOUSE:
1065 if (clip_star.available)
1066 insert_reg('*', TRUE);
1067 break;
1068 }
1069 enter_mouse_col = -1;
1070 return FALSE;
1071 }
1072#endif
1073 enter_mouse_col = -1;
1074
1075 switch (key)
1076 {
1077 case K_LEFTMOUSE:
1078 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1079 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1080 case K_LEFTRELEASE:
1081 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1082 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1083 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1084 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1085 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1086 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1087 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1088 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1089 }
1090 return TRUE;
1091}
1092
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001093/*
1094 * Convert typed key "c" into bytes to send to the job.
1095 * Return the number of bytes in "buf".
1096 */
1097 static int
1098term_convert_key(term_T *term, int c, char *buf)
1099{
1100 VTerm *vterm = term->tl_vterm;
1101 VTermKey key = VTERM_KEY_NONE;
1102 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001103 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001104
1105 switch (c)
1106 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001107 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1108
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001109 /* don't use VTERM_KEY_BACKSPACE, it always
1110 * becomes 0x7f DEL */
1111 case K_BS: c = term_backspace_char; break;
1112
1113 case ESC: key = VTERM_KEY_ESCAPE; break;
1114 case K_DEL: key = VTERM_KEY_DEL; break;
1115 case K_DOWN: key = VTERM_KEY_DOWN; break;
1116 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1117 key = VTERM_KEY_DOWN; break;
1118 case K_END: key = VTERM_KEY_END; break;
1119 case K_S_END: mod = VTERM_MOD_SHIFT;
1120 key = VTERM_KEY_END; break;
1121 case K_C_END: mod = VTERM_MOD_CTRL;
1122 key = VTERM_KEY_END; break;
1123 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1124 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1125 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1126 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1127 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1128 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1129 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1130 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1131 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1132 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1133 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1134 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1135 case K_HOME: key = VTERM_KEY_HOME; break;
1136 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1137 key = VTERM_KEY_HOME; break;
1138 case K_C_HOME: mod = VTERM_MOD_CTRL;
1139 key = VTERM_KEY_HOME; break;
1140 case K_INS: key = VTERM_KEY_INS; break;
1141 case K_K0: key = VTERM_KEY_KP_0; break;
1142 case K_K1: key = VTERM_KEY_KP_1; break;
1143 case K_K2: key = VTERM_KEY_KP_2; break;
1144 case K_K3: key = VTERM_KEY_KP_3; break;
1145 case K_K4: key = VTERM_KEY_KP_4; break;
1146 case K_K5: key = VTERM_KEY_KP_5; break;
1147 case K_K6: key = VTERM_KEY_KP_6; break;
1148 case K_K7: key = VTERM_KEY_KP_7; break;
1149 case K_K8: key = VTERM_KEY_KP_8; break;
1150 case K_K9: key = VTERM_KEY_KP_9; break;
1151 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1152 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1153 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1154 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1155 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1156 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1157 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1158 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1159 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1160 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1161 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1162 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1163 case K_LEFT: key = VTERM_KEY_LEFT; break;
1164 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1165 key = VTERM_KEY_LEFT; break;
1166 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1167 key = VTERM_KEY_LEFT; break;
1168 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1169 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1170 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1171 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1172 key = VTERM_KEY_RIGHT; break;
1173 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1174 key = VTERM_KEY_RIGHT; break;
1175 case K_UP: key = VTERM_KEY_UP; break;
1176 case K_S_UP: mod = VTERM_MOD_SHIFT;
1177 key = VTERM_KEY_UP; break;
1178 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001179 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1180 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001181
Bram Moolenaara42ad572017-11-16 13:08:04 +01001182 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1183 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001184 case K_MOUSELEFT: /* TODO */ return 0;
1185 case K_MOUSERIGHT: /* TODO */ return 0;
1186
1187 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001188 case K_LEFTMOUSE_NM:
1189 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001190 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001191 case K_LEFTRELEASE_NM:
1192 case K_MOUSEMOVE:
1193 case K_MIDDLEMOUSE:
1194 case K_MIDDLEDRAG:
1195 case K_MIDDLERELEASE:
1196 case K_RIGHTMOUSE:
1197 case K_RIGHTDRAG:
1198 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1199 return 0;
1200 other = TRUE;
1201 break;
1202
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001203 case K_X1MOUSE: /* TODO */ return 0;
1204 case K_X1DRAG: /* TODO */ return 0;
1205 case K_X1RELEASE: /* TODO */ return 0;
1206 case K_X2MOUSE: /* TODO */ return 0;
1207 case K_X2DRAG: /* TODO */ return 0;
1208 case K_X2RELEASE: /* TODO */ return 0;
1209
1210 case K_IGNORE: return 0;
1211 case K_NOP: return 0;
1212 case K_UNDO: return 0;
1213 case K_HELP: return 0;
1214 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1215 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1216 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1217 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1218 case K_SELECT: return 0;
1219#ifdef FEAT_GUI
1220 case K_VER_SCROLLBAR: return 0;
1221 case K_HOR_SCROLLBAR: return 0;
1222#endif
1223#ifdef FEAT_GUI_TABLINE
1224 case K_TABLINE: return 0;
1225 case K_TABMENU: return 0;
1226#endif
1227#ifdef FEAT_NETBEANS_INTG
1228 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1229#endif
1230#ifdef FEAT_DND
1231 case K_DROP: return 0;
1232#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001233 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001234 case K_PS: vterm_keyboard_start_paste(vterm);
1235 other = TRUE;
1236 break;
1237 case K_PE: vterm_keyboard_end_paste(vterm);
1238 other = TRUE;
1239 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001240 }
1241
1242 /*
1243 * Convert special keys to vterm keys:
1244 * - Write keys to vterm: vterm_keyboard_key()
1245 * - Write output to channel.
1246 * TODO: use mod_mask
1247 */
1248 if (key != VTERM_KEY_NONE)
1249 /* Special key, let vterm convert it. */
1250 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001251 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001252 /* Normal character, let vterm convert it. */
1253 vterm_keyboard_unichar(vterm, c, mod);
1254
1255 /* Read back the converted escape sequence. */
1256 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1257}
1258
1259/*
1260 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001261 * If "check_job_status" is TRUE update the job status.
1262 */
1263 static int
1264term_job_running_check(term_T *term, int check_job_status)
1265{
1266 /* Also consider the job finished when the channel is closed, to avoid a
1267 * race condition when updating the title. */
1268 if (term != NULL
1269 && term->tl_job != NULL
1270 && channel_is_open(term->tl_job->jv_channel))
1271 {
1272 if (check_job_status)
1273 job_status(term->tl_job);
1274 return (term->tl_job->jv_status == JOB_STARTED
1275 || term->tl_job->jv_channel->ch_keep_open);
1276 }
1277 return FALSE;
1278}
1279
1280/*
1281 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001282 */
1283 int
1284term_job_running(term_T *term)
1285{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001286 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001287}
1288
1289/*
1290 * Return TRUE if "term" has an active channel and used ":term NONE".
1291 */
1292 int
1293term_none_open(term_T *term)
1294{
1295 /* Also consider the job finished when the channel is closed, to avoid a
1296 * race condition when updating the title. */
1297 return term != NULL
1298 && term->tl_job != NULL
1299 && channel_is_open(term->tl_job->jv_channel)
1300 && term->tl_job->jv_channel->ch_keep_open;
1301}
1302
1303/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001304 * Used when exiting: kill the job in "buf" if so desired.
1305 * Return OK when the job finished.
1306 * Return FAIL when the job is still running.
1307 */
1308 int
1309term_try_stop_job(buf_T *buf)
1310{
1311 int count;
1312 char *how = (char *)buf->b_term->tl_kill;
1313
1314#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1315 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1316 {
1317 char_u buff[DIALOG_MSG_SIZE];
1318 int ret;
1319
1320 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1321 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1322 if (ret == VIM_YES)
1323 how = "kill";
1324 else if (ret == VIM_CANCEL)
1325 return FAIL;
1326 }
1327#endif
1328 if (how == NULL || *how == NUL)
1329 return FAIL;
1330
1331 job_stop(buf->b_term->tl_job, NULL, how);
1332
1333 /* wait for up to a second for the job to die */
1334 for (count = 0; count < 100; ++count)
1335 {
1336 /* buffer, terminal and job may be cleaned up while waiting */
1337 if (!buf_valid(buf)
1338 || buf->b_term == NULL
1339 || buf->b_term->tl_job == NULL)
1340 return OK;
1341
1342 /* call job_status() to update jv_status */
1343 job_status(buf->b_term->tl_job);
1344 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1345 return OK;
1346 ui_delay(10L, FALSE);
1347 mch_check_messages();
1348 parse_queued_messages();
1349 }
1350 return FAIL;
1351}
1352
1353/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001354 * Add the last line of the scrollback buffer to the buffer in the window.
1355 */
1356 static void
1357add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1358{
1359 buf_T *buf = term->tl_buffer;
1360 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1361 linenr_T lnum = buf->b_ml.ml_line_count;
1362
1363#ifdef WIN3264
1364 if (!enc_utf8 && enc_codepage > 0)
1365 {
1366 WCHAR *ret = NULL;
1367 int length = 0;
1368
1369 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1370 &ret, &length);
1371 if (ret != NULL)
1372 {
1373 WideCharToMultiByte_alloc(enc_codepage, 0,
1374 ret, length, (char **)&text, &len, 0, 0);
1375 vim_free(ret);
1376 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1377 vim_free(text);
1378 }
1379 }
1380 else
1381#endif
1382 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1383 if (empty)
1384 {
1385 /* Delete the empty line that was in the empty buffer. */
1386 curbuf = buf;
1387 ml_delete(1, FALSE);
1388 curbuf = curwin->w_buffer;
1389 }
1390}
1391
1392 static void
1393cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1394{
1395 attr->width = cell->width;
1396 attr->attrs = cell->attrs;
1397 attr->fg = cell->fg;
1398 attr->bg = cell->bg;
1399}
1400
1401 static int
1402equal_celattr(cellattr_T *a, cellattr_T *b)
1403{
1404 /* Comparing the colors should be sufficient. */
1405 return a->fg.red == b->fg.red
1406 && a->fg.green == b->fg.green
1407 && a->fg.blue == b->fg.blue
1408 && a->bg.red == b->bg.red
1409 && a->bg.green == b->bg.green
1410 && a->bg.blue == b->bg.blue;
1411}
1412
Bram Moolenaard96ff162018-02-18 22:13:29 +01001413/*
1414 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1415 * line at this position. Otherwise at the end.
1416 */
1417 static int
1418add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1419{
1420 if (ga_grow(&term->tl_scrollback, 1) == OK)
1421 {
1422 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1423 + term->tl_scrollback.ga_len;
1424
1425 if (lnum > 0)
1426 {
1427 int i;
1428
1429 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1430 {
1431 *line = *(line - 1);
1432 --line;
1433 }
1434 }
1435 line->sb_cols = 0;
1436 line->sb_cells = NULL;
1437 line->sb_fill_attr = *fill_attr;
1438 ++term->tl_scrollback.ga_len;
1439 return OK;
1440 }
1441 return FALSE;
1442}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001443
1444/*
1445 * Add the current lines of the terminal to scrollback and to the buffer.
1446 * Called after the job has ended and when switching to Terminal-Normal mode.
1447 */
1448 static void
1449move_terminal_to_buffer(term_T *term)
1450{
1451 win_T *wp;
1452 int len;
1453 int lines_skipped = 0;
1454 VTermPos pos;
1455 VTermScreenCell cell;
1456 cellattr_T fill_attr, new_fill_attr;
1457 cellattr_T *p;
1458 VTermScreen *screen;
1459
1460 if (term->tl_vterm == NULL)
1461 return;
1462 screen = vterm_obtain_screen(term->tl_vterm);
1463 fill_attr = new_fill_attr = term->tl_default_color;
1464
1465 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1466 {
1467 len = 0;
1468 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1469 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1470 && cell.chars[0] != NUL)
1471 {
1472 len = pos.col + 1;
1473 new_fill_attr = term->tl_default_color;
1474 }
1475 else
1476 /* Assume the last attr is the filler attr. */
1477 cell2cellattr(&cell, &new_fill_attr);
1478
1479 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1480 ++lines_skipped;
1481 else
1482 {
1483 while (lines_skipped > 0)
1484 {
1485 /* Line was skipped, add an empty line. */
1486 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001487 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001488 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001489 }
1490
1491 if (len == 0)
1492 p = NULL;
1493 else
1494 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1495 if ((p != NULL || len == 0)
1496 && ga_grow(&term->tl_scrollback, 1) == OK)
1497 {
1498 garray_T ga;
1499 int width;
1500 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1501 + term->tl_scrollback.ga_len;
1502
1503 ga_init2(&ga, 1, 100);
1504 for (pos.col = 0; pos.col < len; pos.col += width)
1505 {
1506 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1507 {
1508 width = 1;
1509 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1510 if (ga_grow(&ga, 1) == OK)
1511 ga.ga_len += utf_char2bytes(' ',
1512 (char_u *)ga.ga_data + ga.ga_len);
1513 }
1514 else
1515 {
1516 width = cell.width;
1517
1518 cell2cellattr(&cell, &p[pos.col]);
1519
1520 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1521 {
1522 int i;
1523 int c;
1524
1525 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1526 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1527 (char_u *)ga.ga_data + ga.ga_len);
1528 }
1529 }
1530 }
1531 line->sb_cols = len;
1532 line->sb_cells = p;
1533 line->sb_fill_attr = new_fill_attr;
1534 fill_attr = new_fill_attr;
1535 ++term->tl_scrollback.ga_len;
1536
1537 if (ga_grow(&ga, 1) == FAIL)
1538 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1539 else
1540 {
1541 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1542 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1543 }
1544 ga_clear(&ga);
1545 }
1546 else
1547 vim_free(p);
1548 }
1549 }
1550
1551 /* Obtain the current background color. */
1552 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1553 &term->tl_default_color.fg, &term->tl_default_color.bg);
1554
1555 FOR_ALL_WINDOWS(wp)
1556 {
1557 if (wp->w_buffer == term->tl_buffer)
1558 {
1559 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1560 wp->w_cursor.col = 0;
1561 wp->w_valid = 0;
1562 if (wp->w_cursor.lnum >= wp->w_height)
1563 {
1564 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1565
1566 if (wp->w_topline < min_topline)
1567 wp->w_topline = min_topline;
1568 }
1569 redraw_win_later(wp, NOT_VALID);
1570 }
1571 }
1572}
1573
1574 static void
1575set_terminal_mode(term_T *term, int normal_mode)
1576{
1577 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001578 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001579 if (term->tl_buffer == curbuf)
1580 maketitle();
1581}
1582
1583/*
1584 * Called after the job if finished and Terminal mode is not active:
1585 * Move the vterm contents into the scrollback buffer and free the vterm.
1586 */
1587 static void
1588cleanup_vterm(term_T *term)
1589{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001590 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001591 move_terminal_to_buffer(term);
1592 term_free_vterm(term);
1593 set_terminal_mode(term, FALSE);
1594}
1595
1596/*
1597 * Switch from Terminal-Job mode to Terminal-Normal mode.
1598 * Suspends updating the terminal window.
1599 */
1600 static void
1601term_enter_normal_mode(void)
1602{
1603 term_T *term = curbuf->b_term;
1604
1605 /* Append the current terminal contents to the buffer. */
1606 move_terminal_to_buffer(term);
1607
1608 set_terminal_mode(term, TRUE);
1609
1610 /* Move the window cursor to the position of the cursor in the
1611 * terminal. */
1612 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1613 + term->tl_cursor_pos.row + 1;
1614 check_cursor();
1615 coladvance(term->tl_cursor_pos.col);
1616
1617 /* Display the same lines as in the terminal. */
1618 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1619}
1620
1621/*
1622 * Returns TRUE if the current window contains a terminal and we are in
1623 * Terminal-Normal mode.
1624 */
1625 int
1626term_in_normal_mode(void)
1627{
1628 term_T *term = curbuf->b_term;
1629
1630 return term != NULL && term->tl_normal_mode;
1631}
1632
1633/*
1634 * Switch from Terminal-Normal mode to Terminal-Job mode.
1635 * Restores updating the terminal window.
1636 */
1637 void
1638term_enter_job_mode()
1639{
1640 term_T *term = curbuf->b_term;
1641 sb_line_T *line;
1642 garray_T *gap;
1643
1644 /* Remove the terminal contents from the scrollback and the buffer. */
1645 gap = &term->tl_scrollback;
1646 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1647 && gap->ga_len > 0)
1648 {
1649 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1650 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1651 vim_free(line->sb_cells);
1652 --gap->ga_len;
1653 }
1654 check_cursor();
1655
1656 set_terminal_mode(term, FALSE);
1657
1658 if (term->tl_channel_closed)
1659 cleanup_vterm(term);
1660 redraw_buf_and_status_later(curbuf, NOT_VALID);
1661}
1662
1663/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001664 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001665 * Note: while waiting a terminal may be closed and freed if the channel is
1666 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001667 */
1668 static int
1669term_vgetc()
1670{
1671 int c;
1672 int save_State = State;
1673
1674 State = TERMINAL;
1675 got_int = FALSE;
1676#ifdef WIN3264
1677 ctrl_break_was_pressed = FALSE;
1678#endif
1679 c = vgetc();
1680 got_int = FALSE;
1681 State = save_State;
1682 return c;
1683}
1684
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001685static int mouse_was_outside = FALSE;
1686
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001687/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001688 * Send keys to terminal.
1689 * Return FAIL when the key needs to be handled in Normal mode.
1690 * Return OK when the key was dropped or sent to the terminal.
1691 */
1692 int
1693send_keys_to_term(term_T *term, int c, int typed)
1694{
1695 char msg[KEY_BUF_LEN];
1696 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001697 int dragging_outside = FALSE;
1698
1699 /* Catch keys that need to be handled as in Normal mode. */
1700 switch (c)
1701 {
1702 case NUL:
1703 case K_ZERO:
1704 if (typed)
1705 stuffcharReadbuff(c);
1706 return FAIL;
1707
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001708 case K_TABLINE:
1709 stuffcharReadbuff(c);
1710 return FAIL;
1711
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001712 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001713 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001714 return FAIL;
1715
1716 case K_LEFTDRAG:
1717 case K_MIDDLEDRAG:
1718 case K_RIGHTDRAG:
1719 case K_X1DRAG:
1720 case K_X2DRAG:
1721 dragging_outside = mouse_was_outside;
1722 /* FALLTHROUGH */
1723 case K_LEFTMOUSE:
1724 case K_LEFTMOUSE_NM:
1725 case K_LEFTRELEASE:
1726 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001727 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001728 case K_MIDDLEMOUSE:
1729 case K_MIDDLERELEASE:
1730 case K_RIGHTMOUSE:
1731 case K_RIGHTRELEASE:
1732 case K_X1MOUSE:
1733 case K_X1RELEASE:
1734 case K_X2MOUSE:
1735 case K_X2RELEASE:
1736
1737 case K_MOUSEUP:
1738 case K_MOUSEDOWN:
1739 case K_MOUSELEFT:
1740 case K_MOUSERIGHT:
1741 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001742 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001743 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001744 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001745 || dragging_outside)
1746 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001747 /* click or scroll outside the current window or on status line
1748 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001749 if (typed)
1750 {
1751 stuffcharReadbuff(c);
1752 mouse_was_outside = TRUE;
1753 }
1754 return FAIL;
1755 }
1756 }
1757 if (typed)
1758 mouse_was_outside = FALSE;
1759
1760 /* Convert the typed key to a sequence of bytes for the job. */
1761 len = term_convert_key(term, c, msg);
1762 if (len > 0)
1763 /* TODO: if FAIL is returned, stop? */
1764 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1765 (char_u *)msg, (int)len, NULL);
1766
1767 return OK;
1768}
1769
1770 static void
1771position_cursor(win_T *wp, VTermPos *pos)
1772{
1773 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1774 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1775 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1776}
1777
1778/*
1779 * Handle CTRL-W "": send register contents to the job.
1780 */
1781 static void
1782term_paste_register(int prev_c UNUSED)
1783{
1784 int c;
1785 list_T *l;
1786 listitem_T *item;
1787 long reglen = 0;
1788 int type;
1789
1790#ifdef FEAT_CMDL_INFO
1791 if (add_to_showcmd(prev_c))
1792 if (add_to_showcmd('"'))
1793 out_flush();
1794#endif
1795 c = term_vgetc();
1796#ifdef FEAT_CMDL_INFO
1797 clear_showcmd();
1798#endif
1799 if (!term_use_loop())
1800 /* job finished while waiting for a character */
1801 return;
1802
1803 /* CTRL-W "= prompt for expression to evaluate. */
1804 if (c == '=' && get_expr_register() != '=')
1805 return;
1806 if (!term_use_loop())
1807 /* job finished while waiting for a character */
1808 return;
1809
1810 l = (list_T *)get_reg_contents(c, GREG_LIST);
1811 if (l != NULL)
1812 {
1813 type = get_reg_type(c, &reglen);
1814 for (item = l->lv_first; item != NULL; item = item->li_next)
1815 {
1816 char_u *s = get_tv_string(&item->li_tv);
1817#ifdef WIN3264
1818 char_u *tmp = s;
1819
1820 if (!enc_utf8 && enc_codepage > 0)
1821 {
1822 WCHAR *ret = NULL;
1823 int length = 0;
1824
1825 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1826 (int)STRLEN(s), &ret, &length);
1827 if (ret != NULL)
1828 {
1829 WideCharToMultiByte_alloc(CP_UTF8, 0,
1830 ret, length, (char **)&s, &length, 0, 0);
1831 vim_free(ret);
1832 }
1833 }
1834#endif
1835 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1836 s, (int)STRLEN(s), NULL);
1837#ifdef WIN3264
1838 if (tmp != s)
1839 vim_free(s);
1840#endif
1841
1842 if (item->li_next != NULL || type == MLINE)
1843 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1844 (char_u *)"\r", 1, NULL);
1845 }
1846 list_free(l);
1847 }
1848}
1849
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001850/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001851 * Return TRUE when waiting for a character in the terminal, the cursor of the
1852 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001853 */
1854 int
1855terminal_is_active()
1856{
1857 return in_terminal_loop != NULL;
1858}
1859
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001860#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001861 cursorentry_T *
1862term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1863{
1864 term_T *term = in_terminal_loop;
1865 static cursorentry_T entry;
1866
1867 vim_memset(&entry, 0, sizeof(entry));
1868 entry.shape = entry.mshape =
1869 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1870 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1871 SHAPE_BLOCK;
1872 entry.percentage = 20;
1873 if (term->tl_cursor_blink)
1874 {
1875 entry.blinkwait = 700;
1876 entry.blinkon = 400;
1877 entry.blinkoff = 250;
1878 }
1879 *fg = gui.back_pixel;
1880 if (term->tl_cursor_color == NULL)
1881 *bg = gui.norm_pixel;
1882 else
1883 *bg = color_name2handle(term->tl_cursor_color);
1884 entry.name = "n";
1885 entry.used_for = SHAPE_CURSOR;
1886
1887 return &entry;
1888}
1889#endif
1890
Bram Moolenaard317b382018-02-08 22:33:31 +01001891 static void
1892may_output_cursor_props(void)
1893{
1894 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1895 || last_set_cursor_shape != desired_cursor_shape
1896 || last_set_cursor_blink != desired_cursor_blink)
1897 {
1898 last_set_cursor_color = desired_cursor_color;
1899 last_set_cursor_shape = desired_cursor_shape;
1900 last_set_cursor_blink = desired_cursor_blink;
1901 term_cursor_color(desired_cursor_color);
1902 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1903 /* this will restore the initial cursor style, if possible */
1904 ui_cursor_shape_forced(TRUE);
1905 else
1906 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1907 }
1908}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001909
Bram Moolenaard317b382018-02-08 22:33:31 +01001910/*
1911 * Set the cursor color and shape, if not last set to these.
1912 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913 static void
1914may_set_cursor_props(term_T *term)
1915{
1916#ifdef FEAT_GUI
1917 /* For the GUI the cursor properties are obtained with
1918 * term_get_cursor_shape(). */
1919 if (gui.in_use)
1920 return;
1921#endif
1922 if (in_terminal_loop == term)
1923 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001924 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001925 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001926 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001927 desired_cursor_color = (char_u *)"";
1928 desired_cursor_shape = term->tl_cursor_shape;
1929 desired_cursor_blink = term->tl_cursor_blink;
1930 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001931 }
1932}
1933
Bram Moolenaard317b382018-02-08 22:33:31 +01001934/*
1935 * Reset the desired cursor properties and restore them when needed.
1936 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001937 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001938prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001939{
1940#ifdef FEAT_GUI
1941 if (gui.in_use)
1942 return;
1943#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001944 desired_cursor_color = (char_u *)"";
1945 desired_cursor_shape = -1;
1946 desired_cursor_blink = -1;
1947 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001948}
1949
1950/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001951 * Returns TRUE if the current window contains a terminal and we are sending
1952 * keys to the job.
1953 * If "check_job_status" is TRUE update the job status.
1954 */
1955 static int
1956term_use_loop_check(int check_job_status)
1957{
1958 term_T *term = curbuf->b_term;
1959
1960 return term != NULL
1961 && !term->tl_normal_mode
1962 && term->tl_vterm != NULL
1963 && term_job_running_check(term, check_job_status);
1964}
1965
1966/*
1967 * Returns TRUE if the current window contains a terminal and we are sending
1968 * keys to the job.
1969 */
1970 int
1971term_use_loop(void)
1972{
1973 return term_use_loop_check(FALSE);
1974}
1975
1976/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001977 * Called when entering a window with the mouse. If this is a terminal window
1978 * we may want to change state.
1979 */
1980 void
1981term_win_entered()
1982{
1983 term_T *term = curbuf->b_term;
1984
1985 if (term != NULL)
1986 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001987 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001988 {
1989 reset_VIsual_and_resel();
1990 if (State & INSERT)
1991 stop_insert_mode = TRUE;
1992 }
1993 mouse_was_outside = FALSE;
1994 enter_mouse_col = mouse_col;
1995 enter_mouse_row = mouse_row;
1996 }
1997}
1998
1999/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002000 * Wait for input and send it to the job.
2001 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2002 * when there is no more typahead.
2003 * Return when the start of a CTRL-W command is typed or anything else that
2004 * should be handled as a Normal mode command.
2005 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2006 * the terminal was closed.
2007 */
2008 int
2009terminal_loop(int blocking)
2010{
2011 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002012 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002013 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002014#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002015 int tty_fd = curbuf->b_term->tl_job->jv_channel
2016 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002017#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01002018 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002019
2020 /* Remember the terminal we are sending keys to. However, the terminal
2021 * might be closed while waiting for a character, e.g. typing "exit" in a
2022 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2023 * stored reference. */
2024 in_terminal_loop = curbuf->b_term;
2025
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002026 if (*curwin->w_p_twk != NUL)
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002027 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2029 may_set_cursor_props(curbuf->b_term);
2030
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002031 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002032 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002033#ifdef FEAT_GUI
2034 if (!curbuf->b_term->tl_system)
2035#endif
2036 /* TODO: skip screen update when handling a sequence of keys. */
2037 /* Repeat redrawing in case a message is received while redrawing.
2038 */
2039 while (must_redraw != 0)
2040 if (update_screen(0) == FAIL)
2041 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002042 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002043 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002044
2045 c = term_vgetc();
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002046 if (!term_use_loop_check(TRUE))
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002047 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002048 /* Job finished while waiting for a character. Push back the
2049 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002050 if (c != K_IGNORE)
2051 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002052 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002053 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002054 if (c == K_IGNORE)
2055 continue;
2056
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002057#ifdef UNIX
2058 /*
2059 * The shell or another program may change the tty settings. Getting
2060 * them for every typed character is a bit of overhead, but it's needed
2061 * for the first character typed, e.g. when Vim starts in a shell.
2062 */
2063 if (isatty(tty_fd))
2064 {
2065 ttyinfo_T info;
2066
2067 /* Get the current backspace character of the pty. */
2068 if (get_tty_info(tty_fd, &info) == OK)
2069 term_backspace_char = info.backspace;
2070 }
2071#endif
2072
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002073#ifdef WIN3264
2074 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2075 * Use CTRL-BREAK to kill the job. */
2076 if (ctrl_break_was_pressed)
2077 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2078#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002079 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002080 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002081 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002082#ifdef FEAT_GUI
2083 && !curbuf->b_term->tl_system
2084#endif
2085 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002086 {
2087 int prev_c = c;
2088
2089#ifdef FEAT_CMDL_INFO
2090 if (add_to_showcmd(c))
2091 out_flush();
2092#endif
2093 c = term_vgetc();
2094#ifdef FEAT_CMDL_INFO
2095 clear_showcmd();
2096#endif
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002097 if (!term_use_loop_check(TRUE))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002098 /* job finished while waiting for a character */
2099 break;
2100
2101 if (prev_c == Ctrl_BSL)
2102 {
2103 if (c == Ctrl_N)
2104 {
2105 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2106 term_enter_normal_mode();
2107 ret = FAIL;
2108 goto theend;
2109 }
2110 /* Send both keys to the terminal. */
2111 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2112 }
2113 else if (c == Ctrl_C)
2114 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002115 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002116 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2117 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002118 else if (termwinkey == 0 && c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002119 {
2120 /* "CTRL-W .": send CTRL-W to the job */
2121 c = Ctrl_W;
2122 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002123 else if (termwinkey == 0 && c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002124 {
2125 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2126 c = Ctrl_BSL;
2127 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002128 else if (c == 'N')
2129 {
2130 /* CTRL-W N : go to Terminal-Normal mode. */
2131 term_enter_normal_mode();
2132 ret = FAIL;
2133 goto theend;
2134 }
2135 else if (c == '"')
2136 {
2137 term_paste_register(prev_c);
2138 continue;
2139 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002140 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002141 {
2142 stuffcharReadbuff(Ctrl_W);
2143 stuffcharReadbuff(c);
2144 ret = OK;
2145 goto theend;
2146 }
2147 }
2148# ifdef WIN3264
2149 if (!enc_utf8 && has_mbyte && c >= 0x80)
2150 {
2151 WCHAR wc;
2152 char_u mb[3];
2153
2154 mb[0] = (unsigned)c >> 8;
2155 mb[1] = c;
2156 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2157 c = wc;
2158 }
2159# endif
2160 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2161 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002162 if (c == K_MOUSEMOVE)
2163 /* We are sure to come back here, don't reset the cursor color
2164 * and shape to avoid flickering. */
2165 restore_cursor = FALSE;
2166
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002167 ret = OK;
2168 goto theend;
2169 }
2170 }
2171 ret = FAIL;
2172
2173theend:
2174 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002175 if (restore_cursor)
2176 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002177 return ret;
2178}
2179
2180/*
2181 * Called when a job has finished.
2182 * This updates the title and status, but does not close the vterm, because
2183 * there might still be pending output in the channel.
2184 */
2185 void
2186term_job_ended(job_T *job)
2187{
2188 term_T *term;
2189 int did_one = FALSE;
2190
2191 for (term = first_term; term != NULL; term = term->tl_next)
2192 if (term->tl_job == job)
2193 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002194 VIM_CLEAR(term->tl_title);
2195 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002196 redraw_buf_and_status_later(term->tl_buffer, VALID);
2197 did_one = TRUE;
2198 }
2199 if (did_one)
2200 redraw_statuslines();
2201 if (curbuf->b_term != NULL)
2202 {
2203 if (curbuf->b_term->tl_job == job)
2204 maketitle();
2205 update_cursor(curbuf->b_term, TRUE);
2206 }
2207}
2208
2209 static void
2210may_toggle_cursor(term_T *term)
2211{
2212 if (in_terminal_loop == term)
2213 {
2214 if (term->tl_cursor_visible)
2215 cursor_on();
2216 else
2217 cursor_off();
2218 }
2219}
2220
2221/*
2222 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002223 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002224 */
2225 static int
2226color2index(VTermColor *color, int fg, int *boldp)
2227{
2228 int red = color->red;
2229 int blue = color->blue;
2230 int green = color->green;
2231
Bram Moolenaar46359e12017-11-29 22:33:38 +01002232 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002233 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002234 /* First 16 colors and default: use the ANSI index, because these
2235 * colors can be redefined. */
2236 if (t_colors >= 16)
2237 return color->ansi_index;
2238 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002239 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002240 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002241 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002242 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2243 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2244 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002245 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002246 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2247 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2248 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2249 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2250 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2251 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2252 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2253 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2254 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2255 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2256 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002257 }
2258 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002259
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002260 if (t_colors >= 256)
2261 {
2262 if (red == blue && red == green)
2263 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002264 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002265 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002266 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2267 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2268 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002269 int i;
2270
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002271 if (red < 5)
2272 return 17; /* 00/00/00 */
2273 if (red > 245) /* ff/ff/ff */
2274 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002275 for (i = 0; i < 23; ++i)
2276 if (red < cutoff[i])
2277 return i + 233;
2278 return 256;
2279 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002280 {
2281 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2282 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002283
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002284 /* 216-color cube */
2285 for (ri = 0; ri < 5; ++ri)
2286 if (red < cutoff[ri])
2287 break;
2288 for (gi = 0; gi < 5; ++gi)
2289 if (green < cutoff[gi])
2290 break;
2291 for (bi = 0; bi < 5; ++bi)
2292 if (blue < cutoff[bi])
2293 break;
2294 return 17 + ri * 36 + gi * 6 + bi;
2295 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002296 }
2297 return 0;
2298}
2299
2300/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002301 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002302 */
2303 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002304vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002305{
2306 int attr = 0;
2307
2308 if (cellattrs.bold)
2309 attr |= HL_BOLD;
2310 if (cellattrs.underline)
2311 attr |= HL_UNDERLINE;
2312 if (cellattrs.italic)
2313 attr |= HL_ITALIC;
2314 if (cellattrs.strike)
2315 attr |= HL_STRIKETHROUGH;
2316 if (cellattrs.reverse)
2317 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002318 return attr;
2319}
2320
2321/*
2322 * Store Vterm attributes in "cell" from highlight flags.
2323 */
2324 static void
2325hl2vtermAttr(int attr, cellattr_T *cell)
2326{
2327 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2328 if (attr & HL_BOLD)
2329 cell->attrs.bold = 1;
2330 if (attr & HL_UNDERLINE)
2331 cell->attrs.underline = 1;
2332 if (attr & HL_ITALIC)
2333 cell->attrs.italic = 1;
2334 if (attr & HL_STRIKETHROUGH)
2335 cell->attrs.strike = 1;
2336 if (attr & HL_INVERSE)
2337 cell->attrs.reverse = 1;
2338}
2339
2340/*
2341 * Convert the attributes of a vterm cell into an attribute index.
2342 */
2343 static int
2344cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2345{
2346 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002347
2348#ifdef FEAT_GUI
2349 if (gui.in_use)
2350 {
2351 guicolor_T fg, bg;
2352
2353 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2354 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2355 return get_gui_attr_idx(attr, fg, bg);
2356 }
2357 else
2358#endif
2359#ifdef FEAT_TERMGUICOLORS
2360 if (p_tgc)
2361 {
2362 guicolor_T fg, bg;
2363
2364 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2365 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2366
2367 return get_tgc_attr_idx(attr, fg, bg);
2368 }
2369 else
2370#endif
2371 {
2372 int bold = MAYBE;
2373 int fg = color2index(&cellfg, TRUE, &bold);
2374 int bg = color2index(&cellbg, FALSE, &bold);
2375
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002376 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002377 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002378 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002379 if (fg == 0 && term_default_cterm_fg >= 0)
2380 fg = term_default_cterm_fg + 1;
2381 if (bg == 0 && term_default_cterm_bg >= 0)
2382 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002383 }
2384
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002385 /* with 8 colors set the bold attribute to get a bright foreground */
2386 if (bold == TRUE)
2387 attr |= HL_BOLD;
2388 return get_cterm_attr_idx(attr, fg, bg);
2389 }
2390 return 0;
2391}
2392
2393 static int
2394handle_damage(VTermRect rect, void *user)
2395{
2396 term_T *term = (term_T *)user;
2397
2398 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2399 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002400 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002401 return 1;
2402}
2403
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002404 static void
2405term_scroll_up(term_T *term, int start_row, int count)
2406{
2407 win_T *wp;
2408 VTermColor fg, bg;
2409 VTermScreenCellAttrs attr;
2410 int clear_attr;
2411
2412 /* Set the color to clear lines with. */
2413 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2414 &fg, &bg);
2415 vim_memset(&attr, 0, sizeof(attr));
2416 clear_attr = cell2attr(attr, fg, bg);
2417
2418 FOR_ALL_WINDOWS(wp)
2419 {
2420 if (wp->w_buffer == term->tl_buffer)
2421 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2422 }
2423}
2424
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002425 static int
2426handle_moverect(VTermRect dest, VTermRect src, void *user)
2427{
2428 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002429 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002430
2431 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002432 * redrawing the text. But avoid doing this multiple times, postpone until
2433 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002434 if (dest.start_col == src.start_col
2435 && dest.end_col == src.end_col
2436 && dest.start_row < src.start_row)
2437 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002438 if (dest.start_row == 0)
2439 term->tl_postponed_scroll += count;
2440 else
2441 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002442 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002443
2444 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2445 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2446
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002447 /* Note sure if the scrolling will work correctly, let's do a complete
2448 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002449 redraw_buf_later(term->tl_buffer, NOT_VALID);
2450 return 1;
2451}
2452
2453 static int
2454handle_movecursor(
2455 VTermPos pos,
2456 VTermPos oldpos UNUSED,
2457 int visible,
2458 void *user)
2459{
2460 term_T *term = (term_T *)user;
2461 win_T *wp;
2462
2463 term->tl_cursor_pos = pos;
2464 term->tl_cursor_visible = visible;
2465
2466 FOR_ALL_WINDOWS(wp)
2467 {
2468 if (wp->w_buffer == term->tl_buffer)
2469 position_cursor(wp, &pos);
2470 }
2471 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2472 {
2473 may_toggle_cursor(term);
2474 update_cursor(term, term->tl_cursor_visible);
2475 }
2476
2477 return 1;
2478}
2479
2480 static int
2481handle_settermprop(
2482 VTermProp prop,
2483 VTermValue *value,
2484 void *user)
2485{
2486 term_T *term = (term_T *)user;
2487
2488 switch (prop)
2489 {
2490 case VTERM_PROP_TITLE:
2491 vim_free(term->tl_title);
2492 /* a blank title isn't useful, make it empty, so that "running" is
2493 * displayed */
2494 if (*skipwhite((char_u *)value->string) == NUL)
2495 term->tl_title = NULL;
2496#ifdef WIN3264
2497 else if (!enc_utf8 && enc_codepage > 0)
2498 {
2499 WCHAR *ret = NULL;
2500 int length = 0;
2501
2502 MultiByteToWideChar_alloc(CP_UTF8, 0,
2503 (char*)value->string, (int)STRLEN(value->string),
2504 &ret, &length);
2505 if (ret != NULL)
2506 {
2507 WideCharToMultiByte_alloc(enc_codepage, 0,
2508 ret, length, (char**)&term->tl_title,
2509 &length, 0, 0);
2510 vim_free(ret);
2511 }
2512 }
2513#endif
2514 else
2515 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002516 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002517 if (term == curbuf->b_term)
2518 maketitle();
2519 break;
2520
2521 case VTERM_PROP_CURSORVISIBLE:
2522 term->tl_cursor_visible = value->boolean;
2523 may_toggle_cursor(term);
2524 out_flush();
2525 break;
2526
2527 case VTERM_PROP_CURSORBLINK:
2528 term->tl_cursor_blink = value->boolean;
2529 may_set_cursor_props(term);
2530 break;
2531
2532 case VTERM_PROP_CURSORSHAPE:
2533 term->tl_cursor_shape = value->number;
2534 may_set_cursor_props(term);
2535 break;
2536
2537 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002538 if (desired_cursor_color == term->tl_cursor_color)
2539 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002540 vim_free(term->tl_cursor_color);
2541 if (*value->string == NUL)
2542 term->tl_cursor_color = NULL;
2543 else
2544 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2545 may_set_cursor_props(term);
2546 break;
2547
2548 case VTERM_PROP_ALTSCREEN:
2549 /* TODO: do anything else? */
2550 term->tl_using_altscreen = value->boolean;
2551 break;
2552
2553 default:
2554 break;
2555 }
2556 /* Always return 1, otherwise vterm doesn't store the value internally. */
2557 return 1;
2558}
2559
2560/*
2561 * The job running in the terminal resized the terminal.
2562 */
2563 static int
2564handle_resize(int rows, int cols, void *user)
2565{
2566 term_T *term = (term_T *)user;
2567 win_T *wp;
2568
2569 term->tl_rows = rows;
2570 term->tl_cols = cols;
2571 if (term->tl_vterm_size_changed)
2572 /* Size was set by vterm_set_size(), don't set the window size. */
2573 term->tl_vterm_size_changed = FALSE;
2574 else
2575 {
2576 FOR_ALL_WINDOWS(wp)
2577 {
2578 if (wp->w_buffer == term->tl_buffer)
2579 {
2580 win_setheight_win(rows, wp);
2581 win_setwidth_win(cols, wp);
2582 }
2583 }
2584 redraw_buf_later(term->tl_buffer, NOT_VALID);
2585 }
2586 return 1;
2587}
2588
2589/*
2590 * Handle a line that is pushed off the top of the screen.
2591 */
2592 static int
2593handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2594{
2595 term_T *term = (term_T *)user;
2596
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002597 /* If the number of lines that are stored goes over 'termscrollback' then
2598 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002599 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002600 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002601 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002602 int i;
2603
2604 curbuf = term->tl_buffer;
2605 for (i = 0; i < todo; ++i)
2606 {
2607 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2608 ml_delete(1, FALSE);
2609 }
2610 curbuf = curwin->w_buffer;
2611
2612 term->tl_scrollback.ga_len -= todo;
2613 mch_memmove(term->tl_scrollback.ga_data,
2614 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2615 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
2616 }
2617
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002618 if (ga_grow(&term->tl_scrollback, 1) == OK)
2619 {
2620 cellattr_T *p = NULL;
2621 int len = 0;
2622 int i;
2623 int c;
2624 int col;
2625 sb_line_T *line;
2626 garray_T ga;
2627 cellattr_T fill_attr = term->tl_default_color;
2628
2629 /* do not store empty cells at the end */
2630 for (i = 0; i < cols; ++i)
2631 if (cells[i].chars[0] != 0)
2632 len = i + 1;
2633 else
2634 cell2cellattr(&cells[i], &fill_attr);
2635
2636 ga_init2(&ga, 1, 100);
2637 if (len > 0)
2638 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2639 if (p != NULL)
2640 {
2641 for (col = 0; col < len; col += cells[col].width)
2642 {
2643 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2644 {
2645 ga.ga_len = 0;
2646 break;
2647 }
2648 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2649 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2650 (char_u *)ga.ga_data + ga.ga_len);
2651 cell2cellattr(&cells[col], &p[col]);
2652 }
2653 }
2654 if (ga_grow(&ga, 1) == FAIL)
2655 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2656 else
2657 {
2658 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2659 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2660 }
2661 ga_clear(&ga);
2662
2663 line = (sb_line_T *)term->tl_scrollback.ga_data
2664 + term->tl_scrollback.ga_len;
2665 line->sb_cols = len;
2666 line->sb_cells = p;
2667 line->sb_fill_attr = fill_attr;
2668 ++term->tl_scrollback.ga_len;
2669 ++term->tl_scrollback_scrolled;
2670 }
2671 return 0; /* ignored */
2672}
2673
2674static VTermScreenCallbacks screen_callbacks = {
2675 handle_damage, /* damage */
2676 handle_moverect, /* moverect */
2677 handle_movecursor, /* movecursor */
2678 handle_settermprop, /* settermprop */
2679 NULL, /* bell */
2680 handle_resize, /* resize */
2681 handle_pushline, /* sb_pushline */
2682 NULL /* sb_popline */
2683};
2684
2685/*
2686 * Called when a channel has been closed.
2687 * If this was a channel for a terminal window then finish it up.
2688 */
2689 void
2690term_channel_closed(channel_T *ch)
2691{
2692 term_T *term;
2693 int did_one = FALSE;
2694
2695 for (term = first_term; term != NULL; term = term->tl_next)
2696 if (term->tl_job == ch->ch_job)
2697 {
2698 term->tl_channel_closed = TRUE;
2699 did_one = TRUE;
2700
Bram Moolenaard23a8232018-02-10 18:45:26 +01002701 VIM_CLEAR(term->tl_title);
2702 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002703#ifdef WIN3264
2704 if (term->tl_out_fd != NULL)
2705 {
2706 fclose(term->tl_out_fd);
2707 term->tl_out_fd = NULL;
2708 }
2709#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002710
2711 /* Unless in Terminal-Normal mode: clear the vterm. */
2712 if (!term->tl_normal_mode)
2713 {
2714 int fnum = term->tl_buffer->b_fnum;
2715
2716 cleanup_vterm(term);
2717
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002718 if (term->tl_finish == TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002719 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002720 aco_save_T aco;
2721
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002722 /* ++close or term_finish == "close" */
2723 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002724 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002725 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002726 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002727 break;
2728 }
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002729 if (term->tl_finish == TL_FINISH_OPEN
2730 && term->tl_buffer->b_nwindows == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002731 {
2732 char buf[50];
2733
2734 /* TODO: use term_opencmd */
2735 ch_log(NULL, "terminal job finished, opening window");
2736 vim_snprintf(buf, sizeof(buf),
2737 term->tl_opencmd == NULL
2738 ? "botright sbuf %d"
2739 : (char *)term->tl_opencmd, fnum);
2740 do_cmdline_cmd((char_u *)buf);
2741 }
2742 else
2743 ch_log(NULL, "terminal job finished");
2744 }
2745
2746 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2747 }
2748 if (did_one)
2749 {
2750 redraw_statuslines();
2751
2752 /* Need to break out of vgetc(). */
2753 ins_char_typebuf(K_IGNORE);
2754 typebuf_was_filled = TRUE;
2755
2756 term = curbuf->b_term;
2757 if (term != NULL)
2758 {
2759 if (term->tl_job == ch->ch_job)
2760 maketitle();
2761 update_cursor(term, term->tl_cursor_visible);
2762 }
2763 }
2764}
2765
2766/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002767 * Fill one screen line from a line of the terminal.
2768 * Advances "pos" to past the last column.
2769 */
2770 static void
2771term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2772{
2773 int off = screen_get_current_line_off();
2774
2775 for (pos->col = 0; pos->col < max_col; )
2776 {
2777 VTermScreenCell cell;
2778 int c;
2779
2780 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2781 vim_memset(&cell, 0, sizeof(cell));
2782
2783 c = cell.chars[0];
2784 if (c == NUL)
2785 {
2786 ScreenLines[off] = ' ';
2787 if (enc_utf8)
2788 ScreenLinesUC[off] = NUL;
2789 }
2790 else
2791 {
2792 if (enc_utf8)
2793 {
2794 int i;
2795
2796 /* composing chars */
2797 for (i = 0; i < Screen_mco
2798 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2799 {
2800 ScreenLinesC[i][off] = cell.chars[i + 1];
2801 if (cell.chars[i + 1] == 0)
2802 break;
2803 }
2804 if (c >= 0x80 || (Screen_mco > 0
2805 && ScreenLinesC[0][off] != 0))
2806 {
2807 ScreenLines[off] = ' ';
2808 ScreenLinesUC[off] = c;
2809 }
2810 else
2811 {
2812 ScreenLines[off] = c;
2813 ScreenLinesUC[off] = NUL;
2814 }
2815 }
2816#ifdef WIN3264
2817 else if (has_mbyte && c >= 0x80)
2818 {
2819 char_u mb[MB_MAXBYTES+1];
2820 WCHAR wc = c;
2821
2822 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2823 (char*)mb, 2, 0, 0) > 1)
2824 {
2825 ScreenLines[off] = mb[0];
2826 ScreenLines[off + 1] = mb[1];
2827 cell.width = mb_ptr2cells(mb);
2828 }
2829 else
2830 ScreenLines[off] = c;
2831 }
2832#endif
2833 else
2834 ScreenLines[off] = c;
2835 }
2836 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2837
2838 ++pos->col;
2839 ++off;
2840 if (cell.width == 2)
2841 {
2842 if (enc_utf8)
2843 ScreenLinesUC[off] = NUL;
2844
2845 /* don't set the second byte to NUL for a DBCS encoding, it
2846 * has been set above */
2847 if (enc_utf8 || !has_mbyte)
2848 ScreenLines[off] = NUL;
2849
2850 ++pos->col;
2851 ++off;
2852 }
2853 }
2854}
2855
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002856#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01002857 static void
2858update_system_term(term_T *term)
2859{
2860 VTermPos pos;
2861 VTermScreen *screen;
2862
2863 if (term->tl_vterm == NULL)
2864 return;
2865 screen = vterm_obtain_screen(term->tl_vterm);
2866
2867 /* Scroll up to make more room for terminal lines if needed. */
2868 while (term->tl_toprow > 0
2869 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
2870 {
2871 int save_p_more = p_more;
2872
2873 p_more = FALSE;
2874 msg_row = Rows - 1;
2875 msg_puts((char_u *)"\n");
2876 p_more = save_p_more;
2877 --term->tl_toprow;
2878 }
2879
2880 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2881 && pos.row < Rows; ++pos.row)
2882 {
2883 if (pos.row < term->tl_rows)
2884 {
2885 int max_col = MIN(Columns, term->tl_cols);
2886
2887 term_line2screenline(screen, &pos, max_col);
2888 }
2889 else
2890 pos.col = 0;
2891
2892 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
2893 }
2894
2895 term->tl_dirty_row_start = MAX_ROW;
2896 term->tl_dirty_row_end = 0;
2897 update_cursor(term, TRUE);
2898}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002899#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01002900
2901/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002902 * Return TRUE if window "wp" is to be redrawn with term_update_window().
2903 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002904 * Terminal-Normal mode.
2905 */
2906 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002907term_do_update_window(win_T *wp)
2908{
2909 term_T *term = wp->w_buffer->b_term;
2910
2911 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
2912}
2913
2914/*
2915 * Called to update a window that contains an active terminal.
2916 */
2917 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002918term_update_window(win_T *wp)
2919{
2920 term_T *term = wp->w_buffer->b_term;
2921 VTerm *vterm;
2922 VTermScreen *screen;
2923 VTermState *state;
2924 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02002925 int rows, cols;
2926 int newrows, newcols;
2927 int minsize;
2928 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002929
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002930 vterm = term->tl_vterm;
2931 screen = vterm_obtain_screen(vterm);
2932 state = vterm_obtain_state(vterm);
2933
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002934 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
2935 * SOME_VALID only redraw what was marked dirty. */
2936 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002937 {
2938 term->tl_dirty_row_start = 0;
2939 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002940
2941 if (term->tl_postponed_scroll > 0
2942 && term->tl_postponed_scroll < term->tl_rows / 3)
2943 /* Scrolling is usually faster than redrawing, when there are only
2944 * a few lines to scroll. */
2945 term_scroll_up(term, 0, term->tl_postponed_scroll);
2946 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002947 }
2948
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002949 /*
2950 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002951 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002952 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002953 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002954
Bram Moolenaar498c2562018-04-15 23:45:15 +02002955 newrows = 99999;
2956 newcols = 99999;
2957 FOR_ALL_WINDOWS(twp)
2958 {
2959 /* When more than one window shows the same terminal, use the
2960 * smallest size. */
2961 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002962 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02002963 newrows = MIN(newrows, twp->w_height);
2964 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002965 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02002966 }
2967 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
2968 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
2969
2970 if (term->tl_rows != newrows || term->tl_cols != newcols)
2971 {
2972
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002973
2974 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02002975 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002976 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02002977 newrows);
2978 term_report_winsize(term, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002979 }
2980
2981 /* The cursor may have been moved when resizing. */
2982 vterm_state_get_cursorpos(state, &pos);
2983 position_cursor(wp, &pos);
2984
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002985 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2986 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002987 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002988 if (pos.row < term->tl_rows)
2989 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002990 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002991
Bram Moolenaar13568252018-03-16 20:46:58 +01002992 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002993 }
2994 else
2995 pos.col = 0;
2996
Bram Moolenaarf118d482018-03-13 13:14:00 +01002997 screen_line(wp->w_winrow + pos.row
2998#ifdef FEAT_MENU
2999 + winbar_height(wp)
3000#endif
3001 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003002 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003003 term->tl_dirty_row_start = MAX_ROW;
3004 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003005}
3006
3007/*
3008 * Return TRUE if "wp" is a terminal window where the job has finished.
3009 */
3010 int
3011term_is_finished(buf_T *buf)
3012{
3013 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3014}
3015
3016/*
3017 * Return TRUE if "wp" is a terminal window where the job has finished or we
3018 * are in Terminal-Normal mode, thus we show the buffer contents.
3019 */
3020 int
3021term_show_buffer(buf_T *buf)
3022{
3023 term_T *term = buf->b_term;
3024
3025 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3026}
3027
3028/*
3029 * The current buffer is going to be changed. If there is terminal
3030 * highlighting remove it now.
3031 */
3032 void
3033term_change_in_curbuf(void)
3034{
3035 term_T *term = curbuf->b_term;
3036
3037 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3038 {
3039 free_scrollback(term);
3040 redraw_buf_later(term->tl_buffer, NOT_VALID);
3041
3042 /* The buffer is now like a normal buffer, it cannot be easily
3043 * abandoned when changed. */
3044 set_string_option_direct((char_u *)"buftype", -1,
3045 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3046 }
3047}
3048
3049/*
3050 * Get the screen attribute for a position in the buffer.
3051 * Use a negative "col" to get the filler background color.
3052 */
3053 int
3054term_get_attr(buf_T *buf, linenr_T lnum, int col)
3055{
3056 term_T *term = buf->b_term;
3057 sb_line_T *line;
3058 cellattr_T *cellattr;
3059
3060 if (lnum > term->tl_scrollback.ga_len)
3061 cellattr = &term->tl_default_color;
3062 else
3063 {
3064 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3065 if (col < 0 || col >= line->sb_cols)
3066 cellattr = &line->sb_fill_attr;
3067 else
3068 cellattr = line->sb_cells + col;
3069 }
3070 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3071}
3072
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003073/*
3074 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003075 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003076 */
3077 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003078cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003079{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003080 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003081}
3082
3083/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003084 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003085 */
3086 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003087init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003088{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003089 VTermColor *fg, *bg;
3090 int fgval, bgval;
3091 int id;
3092
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003093 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3094 term->tl_default_color.width = 1;
3095 fg = &term->tl_default_color.fg;
3096 bg = &term->tl_default_color.bg;
3097
3098 /* Vterm uses a default black background. Set it to white when
3099 * 'background' is "light". */
3100 if (*p_bg == 'l')
3101 {
3102 fgval = 0;
3103 bgval = 255;
3104 }
3105 else
3106 {
3107 fgval = 255;
3108 bgval = 0;
3109 }
3110 fg->red = fg->green = fg->blue = fgval;
3111 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003112 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003113
3114 /* The "Terminal" highlight group overrules the defaults. */
3115 id = syn_name2id((char_u *)"Terminal");
3116
Bram Moolenaar46359e12017-11-29 22:33:38 +01003117 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003118#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3119 if (0
3120# ifdef FEAT_GUI
3121 || gui.in_use
3122# endif
3123# ifdef FEAT_TERMGUICOLORS
3124 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003125# ifdef FEAT_VTP
3126 /* Finally get INVALCOLOR on this execution path */
3127 || (!p_tgc && t_colors >= 256)
3128# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003129# endif
3130 )
3131 {
3132 guicolor_T fg_rgb = INVALCOLOR;
3133 guicolor_T bg_rgb = INVALCOLOR;
3134
3135 if (id != 0)
3136 syn_id2colors(id, &fg_rgb, &bg_rgb);
3137
3138# ifdef FEAT_GUI
3139 if (gui.in_use)
3140 {
3141 if (fg_rgb == INVALCOLOR)
3142 fg_rgb = gui.norm_pixel;
3143 if (bg_rgb == INVALCOLOR)
3144 bg_rgb = gui.back_pixel;
3145 }
3146# ifdef FEAT_TERMGUICOLORS
3147 else
3148# endif
3149# endif
3150# ifdef FEAT_TERMGUICOLORS
3151 {
3152 if (fg_rgb == INVALCOLOR)
3153 fg_rgb = cterm_normal_fg_gui_color;
3154 if (bg_rgb == INVALCOLOR)
3155 bg_rgb = cterm_normal_bg_gui_color;
3156 }
3157# endif
3158 if (fg_rgb != INVALCOLOR)
3159 {
3160 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3161
3162 fg->red = (unsigned)(rgb >> 16);
3163 fg->green = (unsigned)(rgb >> 8) & 255;
3164 fg->blue = (unsigned)rgb & 255;
3165 }
3166 if (bg_rgb != INVALCOLOR)
3167 {
3168 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3169
3170 bg->red = (unsigned)(rgb >> 16);
3171 bg->green = (unsigned)(rgb >> 8) & 255;
3172 bg->blue = (unsigned)rgb & 255;
3173 }
3174 }
3175 else
3176#endif
3177 if (id != 0 && t_colors >= 16)
3178 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003179 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003180 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003181 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003182 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003183 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003184 else
3185 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003186#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003187 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003188#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003189
3190 /* In an MS-Windows console we know the normal colors. */
3191 if (cterm_normal_fg_color > 0)
3192 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003193 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003194# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003195 tmp = fg->red;
3196 fg->red = fg->blue;
3197 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003198# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003199 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003200# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003201 else
3202 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003203# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003204
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003205 if (cterm_normal_bg_color > 0)
3206 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003207 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003208# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003209 tmp = bg->red;
3210 bg->red = bg->blue;
3211 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003212# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003213 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003214# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003215 else
3216 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003217# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003218 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003219}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003220
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003221#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3222/*
3223 * Set the 16 ANSI colors from array of RGB values
3224 */
3225 static void
3226set_vterm_palette(VTerm *vterm, long_u *rgb)
3227{
3228 int index = 0;
3229 VTermState *state = vterm_obtain_state(vterm);
3230 for (; index < 16; index++)
3231 {
3232 VTermColor color;
3233 color.red = (unsigned)(rgb[index] >> 16);
3234 color.green = (unsigned)(rgb[index] >> 8) & 255;
3235 color.blue = (unsigned)rgb[index] & 255;
3236 vterm_state_set_palette_color(state, index, &color);
3237 }
3238}
3239
3240/*
3241 * Set the ANSI color palette from a list of colors
3242 */
3243 static int
3244set_ansi_colors_list(VTerm *vterm, list_T *list)
3245{
3246 int n = 0;
3247 long_u rgb[16];
3248 listitem_T *li = list->lv_first;
3249
3250 for (; li != NULL && n < 16; li = li->li_next, n++)
3251 {
3252 char_u *color_name;
3253 guicolor_T guicolor;
3254
3255 color_name = get_tv_string_chk(&li->li_tv);
3256 if (color_name == NULL)
3257 return FAIL;
3258
3259 guicolor = GUI_GET_COLOR(color_name);
3260 if (guicolor == INVALCOLOR)
3261 return FAIL;
3262
3263 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3264 }
3265
3266 if (n != 16 || li != NULL)
3267 return FAIL;
3268
3269 set_vterm_palette(vterm, rgb);
3270
3271 return OK;
3272}
3273
3274/*
3275 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3276 */
3277 static void
3278init_vterm_ansi_colors(VTerm *vterm)
3279{
3280 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3281
3282 if (var != NULL
3283 && (var->di_tv.v_type != VAR_LIST
3284 || var->di_tv.vval.v_list == NULL
3285 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3286 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3287}
3288#endif
3289
Bram Moolenaar52acb112018-03-18 19:20:22 +01003290/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003291 * Handles a "drop" command from the job in the terminal.
3292 * "item" is the file name, "item->li_next" may have options.
3293 */
3294 static void
3295handle_drop_command(listitem_T *item)
3296{
3297 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003298 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003299 int bufnr;
3300 win_T *wp;
3301 tabpage_T *tp;
3302 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003303 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003304
3305 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3306 FOR_ALL_TAB_WINDOWS(tp, wp)
3307 {
3308 if (wp->w_buffer->b_fnum == bufnr)
3309 {
3310 /* buffer is in a window already, go there */
3311 goto_tabpage_win(tp, wp);
3312 return;
3313 }
3314 }
3315
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003316 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003317
3318 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3319 && opt_item->li_tv.vval.v_dict != NULL)
3320 {
3321 dict_T *dict = opt_item->li_tv.vval.v_dict;
3322 char_u *p;
3323
3324 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3325 if (p == NULL)
3326 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3327 if (p != NULL)
3328 {
3329 if (check_ff_value(p) == FAIL)
3330 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3331 else
3332 ea.force_ff = *p;
3333 }
3334 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3335 if (p == NULL)
3336 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3337 if (p != NULL)
3338 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003339 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003340 if (ea.cmd != NULL)
3341 {
3342 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3343 ea.force_enc = 11;
3344 tofree = ea.cmd;
3345 }
3346 }
3347
3348 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3349 if (p != NULL)
3350 get_bad_opt(p, &ea);
3351
3352 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3353 ea.force_bin = FORCE_BIN;
3354 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3355 ea.force_bin = FORCE_BIN;
3356 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3357 ea.force_bin = FORCE_NOBIN;
3358 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3359 ea.force_bin = FORCE_NOBIN;
3360 }
3361
3362 /* open in new window, like ":split fname" */
3363 if (ea.cmd == NULL)
3364 ea.cmd = (char_u *)"split";
3365 ea.arg = fname;
3366 ea.cmdidx = CMD_split;
3367 ex_splitview(&ea);
3368
3369 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003370}
3371
3372/*
3373 * Handles a function call from the job running in a terminal.
3374 * "item" is the function name, "item->li_next" has the arguments.
3375 */
3376 static void
3377handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3378{
3379 char_u *func;
3380 typval_T argvars[2];
3381 typval_T rettv;
3382 int doesrange;
3383
3384 if (item->li_next == NULL)
3385 {
3386 ch_log(channel, "Missing function arguments for call");
3387 return;
3388 }
3389 func = get_tv_string(&item->li_tv);
3390
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003391 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003392 {
3393 ch_log(channel, "Invalid function name: %s", func);
3394 return;
3395 }
3396
3397 argvars[0].v_type = VAR_NUMBER;
3398 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3399 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003400 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003401 2, argvars, /* argv_func */ NULL,
3402 /* firstline */ 1, /* lastline */ 1,
3403 &doesrange, /* evaluate */ TRUE,
3404 /* partial */ NULL, /* selfdict */ NULL) == OK)
3405 {
3406 clear_tv(&rettv);
3407 ch_log(channel, "Function %s called", func);
3408 }
3409 else
3410 ch_log(channel, "Calling function %s failed", func);
3411}
3412
3413/*
3414 * Called by libvterm when it cannot recognize an OSC sequence.
3415 * We recognize a terminal API command.
3416 */
3417 static int
3418parse_osc(const char *command, size_t cmdlen, void *user)
3419{
3420 term_T *term = (term_T *)user;
3421 js_read_T reader;
3422 typval_T tv;
3423 channel_T *channel = term->tl_job == NULL ? NULL
3424 : term->tl_job->jv_channel;
3425
3426 /* We recognize only OSC 5 1 ; {command} */
3427 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3428 return 0; /* not handled */
3429
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003430 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003431 if (reader.js_buf == NULL)
3432 return 1;
3433 reader.js_fill = NULL;
3434 reader.js_used = 0;
3435 if (json_decode(&reader, &tv, 0) == OK
3436 && tv.v_type == VAR_LIST
3437 && tv.vval.v_list != NULL)
3438 {
3439 listitem_T *item = tv.vval.v_list->lv_first;
3440
3441 if (item == NULL)
3442 ch_log(channel, "Missing command");
3443 else
3444 {
3445 char_u *cmd = get_tv_string(&item->li_tv);
3446
Bram Moolenaara997b452018-04-17 23:24:06 +02003447 /* Make sure an invoked command doesn't delete the buffer (and the
3448 * terminal) under our fingers. */
3449 ++term->tl_buffer->b_locked;
3450
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003451 item = item->li_next;
3452 if (item == NULL)
3453 ch_log(channel, "Missing argument for %s", cmd);
3454 else if (STRCMP(cmd, "drop") == 0)
3455 handle_drop_command(item);
3456 else if (STRCMP(cmd, "call") == 0)
3457 handle_call_command(term, channel, item);
3458 else
3459 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003460 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003461 }
3462 }
3463 else
3464 ch_log(channel, "Invalid JSON received");
3465
3466 vim_free(reader.js_buf);
3467 clear_tv(&tv);
3468 return 1;
3469}
3470
3471static VTermParserCallbacks parser_fallbacks = {
3472 NULL, /* text */
3473 NULL, /* control */
3474 NULL, /* escape */
3475 NULL, /* csi */
3476 parse_osc, /* osc */
3477 NULL, /* dcs */
3478 NULL /* resize */
3479};
3480
3481/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003482 * Use Vim's allocation functions for vterm so profiling works.
3483 */
3484 static void *
3485vterm_malloc(size_t size, void *data UNUSED)
3486{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003487 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003488}
3489
3490 static void
3491vterm_memfree(void *ptr, void *data UNUSED)
3492{
3493 vim_free(ptr);
3494}
3495
3496static VTermAllocatorFunctions vterm_allocator = {
3497 &vterm_malloc,
3498 &vterm_memfree
3499};
3500
3501/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003502 * Create a new vterm and initialize it.
3503 */
3504 static void
3505create_vterm(term_T *term, int rows, int cols)
3506{
3507 VTerm *vterm;
3508 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003509 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003510 VTermValue value;
3511
Bram Moolenaar756ef112018-04-10 12:04:27 +02003512 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003513 term->tl_vterm = vterm;
3514 screen = vterm_obtain_screen(vterm);
3515 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3516 /* TODO: depends on 'encoding'. */
3517 vterm_set_utf8(vterm, 1);
3518
3519 init_default_colors(term);
3520
3521 vterm_state_set_default_colors(
3522 vterm_obtain_state(vterm),
3523 &term->tl_default_color.fg,
3524 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003525
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003526 if (t_colors >= 16)
3527 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3528
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003529 /* Required to initialize most things. */
3530 vterm_screen_reset(screen, 1 /* hard */);
3531
3532 /* Allow using alternate screen. */
3533 vterm_screen_enable_altscreen(screen, 1);
3534
3535 /* For unix do not use a blinking cursor. In an xterm this causes the
3536 * cursor to blink if it's blinking in the xterm.
3537 * For Windows we respect the system wide setting. */
3538#ifdef WIN3264
3539 if (GetCaretBlinkTime() == INFINITE)
3540 value.boolean = 0;
3541 else
3542 value.boolean = 1;
3543#else
3544 value.boolean = 0;
3545#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003546 state = vterm_obtain_state(vterm);
3547 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3548 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003549}
3550
3551/*
3552 * Return the text to show for the buffer name and status.
3553 */
3554 char_u *
3555term_get_status_text(term_T *term)
3556{
3557 if (term->tl_status_text == NULL)
3558 {
3559 char_u *txt;
3560 size_t len;
3561
3562 if (term->tl_normal_mode)
3563 {
3564 if (term_job_running(term))
3565 txt = (char_u *)_("Terminal");
3566 else
3567 txt = (char_u *)_("Terminal-finished");
3568 }
3569 else if (term->tl_title != NULL)
3570 txt = term->tl_title;
3571 else if (term_none_open(term))
3572 txt = (char_u *)_("active");
3573 else if (term_job_running(term))
3574 txt = (char_u *)_("running");
3575 else
3576 txt = (char_u *)_("finished");
3577 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3578 term->tl_status_text = alloc((int)len);
3579 if (term->tl_status_text != NULL)
3580 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3581 term->tl_buffer->b_fname, txt);
3582 }
3583 return term->tl_status_text;
3584}
3585
3586/*
3587 * Mark references in jobs of terminals.
3588 */
3589 int
3590set_ref_in_term(int copyID)
3591{
3592 int abort = FALSE;
3593 term_T *term;
3594 typval_T tv;
3595
3596 for (term = first_term; term != NULL; term = term->tl_next)
3597 if (term->tl_job != NULL)
3598 {
3599 tv.v_type = VAR_JOB;
3600 tv.vval.v_job = term->tl_job;
3601 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3602 }
3603 return abort;
3604}
3605
3606/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003607 * Cache "Terminal" highlight group colors.
3608 */
3609 void
3610set_terminal_default_colors(int cterm_fg, int cterm_bg)
3611{
3612 term_default_cterm_fg = cterm_fg - 1;
3613 term_default_cterm_bg = cterm_bg - 1;
3614}
3615
3616/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003617 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003618 * Returns NULL when the buffer is not for a terminal window and logs a message
3619 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003620 */
3621 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003622term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003623{
3624 buf_T *buf;
3625
3626 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3627 ++emsg_off;
3628 buf = get_buf_tv(&argvars[0], FALSE);
3629 --emsg_off;
3630 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003631 {
3632 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003633 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003634 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003635 return buf;
3636}
3637
Bram Moolenaard96ff162018-02-18 22:13:29 +01003638 static int
3639same_color(VTermColor *a, VTermColor *b)
3640{
3641 return a->red == b->red
3642 && a->green == b->green
3643 && a->blue == b->blue
3644 && a->ansi_index == b->ansi_index;
3645}
3646
3647 static void
3648dump_term_color(FILE *fd, VTermColor *color)
3649{
3650 fprintf(fd, "%02x%02x%02x%d",
3651 (int)color->red, (int)color->green, (int)color->blue,
3652 (int)color->ansi_index);
3653}
3654
3655/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003656 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003657 *
3658 * Each screen cell in full is:
3659 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3660 * {characters} is a space for an empty cell
3661 * For a double-width character "+" is changed to "*" and the next cell is
3662 * skipped.
3663 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3664 * when "&" use the same as the previous cell.
3665 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3666 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3667 * {color-idx} is a number from 0 to 255
3668 *
3669 * Screen cell with same width, attributes and color as the previous one:
3670 * |{characters}
3671 *
3672 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3673 *
3674 * Repeating the previous screen cell:
3675 * @{count}
3676 */
3677 void
3678f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3679{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003680 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003681 term_T *term;
3682 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003683 int max_height = 0;
3684 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003685 stat_T st;
3686 FILE *fd;
3687 VTermPos pos;
3688 VTermScreen *screen;
3689 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003690 VTermState *state;
3691 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003692
3693 if (check_restricted() || check_secure())
3694 return;
3695 if (buf == NULL)
3696 return;
3697 term = buf->b_term;
3698
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003699 if (argvars[2].v_type != VAR_UNKNOWN)
3700 {
3701 dict_T *d;
3702
3703 if (argvars[2].v_type != VAR_DICT)
3704 {
3705 EMSG(_(e_dictreq));
3706 return;
3707 }
3708 d = argvars[2].vval.v_dict;
3709 if (d != NULL)
3710 {
3711 max_height = get_dict_number(d, (char_u *)"rows");
3712 max_width = get_dict_number(d, (char_u *)"columns");
3713 }
3714 }
3715
Bram Moolenaard96ff162018-02-18 22:13:29 +01003716 fname = get_tv_string_chk(&argvars[1]);
3717 if (fname == NULL)
3718 return;
3719 if (mch_stat((char *)fname, &st) >= 0)
3720 {
3721 EMSG2(_("E953: File exists: %s"), fname);
3722 return;
3723 }
3724
Bram Moolenaard96ff162018-02-18 22:13:29 +01003725 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3726 {
3727 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3728 return;
3729 }
3730
3731 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3732
3733 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003734 state = vterm_obtain_state(term->tl_vterm);
3735 vterm_state_get_cursorpos(state, &cursor_pos);
3736
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003737 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3738 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003739 {
3740 int repeat = 0;
3741
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003742 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3743 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003744 {
3745 VTermScreenCell cell;
3746 int same_attr;
3747 int same_chars = TRUE;
3748 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003749 int is_cursor_pos = (pos.col == cursor_pos.col
3750 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003751
3752 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3753 vim_memset(&cell, 0, sizeof(cell));
3754
3755 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3756 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003757 int c = cell.chars[i];
3758 int pc = prev_cell.chars[i];
3759
3760 /* For the first character NUL is the same as space. */
3761 if (i == 0)
3762 {
3763 c = (c == NUL) ? ' ' : c;
3764 pc = (pc == NUL) ? ' ' : pc;
3765 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003766 if (cell.chars[i] != prev_cell.chars[i])
3767 same_chars = FALSE;
3768 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3769 break;
3770 }
3771 same_attr = vtermAttr2hl(cell.attrs)
3772 == vtermAttr2hl(prev_cell.attrs)
3773 && same_color(&cell.fg, &prev_cell.fg)
3774 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003775 if (same_chars && cell.width == prev_cell.width && same_attr
3776 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003777 {
3778 ++repeat;
3779 }
3780 else
3781 {
3782 if (repeat > 0)
3783 {
3784 fprintf(fd, "@%d", repeat);
3785 repeat = 0;
3786 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003787 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003788
3789 if (cell.chars[0] == NUL)
3790 fputs(" ", fd);
3791 else
3792 {
3793 char_u charbuf[10];
3794 int len;
3795
3796 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3797 && cell.chars[i] != NUL; ++i)
3798 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003799 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003800 fwrite(charbuf, len, 1, fd);
3801 }
3802 }
3803
3804 /* When only the characters differ we don't write anything, the
3805 * following "|", "@" or NL will indicate using the same
3806 * attributes. */
3807 if (cell.width != prev_cell.width || !same_attr)
3808 {
3809 if (cell.width == 2)
3810 {
3811 fputs("*", fd);
3812 ++pos.col;
3813 }
3814 else
3815 fputs("+", fd);
3816
3817 if (same_attr)
3818 {
3819 fputs("&", fd);
3820 }
3821 else
3822 {
3823 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3824 if (same_color(&cell.fg, &prev_cell.fg))
3825 fputs("&", fd);
3826 else
3827 {
3828 fputs("#", fd);
3829 dump_term_color(fd, &cell.fg);
3830 }
3831 if (same_color(&cell.bg, &prev_cell.bg))
3832 fputs("&", fd);
3833 else
3834 {
3835 fputs("#", fd);
3836 dump_term_color(fd, &cell.bg);
3837 }
3838 }
3839 }
3840
3841 prev_cell = cell;
3842 }
3843 }
3844 if (repeat > 0)
3845 fprintf(fd, "@%d", repeat);
3846 fputs("\n", fd);
3847 }
3848
3849 fclose(fd);
3850}
3851
3852/*
3853 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3854 */
3855 static void
3856dump_is_corrupt(garray_T *gap)
3857{
3858 ga_concat(gap, (char_u *)"CORRUPT");
3859}
3860
3861 static void
3862append_cell(garray_T *gap, cellattr_T *cell)
3863{
3864 if (ga_grow(gap, 1) == OK)
3865 {
3866 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3867 ++gap->ga_len;
3868 }
3869}
3870
3871/*
3872 * Read the dump file from "fd" and append lines to the current buffer.
3873 * Return the cell width of the longest line.
3874 */
3875 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003876read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003877{
3878 int c;
3879 garray_T ga_text;
3880 garray_T ga_cell;
3881 char_u *prev_char = NULL;
3882 int attr = 0;
3883 cellattr_T cell;
3884 term_T *term = curbuf->b_term;
3885 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003886 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003887
3888 ga_init2(&ga_text, 1, 90);
3889 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3890 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003891 cursor_pos->row = -1;
3892 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003893
3894 c = fgetc(fd);
3895 for (;;)
3896 {
3897 if (c == EOF)
3898 break;
3899 if (c == '\n')
3900 {
3901 /* End of a line: append it to the buffer. */
3902 if (ga_text.ga_data == NULL)
3903 dump_is_corrupt(&ga_text);
3904 if (ga_grow(&term->tl_scrollback, 1) == OK)
3905 {
3906 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3907 + term->tl_scrollback.ga_len;
3908
3909 if (max_cells < ga_cell.ga_len)
3910 max_cells = ga_cell.ga_len;
3911 line->sb_cols = ga_cell.ga_len;
3912 line->sb_cells = ga_cell.ga_data;
3913 line->sb_fill_attr = term->tl_default_color;
3914 ++term->tl_scrollback.ga_len;
3915 ga_init(&ga_cell);
3916
3917 ga_append(&ga_text, NUL);
3918 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3919 ga_text.ga_len, FALSE);
3920 }
3921 else
3922 ga_clear(&ga_cell);
3923 ga_text.ga_len = 0;
3924
3925 c = fgetc(fd);
3926 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003927 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003928 {
3929 int prev_len = ga_text.ga_len;
3930
Bram Moolenaar9271d052018-02-25 21:39:46 +01003931 if (c == '>')
3932 {
3933 if (cursor_pos->row != -1)
3934 dump_is_corrupt(&ga_text); /* duplicate cursor */
3935 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3936 cursor_pos->col = ga_cell.ga_len;
3937 }
3938
Bram Moolenaard96ff162018-02-18 22:13:29 +01003939 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3940 c = fgetc(fd);
3941 if (c != EOF)
3942 ga_append(&ga_text, c);
3943 for (;;)
3944 {
3945 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003946 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003947 || c == EOF || c == '\n')
3948 break;
3949 ga_append(&ga_text, c);
3950 }
3951
3952 /* save the character for repeating it */
3953 vim_free(prev_char);
3954 if (ga_text.ga_data != NULL)
3955 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3956 ga_text.ga_len - prev_len);
3957
Bram Moolenaar9271d052018-02-25 21:39:46 +01003958 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003959 {
3960 /* use all attributes from previous cell */
3961 }
3962 else if (c == '+' || c == '*')
3963 {
3964 int is_bg;
3965
3966 cell.width = c == '+' ? 1 : 2;
3967
3968 c = fgetc(fd);
3969 if (c == '&')
3970 {
3971 /* use same attr as previous cell */
3972 c = fgetc(fd);
3973 }
3974 else if (isdigit(c))
3975 {
3976 /* get the decimal attribute */
3977 attr = 0;
3978 while (isdigit(c))
3979 {
3980 attr = attr * 10 + (c - '0');
3981 c = fgetc(fd);
3982 }
3983 hl2vtermAttr(attr, &cell);
3984 }
3985 else
3986 dump_is_corrupt(&ga_text);
3987
3988 /* is_bg == 0: fg, is_bg == 1: bg */
3989 for (is_bg = 0; is_bg <= 1; ++is_bg)
3990 {
3991 if (c == '&')
3992 {
3993 /* use same color as previous cell */
3994 c = fgetc(fd);
3995 }
3996 else if (c == '#')
3997 {
3998 int red, green, blue, index = 0;
3999
4000 c = fgetc(fd);
4001 red = hex2nr(c);
4002 c = fgetc(fd);
4003 red = (red << 4) + hex2nr(c);
4004 c = fgetc(fd);
4005 green = hex2nr(c);
4006 c = fgetc(fd);
4007 green = (green << 4) + hex2nr(c);
4008 c = fgetc(fd);
4009 blue = hex2nr(c);
4010 c = fgetc(fd);
4011 blue = (blue << 4) + hex2nr(c);
4012 c = fgetc(fd);
4013 if (!isdigit(c))
4014 dump_is_corrupt(&ga_text);
4015 while (isdigit(c))
4016 {
4017 index = index * 10 + (c - '0');
4018 c = fgetc(fd);
4019 }
4020
4021 if (is_bg)
4022 {
4023 cell.bg.red = red;
4024 cell.bg.green = green;
4025 cell.bg.blue = blue;
4026 cell.bg.ansi_index = index;
4027 }
4028 else
4029 {
4030 cell.fg.red = red;
4031 cell.fg.green = green;
4032 cell.fg.blue = blue;
4033 cell.fg.ansi_index = index;
4034 }
4035 }
4036 else
4037 dump_is_corrupt(&ga_text);
4038 }
4039 }
4040 else
4041 dump_is_corrupt(&ga_text);
4042
4043 append_cell(&ga_cell, &cell);
4044 }
4045 else if (c == '@')
4046 {
4047 if (prev_char == NULL)
4048 dump_is_corrupt(&ga_text);
4049 else
4050 {
4051 int count = 0;
4052
4053 /* repeat previous character, get the count */
4054 for (;;)
4055 {
4056 c = fgetc(fd);
4057 if (!isdigit(c))
4058 break;
4059 count = count * 10 + (c - '0');
4060 }
4061
4062 while (count-- > 0)
4063 {
4064 ga_concat(&ga_text, prev_char);
4065 append_cell(&ga_cell, &cell);
4066 }
4067 }
4068 }
4069 else
4070 {
4071 dump_is_corrupt(&ga_text);
4072 c = fgetc(fd);
4073 }
4074 }
4075
4076 if (ga_text.ga_len > 0)
4077 {
4078 /* trailing characters after last NL */
4079 dump_is_corrupt(&ga_text);
4080 ga_append(&ga_text, NUL);
4081 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4082 ga_text.ga_len, FALSE);
4083 }
4084
4085 ga_clear(&ga_text);
4086 vim_free(prev_char);
4087
4088 return max_cells;
4089}
4090
4091/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004092 * Return an allocated string with at least "text_width" "=" characters and
4093 * "fname" inserted in the middle.
4094 */
4095 static char_u *
4096get_separator(int text_width, char_u *fname)
4097{
4098 int width = MAX(text_width, curwin->w_width);
4099 char_u *textline;
4100 int fname_size;
4101 char_u *p = fname;
4102 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004103 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004104
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004105 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004106 if (textline == NULL)
4107 return NULL;
4108
4109 fname_size = vim_strsize(fname);
4110 if (fname_size < width - 8)
4111 {
4112 /* enough room, don't use the full window width */
4113 width = MAX(text_width, fname_size + 8);
4114 }
4115 else if (fname_size > width - 8)
4116 {
4117 /* full name doesn't fit, use only the tail */
4118 p = gettail(fname);
4119 fname_size = vim_strsize(p);
4120 }
4121 /* skip characters until the name fits */
4122 while (fname_size > width - 8)
4123 {
4124 p += (*mb_ptr2len)(p);
4125 fname_size = vim_strsize(p);
4126 }
4127
4128 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4129 textline[i] = '=';
4130 textline[i++] = ' ';
4131
4132 STRCPY(textline + i, p);
4133 off = STRLEN(textline);
4134 textline[off] = ' ';
4135 for (i = 1; i < (width - fname_size) / 2; ++i)
4136 textline[off + i] = '=';
4137 textline[off + i] = NUL;
4138
4139 return textline;
4140}
4141
4142/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004143 * Common for "term_dumpdiff()" and "term_dumpload()".
4144 */
4145 static void
4146term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4147{
4148 jobopt_T opt;
4149 buf_T *buf;
4150 char_u buf1[NUMBUFLEN];
4151 char_u buf2[NUMBUFLEN];
4152 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004153 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004154 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004155 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004156 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004157 char_u *textline = NULL;
4158
4159 /* First open the files. If this fails bail out. */
4160 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4161 if (do_diff)
4162 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4163 if (fname1 == NULL || (do_diff && fname2 == NULL))
4164 {
4165 EMSG(_(e_invarg));
4166 return;
4167 }
4168 fd1 = mch_fopen((char *)fname1, READBIN);
4169 if (fd1 == NULL)
4170 {
4171 EMSG2(_(e_notread), fname1);
4172 return;
4173 }
4174 if (do_diff)
4175 {
4176 fd2 = mch_fopen((char *)fname2, READBIN);
4177 if (fd2 == NULL)
4178 {
4179 fclose(fd1);
4180 EMSG2(_(e_notread), fname2);
4181 return;
4182 }
4183 }
4184
4185 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004186 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4187 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4188 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4189 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4190 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004191
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004192 if (opt.jo_term_name == NULL)
4193 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004194 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004195
Bram Moolenaarb571c632018-03-21 22:27:59 +01004196 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004197 if (fname_tofree != NULL)
4198 {
4199 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4200 opt.jo_term_name = fname_tofree;
4201 }
4202 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004203
Bram Moolenaar13568252018-03-16 20:46:58 +01004204 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004205 if (buf != NULL && buf->b_term != NULL)
4206 {
4207 int i;
4208 linenr_T bot_lnum;
4209 linenr_T lnum;
4210 term_T *term = buf->b_term;
4211 int width;
4212 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004213 VTermPos cursor_pos1;
4214 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004215
Bram Moolenaar52acb112018-03-18 19:20:22 +01004216 init_default_colors(term);
4217
Bram Moolenaard96ff162018-02-18 22:13:29 +01004218 rettv->vval.v_number = buf->b_fnum;
4219
4220 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004221 width = read_dump_file(fd1, &cursor_pos1);
4222
4223 /* position the cursor */
4224 if (cursor_pos1.row >= 0)
4225 {
4226 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4227 coladvance(cursor_pos1.col);
4228 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004229
4230 /* Delete the empty line that was in the empty buffer. */
4231 ml_delete(1, FALSE);
4232
4233 /* For term_dumpload() we are done here. */
4234 if (!do_diff)
4235 goto theend;
4236
4237 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4238
Bram Moolenaar4a696342018-04-05 18:45:26 +02004239 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004240 if (textline == NULL)
4241 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004242 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4243 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4244 vim_free(textline);
4245
4246 textline = get_separator(width, fname2);
4247 if (textline == NULL)
4248 goto theend;
4249 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4250 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004251 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004252
4253 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004254 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004255 if (width2 > width)
4256 {
4257 vim_free(textline);
4258 textline = alloc(width2 + 1);
4259 if (textline == NULL)
4260 goto theend;
4261 width = width2;
4262 textline[width] = NUL;
4263 }
4264 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4265
4266 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4267 {
4268 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4269 {
4270 /* bottom part has fewer rows, fill with "-" */
4271 for (i = 0; i < width; ++i)
4272 textline[i] = '-';
4273 }
4274 else
4275 {
4276 char_u *line1;
4277 char_u *line2;
4278 char_u *p1;
4279 char_u *p2;
4280 int col;
4281 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4282 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4283 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4284 ->sb_cells;
4285
4286 /* Make a copy, getting the second line will invalidate it. */
4287 line1 = vim_strsave(ml_get(lnum));
4288 if (line1 == NULL)
4289 break;
4290 p1 = line1;
4291
4292 line2 = ml_get(lnum + bot_lnum);
4293 p2 = line2;
4294 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4295 {
4296 int len1 = utfc_ptr2len(p1);
4297 int len2 = utfc_ptr2len(p2);
4298
4299 textline[col] = ' ';
4300 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004301 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004302 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004303 else if (lnum == cursor_pos1.row + 1
4304 && col == cursor_pos1.col
4305 && (cursor_pos1.row != cursor_pos2.row
4306 || cursor_pos1.col != cursor_pos2.col))
4307 /* cursor in first but not in second */
4308 textline[col] = '>';
4309 else if (lnum == cursor_pos2.row + 1
4310 && col == cursor_pos2.col
4311 && (cursor_pos1.row != cursor_pos2.row
4312 || cursor_pos1.col != cursor_pos2.col))
4313 /* cursor in second but not in first */
4314 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004315 else if (cellattr1 != NULL && cellattr2 != NULL)
4316 {
4317 if ((cellattr1 + col)->width
4318 != (cellattr2 + col)->width)
4319 textline[col] = 'w';
4320 else if (!same_color(&(cellattr1 + col)->fg,
4321 &(cellattr2 + col)->fg))
4322 textline[col] = 'f';
4323 else if (!same_color(&(cellattr1 + col)->bg,
4324 &(cellattr2 + col)->bg))
4325 textline[col] = 'b';
4326 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4327 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4328 textline[col] = 'a';
4329 }
4330 p1 += len1;
4331 p2 += len2;
4332 /* TODO: handle different width */
4333 }
4334 vim_free(line1);
4335
4336 while (col < width)
4337 {
4338 if (*p1 == NUL && *p2 == NUL)
4339 textline[col] = '?';
4340 else if (*p1 == NUL)
4341 {
4342 textline[col] = '+';
4343 p2 += utfc_ptr2len(p2);
4344 }
4345 else
4346 {
4347 textline[col] = '-';
4348 p1 += utfc_ptr2len(p1);
4349 }
4350 ++col;
4351 }
4352 }
4353 if (add_empty_scrollback(term, &term->tl_default_color,
4354 term->tl_top_diff_rows) == OK)
4355 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4356 ++bot_lnum;
4357 }
4358
4359 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4360 {
4361 /* bottom part has more rows, fill with "+" */
4362 for (i = 0; i < width; ++i)
4363 textline[i] = '+';
4364 if (add_empty_scrollback(term, &term->tl_default_color,
4365 term->tl_top_diff_rows) == OK)
4366 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4367 ++lnum;
4368 ++bot_lnum;
4369 }
4370
4371 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004372
4373 /* looks better without wrapping */
4374 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004375 }
4376
4377theend:
4378 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004379 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004380 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004381 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004382 fclose(fd2);
4383}
4384
4385/*
4386 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4387 * bottom files.
4388 * Return FAIL when this is not possible.
4389 */
4390 int
4391term_swap_diff()
4392{
4393 term_T *term = curbuf->b_term;
4394 linenr_T line_count;
4395 linenr_T top_rows;
4396 linenr_T bot_rows;
4397 linenr_T bot_start;
4398 linenr_T lnum;
4399 char_u *p;
4400 sb_line_T *sb_line;
4401
4402 if (term == NULL
4403 || !term_is_finished(curbuf)
4404 || term->tl_top_diff_rows == 0
4405 || term->tl_scrollback.ga_len == 0)
4406 return FAIL;
4407
4408 line_count = curbuf->b_ml.ml_line_count;
4409 top_rows = term->tl_top_diff_rows;
4410 bot_rows = term->tl_bot_diff_rows;
4411 bot_start = line_count - bot_rows;
4412 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4413
4414 /* move lines from top to above the bottom part */
4415 for (lnum = 1; lnum <= top_rows; ++lnum)
4416 {
4417 p = vim_strsave(ml_get(1));
4418 if (p == NULL)
4419 return OK;
4420 ml_append(bot_start, p, 0, FALSE);
4421 ml_delete(1, FALSE);
4422 vim_free(p);
4423 }
4424
4425 /* move lines from bottom to the top */
4426 for (lnum = 1; lnum <= bot_rows; ++lnum)
4427 {
4428 p = vim_strsave(ml_get(bot_start + lnum));
4429 if (p == NULL)
4430 return OK;
4431 ml_delete(bot_start + lnum, FALSE);
4432 ml_append(lnum - 1, p, 0, FALSE);
4433 vim_free(p);
4434 }
4435
4436 if (top_rows == bot_rows)
4437 {
4438 /* rows counts are equal, can swap cell properties */
4439 for (lnum = 0; lnum < top_rows; ++lnum)
4440 {
4441 sb_line_T temp;
4442
4443 temp = *(sb_line + lnum);
4444 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4445 *(sb_line + bot_start + lnum) = temp;
4446 }
4447 }
4448 else
4449 {
4450 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4451 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4452
4453 /* need to copy cell properties into temp memory */
4454 if (temp != NULL)
4455 {
4456 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4457 mch_memmove(term->tl_scrollback.ga_data,
4458 temp + bot_start,
4459 sizeof(sb_line_T) * bot_rows);
4460 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4461 temp + top_rows,
4462 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4463 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4464 + line_count - top_rows,
4465 temp,
4466 sizeof(sb_line_T) * top_rows);
4467 vim_free(temp);
4468 }
4469 }
4470
4471 term->tl_top_diff_rows = bot_rows;
4472 term->tl_bot_diff_rows = top_rows;
4473
4474 update_screen(NOT_VALID);
4475 return OK;
4476}
4477
4478/*
4479 * "term_dumpdiff(filename, filename, options)" function
4480 */
4481 void
4482f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4483{
4484 term_load_dump(argvars, rettv, TRUE);
4485}
4486
4487/*
4488 * "term_dumpload(filename, options)" function
4489 */
4490 void
4491f_term_dumpload(typval_T *argvars, typval_T *rettv)
4492{
4493 term_load_dump(argvars, rettv, FALSE);
4494}
4495
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004496/*
4497 * "term_getaltscreen(buf)" function
4498 */
4499 void
4500f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4501{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004502 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004503
4504 if (buf == NULL)
4505 return;
4506 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4507}
4508
4509/*
4510 * "term_getattr(attr, name)" function
4511 */
4512 void
4513f_term_getattr(typval_T *argvars, typval_T *rettv)
4514{
4515 int attr;
4516 size_t i;
4517 char_u *name;
4518
4519 static struct {
4520 char *name;
4521 int attr;
4522 } attrs[] = {
4523 {"bold", HL_BOLD},
4524 {"italic", HL_ITALIC},
4525 {"underline", HL_UNDERLINE},
4526 {"strike", HL_STRIKETHROUGH},
4527 {"reverse", HL_INVERSE},
4528 };
4529
4530 attr = get_tv_number(&argvars[0]);
4531 name = get_tv_string_chk(&argvars[1]);
4532 if (name == NULL)
4533 return;
4534
4535 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4536 if (STRCMP(name, attrs[i].name) == 0)
4537 {
4538 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4539 break;
4540 }
4541}
4542
4543/*
4544 * "term_getcursor(buf)" function
4545 */
4546 void
4547f_term_getcursor(typval_T *argvars, typval_T *rettv)
4548{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004549 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004550 term_T *term;
4551 list_T *l;
4552 dict_T *d;
4553
4554 if (rettv_list_alloc(rettv) == FAIL)
4555 return;
4556 if (buf == NULL)
4557 return;
4558 term = buf->b_term;
4559
4560 l = rettv->vval.v_list;
4561 list_append_number(l, term->tl_cursor_pos.row + 1);
4562 list_append_number(l, term->tl_cursor_pos.col + 1);
4563
4564 d = dict_alloc();
4565 if (d != NULL)
4566 {
4567 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4568 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4569 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4570 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4571 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4572 ? (char_u *)"" : term->tl_cursor_color);
4573 list_append_dict(l, d);
4574 }
4575}
4576
4577/*
4578 * "term_getjob(buf)" function
4579 */
4580 void
4581f_term_getjob(typval_T *argvars, typval_T *rettv)
4582{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004583 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004584
4585 rettv->v_type = VAR_JOB;
4586 rettv->vval.v_job = NULL;
4587 if (buf == NULL)
4588 return;
4589
4590 rettv->vval.v_job = buf->b_term->tl_job;
4591 if (rettv->vval.v_job != NULL)
4592 ++rettv->vval.v_job->jv_refcount;
4593}
4594
4595 static int
4596get_row_number(typval_T *tv, term_T *term)
4597{
4598 if (tv->v_type == VAR_STRING
4599 && tv->vval.v_string != NULL
4600 && STRCMP(tv->vval.v_string, ".") == 0)
4601 return term->tl_cursor_pos.row;
4602 return (int)get_tv_number(tv) - 1;
4603}
4604
4605/*
4606 * "term_getline(buf, row)" function
4607 */
4608 void
4609f_term_getline(typval_T *argvars, typval_T *rettv)
4610{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004611 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004612 term_T *term;
4613 int row;
4614
4615 rettv->v_type = VAR_STRING;
4616 if (buf == NULL)
4617 return;
4618 term = buf->b_term;
4619 row = get_row_number(&argvars[1], term);
4620
4621 if (term->tl_vterm == NULL)
4622 {
4623 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4624
4625 /* vterm is finished, get the text from the buffer */
4626 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4627 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4628 }
4629 else
4630 {
4631 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4632 VTermRect rect;
4633 int len;
4634 char_u *p;
4635
4636 if (row < 0 || row >= term->tl_rows)
4637 return;
4638 len = term->tl_cols * MB_MAXBYTES + 1;
4639 p = alloc(len);
4640 if (p == NULL)
4641 return;
4642 rettv->vval.v_string = p;
4643
4644 rect.start_col = 0;
4645 rect.end_col = term->tl_cols;
4646 rect.start_row = row;
4647 rect.end_row = row + 1;
4648 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4649 }
4650}
4651
4652/*
4653 * "term_getscrolled(buf)" function
4654 */
4655 void
4656f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4657{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004658 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004659
4660 if (buf == NULL)
4661 return;
4662 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4663}
4664
4665/*
4666 * "term_getsize(buf)" function
4667 */
4668 void
4669f_term_getsize(typval_T *argvars, typval_T *rettv)
4670{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004671 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004672 list_T *l;
4673
4674 if (rettv_list_alloc(rettv) == FAIL)
4675 return;
4676 if (buf == NULL)
4677 return;
4678
4679 l = rettv->vval.v_list;
4680 list_append_number(l, buf->b_term->tl_rows);
4681 list_append_number(l, buf->b_term->tl_cols);
4682}
4683
4684/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004685 * "term_setsize(buf, rows, cols)" function
4686 */
4687 void
4688f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4689{
4690 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4691 term_T *term;
4692 varnumber_T rows, cols;
4693
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004694 if (buf == NULL)
4695 {
4696 EMSG(_("E955: Not a terminal buffer"));
4697 return;
4698 }
4699 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004700 return;
4701 term = buf->b_term;
4702 rows = get_tv_number(&argvars[1]);
4703 rows = rows <= 0 ? term->tl_rows : rows;
4704 cols = get_tv_number(&argvars[2]);
4705 cols = cols <= 0 ? term->tl_cols : cols;
4706 vterm_set_size(term->tl_vterm, rows, cols);
4707 /* handle_resize() will resize the windows */
4708
4709 /* Get and remember the size we ended up with. Update the pty. */
4710 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4711 term_report_winsize(term, term->tl_rows, term->tl_cols);
4712}
4713
4714/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004715 * "term_getstatus(buf)" function
4716 */
4717 void
4718f_term_getstatus(typval_T *argvars, typval_T *rettv)
4719{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004720 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004721 term_T *term;
4722 char_u val[100];
4723
4724 rettv->v_type = VAR_STRING;
4725 if (buf == NULL)
4726 return;
4727 term = buf->b_term;
4728
4729 if (term_job_running(term))
4730 STRCPY(val, "running");
4731 else
4732 STRCPY(val, "finished");
4733 if (term->tl_normal_mode)
4734 STRCAT(val, ",normal");
4735 rettv->vval.v_string = vim_strsave(val);
4736}
4737
4738/*
4739 * "term_gettitle(buf)" function
4740 */
4741 void
4742f_term_gettitle(typval_T *argvars, typval_T *rettv)
4743{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004744 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004745
4746 rettv->v_type = VAR_STRING;
4747 if (buf == NULL)
4748 return;
4749
4750 if (buf->b_term->tl_title != NULL)
4751 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4752}
4753
4754/*
4755 * "term_gettty(buf)" function
4756 */
4757 void
4758f_term_gettty(typval_T *argvars, typval_T *rettv)
4759{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004760 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004761 char_u *p;
4762 int num = 0;
4763
4764 rettv->v_type = VAR_STRING;
4765 if (buf == NULL)
4766 return;
4767 if (argvars[1].v_type != VAR_UNKNOWN)
4768 num = get_tv_number(&argvars[1]);
4769
4770 switch (num)
4771 {
4772 case 0:
4773 if (buf->b_term->tl_job != NULL)
4774 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004775 break;
4776 case 1:
4777 if (buf->b_term->tl_job != NULL)
4778 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004779 break;
4780 default:
4781 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4782 return;
4783 }
4784 if (p != NULL)
4785 rettv->vval.v_string = vim_strsave(p);
4786}
4787
4788/*
4789 * "term_list()" function
4790 */
4791 void
4792f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4793{
4794 term_T *tp;
4795 list_T *l;
4796
4797 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4798 return;
4799
4800 l = rettv->vval.v_list;
4801 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4802 if (tp != NULL && tp->tl_buffer != NULL)
4803 if (list_append_number(l,
4804 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4805 return;
4806}
4807
4808/*
4809 * "term_scrape(buf, row)" function
4810 */
4811 void
4812f_term_scrape(typval_T *argvars, typval_T *rettv)
4813{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004814 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004815 VTermScreen *screen = NULL;
4816 VTermPos pos;
4817 list_T *l;
4818 term_T *term;
4819 char_u *p;
4820 sb_line_T *line;
4821
4822 if (rettv_list_alloc(rettv) == FAIL)
4823 return;
4824 if (buf == NULL)
4825 return;
4826 term = buf->b_term;
4827
4828 l = rettv->vval.v_list;
4829 pos.row = get_row_number(&argvars[1], term);
4830
4831 if (term->tl_vterm != NULL)
4832 {
4833 screen = vterm_obtain_screen(term->tl_vterm);
4834 p = NULL;
4835 line = NULL;
4836 }
4837 else
4838 {
4839 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4840
4841 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4842 return;
4843 p = ml_get_buf(buf, lnum + 1, FALSE);
4844 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4845 }
4846
4847 for (pos.col = 0; pos.col < term->tl_cols; )
4848 {
4849 dict_T *dcell;
4850 int width;
4851 VTermScreenCellAttrs attrs;
4852 VTermColor fg, bg;
4853 char_u rgb[8];
4854 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4855 int off = 0;
4856 int i;
4857
4858 if (screen == NULL)
4859 {
4860 cellattr_T *cellattr;
4861 int len;
4862
4863 /* vterm has finished, get the cell from scrollback */
4864 if (pos.col >= line->sb_cols)
4865 break;
4866 cellattr = line->sb_cells + pos.col;
4867 width = cellattr->width;
4868 attrs = cellattr->attrs;
4869 fg = cellattr->fg;
4870 bg = cellattr->bg;
4871 len = MB_PTR2LEN(p);
4872 mch_memmove(mbs, p, len);
4873 mbs[len] = NUL;
4874 p += len;
4875 }
4876 else
4877 {
4878 VTermScreenCell cell;
4879 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4880 break;
4881 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4882 {
4883 if (cell.chars[i] == 0)
4884 break;
4885 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4886 }
4887 mbs[off] = NUL;
4888 width = cell.width;
4889 attrs = cell.attrs;
4890 fg = cell.fg;
4891 bg = cell.bg;
4892 }
4893 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004894 if (dcell == NULL)
4895 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004896 list_append_dict(l, dcell);
4897
4898 dict_add_nr_str(dcell, "chars", 0, mbs);
4899
4900 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4901 fg.red, fg.green, fg.blue);
4902 dict_add_nr_str(dcell, "fg", 0, rgb);
4903 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4904 bg.red, bg.green, bg.blue);
4905 dict_add_nr_str(dcell, "bg", 0, rgb);
4906
4907 dict_add_nr_str(dcell, "attr",
4908 cell2attr(attrs, fg, bg), NULL);
4909 dict_add_nr_str(dcell, "width", width, NULL);
4910
4911 ++pos.col;
4912 if (width == 2)
4913 ++pos.col;
4914 }
4915}
4916
4917/*
4918 * "term_sendkeys(buf, keys)" function
4919 */
4920 void
4921f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4922{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004923 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004924 char_u *msg;
4925 term_T *term;
4926
4927 rettv->v_type = VAR_UNKNOWN;
4928 if (buf == NULL)
4929 return;
4930
4931 msg = get_tv_string_chk(&argvars[1]);
4932 if (msg == NULL)
4933 return;
4934 term = buf->b_term;
4935 if (term->tl_vterm == NULL)
4936 return;
4937
4938 while (*msg != NUL)
4939 {
4940 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004941 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004942 }
4943}
4944
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004945#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
4946/*
4947 * "term_getansicolors(buf)" function
4948 */
4949 void
4950f_term_getansicolors(typval_T *argvars, typval_T *rettv)
4951{
4952 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
4953 term_T *term;
4954 VTermState *state;
4955 VTermColor color;
4956 char_u hexbuf[10];
4957 int index;
4958 list_T *list;
4959
4960 if (rettv_list_alloc(rettv) == FAIL)
4961 return;
4962
4963 if (buf == NULL)
4964 return;
4965 term = buf->b_term;
4966 if (term->tl_vterm == NULL)
4967 return;
4968
4969 list = rettv->vval.v_list;
4970 state = vterm_obtain_state(term->tl_vterm);
4971 for (index = 0; index < 16; index++)
4972 {
4973 vterm_state_get_palette_color(state, index, &color);
4974 sprintf((char *)hexbuf, "#%02x%02x%02x",
4975 color.red, color.green, color.blue);
4976 if (list_append_string(list, hexbuf, 7) == FAIL)
4977 return;
4978 }
4979}
4980
4981/*
4982 * "term_setansicolors(buf, list)" function
4983 */
4984 void
4985f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
4986{
4987 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
4988 term_T *term;
4989
4990 if (buf == NULL)
4991 return;
4992 term = buf->b_term;
4993 if (term->tl_vterm == NULL)
4994 return;
4995
4996 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
4997 {
4998 EMSG(_(e_listreq));
4999 return;
5000 }
5001
5002 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
5003 EMSG(_(e_invarg));
5004}
5005#endif
5006
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005007/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005008 * "term_setrestore(buf, command)" function
5009 */
5010 void
5011f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5012{
5013#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005014 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005015 term_T *term;
5016 char_u *cmd;
5017
5018 if (buf == NULL)
5019 return;
5020 term = buf->b_term;
5021 vim_free(term->tl_command);
5022 cmd = get_tv_string_chk(&argvars[1]);
5023 if (cmd != NULL)
5024 term->tl_command = vim_strsave(cmd);
5025 else
5026 term->tl_command = NULL;
5027#endif
5028}
5029
5030/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005031 * "term_setkill(buf, how)" function
5032 */
5033 void
5034f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5035{
5036 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5037 term_T *term;
5038 char_u *how;
5039
5040 if (buf == NULL)
5041 return;
5042 term = buf->b_term;
5043 vim_free(term->tl_kill);
5044 how = get_tv_string_chk(&argvars[1]);
5045 if (how != NULL)
5046 term->tl_kill = vim_strsave(how);
5047 else
5048 term->tl_kill = NULL;
5049}
5050
5051/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005052 * "term_start(command, options)" function
5053 */
5054 void
5055f_term_start(typval_T *argvars, typval_T *rettv)
5056{
5057 jobopt_T opt;
5058 buf_T *buf;
5059
5060 init_job_options(&opt);
5061 if (argvars[1].v_type != VAR_UNKNOWN
5062 && get_job_options(&argvars[1], &opt,
5063 JO_TIMEOUT_ALL + JO_STOPONEXIT
5064 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5065 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5066 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5067 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005068 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005069 + JO2_NORESTORE + JO2_TERM_KILL
5070 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005071 return;
5072
Bram Moolenaar13568252018-03-16 20:46:58 +01005073 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005074
5075 if (buf != NULL && buf->b_term != NULL)
5076 rettv->vval.v_number = buf->b_fnum;
5077}
5078
5079/*
5080 * "term_wait" function
5081 */
5082 void
5083f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5084{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005085 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005086
5087 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005088 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005089 if (buf->b_term->tl_job == NULL)
5090 {
5091 ch_log(NULL, "term_wait(): no job to wait for");
5092 return;
5093 }
5094 if (buf->b_term->tl_job->jv_channel == NULL)
5095 /* channel is closed, nothing to do */
5096 return;
5097
5098 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005099 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005100 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5101 {
5102 /* The job is dead, keep reading channel I/O until the channel is
5103 * closed. buf->b_term may become NULL if the terminal was closed while
5104 * waiting. */
5105 ch_log(NULL, "term_wait(): waiting for channel to close");
5106 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5107 {
5108 mch_check_messages();
5109 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005110 if (!buf_valid(buf))
5111 /* If the terminal is closed when the channel is closed the
5112 * buffer disappears. */
5113 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005114 ui_delay(10L, FALSE);
5115 }
5116 mch_check_messages();
5117 parse_queued_messages();
5118 }
5119 else
5120 {
5121 long wait = 10L;
5122
5123 mch_check_messages();
5124 parse_queued_messages();
5125
5126 /* Wait for some time for any channel I/O. */
5127 if (argvars[1].v_type != VAR_UNKNOWN)
5128 wait = get_tv_number(&argvars[1]);
5129 ui_delay(wait, TRUE);
5130 mch_check_messages();
5131
5132 /* Flushing messages on channels is hopefully sufficient.
5133 * TODO: is there a better way? */
5134 parse_queued_messages();
5135 }
5136}
5137
5138/*
5139 * Called when a channel has sent all the lines to a terminal.
5140 * Send a CTRL-D to mark the end of the text.
5141 */
5142 void
5143term_send_eof(channel_T *ch)
5144{
5145 term_T *term;
5146
5147 for (term = first_term; term != NULL; term = term->tl_next)
5148 if (term->tl_job == ch->ch_job)
5149 {
5150 if (term->tl_eof_chars != NULL)
5151 {
5152 channel_send(ch, PART_IN, term->tl_eof_chars,
5153 (int)STRLEN(term->tl_eof_chars), NULL);
5154 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5155 }
5156# ifdef WIN3264
5157 else
5158 /* Default: CTRL-D */
5159 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5160# endif
5161 }
5162}
5163
5164# if defined(WIN3264) || defined(PROTO)
5165
5166/**************************************
5167 * 2. MS-Windows implementation.
5168 */
5169
5170# ifndef PROTO
5171
5172#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5173#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005174#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005175
5176void* (*winpty_config_new)(UINT64, void*);
5177void* (*winpty_open)(void*, void*);
5178void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5179BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5180void (*winpty_config_set_mouse_mode)(void*, int);
5181void (*winpty_config_set_initial_size)(void*, int, int);
5182LPCWSTR (*winpty_conin_name)(void*);
5183LPCWSTR (*winpty_conout_name)(void*);
5184LPCWSTR (*winpty_conerr_name)(void*);
5185void (*winpty_free)(void*);
5186void (*winpty_config_free)(void*);
5187void (*winpty_spawn_config_free)(void*);
5188void (*winpty_error_free)(void*);
5189LPCWSTR (*winpty_error_msg)(void*);
5190BOOL (*winpty_set_size)(void*, int, int, void*);
5191HANDLE (*winpty_agent_process)(void*);
5192
5193#define WINPTY_DLL "winpty.dll"
5194
5195static HINSTANCE hWinPtyDLL = NULL;
5196# endif
5197
5198 static int
5199dyn_winpty_init(int verbose)
5200{
5201 int i;
5202 static struct
5203 {
5204 char *name;
5205 FARPROC *ptr;
5206 } winpty_entry[] =
5207 {
5208 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5209 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5210 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5211 {"winpty_config_set_mouse_mode",
5212 (FARPROC*)&winpty_config_set_mouse_mode},
5213 {"winpty_config_set_initial_size",
5214 (FARPROC*)&winpty_config_set_initial_size},
5215 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5216 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5217 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5218 {"winpty_free", (FARPROC*)&winpty_free},
5219 {"winpty_open", (FARPROC*)&winpty_open},
5220 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5221 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5222 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5223 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5224 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5225 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5226 {NULL, NULL}
5227 };
5228
5229 /* No need to initialize twice. */
5230 if (hWinPtyDLL)
5231 return OK;
5232 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5233 * winpty.dll. */
5234 if (*p_winptydll != NUL)
5235 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5236 if (!hWinPtyDLL)
5237 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5238 if (!hWinPtyDLL)
5239 {
5240 if (verbose)
5241 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5242 : (char_u *)WINPTY_DLL);
5243 return FAIL;
5244 }
5245 for (i = 0; winpty_entry[i].name != NULL
5246 && winpty_entry[i].ptr != NULL; ++i)
5247 {
5248 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5249 winpty_entry[i].name)) == NULL)
5250 {
5251 if (verbose)
5252 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5253 return FAIL;
5254 }
5255 }
5256
5257 return OK;
5258}
5259
5260/*
5261 * Create a new terminal of "rows" by "cols" cells.
5262 * Store a reference in "term".
5263 * Return OK or FAIL.
5264 */
5265 static int
5266term_and_job_init(
5267 term_T *term,
5268 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005269 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005270 jobopt_T *opt,
5271 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005272{
5273 WCHAR *cmd_wchar = NULL;
5274 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005275 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005276 channel_T *channel = NULL;
5277 job_T *job = NULL;
5278 DWORD error;
5279 HANDLE jo = NULL;
5280 HANDLE child_process_handle;
5281 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005282 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005283 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005284 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005285 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005286
5287 if (dyn_winpty_init(TRUE) == FAIL)
5288 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005289 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5290 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005291
5292 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005293 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005294 cmd = argvar->vval.v_string;
5295 }
5296 else if (argvar->v_type == VAR_LIST)
5297 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005298 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005299 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005300 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005301 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005302 if (cmd == NULL || *cmd == NUL)
5303 {
5304 EMSG(_(e_invarg));
5305 goto failed;
5306 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005307
5308 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005309 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005310 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005311 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005312 if (opt->jo_cwd != NULL)
5313 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005314
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005315 win32_build_env(opt->jo_env, &ga_env, TRUE);
5316 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005317
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005318 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5319 if (term->tl_winpty_config == NULL)
5320 goto failed;
5321
5322 winpty_config_set_mouse_mode(term->tl_winpty_config,
5323 WINPTY_MOUSE_MODE_FORCE);
5324 winpty_config_set_initial_size(term->tl_winpty_config,
5325 term->tl_cols, term->tl_rows);
5326 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5327 if (term->tl_winpty == NULL)
5328 goto failed;
5329
5330 spawn_config = winpty_spawn_config_new(
5331 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5332 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5333 NULL,
5334 cmd_wchar,
5335 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005336 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005337 &winpty_err);
5338 if (spawn_config == NULL)
5339 goto failed;
5340
5341 channel = add_channel();
5342 if (channel == NULL)
5343 goto failed;
5344
5345 job = job_alloc();
5346 if (job == NULL)
5347 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005348 if (argvar->v_type == VAR_STRING)
5349 {
5350 int argc;
5351
5352 build_argv_from_string(cmd, &job->jv_argv, &argc);
5353 }
5354 else
5355 {
5356 int argc;
5357
5358 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5359 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005360
5361 if (opt->jo_set & JO_IN_BUF)
5362 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5363
5364 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5365 &child_thread_handle, &error, &winpty_err))
5366 goto failed;
5367
5368 channel_set_pipes(channel,
5369 (sock_T)CreateFileW(
5370 winpty_conin_name(term->tl_winpty),
5371 GENERIC_WRITE, 0, NULL,
5372 OPEN_EXISTING, 0, NULL),
5373 (sock_T)CreateFileW(
5374 winpty_conout_name(term->tl_winpty),
5375 GENERIC_READ, 0, NULL,
5376 OPEN_EXISTING, 0, NULL),
5377 (sock_T)CreateFileW(
5378 winpty_conerr_name(term->tl_winpty),
5379 GENERIC_READ, 0, NULL,
5380 OPEN_EXISTING, 0, NULL));
5381
5382 /* Write lines with CR instead of NL. */
5383 channel->ch_write_text_mode = TRUE;
5384
5385 jo = CreateJobObject(NULL, NULL);
5386 if (jo == NULL)
5387 goto failed;
5388
5389 if (!AssignProcessToJobObject(jo, child_process_handle))
5390 {
5391 /* Failed, switch the way to terminate process with TerminateProcess. */
5392 CloseHandle(jo);
5393 jo = NULL;
5394 }
5395
5396 winpty_spawn_config_free(spawn_config);
5397 vim_free(cmd_wchar);
5398 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005399 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005400
5401 create_vterm(term, term->tl_rows, term->tl_cols);
5402
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005403#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5404 if (opt->jo_set2 & JO2_ANSI_COLORS)
5405 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5406 else
5407 init_vterm_ansi_colors(term->tl_vterm);
5408#endif
5409
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005410 channel_set_job(channel, job, opt);
5411 job_set_options(job, opt);
5412
5413 job->jv_channel = channel;
5414 job->jv_proc_info.hProcess = child_process_handle;
5415 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5416 job->jv_job_object = jo;
5417 job->jv_status = JOB_STARTED;
5418 job->jv_tty_in = utf16_to_enc(
5419 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5420 job->jv_tty_out = utf16_to_enc(
5421 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5422 ++job->jv_refcount;
5423 term->tl_job = job;
5424
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005425 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5426 * open the file here and handle it in. opt->jo_io was changed in
5427 * setup_job_options(), use the original flags here. */
5428 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5429 {
5430 char_u *fname = opt->jo_io_name[PART_OUT];
5431
5432 ch_log(channel, "Opening output file %s", fname);
5433 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5434 if (term->tl_out_fd == NULL)
5435 EMSG2(_(e_notopen), fname);
5436 }
5437
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005438 return OK;
5439
5440failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005441 ga_clear(&ga_cmd);
5442 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005443 vim_free(cmd_wchar);
5444 vim_free(cwd_wchar);
5445 if (spawn_config != NULL)
5446 winpty_spawn_config_free(spawn_config);
5447 if (channel != NULL)
5448 channel_clear(channel);
5449 if (job != NULL)
5450 {
5451 job->jv_channel = NULL;
5452 job_cleanup(job);
5453 }
5454 term->tl_job = NULL;
5455 if (jo != NULL)
5456 CloseHandle(jo);
5457 if (term->tl_winpty != NULL)
5458 winpty_free(term->tl_winpty);
5459 term->tl_winpty = NULL;
5460 if (term->tl_winpty_config != NULL)
5461 winpty_config_free(term->tl_winpty_config);
5462 term->tl_winpty_config = NULL;
5463 if (winpty_err != NULL)
5464 {
5465 char_u *msg = utf16_to_enc(
5466 (short_u *)winpty_error_msg(winpty_err), NULL);
5467
5468 EMSG(msg);
5469 winpty_error_free(winpty_err);
5470 }
5471 return FAIL;
5472}
5473
5474 static int
5475create_pty_only(term_T *term, jobopt_T *options)
5476{
5477 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5478 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5479 char in_name[80], out_name[80];
5480 channel_T *channel = NULL;
5481
5482 create_vterm(term, term->tl_rows, term->tl_cols);
5483
5484 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5485 GetCurrentProcessId(),
5486 curbuf->b_fnum);
5487 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5488 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5489 PIPE_UNLIMITED_INSTANCES,
5490 0, 0, NMPWAIT_NOWAIT, NULL);
5491 if (hPipeIn == INVALID_HANDLE_VALUE)
5492 goto failed;
5493
5494 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5495 GetCurrentProcessId(),
5496 curbuf->b_fnum);
5497 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5498 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5499 PIPE_UNLIMITED_INSTANCES,
5500 0, 0, 0, NULL);
5501 if (hPipeOut == INVALID_HANDLE_VALUE)
5502 goto failed;
5503
5504 ConnectNamedPipe(hPipeIn, NULL);
5505 ConnectNamedPipe(hPipeOut, NULL);
5506
5507 term->tl_job = job_alloc();
5508 if (term->tl_job == NULL)
5509 goto failed;
5510 ++term->tl_job->jv_refcount;
5511
5512 /* behave like the job is already finished */
5513 term->tl_job->jv_status = JOB_FINISHED;
5514
5515 channel = add_channel();
5516 if (channel == NULL)
5517 goto failed;
5518 term->tl_job->jv_channel = channel;
5519 channel->ch_keep_open = TRUE;
5520 channel->ch_named_pipe = TRUE;
5521
5522 channel_set_pipes(channel,
5523 (sock_T)hPipeIn,
5524 (sock_T)hPipeOut,
5525 (sock_T)hPipeOut);
5526 channel_set_job(channel, term->tl_job, options);
5527 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5528 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5529
5530 return OK;
5531
5532failed:
5533 if (hPipeIn != NULL)
5534 CloseHandle(hPipeIn);
5535 if (hPipeOut != NULL)
5536 CloseHandle(hPipeOut);
5537 return FAIL;
5538}
5539
5540/*
5541 * Free the terminal emulator part of "term".
5542 */
5543 static void
5544term_free_vterm(term_T *term)
5545{
5546 if (term->tl_winpty != NULL)
5547 winpty_free(term->tl_winpty);
5548 term->tl_winpty = NULL;
5549 if (term->tl_winpty_config != NULL)
5550 winpty_config_free(term->tl_winpty_config);
5551 term->tl_winpty_config = NULL;
5552 if (term->tl_vterm != NULL)
5553 vterm_free(term->tl_vterm);
5554 term->tl_vterm = NULL;
5555}
5556
5557/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005558 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005559 */
5560 static void
5561term_report_winsize(term_T *term, int rows, int cols)
5562{
5563 if (term->tl_winpty)
5564 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5565}
5566
5567 int
5568terminal_enabled(void)
5569{
5570 return dyn_winpty_init(FALSE) == OK;
5571}
5572
5573# else
5574
5575/**************************************
5576 * 3. Unix-like implementation.
5577 */
5578
5579/*
5580 * Create a new terminal of "rows" by "cols" cells.
5581 * Start job for "cmd".
5582 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005583 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005584 * Return OK or FAIL.
5585 */
5586 static int
5587term_and_job_init(
5588 term_T *term,
5589 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005590 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005591 jobopt_T *opt,
5592 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005593{
5594 create_vterm(term, term->tl_rows, term->tl_cols);
5595
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005596#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5597 if (opt->jo_set2 & JO2_ANSI_COLORS)
5598 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5599 else
5600 init_vterm_ansi_colors(term->tl_vterm);
5601#endif
5602
Bram Moolenaar13568252018-03-16 20:46:58 +01005603 /* This may change a string in "argvar". */
5604 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005605 if (term->tl_job != NULL)
5606 ++term->tl_job->jv_refcount;
5607
5608 return term->tl_job != NULL
5609 && term->tl_job->jv_channel != NULL
5610 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5611}
5612
5613 static int
5614create_pty_only(term_T *term, jobopt_T *opt)
5615{
5616 create_vterm(term, term->tl_rows, term->tl_cols);
5617
5618 term->tl_job = job_alloc();
5619 if (term->tl_job == NULL)
5620 return FAIL;
5621 ++term->tl_job->jv_refcount;
5622
5623 /* behave like the job is already finished */
5624 term->tl_job->jv_status = JOB_FINISHED;
5625
5626 return mch_create_pty_channel(term->tl_job, opt);
5627}
5628
5629/*
5630 * Free the terminal emulator part of "term".
5631 */
5632 static void
5633term_free_vterm(term_T *term)
5634{
5635 if (term->tl_vterm != NULL)
5636 vterm_free(term->tl_vterm);
5637 term->tl_vterm = NULL;
5638}
5639
5640/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005641 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005642 */
5643 static void
5644term_report_winsize(term_T *term, int rows, int cols)
5645{
5646 /* Use an ioctl() to report the new window size to the job. */
5647 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5648 {
5649 int fd = -1;
5650 int part;
5651
5652 for (part = PART_OUT; part < PART_COUNT; ++part)
5653 {
5654 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5655 if (isatty(fd))
5656 break;
5657 }
5658 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5659 mch_signal_job(term->tl_job, (char_u *)"winch");
5660 }
5661}
5662
5663# endif
5664
5665#endif /* FEAT_TERMINAL */