blob: 47f7f201d581dc79a7fafc6cc69607f92aa3726f [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 Moolenaar2e6ab182017-09-20 10:03:07 +02002703
2704 /* Unless in Terminal-Normal mode: clear the vterm. */
2705 if (!term->tl_normal_mode)
2706 {
2707 int fnum = term->tl_buffer->b_fnum;
2708
2709 cleanup_vterm(term);
2710
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002711 if (term->tl_finish == TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002712 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002713 aco_save_T aco;
2714
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002715 /* ++close or term_finish == "close" */
2716 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002717 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002718 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002719 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002720 break;
2721 }
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002722 if (term->tl_finish == TL_FINISH_OPEN
2723 && term->tl_buffer->b_nwindows == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002724 {
2725 char buf[50];
2726
2727 /* TODO: use term_opencmd */
2728 ch_log(NULL, "terminal job finished, opening window");
2729 vim_snprintf(buf, sizeof(buf),
2730 term->tl_opencmd == NULL
2731 ? "botright sbuf %d"
2732 : (char *)term->tl_opencmd, fnum);
2733 do_cmdline_cmd((char_u *)buf);
2734 }
2735 else
2736 ch_log(NULL, "terminal job finished");
2737 }
2738
2739 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2740 }
2741 if (did_one)
2742 {
2743 redraw_statuslines();
2744
2745 /* Need to break out of vgetc(). */
2746 ins_char_typebuf(K_IGNORE);
2747 typebuf_was_filled = TRUE;
2748
2749 term = curbuf->b_term;
2750 if (term != NULL)
2751 {
2752 if (term->tl_job == ch->ch_job)
2753 maketitle();
2754 update_cursor(term, term->tl_cursor_visible);
2755 }
2756 }
2757}
2758
2759/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002760 * Fill one screen line from a line of the terminal.
2761 * Advances "pos" to past the last column.
2762 */
2763 static void
2764term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2765{
2766 int off = screen_get_current_line_off();
2767
2768 for (pos->col = 0; pos->col < max_col; )
2769 {
2770 VTermScreenCell cell;
2771 int c;
2772
2773 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2774 vim_memset(&cell, 0, sizeof(cell));
2775
2776 c = cell.chars[0];
2777 if (c == NUL)
2778 {
2779 ScreenLines[off] = ' ';
2780 if (enc_utf8)
2781 ScreenLinesUC[off] = NUL;
2782 }
2783 else
2784 {
2785 if (enc_utf8)
2786 {
2787 int i;
2788
2789 /* composing chars */
2790 for (i = 0; i < Screen_mco
2791 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2792 {
2793 ScreenLinesC[i][off] = cell.chars[i + 1];
2794 if (cell.chars[i + 1] == 0)
2795 break;
2796 }
2797 if (c >= 0x80 || (Screen_mco > 0
2798 && ScreenLinesC[0][off] != 0))
2799 {
2800 ScreenLines[off] = ' ';
2801 ScreenLinesUC[off] = c;
2802 }
2803 else
2804 {
2805 ScreenLines[off] = c;
2806 ScreenLinesUC[off] = NUL;
2807 }
2808 }
2809#ifdef WIN3264
2810 else if (has_mbyte && c >= 0x80)
2811 {
2812 char_u mb[MB_MAXBYTES+1];
2813 WCHAR wc = c;
2814
2815 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2816 (char*)mb, 2, 0, 0) > 1)
2817 {
2818 ScreenLines[off] = mb[0];
2819 ScreenLines[off + 1] = mb[1];
2820 cell.width = mb_ptr2cells(mb);
2821 }
2822 else
2823 ScreenLines[off] = c;
2824 }
2825#endif
2826 else
2827 ScreenLines[off] = c;
2828 }
2829 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2830
2831 ++pos->col;
2832 ++off;
2833 if (cell.width == 2)
2834 {
2835 if (enc_utf8)
2836 ScreenLinesUC[off] = NUL;
2837
2838 /* don't set the second byte to NUL for a DBCS encoding, it
2839 * has been set above */
2840 if (enc_utf8 || !has_mbyte)
2841 ScreenLines[off] = NUL;
2842
2843 ++pos->col;
2844 ++off;
2845 }
2846 }
2847}
2848
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002849#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01002850 static void
2851update_system_term(term_T *term)
2852{
2853 VTermPos pos;
2854 VTermScreen *screen;
2855
2856 if (term->tl_vterm == NULL)
2857 return;
2858 screen = vterm_obtain_screen(term->tl_vterm);
2859
2860 /* Scroll up to make more room for terminal lines if needed. */
2861 while (term->tl_toprow > 0
2862 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
2863 {
2864 int save_p_more = p_more;
2865
2866 p_more = FALSE;
2867 msg_row = Rows - 1;
2868 msg_puts((char_u *)"\n");
2869 p_more = save_p_more;
2870 --term->tl_toprow;
2871 }
2872
2873 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2874 && pos.row < Rows; ++pos.row)
2875 {
2876 if (pos.row < term->tl_rows)
2877 {
2878 int max_col = MIN(Columns, term->tl_cols);
2879
2880 term_line2screenline(screen, &pos, max_col);
2881 }
2882 else
2883 pos.col = 0;
2884
2885 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
2886 }
2887
2888 term->tl_dirty_row_start = MAX_ROW;
2889 term->tl_dirty_row_end = 0;
2890 update_cursor(term, TRUE);
2891}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002892#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01002893
2894/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002895 * Return TRUE if window "wp" is to be redrawn with term_update_window().
2896 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002897 * Terminal-Normal mode.
2898 */
2899 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002900term_do_update_window(win_T *wp)
2901{
2902 term_T *term = wp->w_buffer->b_term;
2903
2904 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
2905}
2906
2907/*
2908 * Called to update a window that contains an active terminal.
2909 */
2910 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002911term_update_window(win_T *wp)
2912{
2913 term_T *term = wp->w_buffer->b_term;
2914 VTerm *vterm;
2915 VTermScreen *screen;
2916 VTermState *state;
2917 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02002918 int rows, cols;
2919 int newrows, newcols;
2920 int minsize;
2921 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002923 vterm = term->tl_vterm;
2924 screen = vterm_obtain_screen(vterm);
2925 state = vterm_obtain_state(vterm);
2926
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002927 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
2928 * SOME_VALID only redraw what was marked dirty. */
2929 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002930 {
2931 term->tl_dirty_row_start = 0;
2932 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002933
2934 if (term->tl_postponed_scroll > 0
2935 && term->tl_postponed_scroll < term->tl_rows / 3)
2936 /* Scrolling is usually faster than redrawing, when there are only
2937 * a few lines to scroll. */
2938 term_scroll_up(term, 0, term->tl_postponed_scroll);
2939 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002940 }
2941
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002942 /*
2943 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002944 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002945 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002946 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002947
Bram Moolenaar498c2562018-04-15 23:45:15 +02002948 newrows = 99999;
2949 newcols = 99999;
2950 FOR_ALL_WINDOWS(twp)
2951 {
2952 /* When more than one window shows the same terminal, use the
2953 * smallest size. */
2954 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002955 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02002956 newrows = MIN(newrows, twp->w_height);
2957 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002958 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02002959 }
2960 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
2961 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
2962
2963 if (term->tl_rows != newrows || term->tl_cols != newcols)
2964 {
2965
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002966
2967 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02002968 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002969 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02002970 newrows);
2971 term_report_winsize(term, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002972 }
2973
2974 /* The cursor may have been moved when resizing. */
2975 vterm_state_get_cursorpos(state, &pos);
2976 position_cursor(wp, &pos);
2977
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002978 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2979 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002980 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002981 if (pos.row < term->tl_rows)
2982 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002983 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002984
Bram Moolenaar13568252018-03-16 20:46:58 +01002985 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002986 }
2987 else
2988 pos.col = 0;
2989
Bram Moolenaarf118d482018-03-13 13:14:00 +01002990 screen_line(wp->w_winrow + pos.row
2991#ifdef FEAT_MENU
2992 + winbar_height(wp)
2993#endif
2994 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002995 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002996 term->tl_dirty_row_start = MAX_ROW;
2997 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002998}
2999
3000/*
3001 * Return TRUE if "wp" is a terminal window where the job has finished.
3002 */
3003 int
3004term_is_finished(buf_T *buf)
3005{
3006 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3007}
3008
3009/*
3010 * Return TRUE if "wp" is a terminal window where the job has finished or we
3011 * are in Terminal-Normal mode, thus we show the buffer contents.
3012 */
3013 int
3014term_show_buffer(buf_T *buf)
3015{
3016 term_T *term = buf->b_term;
3017
3018 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3019}
3020
3021/*
3022 * The current buffer is going to be changed. If there is terminal
3023 * highlighting remove it now.
3024 */
3025 void
3026term_change_in_curbuf(void)
3027{
3028 term_T *term = curbuf->b_term;
3029
3030 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3031 {
3032 free_scrollback(term);
3033 redraw_buf_later(term->tl_buffer, NOT_VALID);
3034
3035 /* The buffer is now like a normal buffer, it cannot be easily
3036 * abandoned when changed. */
3037 set_string_option_direct((char_u *)"buftype", -1,
3038 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3039 }
3040}
3041
3042/*
3043 * Get the screen attribute for a position in the buffer.
3044 * Use a negative "col" to get the filler background color.
3045 */
3046 int
3047term_get_attr(buf_T *buf, linenr_T lnum, int col)
3048{
3049 term_T *term = buf->b_term;
3050 sb_line_T *line;
3051 cellattr_T *cellattr;
3052
3053 if (lnum > term->tl_scrollback.ga_len)
3054 cellattr = &term->tl_default_color;
3055 else
3056 {
3057 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3058 if (col < 0 || col >= line->sb_cols)
3059 cellattr = &line->sb_fill_attr;
3060 else
3061 cellattr = line->sb_cells + col;
3062 }
3063 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3064}
3065
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003066/*
3067 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003068 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003069 */
3070 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003071cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003072{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003073 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003074}
3075
3076/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003077 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003078 */
3079 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003080init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003081{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003082 VTermColor *fg, *bg;
3083 int fgval, bgval;
3084 int id;
3085
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003086 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3087 term->tl_default_color.width = 1;
3088 fg = &term->tl_default_color.fg;
3089 bg = &term->tl_default_color.bg;
3090
3091 /* Vterm uses a default black background. Set it to white when
3092 * 'background' is "light". */
3093 if (*p_bg == 'l')
3094 {
3095 fgval = 0;
3096 bgval = 255;
3097 }
3098 else
3099 {
3100 fgval = 255;
3101 bgval = 0;
3102 }
3103 fg->red = fg->green = fg->blue = fgval;
3104 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003105 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003106
3107 /* The "Terminal" highlight group overrules the defaults. */
3108 id = syn_name2id((char_u *)"Terminal");
3109
Bram Moolenaar46359e12017-11-29 22:33:38 +01003110 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003111#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3112 if (0
3113# ifdef FEAT_GUI
3114 || gui.in_use
3115# endif
3116# ifdef FEAT_TERMGUICOLORS
3117 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003118# ifdef FEAT_VTP
3119 /* Finally get INVALCOLOR on this execution path */
3120 || (!p_tgc && t_colors >= 256)
3121# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003122# endif
3123 )
3124 {
3125 guicolor_T fg_rgb = INVALCOLOR;
3126 guicolor_T bg_rgb = INVALCOLOR;
3127
3128 if (id != 0)
3129 syn_id2colors(id, &fg_rgb, &bg_rgb);
3130
3131# ifdef FEAT_GUI
3132 if (gui.in_use)
3133 {
3134 if (fg_rgb == INVALCOLOR)
3135 fg_rgb = gui.norm_pixel;
3136 if (bg_rgb == INVALCOLOR)
3137 bg_rgb = gui.back_pixel;
3138 }
3139# ifdef FEAT_TERMGUICOLORS
3140 else
3141# endif
3142# endif
3143# ifdef FEAT_TERMGUICOLORS
3144 {
3145 if (fg_rgb == INVALCOLOR)
3146 fg_rgb = cterm_normal_fg_gui_color;
3147 if (bg_rgb == INVALCOLOR)
3148 bg_rgb = cterm_normal_bg_gui_color;
3149 }
3150# endif
3151 if (fg_rgb != INVALCOLOR)
3152 {
3153 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3154
3155 fg->red = (unsigned)(rgb >> 16);
3156 fg->green = (unsigned)(rgb >> 8) & 255;
3157 fg->blue = (unsigned)rgb & 255;
3158 }
3159 if (bg_rgb != INVALCOLOR)
3160 {
3161 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3162
3163 bg->red = (unsigned)(rgb >> 16);
3164 bg->green = (unsigned)(rgb >> 8) & 255;
3165 bg->blue = (unsigned)rgb & 255;
3166 }
3167 }
3168 else
3169#endif
3170 if (id != 0 && t_colors >= 16)
3171 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003172 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003173 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003174 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003175 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003176 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003177 else
3178 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003179#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003180 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003181#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003182
3183 /* In an MS-Windows console we know the normal colors. */
3184 if (cterm_normal_fg_color > 0)
3185 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003186 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003187# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003188 tmp = fg->red;
3189 fg->red = fg->blue;
3190 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003191# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003192 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003193# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003194 else
3195 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003196# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003197
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003198 if (cterm_normal_bg_color > 0)
3199 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003200 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003201# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003202 tmp = bg->red;
3203 bg->red = bg->blue;
3204 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003205# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003206 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003207# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003208 else
3209 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003210# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003211 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003212}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003213
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003214#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3215/*
3216 * Set the 16 ANSI colors from array of RGB values
3217 */
3218 static void
3219set_vterm_palette(VTerm *vterm, long_u *rgb)
3220{
3221 int index = 0;
3222 VTermState *state = vterm_obtain_state(vterm);
3223 for (; index < 16; index++)
3224 {
3225 VTermColor color;
3226 color.red = (unsigned)(rgb[index] >> 16);
3227 color.green = (unsigned)(rgb[index] >> 8) & 255;
3228 color.blue = (unsigned)rgb[index] & 255;
3229 vterm_state_set_palette_color(state, index, &color);
3230 }
3231}
3232
3233/*
3234 * Set the ANSI color palette from a list of colors
3235 */
3236 static int
3237set_ansi_colors_list(VTerm *vterm, list_T *list)
3238{
3239 int n = 0;
3240 long_u rgb[16];
3241 listitem_T *li = list->lv_first;
3242
3243 for (; li != NULL && n < 16; li = li->li_next, n++)
3244 {
3245 char_u *color_name;
3246 guicolor_T guicolor;
3247
3248 color_name = get_tv_string_chk(&li->li_tv);
3249 if (color_name == NULL)
3250 return FAIL;
3251
3252 guicolor = GUI_GET_COLOR(color_name);
3253 if (guicolor == INVALCOLOR)
3254 return FAIL;
3255
3256 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3257 }
3258
3259 if (n != 16 || li != NULL)
3260 return FAIL;
3261
3262 set_vterm_palette(vterm, rgb);
3263
3264 return OK;
3265}
3266
3267/*
3268 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3269 */
3270 static void
3271init_vterm_ansi_colors(VTerm *vterm)
3272{
3273 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3274
3275 if (var != NULL
3276 && (var->di_tv.v_type != VAR_LIST
3277 || var->di_tv.vval.v_list == NULL
3278 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3279 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3280}
3281#endif
3282
Bram Moolenaar52acb112018-03-18 19:20:22 +01003283/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003284 * Handles a "drop" command from the job in the terminal.
3285 * "item" is the file name, "item->li_next" may have options.
3286 */
3287 static void
3288handle_drop_command(listitem_T *item)
3289{
3290 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003291 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003292 int bufnr;
3293 win_T *wp;
3294 tabpage_T *tp;
3295 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003296 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003297
3298 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3299 FOR_ALL_TAB_WINDOWS(tp, wp)
3300 {
3301 if (wp->w_buffer->b_fnum == bufnr)
3302 {
3303 /* buffer is in a window already, go there */
3304 goto_tabpage_win(tp, wp);
3305 return;
3306 }
3307 }
3308
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003309 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003310
3311 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3312 && opt_item->li_tv.vval.v_dict != NULL)
3313 {
3314 dict_T *dict = opt_item->li_tv.vval.v_dict;
3315 char_u *p;
3316
3317 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3318 if (p == NULL)
3319 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3320 if (p != NULL)
3321 {
3322 if (check_ff_value(p) == FAIL)
3323 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3324 else
3325 ea.force_ff = *p;
3326 }
3327 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3328 if (p == NULL)
3329 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3330 if (p != NULL)
3331 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003332 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003333 if (ea.cmd != NULL)
3334 {
3335 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3336 ea.force_enc = 11;
3337 tofree = ea.cmd;
3338 }
3339 }
3340
3341 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3342 if (p != NULL)
3343 get_bad_opt(p, &ea);
3344
3345 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3346 ea.force_bin = FORCE_BIN;
3347 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3348 ea.force_bin = FORCE_BIN;
3349 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3350 ea.force_bin = FORCE_NOBIN;
3351 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3352 ea.force_bin = FORCE_NOBIN;
3353 }
3354
3355 /* open in new window, like ":split fname" */
3356 if (ea.cmd == NULL)
3357 ea.cmd = (char_u *)"split";
3358 ea.arg = fname;
3359 ea.cmdidx = CMD_split;
3360 ex_splitview(&ea);
3361
3362 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003363}
3364
3365/*
3366 * Handles a function call from the job running in a terminal.
3367 * "item" is the function name, "item->li_next" has the arguments.
3368 */
3369 static void
3370handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3371{
3372 char_u *func;
3373 typval_T argvars[2];
3374 typval_T rettv;
3375 int doesrange;
3376
3377 if (item->li_next == NULL)
3378 {
3379 ch_log(channel, "Missing function arguments for call");
3380 return;
3381 }
3382 func = get_tv_string(&item->li_tv);
3383
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003384 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003385 {
3386 ch_log(channel, "Invalid function name: %s", func);
3387 return;
3388 }
3389
3390 argvars[0].v_type = VAR_NUMBER;
3391 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3392 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003393 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003394 2, argvars, /* argv_func */ NULL,
3395 /* firstline */ 1, /* lastline */ 1,
3396 &doesrange, /* evaluate */ TRUE,
3397 /* partial */ NULL, /* selfdict */ NULL) == OK)
3398 {
3399 clear_tv(&rettv);
3400 ch_log(channel, "Function %s called", func);
3401 }
3402 else
3403 ch_log(channel, "Calling function %s failed", func);
3404}
3405
3406/*
3407 * Called by libvterm when it cannot recognize an OSC sequence.
3408 * We recognize a terminal API command.
3409 */
3410 static int
3411parse_osc(const char *command, size_t cmdlen, void *user)
3412{
3413 term_T *term = (term_T *)user;
3414 js_read_T reader;
3415 typval_T tv;
3416 channel_T *channel = term->tl_job == NULL ? NULL
3417 : term->tl_job->jv_channel;
3418
3419 /* We recognize only OSC 5 1 ; {command} */
3420 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3421 return 0; /* not handled */
3422
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003423 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003424 if (reader.js_buf == NULL)
3425 return 1;
3426 reader.js_fill = NULL;
3427 reader.js_used = 0;
3428 if (json_decode(&reader, &tv, 0) == OK
3429 && tv.v_type == VAR_LIST
3430 && tv.vval.v_list != NULL)
3431 {
3432 listitem_T *item = tv.vval.v_list->lv_first;
3433
3434 if (item == NULL)
3435 ch_log(channel, "Missing command");
3436 else
3437 {
3438 char_u *cmd = get_tv_string(&item->li_tv);
3439
Bram Moolenaara997b452018-04-17 23:24:06 +02003440 /* Make sure an invoked command doesn't delete the buffer (and the
3441 * terminal) under our fingers. */
3442 ++term->tl_buffer->b_locked;
3443
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003444 item = item->li_next;
3445 if (item == NULL)
3446 ch_log(channel, "Missing argument for %s", cmd);
3447 else if (STRCMP(cmd, "drop") == 0)
3448 handle_drop_command(item);
3449 else if (STRCMP(cmd, "call") == 0)
3450 handle_call_command(term, channel, item);
3451 else
3452 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003453 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003454 }
3455 }
3456 else
3457 ch_log(channel, "Invalid JSON received");
3458
3459 vim_free(reader.js_buf);
3460 clear_tv(&tv);
3461 return 1;
3462}
3463
3464static VTermParserCallbacks parser_fallbacks = {
3465 NULL, /* text */
3466 NULL, /* control */
3467 NULL, /* escape */
3468 NULL, /* csi */
3469 parse_osc, /* osc */
3470 NULL, /* dcs */
3471 NULL /* resize */
3472};
3473
3474/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003475 * Use Vim's allocation functions for vterm so profiling works.
3476 */
3477 static void *
3478vterm_malloc(size_t size, void *data UNUSED)
3479{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003480 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003481}
3482
3483 static void
3484vterm_memfree(void *ptr, void *data UNUSED)
3485{
3486 vim_free(ptr);
3487}
3488
3489static VTermAllocatorFunctions vterm_allocator = {
3490 &vterm_malloc,
3491 &vterm_memfree
3492};
3493
3494/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003495 * Create a new vterm and initialize it.
3496 */
3497 static void
3498create_vterm(term_T *term, int rows, int cols)
3499{
3500 VTerm *vterm;
3501 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003502 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003503 VTermValue value;
3504
Bram Moolenaar756ef112018-04-10 12:04:27 +02003505 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003506 term->tl_vterm = vterm;
3507 screen = vterm_obtain_screen(vterm);
3508 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3509 /* TODO: depends on 'encoding'. */
3510 vterm_set_utf8(vterm, 1);
3511
3512 init_default_colors(term);
3513
3514 vterm_state_set_default_colors(
3515 vterm_obtain_state(vterm),
3516 &term->tl_default_color.fg,
3517 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003518
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003519 if (t_colors >= 16)
3520 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3521
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003522 /* Required to initialize most things. */
3523 vterm_screen_reset(screen, 1 /* hard */);
3524
3525 /* Allow using alternate screen. */
3526 vterm_screen_enable_altscreen(screen, 1);
3527
3528 /* For unix do not use a blinking cursor. In an xterm this causes the
3529 * cursor to blink if it's blinking in the xterm.
3530 * For Windows we respect the system wide setting. */
3531#ifdef WIN3264
3532 if (GetCaretBlinkTime() == INFINITE)
3533 value.boolean = 0;
3534 else
3535 value.boolean = 1;
3536#else
3537 value.boolean = 0;
3538#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003539 state = vterm_obtain_state(vterm);
3540 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3541 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003542}
3543
3544/*
3545 * Return the text to show for the buffer name and status.
3546 */
3547 char_u *
3548term_get_status_text(term_T *term)
3549{
3550 if (term->tl_status_text == NULL)
3551 {
3552 char_u *txt;
3553 size_t len;
3554
3555 if (term->tl_normal_mode)
3556 {
3557 if (term_job_running(term))
3558 txt = (char_u *)_("Terminal");
3559 else
3560 txt = (char_u *)_("Terminal-finished");
3561 }
3562 else if (term->tl_title != NULL)
3563 txt = term->tl_title;
3564 else if (term_none_open(term))
3565 txt = (char_u *)_("active");
3566 else if (term_job_running(term))
3567 txt = (char_u *)_("running");
3568 else
3569 txt = (char_u *)_("finished");
3570 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3571 term->tl_status_text = alloc((int)len);
3572 if (term->tl_status_text != NULL)
3573 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3574 term->tl_buffer->b_fname, txt);
3575 }
3576 return term->tl_status_text;
3577}
3578
3579/*
3580 * Mark references in jobs of terminals.
3581 */
3582 int
3583set_ref_in_term(int copyID)
3584{
3585 int abort = FALSE;
3586 term_T *term;
3587 typval_T tv;
3588
3589 for (term = first_term; term != NULL; term = term->tl_next)
3590 if (term->tl_job != NULL)
3591 {
3592 tv.v_type = VAR_JOB;
3593 tv.vval.v_job = term->tl_job;
3594 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3595 }
3596 return abort;
3597}
3598
3599/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003600 * Cache "Terminal" highlight group colors.
3601 */
3602 void
3603set_terminal_default_colors(int cterm_fg, int cterm_bg)
3604{
3605 term_default_cterm_fg = cterm_fg - 1;
3606 term_default_cterm_bg = cterm_bg - 1;
3607}
3608
3609/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003610 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003611 * Returns NULL when the buffer is not for a terminal window and logs a message
3612 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003613 */
3614 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003615term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003616{
3617 buf_T *buf;
3618
3619 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3620 ++emsg_off;
3621 buf = get_buf_tv(&argvars[0], FALSE);
3622 --emsg_off;
3623 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003624 {
3625 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003626 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003627 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003628 return buf;
3629}
3630
Bram Moolenaard96ff162018-02-18 22:13:29 +01003631 static int
3632same_color(VTermColor *a, VTermColor *b)
3633{
3634 return a->red == b->red
3635 && a->green == b->green
3636 && a->blue == b->blue
3637 && a->ansi_index == b->ansi_index;
3638}
3639
3640 static void
3641dump_term_color(FILE *fd, VTermColor *color)
3642{
3643 fprintf(fd, "%02x%02x%02x%d",
3644 (int)color->red, (int)color->green, (int)color->blue,
3645 (int)color->ansi_index);
3646}
3647
3648/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003649 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003650 *
3651 * Each screen cell in full is:
3652 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3653 * {characters} is a space for an empty cell
3654 * For a double-width character "+" is changed to "*" and the next cell is
3655 * skipped.
3656 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3657 * when "&" use the same as the previous cell.
3658 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3659 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3660 * {color-idx} is a number from 0 to 255
3661 *
3662 * Screen cell with same width, attributes and color as the previous one:
3663 * |{characters}
3664 *
3665 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3666 *
3667 * Repeating the previous screen cell:
3668 * @{count}
3669 */
3670 void
3671f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3672{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003673 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003674 term_T *term;
3675 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003676 int max_height = 0;
3677 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003678 stat_T st;
3679 FILE *fd;
3680 VTermPos pos;
3681 VTermScreen *screen;
3682 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003683 VTermState *state;
3684 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003685
3686 if (check_restricted() || check_secure())
3687 return;
3688 if (buf == NULL)
3689 return;
3690 term = buf->b_term;
3691
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003692 if (argvars[2].v_type != VAR_UNKNOWN)
3693 {
3694 dict_T *d;
3695
3696 if (argvars[2].v_type != VAR_DICT)
3697 {
3698 EMSG(_(e_dictreq));
3699 return;
3700 }
3701 d = argvars[2].vval.v_dict;
3702 if (d != NULL)
3703 {
3704 max_height = get_dict_number(d, (char_u *)"rows");
3705 max_width = get_dict_number(d, (char_u *)"columns");
3706 }
3707 }
3708
Bram Moolenaard96ff162018-02-18 22:13:29 +01003709 fname = get_tv_string_chk(&argvars[1]);
3710 if (fname == NULL)
3711 return;
3712 if (mch_stat((char *)fname, &st) >= 0)
3713 {
3714 EMSG2(_("E953: File exists: %s"), fname);
3715 return;
3716 }
3717
Bram Moolenaard96ff162018-02-18 22:13:29 +01003718 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3719 {
3720 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3721 return;
3722 }
3723
3724 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3725
3726 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003727 state = vterm_obtain_state(term->tl_vterm);
3728 vterm_state_get_cursorpos(state, &cursor_pos);
3729
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003730 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3731 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003732 {
3733 int repeat = 0;
3734
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003735 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3736 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003737 {
3738 VTermScreenCell cell;
3739 int same_attr;
3740 int same_chars = TRUE;
3741 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003742 int is_cursor_pos = (pos.col == cursor_pos.col
3743 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003744
3745 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3746 vim_memset(&cell, 0, sizeof(cell));
3747
3748 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3749 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003750 int c = cell.chars[i];
3751 int pc = prev_cell.chars[i];
3752
3753 /* For the first character NUL is the same as space. */
3754 if (i == 0)
3755 {
3756 c = (c == NUL) ? ' ' : c;
3757 pc = (pc == NUL) ? ' ' : pc;
3758 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003759 if (cell.chars[i] != prev_cell.chars[i])
3760 same_chars = FALSE;
3761 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3762 break;
3763 }
3764 same_attr = vtermAttr2hl(cell.attrs)
3765 == vtermAttr2hl(prev_cell.attrs)
3766 && same_color(&cell.fg, &prev_cell.fg)
3767 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003768 if (same_chars && cell.width == prev_cell.width && same_attr
3769 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003770 {
3771 ++repeat;
3772 }
3773 else
3774 {
3775 if (repeat > 0)
3776 {
3777 fprintf(fd, "@%d", repeat);
3778 repeat = 0;
3779 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003780 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003781
3782 if (cell.chars[0] == NUL)
3783 fputs(" ", fd);
3784 else
3785 {
3786 char_u charbuf[10];
3787 int len;
3788
3789 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3790 && cell.chars[i] != NUL; ++i)
3791 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003792 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003793 fwrite(charbuf, len, 1, fd);
3794 }
3795 }
3796
3797 /* When only the characters differ we don't write anything, the
3798 * following "|", "@" or NL will indicate using the same
3799 * attributes. */
3800 if (cell.width != prev_cell.width || !same_attr)
3801 {
3802 if (cell.width == 2)
3803 {
3804 fputs("*", fd);
3805 ++pos.col;
3806 }
3807 else
3808 fputs("+", fd);
3809
3810 if (same_attr)
3811 {
3812 fputs("&", fd);
3813 }
3814 else
3815 {
3816 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3817 if (same_color(&cell.fg, &prev_cell.fg))
3818 fputs("&", fd);
3819 else
3820 {
3821 fputs("#", fd);
3822 dump_term_color(fd, &cell.fg);
3823 }
3824 if (same_color(&cell.bg, &prev_cell.bg))
3825 fputs("&", fd);
3826 else
3827 {
3828 fputs("#", fd);
3829 dump_term_color(fd, &cell.bg);
3830 }
3831 }
3832 }
3833
3834 prev_cell = cell;
3835 }
3836 }
3837 if (repeat > 0)
3838 fprintf(fd, "@%d", repeat);
3839 fputs("\n", fd);
3840 }
3841
3842 fclose(fd);
3843}
3844
3845/*
3846 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3847 */
3848 static void
3849dump_is_corrupt(garray_T *gap)
3850{
3851 ga_concat(gap, (char_u *)"CORRUPT");
3852}
3853
3854 static void
3855append_cell(garray_T *gap, cellattr_T *cell)
3856{
3857 if (ga_grow(gap, 1) == OK)
3858 {
3859 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3860 ++gap->ga_len;
3861 }
3862}
3863
3864/*
3865 * Read the dump file from "fd" and append lines to the current buffer.
3866 * Return the cell width of the longest line.
3867 */
3868 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003869read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003870{
3871 int c;
3872 garray_T ga_text;
3873 garray_T ga_cell;
3874 char_u *prev_char = NULL;
3875 int attr = 0;
3876 cellattr_T cell;
3877 term_T *term = curbuf->b_term;
3878 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003879 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003880
3881 ga_init2(&ga_text, 1, 90);
3882 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3883 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003884 cursor_pos->row = -1;
3885 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003886
3887 c = fgetc(fd);
3888 for (;;)
3889 {
3890 if (c == EOF)
3891 break;
3892 if (c == '\n')
3893 {
3894 /* End of a line: append it to the buffer. */
3895 if (ga_text.ga_data == NULL)
3896 dump_is_corrupt(&ga_text);
3897 if (ga_grow(&term->tl_scrollback, 1) == OK)
3898 {
3899 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3900 + term->tl_scrollback.ga_len;
3901
3902 if (max_cells < ga_cell.ga_len)
3903 max_cells = ga_cell.ga_len;
3904 line->sb_cols = ga_cell.ga_len;
3905 line->sb_cells = ga_cell.ga_data;
3906 line->sb_fill_attr = term->tl_default_color;
3907 ++term->tl_scrollback.ga_len;
3908 ga_init(&ga_cell);
3909
3910 ga_append(&ga_text, NUL);
3911 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3912 ga_text.ga_len, FALSE);
3913 }
3914 else
3915 ga_clear(&ga_cell);
3916 ga_text.ga_len = 0;
3917
3918 c = fgetc(fd);
3919 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003920 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003921 {
3922 int prev_len = ga_text.ga_len;
3923
Bram Moolenaar9271d052018-02-25 21:39:46 +01003924 if (c == '>')
3925 {
3926 if (cursor_pos->row != -1)
3927 dump_is_corrupt(&ga_text); /* duplicate cursor */
3928 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3929 cursor_pos->col = ga_cell.ga_len;
3930 }
3931
Bram Moolenaard96ff162018-02-18 22:13:29 +01003932 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3933 c = fgetc(fd);
3934 if (c != EOF)
3935 ga_append(&ga_text, c);
3936 for (;;)
3937 {
3938 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003939 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003940 || c == EOF || c == '\n')
3941 break;
3942 ga_append(&ga_text, c);
3943 }
3944
3945 /* save the character for repeating it */
3946 vim_free(prev_char);
3947 if (ga_text.ga_data != NULL)
3948 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3949 ga_text.ga_len - prev_len);
3950
Bram Moolenaar9271d052018-02-25 21:39:46 +01003951 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003952 {
3953 /* use all attributes from previous cell */
3954 }
3955 else if (c == '+' || c == '*')
3956 {
3957 int is_bg;
3958
3959 cell.width = c == '+' ? 1 : 2;
3960
3961 c = fgetc(fd);
3962 if (c == '&')
3963 {
3964 /* use same attr as previous cell */
3965 c = fgetc(fd);
3966 }
3967 else if (isdigit(c))
3968 {
3969 /* get the decimal attribute */
3970 attr = 0;
3971 while (isdigit(c))
3972 {
3973 attr = attr * 10 + (c - '0');
3974 c = fgetc(fd);
3975 }
3976 hl2vtermAttr(attr, &cell);
3977 }
3978 else
3979 dump_is_corrupt(&ga_text);
3980
3981 /* is_bg == 0: fg, is_bg == 1: bg */
3982 for (is_bg = 0; is_bg <= 1; ++is_bg)
3983 {
3984 if (c == '&')
3985 {
3986 /* use same color as previous cell */
3987 c = fgetc(fd);
3988 }
3989 else if (c == '#')
3990 {
3991 int red, green, blue, index = 0;
3992
3993 c = fgetc(fd);
3994 red = hex2nr(c);
3995 c = fgetc(fd);
3996 red = (red << 4) + hex2nr(c);
3997 c = fgetc(fd);
3998 green = hex2nr(c);
3999 c = fgetc(fd);
4000 green = (green << 4) + hex2nr(c);
4001 c = fgetc(fd);
4002 blue = hex2nr(c);
4003 c = fgetc(fd);
4004 blue = (blue << 4) + hex2nr(c);
4005 c = fgetc(fd);
4006 if (!isdigit(c))
4007 dump_is_corrupt(&ga_text);
4008 while (isdigit(c))
4009 {
4010 index = index * 10 + (c - '0');
4011 c = fgetc(fd);
4012 }
4013
4014 if (is_bg)
4015 {
4016 cell.bg.red = red;
4017 cell.bg.green = green;
4018 cell.bg.blue = blue;
4019 cell.bg.ansi_index = index;
4020 }
4021 else
4022 {
4023 cell.fg.red = red;
4024 cell.fg.green = green;
4025 cell.fg.blue = blue;
4026 cell.fg.ansi_index = index;
4027 }
4028 }
4029 else
4030 dump_is_corrupt(&ga_text);
4031 }
4032 }
4033 else
4034 dump_is_corrupt(&ga_text);
4035
4036 append_cell(&ga_cell, &cell);
4037 }
4038 else if (c == '@')
4039 {
4040 if (prev_char == NULL)
4041 dump_is_corrupt(&ga_text);
4042 else
4043 {
4044 int count = 0;
4045
4046 /* repeat previous character, get the count */
4047 for (;;)
4048 {
4049 c = fgetc(fd);
4050 if (!isdigit(c))
4051 break;
4052 count = count * 10 + (c - '0');
4053 }
4054
4055 while (count-- > 0)
4056 {
4057 ga_concat(&ga_text, prev_char);
4058 append_cell(&ga_cell, &cell);
4059 }
4060 }
4061 }
4062 else
4063 {
4064 dump_is_corrupt(&ga_text);
4065 c = fgetc(fd);
4066 }
4067 }
4068
4069 if (ga_text.ga_len > 0)
4070 {
4071 /* trailing characters after last NL */
4072 dump_is_corrupt(&ga_text);
4073 ga_append(&ga_text, NUL);
4074 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4075 ga_text.ga_len, FALSE);
4076 }
4077
4078 ga_clear(&ga_text);
4079 vim_free(prev_char);
4080
4081 return max_cells;
4082}
4083
4084/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004085 * Return an allocated string with at least "text_width" "=" characters and
4086 * "fname" inserted in the middle.
4087 */
4088 static char_u *
4089get_separator(int text_width, char_u *fname)
4090{
4091 int width = MAX(text_width, curwin->w_width);
4092 char_u *textline;
4093 int fname_size;
4094 char_u *p = fname;
4095 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004096 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004097
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004098 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004099 if (textline == NULL)
4100 return NULL;
4101
4102 fname_size = vim_strsize(fname);
4103 if (fname_size < width - 8)
4104 {
4105 /* enough room, don't use the full window width */
4106 width = MAX(text_width, fname_size + 8);
4107 }
4108 else if (fname_size > width - 8)
4109 {
4110 /* full name doesn't fit, use only the tail */
4111 p = gettail(fname);
4112 fname_size = vim_strsize(p);
4113 }
4114 /* skip characters until the name fits */
4115 while (fname_size > width - 8)
4116 {
4117 p += (*mb_ptr2len)(p);
4118 fname_size = vim_strsize(p);
4119 }
4120
4121 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4122 textline[i] = '=';
4123 textline[i++] = ' ';
4124
4125 STRCPY(textline + i, p);
4126 off = STRLEN(textline);
4127 textline[off] = ' ';
4128 for (i = 1; i < (width - fname_size) / 2; ++i)
4129 textline[off + i] = '=';
4130 textline[off + i] = NUL;
4131
4132 return textline;
4133}
4134
4135/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004136 * Common for "term_dumpdiff()" and "term_dumpload()".
4137 */
4138 static void
4139term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4140{
4141 jobopt_T opt;
4142 buf_T *buf;
4143 char_u buf1[NUMBUFLEN];
4144 char_u buf2[NUMBUFLEN];
4145 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004146 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004147 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004148 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004149 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004150 char_u *textline = NULL;
4151
4152 /* First open the files. If this fails bail out. */
4153 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4154 if (do_diff)
4155 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4156 if (fname1 == NULL || (do_diff && fname2 == NULL))
4157 {
4158 EMSG(_(e_invarg));
4159 return;
4160 }
4161 fd1 = mch_fopen((char *)fname1, READBIN);
4162 if (fd1 == NULL)
4163 {
4164 EMSG2(_(e_notread), fname1);
4165 return;
4166 }
4167 if (do_diff)
4168 {
4169 fd2 = mch_fopen((char *)fname2, READBIN);
4170 if (fd2 == NULL)
4171 {
4172 fclose(fd1);
4173 EMSG2(_(e_notread), fname2);
4174 return;
4175 }
4176 }
4177
4178 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004179 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4180 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4181 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4182 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4183 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004184
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004185 if (opt.jo_term_name == NULL)
4186 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004187 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004188
Bram Moolenaarb571c632018-03-21 22:27:59 +01004189 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004190 if (fname_tofree != NULL)
4191 {
4192 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4193 opt.jo_term_name = fname_tofree;
4194 }
4195 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004196
Bram Moolenaar13568252018-03-16 20:46:58 +01004197 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004198 if (buf != NULL && buf->b_term != NULL)
4199 {
4200 int i;
4201 linenr_T bot_lnum;
4202 linenr_T lnum;
4203 term_T *term = buf->b_term;
4204 int width;
4205 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004206 VTermPos cursor_pos1;
4207 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004208
Bram Moolenaar52acb112018-03-18 19:20:22 +01004209 init_default_colors(term);
4210
Bram Moolenaard96ff162018-02-18 22:13:29 +01004211 rettv->vval.v_number = buf->b_fnum;
4212
4213 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004214 width = read_dump_file(fd1, &cursor_pos1);
4215
4216 /* position the cursor */
4217 if (cursor_pos1.row >= 0)
4218 {
4219 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4220 coladvance(cursor_pos1.col);
4221 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004222
4223 /* Delete the empty line that was in the empty buffer. */
4224 ml_delete(1, FALSE);
4225
4226 /* For term_dumpload() we are done here. */
4227 if (!do_diff)
4228 goto theend;
4229
4230 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4231
Bram Moolenaar4a696342018-04-05 18:45:26 +02004232 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004233 if (textline == NULL)
4234 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004235 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4236 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4237 vim_free(textline);
4238
4239 textline = get_separator(width, fname2);
4240 if (textline == NULL)
4241 goto theend;
4242 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4243 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004244 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004245
4246 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004247 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004248 if (width2 > width)
4249 {
4250 vim_free(textline);
4251 textline = alloc(width2 + 1);
4252 if (textline == NULL)
4253 goto theend;
4254 width = width2;
4255 textline[width] = NUL;
4256 }
4257 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4258
4259 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4260 {
4261 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4262 {
4263 /* bottom part has fewer rows, fill with "-" */
4264 for (i = 0; i < width; ++i)
4265 textline[i] = '-';
4266 }
4267 else
4268 {
4269 char_u *line1;
4270 char_u *line2;
4271 char_u *p1;
4272 char_u *p2;
4273 int col;
4274 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4275 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4276 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4277 ->sb_cells;
4278
4279 /* Make a copy, getting the second line will invalidate it. */
4280 line1 = vim_strsave(ml_get(lnum));
4281 if (line1 == NULL)
4282 break;
4283 p1 = line1;
4284
4285 line2 = ml_get(lnum + bot_lnum);
4286 p2 = line2;
4287 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4288 {
4289 int len1 = utfc_ptr2len(p1);
4290 int len2 = utfc_ptr2len(p2);
4291
4292 textline[col] = ' ';
4293 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004294 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004295 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004296 else if (lnum == cursor_pos1.row + 1
4297 && col == cursor_pos1.col
4298 && (cursor_pos1.row != cursor_pos2.row
4299 || cursor_pos1.col != cursor_pos2.col))
4300 /* cursor in first but not in second */
4301 textline[col] = '>';
4302 else if (lnum == cursor_pos2.row + 1
4303 && col == cursor_pos2.col
4304 && (cursor_pos1.row != cursor_pos2.row
4305 || cursor_pos1.col != cursor_pos2.col))
4306 /* cursor in second but not in first */
4307 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004308 else if (cellattr1 != NULL && cellattr2 != NULL)
4309 {
4310 if ((cellattr1 + col)->width
4311 != (cellattr2 + col)->width)
4312 textline[col] = 'w';
4313 else if (!same_color(&(cellattr1 + col)->fg,
4314 &(cellattr2 + col)->fg))
4315 textline[col] = 'f';
4316 else if (!same_color(&(cellattr1 + col)->bg,
4317 &(cellattr2 + col)->bg))
4318 textline[col] = 'b';
4319 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4320 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4321 textline[col] = 'a';
4322 }
4323 p1 += len1;
4324 p2 += len2;
4325 /* TODO: handle different width */
4326 }
4327 vim_free(line1);
4328
4329 while (col < width)
4330 {
4331 if (*p1 == NUL && *p2 == NUL)
4332 textline[col] = '?';
4333 else if (*p1 == NUL)
4334 {
4335 textline[col] = '+';
4336 p2 += utfc_ptr2len(p2);
4337 }
4338 else
4339 {
4340 textline[col] = '-';
4341 p1 += utfc_ptr2len(p1);
4342 }
4343 ++col;
4344 }
4345 }
4346 if (add_empty_scrollback(term, &term->tl_default_color,
4347 term->tl_top_diff_rows) == OK)
4348 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4349 ++bot_lnum;
4350 }
4351
4352 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4353 {
4354 /* bottom part has more rows, fill with "+" */
4355 for (i = 0; i < width; ++i)
4356 textline[i] = '+';
4357 if (add_empty_scrollback(term, &term->tl_default_color,
4358 term->tl_top_diff_rows) == OK)
4359 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4360 ++lnum;
4361 ++bot_lnum;
4362 }
4363
4364 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004365
4366 /* looks better without wrapping */
4367 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004368 }
4369
4370theend:
4371 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004372 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004373 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004374 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004375 fclose(fd2);
4376}
4377
4378/*
4379 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4380 * bottom files.
4381 * Return FAIL when this is not possible.
4382 */
4383 int
4384term_swap_diff()
4385{
4386 term_T *term = curbuf->b_term;
4387 linenr_T line_count;
4388 linenr_T top_rows;
4389 linenr_T bot_rows;
4390 linenr_T bot_start;
4391 linenr_T lnum;
4392 char_u *p;
4393 sb_line_T *sb_line;
4394
4395 if (term == NULL
4396 || !term_is_finished(curbuf)
4397 || term->tl_top_diff_rows == 0
4398 || term->tl_scrollback.ga_len == 0)
4399 return FAIL;
4400
4401 line_count = curbuf->b_ml.ml_line_count;
4402 top_rows = term->tl_top_diff_rows;
4403 bot_rows = term->tl_bot_diff_rows;
4404 bot_start = line_count - bot_rows;
4405 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4406
4407 /* move lines from top to above the bottom part */
4408 for (lnum = 1; lnum <= top_rows; ++lnum)
4409 {
4410 p = vim_strsave(ml_get(1));
4411 if (p == NULL)
4412 return OK;
4413 ml_append(bot_start, p, 0, FALSE);
4414 ml_delete(1, FALSE);
4415 vim_free(p);
4416 }
4417
4418 /* move lines from bottom to the top */
4419 for (lnum = 1; lnum <= bot_rows; ++lnum)
4420 {
4421 p = vim_strsave(ml_get(bot_start + lnum));
4422 if (p == NULL)
4423 return OK;
4424 ml_delete(bot_start + lnum, FALSE);
4425 ml_append(lnum - 1, p, 0, FALSE);
4426 vim_free(p);
4427 }
4428
4429 if (top_rows == bot_rows)
4430 {
4431 /* rows counts are equal, can swap cell properties */
4432 for (lnum = 0; lnum < top_rows; ++lnum)
4433 {
4434 sb_line_T temp;
4435
4436 temp = *(sb_line + lnum);
4437 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4438 *(sb_line + bot_start + lnum) = temp;
4439 }
4440 }
4441 else
4442 {
4443 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4444 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4445
4446 /* need to copy cell properties into temp memory */
4447 if (temp != NULL)
4448 {
4449 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4450 mch_memmove(term->tl_scrollback.ga_data,
4451 temp + bot_start,
4452 sizeof(sb_line_T) * bot_rows);
4453 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4454 temp + top_rows,
4455 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4456 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4457 + line_count - top_rows,
4458 temp,
4459 sizeof(sb_line_T) * top_rows);
4460 vim_free(temp);
4461 }
4462 }
4463
4464 term->tl_top_diff_rows = bot_rows;
4465 term->tl_bot_diff_rows = top_rows;
4466
4467 update_screen(NOT_VALID);
4468 return OK;
4469}
4470
4471/*
4472 * "term_dumpdiff(filename, filename, options)" function
4473 */
4474 void
4475f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4476{
4477 term_load_dump(argvars, rettv, TRUE);
4478}
4479
4480/*
4481 * "term_dumpload(filename, options)" function
4482 */
4483 void
4484f_term_dumpload(typval_T *argvars, typval_T *rettv)
4485{
4486 term_load_dump(argvars, rettv, FALSE);
4487}
4488
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004489/*
4490 * "term_getaltscreen(buf)" function
4491 */
4492 void
4493f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4494{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004495 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004496
4497 if (buf == NULL)
4498 return;
4499 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4500}
4501
4502/*
4503 * "term_getattr(attr, name)" function
4504 */
4505 void
4506f_term_getattr(typval_T *argvars, typval_T *rettv)
4507{
4508 int attr;
4509 size_t i;
4510 char_u *name;
4511
4512 static struct {
4513 char *name;
4514 int attr;
4515 } attrs[] = {
4516 {"bold", HL_BOLD},
4517 {"italic", HL_ITALIC},
4518 {"underline", HL_UNDERLINE},
4519 {"strike", HL_STRIKETHROUGH},
4520 {"reverse", HL_INVERSE},
4521 };
4522
4523 attr = get_tv_number(&argvars[0]);
4524 name = get_tv_string_chk(&argvars[1]);
4525 if (name == NULL)
4526 return;
4527
4528 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4529 if (STRCMP(name, attrs[i].name) == 0)
4530 {
4531 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4532 break;
4533 }
4534}
4535
4536/*
4537 * "term_getcursor(buf)" function
4538 */
4539 void
4540f_term_getcursor(typval_T *argvars, typval_T *rettv)
4541{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004542 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004543 term_T *term;
4544 list_T *l;
4545 dict_T *d;
4546
4547 if (rettv_list_alloc(rettv) == FAIL)
4548 return;
4549 if (buf == NULL)
4550 return;
4551 term = buf->b_term;
4552
4553 l = rettv->vval.v_list;
4554 list_append_number(l, term->tl_cursor_pos.row + 1);
4555 list_append_number(l, term->tl_cursor_pos.col + 1);
4556
4557 d = dict_alloc();
4558 if (d != NULL)
4559 {
4560 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4561 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4562 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4563 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4564 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4565 ? (char_u *)"" : term->tl_cursor_color);
4566 list_append_dict(l, d);
4567 }
4568}
4569
4570/*
4571 * "term_getjob(buf)" function
4572 */
4573 void
4574f_term_getjob(typval_T *argvars, typval_T *rettv)
4575{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004576 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004577
4578 rettv->v_type = VAR_JOB;
4579 rettv->vval.v_job = NULL;
4580 if (buf == NULL)
4581 return;
4582
4583 rettv->vval.v_job = buf->b_term->tl_job;
4584 if (rettv->vval.v_job != NULL)
4585 ++rettv->vval.v_job->jv_refcount;
4586}
4587
4588 static int
4589get_row_number(typval_T *tv, term_T *term)
4590{
4591 if (tv->v_type == VAR_STRING
4592 && tv->vval.v_string != NULL
4593 && STRCMP(tv->vval.v_string, ".") == 0)
4594 return term->tl_cursor_pos.row;
4595 return (int)get_tv_number(tv) - 1;
4596}
4597
4598/*
4599 * "term_getline(buf, row)" function
4600 */
4601 void
4602f_term_getline(typval_T *argvars, typval_T *rettv)
4603{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004604 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004605 term_T *term;
4606 int row;
4607
4608 rettv->v_type = VAR_STRING;
4609 if (buf == NULL)
4610 return;
4611 term = buf->b_term;
4612 row = get_row_number(&argvars[1], term);
4613
4614 if (term->tl_vterm == NULL)
4615 {
4616 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4617
4618 /* vterm is finished, get the text from the buffer */
4619 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4620 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4621 }
4622 else
4623 {
4624 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4625 VTermRect rect;
4626 int len;
4627 char_u *p;
4628
4629 if (row < 0 || row >= term->tl_rows)
4630 return;
4631 len = term->tl_cols * MB_MAXBYTES + 1;
4632 p = alloc(len);
4633 if (p == NULL)
4634 return;
4635 rettv->vval.v_string = p;
4636
4637 rect.start_col = 0;
4638 rect.end_col = term->tl_cols;
4639 rect.start_row = row;
4640 rect.end_row = row + 1;
4641 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4642 }
4643}
4644
4645/*
4646 * "term_getscrolled(buf)" function
4647 */
4648 void
4649f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4650{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004651 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004652
4653 if (buf == NULL)
4654 return;
4655 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4656}
4657
4658/*
4659 * "term_getsize(buf)" function
4660 */
4661 void
4662f_term_getsize(typval_T *argvars, typval_T *rettv)
4663{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004664 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004665 list_T *l;
4666
4667 if (rettv_list_alloc(rettv) == FAIL)
4668 return;
4669 if (buf == NULL)
4670 return;
4671
4672 l = rettv->vval.v_list;
4673 list_append_number(l, buf->b_term->tl_rows);
4674 list_append_number(l, buf->b_term->tl_cols);
4675}
4676
4677/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004678 * "term_setsize(buf, rows, cols)" function
4679 */
4680 void
4681f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4682{
4683 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4684 term_T *term;
4685 varnumber_T rows, cols;
4686
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004687 if (buf == NULL)
4688 {
4689 EMSG(_("E955: Not a terminal buffer"));
4690 return;
4691 }
4692 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004693 return;
4694 term = buf->b_term;
4695 rows = get_tv_number(&argvars[1]);
4696 rows = rows <= 0 ? term->tl_rows : rows;
4697 cols = get_tv_number(&argvars[2]);
4698 cols = cols <= 0 ? term->tl_cols : cols;
4699 vterm_set_size(term->tl_vterm, rows, cols);
4700 /* handle_resize() will resize the windows */
4701
4702 /* Get and remember the size we ended up with. Update the pty. */
4703 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4704 term_report_winsize(term, term->tl_rows, term->tl_cols);
4705}
4706
4707/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004708 * "term_getstatus(buf)" function
4709 */
4710 void
4711f_term_getstatus(typval_T *argvars, typval_T *rettv)
4712{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004713 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004714 term_T *term;
4715 char_u val[100];
4716
4717 rettv->v_type = VAR_STRING;
4718 if (buf == NULL)
4719 return;
4720 term = buf->b_term;
4721
4722 if (term_job_running(term))
4723 STRCPY(val, "running");
4724 else
4725 STRCPY(val, "finished");
4726 if (term->tl_normal_mode)
4727 STRCAT(val, ",normal");
4728 rettv->vval.v_string = vim_strsave(val);
4729}
4730
4731/*
4732 * "term_gettitle(buf)" function
4733 */
4734 void
4735f_term_gettitle(typval_T *argvars, typval_T *rettv)
4736{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004737 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004738
4739 rettv->v_type = VAR_STRING;
4740 if (buf == NULL)
4741 return;
4742
4743 if (buf->b_term->tl_title != NULL)
4744 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4745}
4746
4747/*
4748 * "term_gettty(buf)" function
4749 */
4750 void
4751f_term_gettty(typval_T *argvars, typval_T *rettv)
4752{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004753 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004754 char_u *p;
4755 int num = 0;
4756
4757 rettv->v_type = VAR_STRING;
4758 if (buf == NULL)
4759 return;
4760 if (argvars[1].v_type != VAR_UNKNOWN)
4761 num = get_tv_number(&argvars[1]);
4762
4763 switch (num)
4764 {
4765 case 0:
4766 if (buf->b_term->tl_job != NULL)
4767 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004768 break;
4769 case 1:
4770 if (buf->b_term->tl_job != NULL)
4771 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004772 break;
4773 default:
4774 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4775 return;
4776 }
4777 if (p != NULL)
4778 rettv->vval.v_string = vim_strsave(p);
4779}
4780
4781/*
4782 * "term_list()" function
4783 */
4784 void
4785f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4786{
4787 term_T *tp;
4788 list_T *l;
4789
4790 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4791 return;
4792
4793 l = rettv->vval.v_list;
4794 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4795 if (tp != NULL && tp->tl_buffer != NULL)
4796 if (list_append_number(l,
4797 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4798 return;
4799}
4800
4801/*
4802 * "term_scrape(buf, row)" function
4803 */
4804 void
4805f_term_scrape(typval_T *argvars, typval_T *rettv)
4806{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004807 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004808 VTermScreen *screen = NULL;
4809 VTermPos pos;
4810 list_T *l;
4811 term_T *term;
4812 char_u *p;
4813 sb_line_T *line;
4814
4815 if (rettv_list_alloc(rettv) == FAIL)
4816 return;
4817 if (buf == NULL)
4818 return;
4819 term = buf->b_term;
4820
4821 l = rettv->vval.v_list;
4822 pos.row = get_row_number(&argvars[1], term);
4823
4824 if (term->tl_vterm != NULL)
4825 {
4826 screen = vterm_obtain_screen(term->tl_vterm);
4827 p = NULL;
4828 line = NULL;
4829 }
4830 else
4831 {
4832 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4833
4834 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4835 return;
4836 p = ml_get_buf(buf, lnum + 1, FALSE);
4837 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4838 }
4839
4840 for (pos.col = 0; pos.col < term->tl_cols; )
4841 {
4842 dict_T *dcell;
4843 int width;
4844 VTermScreenCellAttrs attrs;
4845 VTermColor fg, bg;
4846 char_u rgb[8];
4847 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4848 int off = 0;
4849 int i;
4850
4851 if (screen == NULL)
4852 {
4853 cellattr_T *cellattr;
4854 int len;
4855
4856 /* vterm has finished, get the cell from scrollback */
4857 if (pos.col >= line->sb_cols)
4858 break;
4859 cellattr = line->sb_cells + pos.col;
4860 width = cellattr->width;
4861 attrs = cellattr->attrs;
4862 fg = cellattr->fg;
4863 bg = cellattr->bg;
4864 len = MB_PTR2LEN(p);
4865 mch_memmove(mbs, p, len);
4866 mbs[len] = NUL;
4867 p += len;
4868 }
4869 else
4870 {
4871 VTermScreenCell cell;
4872 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4873 break;
4874 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4875 {
4876 if (cell.chars[i] == 0)
4877 break;
4878 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4879 }
4880 mbs[off] = NUL;
4881 width = cell.width;
4882 attrs = cell.attrs;
4883 fg = cell.fg;
4884 bg = cell.bg;
4885 }
4886 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004887 if (dcell == NULL)
4888 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004889 list_append_dict(l, dcell);
4890
4891 dict_add_nr_str(dcell, "chars", 0, mbs);
4892
4893 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4894 fg.red, fg.green, fg.blue);
4895 dict_add_nr_str(dcell, "fg", 0, rgb);
4896 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4897 bg.red, bg.green, bg.blue);
4898 dict_add_nr_str(dcell, "bg", 0, rgb);
4899
4900 dict_add_nr_str(dcell, "attr",
4901 cell2attr(attrs, fg, bg), NULL);
4902 dict_add_nr_str(dcell, "width", width, NULL);
4903
4904 ++pos.col;
4905 if (width == 2)
4906 ++pos.col;
4907 }
4908}
4909
4910/*
4911 * "term_sendkeys(buf, keys)" function
4912 */
4913 void
4914f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4915{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004916 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004917 char_u *msg;
4918 term_T *term;
4919
4920 rettv->v_type = VAR_UNKNOWN;
4921 if (buf == NULL)
4922 return;
4923
4924 msg = get_tv_string_chk(&argvars[1]);
4925 if (msg == NULL)
4926 return;
4927 term = buf->b_term;
4928 if (term->tl_vterm == NULL)
4929 return;
4930
4931 while (*msg != NUL)
4932 {
4933 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004934 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004935 }
4936}
4937
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004938#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
4939/*
4940 * "term_getansicolors(buf)" function
4941 */
4942 void
4943f_term_getansicolors(typval_T *argvars, typval_T *rettv)
4944{
4945 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
4946 term_T *term;
4947 VTermState *state;
4948 VTermColor color;
4949 char_u hexbuf[10];
4950 int index;
4951 list_T *list;
4952
4953 if (rettv_list_alloc(rettv) == FAIL)
4954 return;
4955
4956 if (buf == NULL)
4957 return;
4958 term = buf->b_term;
4959 if (term->tl_vterm == NULL)
4960 return;
4961
4962 list = rettv->vval.v_list;
4963 state = vterm_obtain_state(term->tl_vterm);
4964 for (index = 0; index < 16; index++)
4965 {
4966 vterm_state_get_palette_color(state, index, &color);
4967 sprintf((char *)hexbuf, "#%02x%02x%02x",
4968 color.red, color.green, color.blue);
4969 if (list_append_string(list, hexbuf, 7) == FAIL)
4970 return;
4971 }
4972}
4973
4974/*
4975 * "term_setansicolors(buf, list)" function
4976 */
4977 void
4978f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
4979{
4980 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
4981 term_T *term;
4982
4983 if (buf == NULL)
4984 return;
4985 term = buf->b_term;
4986 if (term->tl_vterm == NULL)
4987 return;
4988
4989 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
4990 {
4991 EMSG(_(e_listreq));
4992 return;
4993 }
4994
4995 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
4996 EMSG(_(e_invarg));
4997}
4998#endif
4999
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005000/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005001 * "term_setrestore(buf, command)" function
5002 */
5003 void
5004f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5005{
5006#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005007 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005008 term_T *term;
5009 char_u *cmd;
5010
5011 if (buf == NULL)
5012 return;
5013 term = buf->b_term;
5014 vim_free(term->tl_command);
5015 cmd = get_tv_string_chk(&argvars[1]);
5016 if (cmd != NULL)
5017 term->tl_command = vim_strsave(cmd);
5018 else
5019 term->tl_command = NULL;
5020#endif
5021}
5022
5023/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005024 * "term_setkill(buf, how)" function
5025 */
5026 void
5027f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5028{
5029 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5030 term_T *term;
5031 char_u *how;
5032
5033 if (buf == NULL)
5034 return;
5035 term = buf->b_term;
5036 vim_free(term->tl_kill);
5037 how = get_tv_string_chk(&argvars[1]);
5038 if (how != NULL)
5039 term->tl_kill = vim_strsave(how);
5040 else
5041 term->tl_kill = NULL;
5042}
5043
5044/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005045 * "term_start(command, options)" function
5046 */
5047 void
5048f_term_start(typval_T *argvars, typval_T *rettv)
5049{
5050 jobopt_T opt;
5051 buf_T *buf;
5052
5053 init_job_options(&opt);
5054 if (argvars[1].v_type != VAR_UNKNOWN
5055 && get_job_options(&argvars[1], &opt,
5056 JO_TIMEOUT_ALL + JO_STOPONEXIT
5057 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5058 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5059 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5060 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005061 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005062 + JO2_NORESTORE + JO2_TERM_KILL
5063 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005064 return;
5065
Bram Moolenaar13568252018-03-16 20:46:58 +01005066 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005067
5068 if (buf != NULL && buf->b_term != NULL)
5069 rettv->vval.v_number = buf->b_fnum;
5070}
5071
5072/*
5073 * "term_wait" function
5074 */
5075 void
5076f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5077{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005078 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005079
5080 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005081 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005082 if (buf->b_term->tl_job == NULL)
5083 {
5084 ch_log(NULL, "term_wait(): no job to wait for");
5085 return;
5086 }
5087 if (buf->b_term->tl_job->jv_channel == NULL)
5088 /* channel is closed, nothing to do */
5089 return;
5090
5091 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005092 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005093 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5094 {
5095 /* The job is dead, keep reading channel I/O until the channel is
5096 * closed. buf->b_term may become NULL if the terminal was closed while
5097 * waiting. */
5098 ch_log(NULL, "term_wait(): waiting for channel to close");
5099 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5100 {
5101 mch_check_messages();
5102 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005103 if (!buf_valid(buf))
5104 /* If the terminal is closed when the channel is closed the
5105 * buffer disappears. */
5106 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005107 ui_delay(10L, FALSE);
5108 }
5109 mch_check_messages();
5110 parse_queued_messages();
5111 }
5112 else
5113 {
5114 long wait = 10L;
5115
5116 mch_check_messages();
5117 parse_queued_messages();
5118
5119 /* Wait for some time for any channel I/O. */
5120 if (argvars[1].v_type != VAR_UNKNOWN)
5121 wait = get_tv_number(&argvars[1]);
5122 ui_delay(wait, TRUE);
5123 mch_check_messages();
5124
5125 /* Flushing messages on channels is hopefully sufficient.
5126 * TODO: is there a better way? */
5127 parse_queued_messages();
5128 }
5129}
5130
5131/*
5132 * Called when a channel has sent all the lines to a terminal.
5133 * Send a CTRL-D to mark the end of the text.
5134 */
5135 void
5136term_send_eof(channel_T *ch)
5137{
5138 term_T *term;
5139
5140 for (term = first_term; term != NULL; term = term->tl_next)
5141 if (term->tl_job == ch->ch_job)
5142 {
5143 if (term->tl_eof_chars != NULL)
5144 {
5145 channel_send(ch, PART_IN, term->tl_eof_chars,
5146 (int)STRLEN(term->tl_eof_chars), NULL);
5147 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5148 }
5149# ifdef WIN3264
5150 else
5151 /* Default: CTRL-D */
5152 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5153# endif
5154 }
5155}
5156
5157# if defined(WIN3264) || defined(PROTO)
5158
5159/**************************************
5160 * 2. MS-Windows implementation.
5161 */
5162
5163# ifndef PROTO
5164
5165#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5166#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005167#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005168
5169void* (*winpty_config_new)(UINT64, void*);
5170void* (*winpty_open)(void*, void*);
5171void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5172BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5173void (*winpty_config_set_mouse_mode)(void*, int);
5174void (*winpty_config_set_initial_size)(void*, int, int);
5175LPCWSTR (*winpty_conin_name)(void*);
5176LPCWSTR (*winpty_conout_name)(void*);
5177LPCWSTR (*winpty_conerr_name)(void*);
5178void (*winpty_free)(void*);
5179void (*winpty_config_free)(void*);
5180void (*winpty_spawn_config_free)(void*);
5181void (*winpty_error_free)(void*);
5182LPCWSTR (*winpty_error_msg)(void*);
5183BOOL (*winpty_set_size)(void*, int, int, void*);
5184HANDLE (*winpty_agent_process)(void*);
5185
5186#define WINPTY_DLL "winpty.dll"
5187
5188static HINSTANCE hWinPtyDLL = NULL;
5189# endif
5190
5191 static int
5192dyn_winpty_init(int verbose)
5193{
5194 int i;
5195 static struct
5196 {
5197 char *name;
5198 FARPROC *ptr;
5199 } winpty_entry[] =
5200 {
5201 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5202 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5203 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5204 {"winpty_config_set_mouse_mode",
5205 (FARPROC*)&winpty_config_set_mouse_mode},
5206 {"winpty_config_set_initial_size",
5207 (FARPROC*)&winpty_config_set_initial_size},
5208 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5209 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5210 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5211 {"winpty_free", (FARPROC*)&winpty_free},
5212 {"winpty_open", (FARPROC*)&winpty_open},
5213 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5214 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5215 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5216 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5217 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5218 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5219 {NULL, NULL}
5220 };
5221
5222 /* No need to initialize twice. */
5223 if (hWinPtyDLL)
5224 return OK;
5225 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5226 * winpty.dll. */
5227 if (*p_winptydll != NUL)
5228 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5229 if (!hWinPtyDLL)
5230 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5231 if (!hWinPtyDLL)
5232 {
5233 if (verbose)
5234 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5235 : (char_u *)WINPTY_DLL);
5236 return FAIL;
5237 }
5238 for (i = 0; winpty_entry[i].name != NULL
5239 && winpty_entry[i].ptr != NULL; ++i)
5240 {
5241 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5242 winpty_entry[i].name)) == NULL)
5243 {
5244 if (verbose)
5245 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5246 return FAIL;
5247 }
5248 }
5249
5250 return OK;
5251}
5252
5253/*
5254 * Create a new terminal of "rows" by "cols" cells.
5255 * Store a reference in "term".
5256 * Return OK or FAIL.
5257 */
5258 static int
5259term_and_job_init(
5260 term_T *term,
5261 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005262 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005263 jobopt_T *opt,
5264 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005265{
5266 WCHAR *cmd_wchar = NULL;
5267 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005268 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005269 channel_T *channel = NULL;
5270 job_T *job = NULL;
5271 DWORD error;
5272 HANDLE jo = NULL;
5273 HANDLE child_process_handle;
5274 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005275 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005276 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005277 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005278 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005279
5280 if (dyn_winpty_init(TRUE) == FAIL)
5281 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005282 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5283 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005284
5285 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005286 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005287 cmd = argvar->vval.v_string;
5288 }
5289 else if (argvar->v_type == VAR_LIST)
5290 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005291 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005292 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005293 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005294 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005295 if (cmd == NULL || *cmd == NUL)
5296 {
5297 EMSG(_(e_invarg));
5298 goto failed;
5299 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005300
5301 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005302 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005303 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005304 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005305 if (opt->jo_cwd != NULL)
5306 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005307
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005308 win32_build_env(opt->jo_env, &ga_env, TRUE);
5309 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005310
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005311 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5312 if (term->tl_winpty_config == NULL)
5313 goto failed;
5314
5315 winpty_config_set_mouse_mode(term->tl_winpty_config,
5316 WINPTY_MOUSE_MODE_FORCE);
5317 winpty_config_set_initial_size(term->tl_winpty_config,
5318 term->tl_cols, term->tl_rows);
5319 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5320 if (term->tl_winpty == NULL)
5321 goto failed;
5322
5323 spawn_config = winpty_spawn_config_new(
5324 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5325 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5326 NULL,
5327 cmd_wchar,
5328 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005329 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005330 &winpty_err);
5331 if (spawn_config == NULL)
5332 goto failed;
5333
5334 channel = add_channel();
5335 if (channel == NULL)
5336 goto failed;
5337
5338 job = job_alloc();
5339 if (job == NULL)
5340 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005341 if (argvar->v_type == VAR_STRING)
5342 {
5343 int argc;
5344
5345 build_argv_from_string(cmd, &job->jv_argv, &argc);
5346 }
5347 else
5348 {
5349 int argc;
5350
5351 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5352 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005353
5354 if (opt->jo_set & JO_IN_BUF)
5355 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5356
5357 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5358 &child_thread_handle, &error, &winpty_err))
5359 goto failed;
5360
5361 channel_set_pipes(channel,
5362 (sock_T)CreateFileW(
5363 winpty_conin_name(term->tl_winpty),
5364 GENERIC_WRITE, 0, NULL,
5365 OPEN_EXISTING, 0, NULL),
5366 (sock_T)CreateFileW(
5367 winpty_conout_name(term->tl_winpty),
5368 GENERIC_READ, 0, NULL,
5369 OPEN_EXISTING, 0, NULL),
5370 (sock_T)CreateFileW(
5371 winpty_conerr_name(term->tl_winpty),
5372 GENERIC_READ, 0, NULL,
5373 OPEN_EXISTING, 0, NULL));
5374
5375 /* Write lines with CR instead of NL. */
5376 channel->ch_write_text_mode = TRUE;
5377
5378 jo = CreateJobObject(NULL, NULL);
5379 if (jo == NULL)
5380 goto failed;
5381
5382 if (!AssignProcessToJobObject(jo, child_process_handle))
5383 {
5384 /* Failed, switch the way to terminate process with TerminateProcess. */
5385 CloseHandle(jo);
5386 jo = NULL;
5387 }
5388
5389 winpty_spawn_config_free(spawn_config);
5390 vim_free(cmd_wchar);
5391 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005392 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005393
5394 create_vterm(term, term->tl_rows, term->tl_cols);
5395
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005396#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5397 if (opt->jo_set2 & JO2_ANSI_COLORS)
5398 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5399 else
5400 init_vterm_ansi_colors(term->tl_vterm);
5401#endif
5402
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005403 channel_set_job(channel, job, opt);
5404 job_set_options(job, opt);
5405
5406 job->jv_channel = channel;
5407 job->jv_proc_info.hProcess = child_process_handle;
5408 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5409 job->jv_job_object = jo;
5410 job->jv_status = JOB_STARTED;
5411 job->jv_tty_in = utf16_to_enc(
5412 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5413 job->jv_tty_out = utf16_to_enc(
5414 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5415 ++job->jv_refcount;
5416 term->tl_job = job;
5417
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005418 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5419 * open the file here and handle it in. opt->jo_io was changed in
5420 * setup_job_options(), use the original flags here. */
5421 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5422 {
5423 char_u *fname = opt->jo_io_name[PART_OUT];
5424
5425 ch_log(channel, "Opening output file %s", fname);
5426 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5427 if (term->tl_out_fd == NULL)
5428 EMSG2(_(e_notopen), fname);
5429 }
5430
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005431 return OK;
5432
5433failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005434 ga_clear(&ga_cmd);
5435 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005436 vim_free(cmd_wchar);
5437 vim_free(cwd_wchar);
5438 if (spawn_config != NULL)
5439 winpty_spawn_config_free(spawn_config);
5440 if (channel != NULL)
5441 channel_clear(channel);
5442 if (job != NULL)
5443 {
5444 job->jv_channel = NULL;
5445 job_cleanup(job);
5446 }
5447 term->tl_job = NULL;
5448 if (jo != NULL)
5449 CloseHandle(jo);
5450 if (term->tl_winpty != NULL)
5451 winpty_free(term->tl_winpty);
5452 term->tl_winpty = NULL;
5453 if (term->tl_winpty_config != NULL)
5454 winpty_config_free(term->tl_winpty_config);
5455 term->tl_winpty_config = NULL;
5456 if (winpty_err != NULL)
5457 {
5458 char_u *msg = utf16_to_enc(
5459 (short_u *)winpty_error_msg(winpty_err), NULL);
5460
5461 EMSG(msg);
5462 winpty_error_free(winpty_err);
5463 }
5464 return FAIL;
5465}
5466
5467 static int
5468create_pty_only(term_T *term, jobopt_T *options)
5469{
5470 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5471 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5472 char in_name[80], out_name[80];
5473 channel_T *channel = NULL;
5474
5475 create_vterm(term, term->tl_rows, term->tl_cols);
5476
5477 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5478 GetCurrentProcessId(),
5479 curbuf->b_fnum);
5480 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5481 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5482 PIPE_UNLIMITED_INSTANCES,
5483 0, 0, NMPWAIT_NOWAIT, NULL);
5484 if (hPipeIn == INVALID_HANDLE_VALUE)
5485 goto failed;
5486
5487 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5488 GetCurrentProcessId(),
5489 curbuf->b_fnum);
5490 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5491 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5492 PIPE_UNLIMITED_INSTANCES,
5493 0, 0, 0, NULL);
5494 if (hPipeOut == INVALID_HANDLE_VALUE)
5495 goto failed;
5496
5497 ConnectNamedPipe(hPipeIn, NULL);
5498 ConnectNamedPipe(hPipeOut, NULL);
5499
5500 term->tl_job = job_alloc();
5501 if (term->tl_job == NULL)
5502 goto failed;
5503 ++term->tl_job->jv_refcount;
5504
5505 /* behave like the job is already finished */
5506 term->tl_job->jv_status = JOB_FINISHED;
5507
5508 channel = add_channel();
5509 if (channel == NULL)
5510 goto failed;
5511 term->tl_job->jv_channel = channel;
5512 channel->ch_keep_open = TRUE;
5513 channel->ch_named_pipe = TRUE;
5514
5515 channel_set_pipes(channel,
5516 (sock_T)hPipeIn,
5517 (sock_T)hPipeOut,
5518 (sock_T)hPipeOut);
5519 channel_set_job(channel, term->tl_job, options);
5520 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5521 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5522
5523 return OK;
5524
5525failed:
5526 if (hPipeIn != NULL)
5527 CloseHandle(hPipeIn);
5528 if (hPipeOut != NULL)
5529 CloseHandle(hPipeOut);
5530 return FAIL;
5531}
5532
5533/*
5534 * Free the terminal emulator part of "term".
5535 */
5536 static void
5537term_free_vterm(term_T *term)
5538{
5539 if (term->tl_winpty != NULL)
5540 winpty_free(term->tl_winpty);
5541 term->tl_winpty = NULL;
5542 if (term->tl_winpty_config != NULL)
5543 winpty_config_free(term->tl_winpty_config);
5544 term->tl_winpty_config = NULL;
5545 if (term->tl_vterm != NULL)
5546 vterm_free(term->tl_vterm);
5547 term->tl_vterm = NULL;
5548}
5549
5550/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005551 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005552 */
5553 static void
5554term_report_winsize(term_T *term, int rows, int cols)
5555{
5556 if (term->tl_winpty)
5557 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5558}
5559
5560 int
5561terminal_enabled(void)
5562{
5563 return dyn_winpty_init(FALSE) == OK;
5564}
5565
5566# else
5567
5568/**************************************
5569 * 3. Unix-like implementation.
5570 */
5571
5572/*
5573 * Create a new terminal of "rows" by "cols" cells.
5574 * Start job for "cmd".
5575 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005576 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005577 * Return OK or FAIL.
5578 */
5579 static int
5580term_and_job_init(
5581 term_T *term,
5582 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005583 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005584 jobopt_T *opt,
5585 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005586{
5587 create_vterm(term, term->tl_rows, term->tl_cols);
5588
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005589#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5590 if (opt->jo_set2 & JO2_ANSI_COLORS)
5591 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5592 else
5593 init_vterm_ansi_colors(term->tl_vterm);
5594#endif
5595
Bram Moolenaar13568252018-03-16 20:46:58 +01005596 /* This may change a string in "argvar". */
5597 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005598 if (term->tl_job != NULL)
5599 ++term->tl_job->jv_refcount;
5600
5601 return term->tl_job != NULL
5602 && term->tl_job->jv_channel != NULL
5603 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5604}
5605
5606 static int
5607create_pty_only(term_T *term, jobopt_T *opt)
5608{
5609 create_vterm(term, term->tl_rows, term->tl_cols);
5610
5611 term->tl_job = job_alloc();
5612 if (term->tl_job == NULL)
5613 return FAIL;
5614 ++term->tl_job->jv_refcount;
5615
5616 /* behave like the job is already finished */
5617 term->tl_job->jv_status = JOB_FINISHED;
5618
5619 return mch_create_pty_channel(term->tl_job, opt);
5620}
5621
5622/*
5623 * Free the terminal emulator part of "term".
5624 */
5625 static void
5626term_free_vterm(term_T *term)
5627{
5628 if (term->tl_vterm != NULL)
5629 vterm_free(term->tl_vterm);
5630 term->tl_vterm = NULL;
5631}
5632
5633/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005634 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005635 */
5636 static void
5637term_report_winsize(term_T *term, int rows, int cols)
5638{
5639 /* Use an ioctl() to report the new window size to the job. */
5640 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5641 {
5642 int fd = -1;
5643 int part;
5644
5645 for (part = PART_OUT; part < PART_COUNT; ++part)
5646 {
5647 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5648 if (isatty(fd))
5649 break;
5650 }
5651 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5652 mch_signal_job(term->tl_job, (char_u *)"winch");
5653 }
5654}
5655
5656# endif
5657
5658#endif /* FEAT_TERMINAL */